New Technologies

  • Java
  • Javascript
  • DTML
  • Dot Net
  • ASP .Net
  • C# .Net
  • PHP
Your Ad Here

Monday, June 30, 2008

Problem in removing elements from a collection using For-Loop


For-loops allows to traverse a collection but when I tried to remove elements from a collection in For-loop it so happened that after deleting one element at particular location in collection, the positions of rest of the element in collection changed and when I again tried to delete another element in the same loop the element hasn't got deleted.

Firstly I thought that this problem may be solved by using size() method in for statement as

<!--[if gte vml 1]&gt; &lt;![endif]--><!--[if !vml]--><!--[endif]--><!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

because may be change in size of collection dynamically causing the problem. But I this solution didn't work.

I concluded from this that whenever we delete multiple elements in same for-loop some of the elements are missed or skipped due to shuffling of positions during the loop.

Also, there is a need of generic method to traverse and modify any form of collection. An iterator can be used for this purpose.

We need to see the element before we can decide that it is the one that should be removed from a collection. But in for-loop it is not necessary to lookup and then change. That is use of for-loop can make an attempt to change or remove an element without looking in it. So a tightly coupled mechanism for lookup and then change is needed. An iterator of collection Framework can be useful in solving this problem.

To find how for-loop caused problem and how iterator can solve this I have discussed about following in this BLOG:

1.Problem with For-Loop.
2.How Iterator are different from For-loop
3.Concept of Removing Elements using Iterator
4.For-Each Construct: The Enhanced For-Loop
5.Problem and Restrictions with the enhanced for loop
6.Example: JDOM multiple element deletion from ElementList problem
7.An Example of remove element using For-loop and Iterator

Problems with For-Loop

There are some basic disadvantages to using the traditional For-loop when we want to deal with more complex data structures. Fortunately, with the Collections framework, Java introduced the use of an Iterator. An Iterator allows us to move through the elements of a data structure with several advantages over the traditional For-loop.
First, with iterator we don't have to worry about explicitly managing the movement of the index. With the For-loop, we need to specify the upper and lower bounds, and if a mistake is made our program will terminate with an IndexOutOfBoundsException.
Second, we can use the Iterator interface to move over several datatypes, even through those that don't have a natural ordering to them. For example, we can use an Iterator to display the contents of a HashMap.
Finally, the Iterator allows us to remove elements from the underlying collection simply, again saving us from having to worry about recalculating the loop bounds or the new index position.

Iterators are different from For-loop

We can perform lookup directly using index of element independent of position change in For-loop using index++. While in Iterators the lookup and position change are tightly coupled. The only way to look up an element is to call next, and that lookup advances the position. Instead, we should think of Java iterators as being between elements. When we call next, the iterator jumps over the next element, and it returns a reference to the element that it just passed.

The For-loop is in many ways similar to a while loop – in particular; it is pre-tested rather than post-tested, while in case of iterator it is post tested. It is most often used when a fixed number of iterations are required, with this number known in advance.

Concept of Removing Elements using Iterator

Problem: How to remove element from collection and to avoid unexpected results after deletion?
Solution: We can use iterator. Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

An Iterator is an object that enables us to traverse through a collection, and to remove elements from the collection selectively, if desired. We get an Iterator for a collection by calling its iterator method.

The Iterator interface is:

The hasNext method returns true if the iteration has more elements, and the next method returns the next element in the iteration. The remove method removes from the underlying Collection the last element that was returned by next.

In many situations, that make sense—we need to see the element before we can decide that it is the one that should be removed. But if we want to remove an element in a particular position, we still need to skip past the element. For example, here is how you remove the first element in a collection of strings.

The remove method may be called only once per call to next and throws an exception if this rule is violated. There is a dependency between calls to the next and remove methods. It is illegal to call remove if it wasn't preceded by a call to next. If we try, an IllegalStateException is thrown.

If we want to remove two adjacent elements, we cannot simply call

it.remove();
it.remove(); // Error!

Instead, we must first call next to jump over the element to be removed.

it.remove();
it.next();
it.remove(); // Ok

Problem: Collections can be represented in many of forms. With such a variety of traversal mechanisms for different forms of collection, how can we hope to come up with a single generic method that will work for collections that are stored in wildly different forms?

Solution: This problem is solved by iterators. An iterator is an object that can be used to traverse a collection. Different types of collections have different types of iterators, but all iterators are used in the same way. An algorithm that uses an iterator to traverse a collection is generic, because the same technique can be applied to any type of collection.

Using iterators, we can write code for printing all the items in any collection. Suppose that coll is of type Collection. Then we can say:

Iterator iter = coll.iterator();
while ( iter.hasNext() ) {
Object item = iter.next();
System.out.println(item);
}

The same general form will work for other types of processing. For example, here is a subroutine that will remove all null values from any collection (as long as that collection supports removal of values):

void removeNullValues( Collection coll ) {
Iterator iter = coll.iterator():
while ( iter.hasNext() ) {
Object item = iter.next();
if (item == null)
iter.remove();
}
}

For-Each Construct : The Enhanced For-Loop

The for-each construct allows you to concisely traverse a collection or array using a for loop. The following code uses the for-each construct to print out each element of a collection on a separate line:

for (Object o : collection)
System.out.println(o);

Problem and Restrictions with the enhanced for loop

The syntax of the for(:) loop does not use an iterator for the collection.
CANNOT be used to remove elements from a collection. The 'for-each' loop hides the iterator, so you CANNOT call remove(). Therefore, the 'for-each' loop is not usable for filtering:

Example: JDOM element deletion from ElementList problem

JDOM element deletion from ElementList problemI have one XML file with multiple table elements like this. I am using Jdom for xml changes.

I want to delete the "table" elements which are having parentId="1″.
For deleting I am using the following code:

<!--[if gte vml 1]&gt; &lt;![endif]--><!--[if !vml]--><!--[endif]-->

tableList contains List of table Elementvalues.

But, I am getting the following result:

<!--[if gte vml 1]&gt; &lt;![endif]--><!--[if !vml]--><!--[endif]-->

Problem:Some of specified table elements are not deleted I think the problem is not with XML stuff but the loop iterating over a container is causing the problem. In loop, I am removing elements from the container, which in effect will shrink the size and hence will create possibilities to miss some locations.
Idiom: Do not remove items from a dynamic container while iterating over the same.
Solution: Use "Iterators" instead of the For-loop.

An Example of remove element using For-loop and Iterator

With all that data stored in our Array, we of course want some way to access that data. Using an Array inspector such as FetchItemAt() of course works, but there are times when we wish to walk our Array from one point to another, perhaps looking for a specific element or perhaps performing an operation on or with elements in the Array. This is where Iterators come in to play. An Iterator provides us with a means of sequentially traversing an Array. Again we could use a loop and FetchItemAt() to traverse our Array, but consider the following situation:

<!--[if gte vml 1]&gt; &lt;![endif]--><!--[if !vml]--><!--[endif]-->

What would happen in the above situation if targetData was found? It would of course be removed from the Array. After removing the item from the Array, the Array is now one less and numItems is no longer valid. When i == numItems, we could be in for some unexpected results! And if there happened to be more than one instance of targetData in the Array, we could be in for trouble a lot sooner. Instead, we can try using an Iterator:

<!--[if gte vml 1]&gt; &lt;![endif]--><!--[if !vml]--><!--[endif]-->

The two blocks of code perform the same function, but the latter version is savvier to the Array changing underneath it. The Iterators are not locked to certain numbers as the first example is, but rather to concepts such as "Next" and "Previous" to walk the Array. Additionally, an Array can have multiple Iterators.

Sunday, June 29, 2008

Free Online File Format Converter

http://media-convert.com/

This is the link for free online file format converter. Here we can convert Movies, Sounds, Data, Text Documents, Presentation, Ringtones, Images and Compressed Archives from one format to another format.

Using the window.open method — 3 methods to open window

Using the window.open method

The syntax of the window.open method is given below:

open (URL, windowName[, windowFeatures])

URL
The URL of the page to open in the new window. This argument could be blank.

windowName
A name to be given to the new window. The name can be used to refer this window again.

windowFeatures
A string that determines the various window features to be included in the popup window (like status bar, address bar etc)

The following code opens a new browser window with standard features.

window.open ("http://www.javascript-coder.com","mywindow");

Note: The popups created using 'window.open()' can get blocked by popup blockers.
Click here to find out how to create popups that does not get blocked.

Changing the features of the Popup

You can control the features of the popup using the last argument to the window.open method. The following code opens a window with a status bar and no extra features.
window.open ("http://www.javascript-coder.com","mywindow","status=1");

The code below opens a window with toolbar and status bar.
window.open ("http://www.javascript-coder.com",
"mywindow","status=1,toolbar=1");

The table shows the features and the string tokens you can use:

status

The status bar at the bottom of the window.

toolbar

The standard browser toolbar, with buttons such as Back and Forward.

location

The Location entry field where you enter the URL.

menubar

The menu bar of the window

directories

The standard browser directory buttons, such as What's New and What's Cool

resizable

Allow/Disallow the user to resize the window.

scrollbars

Enable the scrollbars if the document is bigger than the window

height

Specifies the height of the window in pixels. (example: height='350′)

width

Specifies the width of the window in pixels.

Examples
The following code opens a window with menu bar. The window is resizable and is having 350 pixels width and 250 pixels height.
window.open ("http://www.javascript-coder.com",
"mywindow","menubar=1,resizable=1,width=350,height=250");

Example 1

A window with location bar, status bar, scroll bar and of size 100 X 100
window.open ("http://www.javascript-coder.com",
"mywindow","location=1,status=1,scrollbars=1,
width=100,height=100");

Example 2

Moving the window to a desired location

You can use the window.moveTo function to move the popup window to a desired location.
The code below shows positioning the popup at a desired location

function mypopup()
{
mywindow = window.open ("http://www.javascript-coder.com",
"mywindow","location=1,status=1,scrollbars=1,
width=100,height=100");
mywindow.moveTo(0,0);
}

The code positions the popup on the top left corner of the screen.

Putting it all together

Now we will combine all these information to create the popup windows of different types.
The Code below opens a popup window when you enter the page:

<html>
<head>
<title>JavaScript Popup Example 3</title>
</head>
<SCRIPT language="JavaScript1.2">
function poponload()
{
testwindow= window.open ("", "mywindow",
"location=1,status=1,scrollbars=1,width=100,height=100");
testwindow.moveTo(0,0);
}
</SCRIPT>
<body onload="javascript: poponload()">
<H1>JavaScript Popup Example 3</H1>
</body>
</html>

Notice that the URL is kept blank. This will open a blank window. You can see the code in work in this file:
JavaScript Popup Example 3

Popup On Exit

The following code pops up a window when the user exits a page.

<html>
<head>
<title>JavaScript Popup Example 3</title>
</head>
<SCRIPT language="JavaScript1.2">
function exitpop()
{
my_window= window.open ("",
"mywindow1","status=1,width=350,height=150");
my_window.document.write('<H1>Popup Test!</H1>');
}
</SCRIPT>
<body onunload="javascript: exitpop()"
>
<H1>JavaScript Popup Example 4</H1>
</body>
</html>

The code contains an extra line:
my_window.document.write('<H1>Popup Test!</H1>')
This code displays a line 'Popup Test!' in the popup.

The code is available in the file:
JavaScript Popup Example 4

The next page shows you how to close a popup window

To configure the default error page in a webproject in java

first open web.xml

and insert the following example code

<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>

and then create the error information page that is error.jsp.

JavaFX as Rich Internet Application Platform

JavaOne wrapped up on Friday. We hosted individuals from across the globe, and from every industry: consumer electronics and gaming, to enterprise IT, space exploration, factory automation, the automotive industry, academia - like the network itself, Java delivers something for nearly everyone, everywhere.

This year’s biggest announcements centered around Java’s role in the future of rich internet applications (or RIA’s). What’s a rich internet application? It depends on your perspective - from mine, it’s any network connected application that persists in front of a user, typically outside a browser, that can operate when disconnected from the network.

On the one hand, I’d claim Java’s always been a RIA platform - before the world really wanted one. Early Java applets delivered interactivity, but at the expense of development complexity and, in the early days, performance - when a browser, and more recently Javascript, would suffice.

But browser based applications are hitting complexity and performance limits, and content owners are striving for higher levels of engagement (via high definition video, or advanced interactivity). Developers are demanding something new - the browser’s a wonderfully accessible programming model, but it’s a weak deployment model for rich/disconnected applications.

An unspoken driver of RIA is also business model evolution - many companies behind rich applications are seeking independence from browsers and search engines, whose default settings and corporate parents present a competitive threat. There’s a growing appetite for locally installed applications that build rich, direct and permanent engagement with consumers. No one wants to pay a toll to meet their own customers.

With that in mind, as we looked to reinvent the Java platform, we heard a consistent set of requirements. And not just from coders, but from sports francishes seeking to directly engage their fans, media companies wanting to bypass browser defaults, to artists and businesses and device manufacturers - everyone’s looking to uniquely engage consumers via the network. These audiences have nearly identitical requirements for a RIA platform - they want technology that:

  • Reaches every internet consumer - on desktops, mobile, and new devices, too.
  • Delivers high performance - and the ability to engage creative professsionals in the design process.
  • Leverages existing skills and enterprise infrastructure.
  • Is totally free, and open source.
  • Provides content owners with control and ownership of their own data.

At JavaOne last week, we addressed every one of those issues - here’s how:

First, RIA developers want to reach every consumer on earth, and on every device.

Why? Because the market is in front of consumers - no matter what screen they may be using. Desktop, mobile phone, personal navigation, digital book - you name it. The market’s in front of all the screens in your life, not just a PC.

That said, on PC’s alone, Java’s popularity has grown in the last few years, as measured by runtime downloads - we routinely download 40 to 50 million new Java runtimes a month, and update more than a billion every year. The adoption of the Java platform exceeds the adoption of Microsoft’s Windows itself - Sun’s Java runtime environment (JRE) is preloaded on nearly every Windows machine (from HP, Dell, Lenovo, etc.), but also runs on Apple’s Macintosh, Ubuntu, Fedora, SuSe, Solaris and OpenSolaris desktops. In addition, a JRE is present on billions - yes, billions - of wireless and mobile devices, from automobile dashboards and navigation devices, to Amazon’s Kindle (did you know Amazon’s Kindle is a Java platform?).

Which is to say, the Java platform reaches more people than any other software technology the world has ever seen.

Second, RIA developers want performance, functionality AND simplicity.

Why? Because content owners and application developers want to engage consumers - and want to engage artists and creative professionals in the workflow.

Java’s history with simplicity isn’t perfect - which is why our teams have rewritten the applet model, and focused so intently on making the new consumer Java runtime environment (download a beta version here) exceptionally fast to load within a web page, exceptionally performant for complex interactivity, and trivially accessible to consumers. We’ve also simplified Java with a scripting language, JavaFX script, that enables creative professionals to engage with coders to create immersive experiences, while embracing the creative tool chain (from interaction design to pixel manipulation) used by the worlds designers and digital artists.

And I’m really pleased we’ve solved the desktop installation problem, by making JavaFX applets separable from a web page with a simple drag and drop (click the image above to watch this demonstrated). Developers can now bypass the browser to trivially install apps on desktops - once the applet’s dropped on the desktop, content owners have a direct relationship with their consumers.

You might have also seen that we’re adding full high quality audio and video codecs to Java on every platform on which it runs - resolving another gap for RIA developers, support for time-based media (click here for a demo of high performance video).

Third, enterprises want to reuse their existing Java skills and assets in moving to RIA.

Nearly every enterprise employs programmers with Java skills - it’s still the number one internet language taught across the world, and found pervasively in global business infrastructure. As businesses move to engage their customers via RIA platforms, reusing existing skills, and connecting RIA’s to existing systems, gives the Java community a unique ability to build from what exists - rather than attempt to replace it.

This familiarity also allows businesses and developer teams to focus on engaging with consumers - rather than irritating IT with new infrastructure requirements (JavaFX developers simply link to existing enterprise infrastructure, vs. requiring new systems for RIA apps).

Fourth, RIA developers want free and open platforms.

Why free? Because developers don’t want to encumber their applications with royalty bearing dependencies, or use technologies that predefine where consumers might appear. You don’t build developer communities around closed source, you build user communities - and this is an instance where developer selection and adoption will define the broadest RIA marketplace. JavaFX will, like all of Sun’s software platforms, be made freely available as open source, and it’ll be released via the GPL (v2) license.

And lest you think free and open software is the province of those with goatees and tattoos… we’re seeing a rising tide of developing nations mandating free and open software in government and academic procurement. Why? To protect choice, and build indigenous opportunity - there’s no reason to build dependencies upon proprietary software if you can avoid it.

Lastly, lets face it, the real value in Web 2.0 is the data - not the app. And that data is YOURS.

If you’ve been watching the social media space as carefully as we have, you understand the value of instrumentation and intentionality in building a business on the web. Knowing what users are doing with your product, whether it’s a fantasy cricket league or a consumer banking application, enables more innovative business models, the delivery of higher value services, placement of more valuable ads - data allows for better decisions, and better value creation (and bluntly put, higher CPA).

But most rich internet applications are built, then deployed - into a fog. Developers who leave the confines of the browser either lose access to information about what their users are doing, or have to rely upon a technology provider that’s inserting itself into their data stream. And some of those technology providers compete with content developers.

With a project code named Project Insight, we’ll be instrumenting the Java platform to enable developers to harvest the data stream generated by their RIA content. JavaFX developers can focus on their business models - rather than enhancing someone else’s.

_______________________

With all that said, what’s the success of JavaFX worth to Sun?

By definition, it’s worth more to Sun than the adoption of someone else’s platform (known as “positive option value”) - and the proprietary infrastructure used to serve it (don’t forget, RIA’s have rich internet back-ends (RIBs?). And in the RIA world, all the options are going to be priced at free, anyways - this isn’t a contest to be won on price.

From where I sit, the platform likely to win will be the one that sets developers free - to pursue markets, opportunities and customer experiences as they define them, not as vendors define them. Now, setting developers free - that’s where we can excel. It’s in the DNA of everything we do.

For developers, learn more at JavaFX.com. And be sure to check out NetBeans - like Java itself, it’s starting to rock the free world…

See also

A portal is a web page that contains individual and customizable web applications. For example, My Yahoo is a portal page. The portal provides value-added services, such as single sign-on, customization, content aggregation, and localization.

Individual web applications that are added to the portal page are called portlets. A portlet is a Java technology web component that is based on the JSR 168 specification and JSR 286, which includes Web Service for Remote Portlets (WSRP). Portlets are managed by portlet containers that supply dynamic content. Portals employ portlets as pluggable user-interface components that provide users with desired content such as RSS feeds, mashups of services such as the current weather in a given area, or even static content such as a group of hyperlinks.

In the past, creating portlets was a complex process. Now, you can quickly and easily create and test portlets using the NetBeans IDE 6.0 and the OpenPortal Portlet Container 2.0 Beta 2. Deploying the portlets onto the server is also simple.

This article shows you how to create portlets and provide dynamic content through drag-and-drop widgets in the NetBeans IDE. The example portlet in this article uses the jMaki Tabbed View widget, pulls in RSS feeds, and uses static links from the New to Java Programming Center.

What You Need to Get Started

To create and test portlets, you need the following software installed on your computer:

For instructions on installing the OpenPortal Portlet Container 2.0 Beta 2, see the installation page. You must download and install the OpenPortal Portlet Container before you follow the next steps.

The portlet container works similarly to servlet containers. A portlet container does the following:

  • Provides the runtime environment for portlets
  • Manages the life cycle of portlets
  • Provides persistent storage for storing portlet preferences
  • Caches the portlets
  • Receives requests from the portal to execute requests on the portlet

Once you have installed the necessary software, start the NetBeans IDE. Next, install the portlet and portlet container plug-ins by following these steps:

  1. Go to Tools in the main menu.
  2. Select Plug-ins.
  3. Click on the Available Plug-ins tab.
  4. Check the boxes for Portlets, the OpenPortal Portlet Container, and jMaki Ajax Support.
  5. Click the Install button and follow the directions from there. You may need to accept a few licenses before the installation process can complete.

Lastly, add the OpenPortal Portlet Container server:

  1. Go to Tools in the main menu.
  2. Select Servers.
  3. Click on Add Server.
  4. Select OpenPortal Portlet Container 2.0 from the list.
  5. Click Next.
  6. Use Browse to set the location in which to install the GlassFish application server. You may need to search your system separately to discover where the NetBeans IDE installed the GlassFish application server.
  7. Click OK.

You are now ready to create a portlet.

Creating a Portlet Project

As you do whenever you create an application in the NetBeans IDE, go to File > New Project, and choose Web > Web Application, then click Next. For the name of this project, type New2JavaPortlet. In the Server drop-down menu, choose OpenPortal Portlet Container 2.0 Beta, then click Next. In the next screen, check the jMaki Ajax Framework box. In the lower half of the pane, you get a selection of layouts. Scroll to the bottom, and choose No CSS Style.

Lastly, at the top of the screen, check the Portlets Support box. Use the Portlet Version drop-down menu and select 2.0, then check the Create Portlet box. In Portlet Class Name, type New2JavaPortlet. Note that the project name and the portlet name must be the same. The other fields are filled in automatically. Click Finish.

Because of the way that portlets are set up within the container, you will not need the displayed index.jsp page. On the left side of the screen, under the Projects tab, you see index.jsp listed. Right-click on index.jsp and select Delete. The file you are going to work on is named New2JavaPortlet_view.jsp. You can find that file by expanding the WEB-INF directory, then the jsp directory. Double-click the file name New2JavaPortlet_view.jsp The file now opens in the workspace.


How the Java Portlet Works

Even though all you've done is create a portlet project, the NetBeans IDE has already written an essential class for you. From the Projects tab, expand the Source Packages. Then expand com.text, and open the file New2JavaPortlet.java by double-clicking the file name.

The New2JavaPortlet extends a GenericPortlet class, which is provided, that implements the render() method and delegates the call to more specific methods to display the portlet based on its mode. Developers can extend GenericPortlet and implement as many of the following specialized render methods as are necessary for their portlet:

  • doView() Called by render() when the portlet is in View mode. Intended to contain logic that displays the View page for the portlet.
  • doEdit() Called by render() when the portlet is in Edit mode. Intended to contain logic that displays the Edit page for the portlet.
  • doHelp() Called by render() when the portlet is in Help mode. Intended to contain logic that displays the Help page for the portlet.

Notice that the New2JavaPortlet calls these methods, locating the pages for each. In this article, you will put the content of the portlet in the View page through drag-and-drop widgets and some HTML code. But you can extend this GenericPortlet class for other portlets. You can also go back later and modify the Edit or Help page. Once you have had a good look at the New2JavaPortlet class, you can close it.

When you build and run the portlet, the browser will display the New2JavaPortlet_view.jsp. Currently, this page contains only the static text: New2JavaPortlet - VIEW MODE. Because it is a JavaServer Pages (JSP) technology page, you can add any scripts or JSP tag libraries that you wish, and treat it like any other JSP page.

Test your portlet environment now before adding more content: From the main menu, click Build and select Build Main Project. Once the build is successfully completed, go to the main menu and click Run. Select Run Main Project. This takes a little longer as the application server is started, the portlet container is started, and a browser window is opened.

Notice that the portlet project name is the same as the portlet itself. Once you see that your development and testing environments are working properly, you can add content to replace the static text on the New2JavaPortlet_view.jsp page. To see the changes that you make to your portlet, you undeploy and deploy the portlet, as explained in the next section.

Adding Dynamic and Static Content to the Portlet

Because this portlet will contain several kinds of content, organize the content for a small area on a web page by using tabbed panes. You can choose other types of layouts, of course, but for this example, use the jMaki widget named Tabbed View. On the right side of your screen, notice that you have many available widgets to drag and drop. Check to be sure that the jMaki Yahoo widgets list is expanded .

Within the workspace page, delete the static text that says New2JavaPortlet - VIEW MODE. Also, delete the surrounding HTML code for bold: <b></b>. Now drag and drop the Tabbed View widget, shown highlighted in white , from the palette onto the page, exactly where you have just deleted text. Once you have dropped the Tabbed View widget onto the page, the following code appears on the page:

<a:widget name="yahoo.tabbedview"
   value="{items:[
           {label : 'My Tab', content : 'Some Content'},
           {id : 'bar', label : 'My Tab 2', include : 'test.jsp ', lazyLoad : true },
           {label : 'My Tab 3', content : 'More Content',  selected : true}
          ]
         }" />

The action of dragging and dropping a jMaki widget onto the page causes the creation in the resources directory of all the files necessary to build that widget.

To get an idea for how this widget works, save the file. Next, right-click the project name in the Projects pane and select Undeploy and Deploy. Once it is built, run the project: Go to the main menu, click Run, and select Run Main Project. When the project runs, your changes appear in the browser window. Click on each of the tabs in the Tabbed View pane. Notice on the tab named My Tab 2 that the file test.jsp was not loaded. This is only because a test.jsp had not been created, but it does demonstrate how you call a JSP page to appear in the pane.

For the New2JavaPortlet, you are going to create new JSP pages that the widget will call. Each of these pages provides the content for each of the tabs. On the New2JavaPortlet_view.jsp page, replace the code shown earlier with the following code:

<a:widget name="yahoo.tabbedview"
   value="{items:[
           {id : 'bar', label : 'Popular & New', include : '/New2JavaPortlet/whatsnew.jsp ', selected : true },
           { label : 'Java Fundamentals', include : '/New2JavaPortlet/fundamentals.jsp ', lazyLoad : true },
           { label : 'Downloads', include : '/New2JavaPortlet/downloads.jsp ', lazyLoad : true },
          ]
         }" />

This code calls three JSP pages: whatsnew.jsp, fundamentals.jsp, and downloads.jsp.

The next step is to create those pages. In the Projects pane, right-click on Web Pages. Then select New, and lastly JSP. Notice that you are saving these pages into the Web Pages directory, not the jsp directory that the portlet container created for the New2JavaPortlet_view.jsp. Any JSP pages that you create must go into the Web Pages


Create three JSP pages in this manner, naming them whatsnew, fundamentals, and downloads. The NetBeans IDE automatically adds the .jsp extension, so don't include that in the file name.

Next, run Undeploy and Deploy again. Then click on the Run menu, and select Run Main Project. This time, note that the tab names have changed. As you click on each tab name, you get the JSP pages that you just created because of the code you replaced. Open each of these JSP pages — downloads.jsp, fundamentals.jsp, and whatsnew.jsp — and add content as described in the following subsections.

The downloads.jsp Page

This page contains simple static content, a title, and a list of links. Do not change the first two lines of code that appear at the top of the page:

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

But replace all of the HTML code with the following:

<h3>Downloads for New Developers</h3>
 
<ul>
  <li><a href="http://java.sun.com/javase/downloads/i">Java SE (JDK)</a>
  <li><a href="http://www.netbeans.org/">NetBeans IDE</a>
  <li><a href="http://www.mysql.com">MySQL Database</a>
</ul>

The fundamentals.jsp Page

This page will provide dynamic content, pulling in an RSS feed. Again, leave the first two lines of code alone, and remove all of the HTML code. Next, from the jMaki Widgets palette on the right side of the display, drag and drop the Block List widget onto the page.

The following code should appear on your page:

<a:widget name="jmaki.blockList" value="[
{title : 'jMaki Project Home', link : 'https://ajax.dev.java.net', description : 'Where to go for the latest jMaki.' },
{title : 'jMaki Widgets Home', link : 'https://widgets.dev.java.net', description : 'The source for the latest jMaki widgets.' },
{title : 'jMaki-Charting Home', link : 'https://jmaki-charting.dev.java.net', description : 'Enables complex charts rendered on the client in any modern browser.' }
]"  />

The widget provides placeholder text only. Replace everything with the following code:

<h3>Java Technology Fundamentals</h3>
 
<a:widget name="jmaki.blockList" service="/xhp?id=rss"  />

In order to populate the widget with data from an external service, such as an RSS feed, you must replace the value attribute with service="/xhp?id=rss". If any page consists of a jMaki widget, then the jMaki runtime is bundled with the application. The runtime consists of jmaki.xhp.XmlHttpProxyServlet class that maps to the /xhp URL pattern within the application context.

The identifier or ID specified in the URL, rss, is configured in a configuration file named xhp.json. This file consists of a list of default external services that the widgets in a page can access. You can specify each entry in the xhp.json file by using up to five different parameters:

  • ID: This required parameter is a unique identifier for the entry.
  • URL: This required parameter gives the location of the external service.
  • Parameters: These optional parameters specify the default values passed to the URL.
  • API key: This is an optional parameter to invoke the service with a specific key.
  • Stylesheet: This is an optional parameter to process the response.

Next, you must change the xhp.json file. Go to the Projects tab and expand the resources directory. Double-click the file xhp.json, and scroll to the bottom of that page. Search for this code in the xhp.json file:

{"id": "rss",
      "url":"http://weblogs.java.net/blog/ludo/index.rdf",
      "xslStyleSheet": "rss.xsl"
  }

The tag and the default entry tell the jMaki runtime to fetch the RSS feed from http://weblogs.java.net/blog/ludo/index.rdf, apply the rss.xsl stylesheet — which understands the multiple RSS/Atom formats — to the received response, and convert the data into a common JavaScript Object Notation (JSON) data format of the type "dataType" : "jMakiRSS". The jMaki Block List widget can convert jmakiRSS data to its specific data model.

But the intention of this article is not to pull in Ludovic Champenois's blog. So change the URL of http://weblogs.java.net/blog/ludo/index.rdf to http://blogs.sun.com/JavaFundamentals/feed/entries/rss.

Additionally, you will pull in another feed on the whatsnew.jsp page, so change the URL in the code as shown in the following code snippet. The new URL is highlighted in red.

{"id": "rss2",
      "url":"http://blogs.sun.com/new2javaUpdates/feed/entries/rss",
      "xslStyleSheet": "rss.xsl"
   }

Notice that the ID for the second RSS feed to pull in is named rss2. Notice also that the URL pulls in the blogs from the "What's New" section of the New to Java Programming Center. Save the xhp.json file. Because you've added another block of code to pull in the second feed, you must separate the two with a comma after the closing curly bracket (}) of the first block. The following code snippet shows the added comma in red on the fourth line:

    {"id": "rss",
      "url":"http://blogs.sun.com/JavaFundamentals/feed/entries/rss",
      "xslStyleSheet": "rss.xsl"
     },
    {"id": "rss2″,
      "url":"http://blogs.sun.com/new2javaUpdates/feed/entries/rss",
      "xslStyleSheet": "rss.xsl"
     }

The whatsnew.jsp Page

Go to the whatsnew.jsp page, and delete the HTML code. Add the following static HTML code:

<h3>What's Popular</h3>
 
<ul>
  <li><a href="http://java.sun.com/docs/books/tutorial/">The Java Tutorial</a></li>
  <li><a href="http://blogs.sun.com/JavaFundamentals/">Java Technology Fundamentals</a></li>
  <li><a href="http://blogs.sun.com/CoreJavaTechTips/">Core Tech Tips</a></li>
  <li><a href="http://java.sun.com/developer/onlineTraining/tools/netbeans/">Easy Web Site Creation in the NetBeans IDE</a></li>
  <li><a href="http://java.sun.com/javaee/5/docs/tutorial/doc/">The Java EE 5 Tutorial</a></li>
</ul>
 
<h3>What's New</h3>

Next, from the jMaki Widgets palette on the right side of the display, drag and drop the Block List widget onto the page. Change the code as shown here:

<a:widget name="jmaki.blockList" service="/xhp?id=rss2"  />

Customizing the jMaki Widgets

All the files that you need for customizing any of the widgets are available in the resources directory by widget name. In this case, look under jMaki for the files for the block list. Expand the blocklist directory, and open the file called component.css.

Change the line that says height : 85px; to height : 25px; and save the file.

Next, open the component.html file, and delete the following code from it:

<br/>
@{description}<br/>

This removes the descriptions from the RSS feeds, leaving only the title as a link. You can also add content, such as a date, by adding it to this file. Now, save all the files, click Undeploy and Deploy, then run the portlet again by clicking on Run in the menu and selecting Run Main Project.

Again, click Undeploy and Deploy. Then click Run the application. You now see the pages that you've created with the content. Notice also that the block list is taking up a lot of room. You can customize jMaki widgets easily by going to the Projects tab, expanding the resources directory, expanding the jMaki directory and then blockList. Edit component.css so that the height is just 25 pixels (25px).

Click Undeploy and Deploy again. When you run the portlet.

Your portlet is now complete. Once the portlet is deployed, users can add the portlet to their portal page and have access to the information they want on their page. You can tailor portlets in many different ways to suit the needs of your web site. The NetBeans IDE provides many widgets that you can drag and drop, but you are not limited by what that palette provides. You can also create your own widgets, or use Java code to create an unlimited number of objects to get the functionality that you want.

The next step is to archive the entire project in a ZIP file and send it to the server administrator. If you are also the server administrator, read the next section.

Packaging and Deployment

The portlet specification specifies the packaging and deployment of portlets as part of standard Web Application Archive (WAR) files that may contain other web components, such as JSP pages and servlets. In addition to the web.xml deployment descriptor now found in WAR files, the portlet.xml file in the WEB-INF directory descriptor defines all portlets and portlet-related configurations. An XML schema included in the portlet specification JSR 168 defines the standard elements for portlet configuration stored in the portlet.xml file.

Each portal-server vendor must provide a tool to parse the portlet descriptor file and deploy the portlet. These tools likely exist in GUI form as well as in command-line form. Developers will be able to integrate the command-line deployment tools with the Apache Ant tool. This creates additional development environment possibilities, because most development tools provide an interface for Apache Ant.

To deploy the project onto the server, see the documentation for your portal server for complete details. Most portal servers will allow you to deploy the WAR file, which is located in your project's dist directory after you perform a build. Depending on your portal server, this may be deployed by using the Ant command, copying the WAR to your portal autodeploy directory, or using the administrative feature of your portal server.

Summary

Now that you have created a portlet, you can create other types of portlets for the portal page for your users. Portlets can include components such as local weather, the latest news, live sports scores, maps, and RSS feeds from other sites. Portlets allow your users to customize the web page to meet their specific needs, and this keeps them coming back to your web site.

For More Information

Your Ad Here