Tech all over the world
Saturday, April 29, 2006
  Enterprise Java Technologies Tech Tips, April 29, 2006 (Porting Java WSDP 2.0 Web Services, Call Flow Monitoring)
You are receiving this e-mail because you elected to receive e-mail from Sun Microsystems, Inc. To update your communications preferences, please see the link at the bottom of this message. We respect your privacy and post our privacy policy prominently on our Web site http://sun.com/privacy/

Please do not reply to the mailed version of the newsletter, this alias is not monitored. Feedback options are listed in the footer for both content and delivery issues.
  Welcome to the Enterprise Java Technologies Tech Tips.
Enterprise Java Technologies
TECHNICAL TIPS
April 29, 2006
View this issue as simple text
In this Issue
 
Welcome to the Enterprise Java Technologies Tech Tips for February 25, 2006. Here you'll get tips on using enterprise Java technologies and APIs, such as those in Java 2 Platform, Enterprise Edition (J2EE) and Java Platform, Enterprise Edition (Java EE).

This issue covers:

» Porting Java WSDP 2.0-Based Web Services to Java EE 5
» Call Flow Monitoring in GlassFish

These tips were developed using an open source reference implementation of Java EE 5 called GlassFish. You can download GlassFish from the GlassFish Community Downloads page.

You can download the sample archive for the tip Porting Java WSDP 2.0-Based Web Services to Java EE 5. You can download the sample archive for the Call Flow Monitoring in GlassFish tip..

Any use of this code and/or information below is subject to the license terms.

See the Subscribe/Unsubscribe note at the end of this newsletter to subscribe to Tech Tips that focus on technologies and products in other Java platforms.

PORTING JAVA WSDP 2.0-BASED WEB SERVICES TO JAVA EE 5
 
by Vijay Ramachandran

One of the technologies available in J2EE for developing and deploying web services is Java API for XML-Based RPC (JAX-RPC). However, using JAX-RPC technology requires a developer to specify a lot of information in deployment descriptors such as webservices.xml, web.xml, and ejb-jar.xml. These requirements are seen by many programmers as cumbersome and confusing.

To simplify the web services programming model, the Java API for XML Web Services (JAX-WS) was introduced. The main focus of JAX-WS technology is ease of web services development and deployment. A lot of this simplicity results from annotations. An earlier Tech Tip, "Developing Web Services Using JAX-WS" showed some of these annotations in use. These and other JAX-WS features have eliminated the requirement for deployment descriptors.

JAX-WS technology was initially made available in the Java Web Services Developer Pack (Java WSDP) Version 2.0. This allowed early adopters to develop JAX-WS-based web services and deploy them on J2EE 1.4 implementations such as the J2EE 1.4 SDK (which includes the Sun Java System Application Server 8.2 Platform Edition) or Apache Tomcat. However, because JAX-WS technology became available after the release of J2EE 1.4, using it with that level of the platform required the addition of some platform-specific information in various deployment descriptors. Unfortunately, that platform-specific information restricts porting to Java EE 5 of any JAX-WS-based web services developed using Java WSDP 2.0.

This Tech Tip describes what you need to do to change a JAX-WS-based web service developed using Java WSDP 2.0 and deployed on the J2EE 1.4 platform so that it can be ported to the Java EE5 platform.

Getting Started

A sample package accompanies this tip to help demonstrate the migration process. It contains the source code and associated files for building a web service. Two versions of the code and files are provided. One version is for building a web service using Java WSDP 2.0 and deploying it on Java System Application Server 8.2 Platform Edition. The other version is for building and deploying a web service on GlassFish, an open source reference implementation of Java EE 5.

If you haven't already done so, download and install the following:

Then download the sample package for the tip and extract its contents. You should now see the newly extracted directory as <sample_install_dir>/ttapr2006migws, where <sample_install_dir> is the directory in which you installed the sample package. You can find the two versions of the code and files in the jwsdp-as82 directory and jwsdp-gf directories below the ttapr2006migws directory.

Building a Web Service With Java WSDP 2.0

To build the web service, you need to:

  1. Write an endpoint implementation class.
  2. Compile the endpoint implementation class.
  3. Generate portable artifacts required for web service
  4. execution.
  5. Package the web service as a WAR file and deploy it.
An endpoint implementation class, AddNumbers, is provided in the jwsdp-82\endpoint directory. You can compile the web service and generate the portable artifacts it needs, by executing an asant task that's defined in the build file in the jwsdp-82 directory. First start Java Application Server 8.2 Platform Edition:
    %S1AS_HOME%\bin\asadmin start-domain  
Then execute the following command:
    <sample_install_dir>\jwsdp-82\asant service  
The service task compiles the endpoint implementation class and runs the wsgen tool to generate the portable artifacts.

To package the web service as a WAR file and deploy it, execute the following command (on one line):
    %S1AS_HOME%\bin\asadmin deploy     <sample_install_dir>\jwsdp-82\build\jwsdp-add.war 
What's significant here from a portability point of view is that this process requires various descriptor files: a web.xml file (in this case, jwsdp-web.xml) and sun-jaxws.xml. These need to be packaged with the web service for deployment.

The web.xml file includes a <listener> element that registers a servlet context listener for the web application being deployed.
    <listener>     <listener-class>     com.sun.xml.ws.transport.http.servlet.WSServletContextListener     </listener-class>    </listener> 
The registration of the servlet context listener is required by the Java WSDP 2.0 to do all the needed initialization for the web service endpoint when the WAR is deployed.
    <servlet>      <servlet-name>AddService</servlet-name>      <servlet-class>       com.sun.xml.ws.transport.http.servlet.WSServlet      </servlet-class>      <load-on-startup>1</load-on-startup>    </servlet> 
The web.xml file also includes a <servlet> element that points to com.sun.xml.ws.transport.http.servlet.WSServlet. This reference is specific to the Java WSDP platform. It's required so that all requests for the URL defined for this web service endpoint get routed through a common servlet. The common servlet then routes the requests to the appropriate web service endpoint.

The sun-jaxws.xml file contains additional information about the endpoint.

After you deploy the web service, you can view its generated WSDL file by pointing your browser to the URL http://localhost:8080/jwsdp-add/addnum?wsdl. A client references this WSDL file to use the web service.

Although the deployed web service is certainly valid and usable by J2EE and Java EE 5 clients, it's not portable to all Java EE containers. That's because the content of the jwsdp-web.xml file contains platform-specific information. In addition, the sun-jaxws.xml file is a vendor-specific file.

Now let's look at how to make the web service portable so that you can use it in Java EE 5.

Making the Web Service Portable

The specification "Implementing Enterprise Web Services", JSR-109, specifies the programming model for implementing a web service in Java EE 5. To make a web service developed using Java WSDP 2.0 and deployed on the J2EE 1.4 platform deployable on the Java EE5 platform, you need to ensure that it conforms to the JSR-109 specification.

You still need to provide an endpoint implementation class and compile it. However based on JSR-109, you no longer package the vendor-specific descriptor file, sun-jaxws.xml. All information required about the endpoint is derived by the platform implementation from the @WebService annotation in the endpoint implementation class.

Also, you no longer need to package a web.xml file. If you don't provide the file, the platform will define a default one. However if you do provide it for packaging with the web service, you need to ensure that:
  • The web.xml file points to the latest servlet schema:
          <web-app xmlns="http://java.sun.com/xml/ns/javaee"       xmlns:j2ee="http://java.sun.com/xml/ns/javaee"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       version="2.5" xsi:schemaLocation=      "http://java.sun.com/xml/ns/javaee       http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 
    This is important because annotation processing will happen only for applications that use Java EE5-based descriptors.


  • There is no need for the <listener> element in the web.xml file. All the required initializations are done as part of the deployment of the web service in Java EE platform.


  • A <servlet> element is required in which the <servlet-name> is the port-component-name of the web service endpoint (that is, @WebService.name). For example:
          <servlet>      <servlet-name>AddNumbers</servlet-name>      <servlet-class>endpoint.AddNumbers</servlet-class>      <load-on-startup>1</load-on-startup>      </servlet> 
    If you don't provide a <servlet-name> element, the name defaults to the simple name of the endpoint implementation class, and the <servlet-class> defaults to the full name of the endpoint implementation class.

You can see this by examining the files provided in the jwsdp-gf directory of the sample archive. Notice that there is no sun-jaxws.xml file. Also notice that in the jwsdp-web.xml file there is no <listener> element, and the <servlet> element follows the rules mentioned previously.

One other important item of note: You have the option of running the wsgen tool to generate portable artifacts or not. If you don't run wsgen, the Java EE 5 platform implementation will generate portable artifacts for you at the time of deployment.

You can build and deploy the same JAX-WS-based web service as you did for J2EE 1.4. This time you'll build and deploy it in Java EE 5, using the files in the jwsdp-gf directory. You can find the endpoint implementation class, AddNumbers, in the jwsdp-web.xml file\endpoint directory.

Start GlassFish as follows:

     %GLASSFISH_HOME%\bin\asadmin start-domain  

Then execute the following commands:

    <sample_install_dir>\jwsdp-gf\asant service          %GLASSFISH_HOME%\bin\asadmin deploy     <sample_install_dir>\jwsdp-gf\build\javaee-add.war 

Notice that the service task does not run wsgen. There is no wsgen in the build file for the task. The portable artifacts are generated automatically when you deploy the WAR file.

After you deploy the web service, you can view its generated WSDL file by pointing your browser to the URL http://localhost:8080/javaee-add/addnum?wsdl.

In summary, the Java EE 5 platform makes the service portable by:
  • Not requiring you to package all portable artifacts. Because of that, you do not need to run platform-specific tools such as wsgen.
  • Not requiring you to package platform-specific descriptors such as sun-jaxws.xml.
  • Not requiring a web.xml file for packaging. However, if you provide a web.xml for packaging, its contents do not have any platform-specific information.
About the Author

Vijay Ramachandran is a senior member of the Sun Java Application Server team. He has worked in the J2EE group for the last six years, and was a key contributor to the deployment and web services-related features of Sun Java System Application Server versions 8.X and 9.X. Previously, Vijay was the technical lead for Java BluePrints team, where he co-authored books on the J2EE 1.3 and 1.4 platforms.

Back to Top

CALL FLOW MONITORING IN GLASSFISH
 
by Harpreet Singh and Anissa Lam

The January 28, 2006 Tech Tip, Monitoring Web Services describes how you can use GlassFish, an open source application server implementation of Java EE 5, to monitor web services. However, there are other useful monitoring and management capabilities in GlassFish. One important GlassFish feature called Call Flow enables you to monitor applications deployed in the application server. A developer can use this feature at development time to see how the application behaves. An administrator can use this feature to monitor the runtime behavior of deployed applications.

Call Flow collects runtime information about an application, such as the time spent in various containers, and time spent in the application code. This information can help in performance tuning and debugging an application. Calls from the application are monitored as they flow through various containers in the application server and through the application code. For example, consider a servlet in the application that calls a method on an enterprise bean. In this scenario, Call Flow monitors the request as it enters the web container, and continues monitoring the request as it flows from the servlet's service method, to the EJB container, and finally to the enterprise bean method. CallFlow then writes the collected information to a persistent storage device.

You can then examine the recorded information. You can also "drill down" to get further information about a specific application request.

This Tech Tip shows you how to use Call Flow from the GlassFish Administration Console to monitor an enterprise application.

Step 1: Getting Started

If you haven't already done so, download GlassFish from the GlassFish Community Downloads page.

Then set the following environment variables:
  • GLASSFISH_HOME: This should point to where you installed GlassFish (for example C:\Sun\AppServer)

  • JAVA_HOME: This should point to the location of JDK 5.0 on your system.

Step 2: Start GlassFish

Start GlassFish by entering the following command:
    <GF_install_dir>/bin/asadmin start-domain domain1 
where <GF_install_dir> is the directory in which you installed GlassFish.

Step 3. Start the Administration Console

After GlassFish starts, open the Administration Console by pointing your browser to:
    http://localhost:4848 
The host ID localhost is the default host ID and 4848 is the default port number for the Administration Console. Change these values, as appropriate, for your configuration.

Then login with the appropriate administrator user name and password (the default username is admin, and the default password is adminadmin).

Step 4: Enable Call Flow

You can enable Call Flow either in the Administration Console or by command.

To enable Call Flow from the Administration Console, do the following:
  1. In the tree component, select the Application Server node.
  2. Click the Monitor tab.
  3. Click the Call Flow tab. The Call Flow page appears.
  4. Check the Enabled checkbox in the Configuration section of the page to initiate Call Flow monitoring for the server.
  5. Optionally, specify the client host IP address and user ID for which you want to enable monitoring. Doing this can be very useful in a production system to track the flow (and possible performance problems) for a particular type of request.
  6. Click Save

To enable Call Flow by command, enter the following command (on one line):
     <GF_install_dir>/bin/asadmin asadmin     start-callflow-monitoring server 

Step 5: Download and Deploy the Sample Archive

Download the sample archive for the tip. The sample archive is a deployable archive for an enterprise application that you will monitor with Call Flow.

After you download the sample archive deploy it. You can do this in various ways. For example, you can copy the sample archive to the GlassFish autodeploy directory (<GF_install_dir>/domains/domain1/autodeploy), or you can use the Administration Console to deploy the sample archive.

Step 6. Run the Application

Run the deployed application by entering the URL http://localhost:8080/helloworld in a browser window other than the one running the Administration Console. You should see a page that says "Hello World Sample Application". You should also see a prompt to enter a name.

Enter a name, for example "Duke" and click the Process button. In response you should see a page that says something like this:
    Hello World !     Good morning, Duke. Enjoy your morning.  

Step 7: Display Call Flow Data

Use the Administration Console to view the data that was recorded by Call Flow. Although Call Flow needs to be enabled to monitor and record call flow data, it doesn't need to be enabled for you to view data it already recorded. So you can optionally disable Call Flow before you view the data. (See "Step 8: Disable Call Flow" for instructions on how disable Call Flow.)

You can find the call flow data in the Call Flow Data section of the Call Flow page in the Administration Console. The data is displayed in a table, with each row of the table displaying data for a specific request. You should see a row of data for the Hello World sample application that you ran.

The table includes data such as the time stamp when the request was processed by the application server, the principal used to send the request (a call that is made without any user principal is displayed in the table as "anonymous"), and the name of the application to which the request was sent to.

If you want to delete the data for a request listed in the table, check the checkbox of that row and click the Delete button. This will remove the data permanently. There is a drop down menu that allows you to filter the request. By default, data for all requests to the server are displayed. You can filter the displayed data based on:
  • The final status of a request, that is, Success or Failure

  • The start container, that is, the container in which the request originated. The containers are WEB, Web Service, EJB, Timer EJB, and Asynchronous Message. Note that JMS messages directed to the application server are flagged as asynchronous messages. So if you want data displayed about JMS messages, select Asynchronous Message as the start container. Also, if you want data about IIOP messages displayed (as well as data about EJB requests), select EJB as the start container.
Filtering does not delete any recorded data, it simply controls what is displayed in the table.

You can display more detailed data about a request by clicking on the entry for the request in the Time Stamp column. In response, you should see a Call Flow Details page that displays information such as the response time for the request, and how much time the request spent in each container. You'll also see a table that presents in sequence the call flow of the request through the containers. For each step in the calling sequence, the table displays the pertinent container, component, and method.

You can display the a parent-child view of the methods called in the call flow by clicking the View Tree button.

Step 8: Disable Call Flow

As is the case for enabling Call Flow, you can disable it from the Administration console or by command. To display Call Flow from the Administration Console, uncheck the Enabled checkbox on the Call Flow configuration page.

To disable Call Flow by command, enter the following command (on one line):
    <GF_install_dir>/bin/asadmin asadmin     stop-callflow-monitoring server 

Note that Call Flow is automatically disabled when you stop the application server. After you next start the application server, you can reenable Call Flow by rechecking the Enabled checkbox on the Call Flow configuration page.

Additional Information About Call Flow

For more information about Call Flow, see the GlassFish project CallFlow home page.

About the Authors

Harpreet Singh is a member of Sun Java System Application Server group at Sun Microsystems. He has been involved in J2EE development from the last seven years. His current interests are call flow monitoring and web services management. In the past, he has been a key contributor in security infrastructure of the Application Server.

Anissa Lam is a member of the Sun Java System Application Server group at Sun Microsystems. She has worked in the J2EE group for the last five years, focusing on various IDEs, such as Sun Java Studio, and deployment tools. Anissa has been a key contributor to the Administration Console function of the Application Server.

Back to Top

Rate and Review
Tell us what you think of the content of this page.
Excellent   Good   Fair   Poor  
Comments:
If you would like a reply to your comment, please submit your email address:
Note: We may not respond to all submitted comments.
Comments? Send your feedback on the Tech Tips: http://developers.sun.com/contact/feedback.jsp?category=newslet

Subscribe to the following newsletters for the latest information about technologies and products in other Java platforms:
  • Core Java Technologies Tech Tips. Get tips on using core Java technologies and APIs, such as those in the Java 2 Platform, Standard Edition (J2SE).
  • Wireless Developer Tech Tips. Get tips on using wireless Java technologies and APIs, such as those in the Java 2 Platform, Micro Edition (J2ME).
You can subscribe to these and other Java technology developer newsletters or manage your current newsletter subscriptions on the Sun Developer Network Subscriptions page

IMPORTANT: Please read our Terms of Use, Privacy, and Licensing policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/
http://developer.java.sun.com/berkeley_license.html

ARCHIVES: You'll find the Enterprise Java Technologies Tech Tips archives at:
http://java.sun.com/developer/EJTechTips/index.html

© 2006 Sun Microsystems, Inc. All Rights Reserved. For information on Sun's trademarks see: http://sun.com/suntrademarks
Java, J2EE, J2SE, J2ME, and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.



Please unsubscribe me from this newsletter.


 
Tuesday, April 25, 2006
  April 2006 Sun Java Studio Enterprise Developer Newsletter
You are receiving this e-mail {e-mail address} because you elected to receive e-mail from Sun Microsystems, Inc. To update your communications preferences, please see the link at the bottom of this message. We respect your privacy and post our privacy policy prominently on our Web site http://sun.com/privacy/

Please do not reply to the mailed version of the newsletter, this alias is not monitored. Feedback options are listed in the footer for both content and delivery issues.

Sun Java Studio Enterprise Developer
NEWSLETTER
April 2006, Vol. 5 No. 04

Welcome to the Sun Java Studio, Enterprise Developer Newsletter!

The Sun Java Studio Enterprise Developer Newsletter is published monthly to bring you the latest information about the Sun Java Studio Enterprise integrated development environment (IDE), including tools, events, early access programs, free downloads, product releases - all conveniently delivered to your inbox.

EVENTS: Upcoming Events for the Enterprise Developer
 
Register Today for Sun Tech Days
Tap the power of Java technology and the Solaris platform with in-depth technical training at the Sun Tech Days conference in Johannesburg, South Africa, May 3-4.
 
 
2006 JavaOne Conference
Attend the 2006 JavaOne conference, May 16-19 at Moscone Center in San Franciso, and hear from some of the best and brightest in the industry at the technical sessions - check the web site for the latest Conference offerings.
 
 
New Training: Become a Sun Java Studio Creator Pro in 3 days!
Learn how to build cool web applications that access databases, EJBcomponents, and web services using GUI and AJAX-enabled components.Check out the new course coming to San Franisco, CA, Atlanta, GA, and Burlington, MA in June.

 

EDITORIAL

 

By Prakash Narayan,Senior Engineering Manager, Sun Java Studio Enterprise and Marina Sum, Technical Writer, Sun Java Studio Enterprise.

The countdown to the largest annual developer conference is on! 2006 JavaOne, the premier assembly of Java developers worldwide, will be held on May 16-19 in the Moscone Center, San Francisco, California. Check out the session schedule to see what you won't want to miss. Especially noteworthy are the JavaOne sessions, Birds of a Feather sessions (BOFs), and Hands-On Labs on the Java EE 5 platform and NetBeans Enterprise Pack 5.5, as highlighted below. In particular, the BOF on Schema Design Patterns, hosted by four Java Studio Enterprise engineers, is well worth attending. And if you're in town early, stop by the Argent Hotel near Moscone Center on Monday, May 15. The NetBeans Software Team will be hosting a free companion event, NetBeans Day. Technical luminaries, such as James Gosling, the father of Java technology, will discuss NetBeans and the future of Java developer tools.

For more on the technical sessions and hand on labs you don't want to miss, click here.

 

FEATURES

»

Designing Patterns With UML
By virtue of their seamlessness, clarity, and versatility, design patterns in Unified Modeling Language are a tremendous help for software architectures. This article describes the pattern types and the procedures for creating them and applying them to application components.

 

NEWS

»

Sun Microsystems Announces Open Source Enterprise Development Tool Project
On April 11th 2006, the Sun Developer Tools team released plans to open source major elements of the Sun Java Studio Enterprise -- our enterprise-class development tool -- as a project on NetBeans.org. This new project, which will be released as the NetBeans Enterprise Pack, continues Sun's mission of growth via sharing and participation.

For more insight and information on this announcement, check out Marina Sum's blog.

 

»

Sun Java Studio Enterprise Has a New Face!
Our web pages for the IDE have been updated in a new format and look-and-feel. The change is not just skin-deep: we've arranged the content to improve your experience as you use the site, including a new Subject Index for our tutorials,docs, articles, and other content.

 

»

NetBeans Enterprise Pack 5.5 Preview. Download Today and enter for a chance to win an Apple iPod Nano.
This preview release introduces UML modeling, XML tools, and web services orchestration to the NetBeans community. It is available as an integrated bundle along with NetBeans IDE 5.5 Preview and Sun Java System Application Server Platform Edition 9 Beta.

We want to know what you think of the NetBeans Enterprise Pack 5.5 Preview. Give us your feedback to help us enhance this next-generation development platform, and we'll give you a chance to win an Apple iPod Nano!

 

»

Have a question or need help? Join the Java Studio Enterprise Community Forums
The Java Studio Enterprise Community Forum is the place to ask questions about using the Java Studio Enterprise IDE for developing applications and web services. The forum is monitored by Java Studio Enterprise engineers, as well as other knowledgeable members of the NetBeans and Java technology developer communities. Browse through existing threads, answer questions, or start your own thread.

 

 
 
Thanks for tuning in to the Sun Java Studio Enterprise Developer Newsletter!

Best regards,
Sun Microsystems, Inc.

 

Rate and Review
Tell us what you think of the content of this page.
Excellent   Good   Fair   Poor  
Comments:
If you would like a reply to your comment, please submit your email address:
Note: We may not respond to all submitted comments.
Comments and Contact Information: There are three ways to send your feedback about the Sun Java Studio, Enterprise Developer Newsletter:

Fill out the web form at http://developers.sun.com/contact/feedback.jsp?category=newslet

Mail your feedback to the following address: Sun Java Studio Editorial Team, MS: 4150 Network Circle, Santa Clara, CA 95054, USA

Subscribe/Unsubscribe: Subscribe to other Java technology newsletters:

You can subscribe to these and other Sun Developer Network publications on the SDN Newsletters and Publications page.
- To subscribe, visit https://softwarereg.sun.com/registration/developer/en_US/subscriptions, select the newsletters you want to subscribe to, and click "Update."
- To unsubscribe, go to https://softwarereg.sun.com/registration/developer/en_US/subscriptions, uncheck the appropriate checkbox, and click "Update."

IMPORTANT: Please read our Licensing and Terms of Use policies:
http://developers.sun.com/berkeley_license.html
http://www.sun.com/share/text/termsofuse.html

Privacy Statement: Sun respects your online time and privacy (http://sun.com/privacy). You have received this based on your email preferences. If you would prefer not to receive this information, please follow the steps at the bottom of this message to unsubscribe.

© 2006 Sun Microsystems, Inc. All Rights Reserved. For information on Sun's trademarks see: http://sun.com/suntrademarks
Java, J2EE, J2SE, J2ME, and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.

This document is protected by copyright. For more information, see: http://java.sun.com/developer/copyright.html

This service may provide, or third parties may provide, links to other Internet sites or resources. Because Sun has no control over such sites and resources, you acknowledge and agree that Sun is not responsible for the availability of such external sites or resources, and does not endorse and is not responsible or liable for any content, advertising, products, or other materials on or available from such sites or resources. Sun will not be responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, goods or services available on or through any such site or resource.



Please unsubscribe me from this newsletter.


 
Saturday, April 15, 2006
  Core Java Technologies Tech Tips, April 15, 2006 (Indexed Property Changes, Java 2D API Enhancements)
You are receiving this e-mail because you elected to receive e-mail from Sun Microsystems, Inc. To update your communications preferences, please see the link at the bottom of this message. We respect your privacy and post our privacy policy prominently on our Web site http://sun.com/privacy/

Please do not reply to the mailed version of the newsletter, this alias is not monitored. Feedback options are listed in the footer for both content and delivery issues.
  Welcome to the Core Java Technologies Tech Tips.
Core Java Technologies
TECHNICAL TIPS
April 15, 2006
View this issue as simple text
In This Issue
 
Welcome to the Core Java Technologies Tech Tips for April 15, 2006. Here you'll get tips on using core Java technologies and APIs, such as those in Java 2 Platform, Standard Edition (J2SE).

This issue covers:

» Reporting Indexed Property Changes in Beans
» Java 2D API Enhancements in J2SE 5.0

These tips were developed using Java 2 Platform, Standard Edition Development Kit 5.0 (JDK 5.0). You can download JDK 5.0 at http://java.sun.com/j2se/1.5.0/download.jsp.

This issue of the Core Java Technologies Tech Tips is written by John Zukowski, president of JZ Ventures, Inc. (http://www.jzventures.com).

See the Subscribe/Unsubscribe note at the end of this newsletter to subscribe to Tech Tips that focus on technologies and products in other Java platforms.

REPORTING INDEXED PROPERTY CHANGES IN BEANS
 

In J2SE 5.0, a number of features were added to the JavaBeans component API. One of these was support for IndexedPropertyChangeEvent. The JavaBeans component API provided a way to report changes to a regular property of a JavaBeans component (also called a JavaBean or just a "bean"). The support for IndexedPropertyChangeEvent added the ability to report additional information about changes to an indexed property of a bean.

Most people are familiar with JavaBean component properties. Simply add set and get methods to your class and you have a read-write property defined by whatever the name is after set and get. In other words, if your class has methods named setName() and getName(), your class has a JavaBean component property named name.

There are two types of component properties: regular and indexed. Indexed properties are distinguished from regular properties in that they have multiple values, where each value is accessed by an index. The set and get methods for a regular property such as name would look like this:

Regular property:
  • public void setName(String name)
  • public String getName()
If name is an indexed property, the methods look like this:

Indexed property:
  • public void setName(int index, String name)
  • public String getName(int index)
  • public void setName(String[] names)
  • public String[] getName()
Beans can be designed to notify you of their property changes. You can register a PropertyChangeListener object with the bean through the addPropertyChangeListener() method. The listener is then notified of changes through PropertyChangeEvent objects or IndexedPropertyChangeEvent objects. A property that generates a PropertyChangeEvent when its value changes is called a bound property.

The PropertyChangeListener class has one method:
    public void propertyChange(PropertyChangeEvent pce) 
If the argument to propertyChange() is of type PropertyChangeEvent, how do you get notified with an IndexedPropertyChangeEvent? The answer derives from the fact that the IndexedPropertyChangeEvent class is a subclass of PropertyChangeEvent. So, inside your propertyChange() you need an instanceof check to see what type of argument you get:

    public void propertyChange(PropertyChangeEvent pce) {      String name = pce.getPropertyName();      if (pce instanceof IndexedPropertyChangeEvent) {        IndexedPropertyChangeEvent ipce =          (IndexedPropertyChangeEvent) pce;        int index = ipce.getIndex();        System.out.println("Property: " + name + "; index: "         + index);      } else {        System.out.println("Property: " + name);      }      System.out.println("; value: " + pce.getNewValue());    } 
Before viewing an example program that uses IndexedPropertyChangeEvent, let's focus on how to report a change to a bound indexed property. The following code reports the update of the name indexed property shown previously:

    private PropertyChangeSupport changeSupport;     public ClassConstructor() {      changeSupport = new PropertyChangeSupport(this);    }     public void setName(int index, String name) {      String oldName = this.name;      this.name = name;      changeSupport.fireIndexedPropertyChange("name", index,        oldName, name);    } 
The PropertyChangeSupport class is a support class found in the java.beans package (the package for the JavaBeans component API). The fireIndexedPropertyChange() method reports a change to the bound indexed property (in this case, name) to any listeners that were registered through the addPropertyChangeListener() method.

Here's what the full example looks like:
    import java.beans.*;    import java.util.*;        public class IndexedSampleBean {          private PropertyChangeSupport changeSupport;          private Map<Integer, String> names;          private String title;          public IndexedSampleBean() {        changeSupport = new PropertyChangeSupport(this);        names = new HashMap<Integer, String>();      }          public void setTitle(String title) {        String oldTitle = this.title;        this.title = title;        changeSupport.firePropertyChange("title", oldTitle, title);      }          public String getTitle() {        return title;      }          public void setName(int index, String name) {          String oldName = names.get(index);          names.put(index, name);          changeSupport.fireIndexedPropertyChange("name", index,                    oldName, name);      }          public String getName(int index) {        return names.get(index);      }          public void addPropertyChangeListener(       PropertyChangeListener l) {          changeSupport.addPropertyChangeListener(l);      }       public void removePropertyChangeListener(       PropertyChangeListener l) {          changeSupport.removePropertyChangeListener(l);      }          public static void main(String[] args) throws Exception {        IndexedSampleBean bean = new IndexedSampleBean();        PropertyChangeListener listener =           new PropertyChangeListener() {            public void propertyChange(PropertyChangeEvent pce) {              String name = pce.getPropertyName();              if (pce instanceof IndexedPropertyChangeEvent) {                IndexedPropertyChangeEvent ipce =                  (IndexedPropertyChangeEvent) pce;                int index = ipce.getIndex();                System.out.print("Property: " + name +                  "; index: " + index);              } else {                System.out.print("Property: " + name);              }              System.out.println("; value: " + pce.getNewValue());            }        };        bean.addPropertyChangeListener(listener);        bean.setName(1, "John");        bean.setName(2, "Ed");        bean.setName(3, "Mary");        bean.setName(4, "Joan");        bean.setTitle("Captain");        System.out.println("Name at 3 is: " + bean.getName(3));        System.out.println("Title is: " + bean.getTitle());      }    } 
The class defines an indexed property named name and sets the name at four positions. In addition, a regular bound property named title is also present and set. The listener is notified for each call to set the name or title and then print the property name, index (if appropriate), and value. The class then gets the name at one specific position and prints it, before printing the single title.

Running the program produces the following results:
  >java IndexedSample      Property: name index: 1 value: John     Property: name index: 2 value: Ed     Property: name index: 3 value: Mary     Property: name index: 4 value: Joan     Property: title; value: Captain     Name at 3 is: Mary     Title is: Captain 
For more information about the support for IndexedPropertyChangeEvent in the JavaBeans component API, see API Enhancements to the JavaBeans Component API in J2SE 5.0. Also see the JavaBeans Trail in the Java Tutorial.

Back to Top

JAVA 2D API ENHANCEMENTS IN J2SE 5.0
 

Each new release of the standard edition of the Java platform brings both big and small improvements. Most people hear about all the big new features such as Generics or the new concurrency utilities package. What people don't always hear about are the small new features. These features are rarely mentioned because they are useful to a smaller audience than some of the bigger features. This tip describes several of these small enhancements to the Java 2D API added in J2SE 5.0. What actually happens when you use the new features often depends on your operating environment and your hardware. In some cases, using these features might provide very little (if any) benefit.

Bicubic Interpolation

One Java 2D API enhancement has to do with image scaling -- it also affects rotation and other affine transformations. The RenderingHints class has two constants that deal with different interpolation options: VALUE_INTERPOLATION_BILINEAR and VALUE_INTERPOLATION_BICUBIC. Setting the KEY_INTERPOLATION hint to one of the two options tells the underlying system what rules to follow when scaling an image. Prior to J2SE 5.0, the two hint values produced the same result. Because RenderingHints are simply hints, they could be ignored. In fact, the bicubic setting was always ignored, and instead, bilinear interpolation was used.

If you are unfamiliar with the two interpolation options, it helps to understand what happens when scaling up an image. For instance, where do all those new pixels in the scaled up image come from? With bilinear scaling, the pixels come from the 2x2 rectangle of pixels from the source image that are closest to the scaled pixel. The rectangle of pixels are blended using a linear function in both X and Y. With bicubic scaling, they come from the 4x4 area that surrounds the scaled pixel. The rectangle of pixels are blended using a cubic function in both X and Y. Because of the increased area and algorithmic complexity, bicubic scaling tends to create a better looking scaled image, but at the cost of performance.

In J2SE 5.0, the bicubic setting is honored. You can see this by running the following test program. When you run the program, specify an image file. The program sets the RenderingHints with the two constants, VALUE_INTERPOLATION_BILINEAR and VALUE_INTERPOLATION_BICUBIC, and reports interpolation algorithm differences (if any). First run the program with JDK 1.4 and then with JDK 5.0. You'll see that interpolation algorithm differences are reported only with the newer JDK.
    import java.awt.*;    import java.awt.image.*;    import java.io.*;    import javax.swing.*;    import javax.imageio.*;          public class Bicubic {      public static void main(String args[]) throws IOException {        if (args.length == 0) {          System.err.println(            "Provide image name on command line");          System.exit(-1);        }        Image image = ImageIO.read(new File(args[0]));        int w = image.getWidth(null);        int h = image.getHeight(null);        BufferedImage bilinear = new BufferedImage(2*w, 2*h,          BufferedImage.TYPE_INT_RGB);        BufferedImage bicubic = new BufferedImage(2*w, 2*h,          BufferedImage.TYPE_INT_RGB);               Graphics2D bg = bilinear.createGraphics();        bg.setRenderingHint(RenderingHints.KEY_INTERPOLATION,          RenderingHints.VALUE_INTERPOLATION_BILINEAR);        bg.scale(2, 2);        bg.drawImage(image, 0, 0, null);        bg.dispose();               bg = bicubic.createGraphics();        bg.setRenderingHint(RenderingHints.KEY_INTERPOLATION,         RenderingHints.VALUE_INTERPOLATION_BICUBIC);       bg.scale(2, 2);       bg.drawImage(image, 0, 0, null);       bg.dispose();              for(int i=0; i<2*w; i++)         for(int j=0; j<2*h; j++)           if (bilinear.getRGB(i, j) != bicubic.getRGB(i, j))             System.out.println("Interpolation algo differ");     }    }  
For the JDK 1.4 environment, there is no output from running the program:
    > java Bicubic image.jpg      [No Output] 
For the JDK 1.5 environment, every pixel that differs is reported.
    > java Bicubic image.jpg      Interpolation algo differ      Interpolation algo differ      Interpolation algo differ      Interpolation algo differ      Interpolation algo differ      .... repeated many times 
OpenGL Acceleration

The February 8, 2005 Tech Tip Introduction to JOGL described the Java programming language binding for the OpenGL 3D graphics API. In J2SE 5.0, there are some OpenGL options available to accelerate the core functionality of the 2D API. The options are "under the covers" -- they don't require the user to know how to program in OpenGL. By default, the acceleration option is disabled. To enable the option, set the sun.java2d.opengl system property to true. If you want verbose output sent about the OpenGL-based pipeline, use a value of True (uppercase T) instead of t. To see the results, use the Java 2D demo code that comes with the JDK.
    java -Dsun.java2d.opengl=True -jar Java2Demo.jar 
You can find out more about the OpenGL-based pipeline in Behind the Graphics2D: The OpenGL-based Pipeline.

Creating Fonts

Prior to J2SE 5.0, the Font class allowed you to create TrueType fonts from an InputStream through the createFont() method:
    public static Font createFont(int fontFormat,           InputStream fontStream) 
where fontFormat is Font.TRUETYPE_FONT. J2SE 5.0 makes two changes to this support. First, you can create Adobe Type 1 fonts. Second, you can create a font directly from a File object with the new createFont() method signature:
    public static Font createFont(int fontFormat,            File fontFile) 
If you simply want the fonts installed, that is, you don't want to create them with either method, you can copy the font files to the $JREHOME/lib/fonts directory. They will be automatically picked up by the runtime environment when installed in that directory.

Image Acceleration

The last set of new Java 2D features to explore relates to image acceleration. These features depend on underlying support in your system. If your system doesn't support these features, they are simply ignored.

The first image acceleration feature is buffered image caching. Video memory supports the caching of managed images. In general, programs that use the kind of images that can be managed tend to perform better that those that use unmanaged images. Prior to J2SE 5.0, only images created with the createImage() method of Component or with the createCompatibleImage() method of GraphicsConfiguration were managed by the Java 2D implementation. Now all images created with one of the BufferedImage constructors are managed by the Java 2D implementation.

Another new image acceleration feature is the ability to control the hardware acceleration of images. Note however that in J2SE 5.0, the methods used to control the hardware acceleration of images are not fully operational. See Methods for Controlling Hardware Acceleration of Images for more details.

The availability of this support depends on the platform and the type of image content. Also, on Microsoft Windows platforms, to see results, you sometimes need to set the sun.java2d.translaccel system property to true. See the description of translaccel in System Properties for Microsoft Windows Platforms for more information about the flag.

When creating Java programs, you can tell the underlying system that you want to optimize certain image operations. You do this by prioritizing how the system stores particular images in accelerated memory if possible. The key phrase here is "if possible." Prior to J2SE 5.0, you could request VolatileImage objects to be stored in accelerated memory. With J2SE 5.0, you can also request that regular Image objects be placed there. And you can create transparent VolatileImage objects. Previously, you could only create opaque ones.

The getCapabilities() method is now defined in both Image and VolatileImage -- not only in VolatileImage. This method can be used to discover if an image currently is accelerated. You can also specify the acceleration priority with the setAccelerationPriority() method, or identify its priority setting with the getAccelerationPriority() method. When its acceleration priority is zero, attempts to accelerate the specific image are disabled. The priority setting is just a hint though, and the JDK implementation can honor (or not honor) it as it sees fit.

To create transparent VolatileImage objects, use one of the two new createCompatibleVolatileImage() methods:
  • createCompatibleVolatileImage(     int width, int height, int transparency)
  • createCompatibleVolatileImage(     int width, int height, ImageCapabilities caps,      int transparency)
Summary

As the Java platform continues to grow, watch for all those little features that don't get as much attention as the bigger ones. Little things, such as Common Unix Printer System (CUPS) printer support for Solaris and Linux, get added with little fanfare. If you happen to have a CUPS printer, the new feature is important. Be sure to read the release notes to see if a new feature is something you've been waiting for. See also the description of new features and enhancements for J2SE 5.0.

Back to Top

Rate and Review
Tell us what you think of the content of this page.
Excellent   Good   Fair   Poor  
Comments:
If you would like a reply to your comment, please submit your email address:
Note: We may not respond to all submitted comments.
Comments? Send your feedback on the Tech Tips: http://developers.sun.com/contact/feedback.jsp?category=newslet

If you have your own Tech Tip that you would like to share with others, you're encouraged to post it in an appropriate Sun Developer Network forum.

Subscribe to the following newsletters for the latest information about technologies and products in other Java platforms:
  • Enterprise Java Technologies Tech Tips. Get tips on using enterprise Java technologies and APIs, such as those in the Java 2 Platform, Enterprise Edition (J2EE).
  • Wireless Developer Tech Tips. Get tips on using wireless Java technologies and APIs, such as those in the Java 2 Platform, Micro Edition (J2ME).
You can subscribe to these and other Java technology developer newsletters or manage your current newsletter subscriptions on the Sun Developer Network Subscriptions page

ARCHIVES: You'll find the Core Java Technologies Tech Tips archives at:
http://java.sun.com/developer/JDCTechTips/index.html

IMPORTANT: Please read our Terms of Use, Privacy, and Licensing policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/
http://developer.java.sun.com/berkeley_license.html

© 2006 Sun Microsystems, Inc. All Rights Reserved. For information on Sun's trademarks see: http://sun.com/suntrademarks
Java, J2EE, J2SE, J2ME, and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.

Sun Microsystems, Inc. 10 Network Circle, MPK10-209 Menlo Park, CA 94025 US



Please unsubscribe me from this newsletter.


 
News, Articles, events from all over the world

My Photo
Name:
Location: India

Born on shraavana shudha chauthi of dundubhi naama samvaswara, Im kiran alias kini alias kiri bought up by loving parents. Being from agricultural family I have learnt plowing, carting but never learnt climbing trees. Now away from home I have lost touch with the agricultural skills.

ARCHIVES
January 2006 / February 2006 / March 2006 / April 2006 / May 2006 / June 2006 / July 2006 / August 2006 / September 2006 / October 2006 / November 2006 / December 2006 / April 2007 / May 2007 / June 2007 / July 2007 / August 2007 / September 2007 / October 2007 / November 2007 / December 2007 / January 2008 / February 2008 / March 2008 / April 2008 / May 2008 / June 2008 / July 2008 / August 2008 / September 2008 / October 2008 / November 2008 / December 2008 / January 2009 / February 2009 / March 2009 / April 2009 /


Powered by Blogger