★ wanayoo — archive 1999 http://blogs.oracle.com/arungupta/tags/javaeeNouvelle recherche | Portail wanayoo

Saturday Mar 26, 2011

Eclipse Con 2011 Hands-on Lab delivered: OSGi, JavaEE, GlassFish, Eclipse a powerful foursome

Sahoo and I delivered OSGi-enabled Java EE Applications using GlassFish and Eclipse Hands-on Lab at Eclipse Con 2011 earlier this week. The conference had an excellent line up of sessions, speakers, receptions and I wanted to engage but could attend only one day. The keynote on the third day titled "The Java Renaissance" was jointly delivered by Mark Reinhold, Chief Architect of the Java Platform group at Oracle and John Duimovich, Java CTO at IBM. Read more coverage of the keynote and Oracle's participation here.


The hands-on built a simple User Registration and Authorization application and showed different combinations of OSGi and Java EE development and deployment in GlassFish. The first step was to to deploy a simple OSGi service and client in GlassFish. Then the OSGi client was replaced by a Web Application Bundle (aka hybrid application) which used @OSGiService for dynamic discovery, bind, inject, and track the OSGi service (more details in TOTD #154). Then the service bundle was replaced by a JavaEE application using EJB and JPA. There were detailed instructions (PDF) to go through all the exercises. The screencast #38 (video) walks you through building the entire application, the video inlined here too:

About 35 attendees were able to make progress after the spotty Internet connection started working. The 5 USB sticks provided by Eclipse Con turned out pretty handy to pre-load all the software requisites. We shared a zip of our ".m2" directories and "m2eclipse-\*" plugins directory for the folks with no Internet. The high point for me was when one of the attendees finished the entire lab in a little over an hour and left. That also helped us assess the quality of document which we tried to make pretty self explanatory. We found one missing instruction from the document and have already fixed it. Overall, about 60% of the attendees completed the lab and rest of them left with partial setup and instructions. Let us know if you attended the lab and found it useful.

Many thanks to Doug and Ankush, the Student Assistants assigned by EclipseCon for our labs, to help attendees keep chugging along!

I was also "lucky" to win a BlackBerry 9670 smartphone + remote stereo bluetooth gateway + international charger + headset. The RIM folks told me that this worth $700 but Amzon sells the raw phone for $19.99. The total cost comes out way under $100 even after including all the accessories. Anyway this device runs only on Sprint so of no use to me. Are you interested in purchasing ? :-)

The reception in the evening (typically the best part) was great and gave me a chance to socialize with several folks. Here are some pictures captured from the event:

Technorati: conf eclipsecon osgi javaee glassfish eclipse

Wednesday Mar 23, 2011

Screencast #38: "Developing OSGi-enabled Java EE Applications using GlassFish" Tutorial at EclipseCon 2011

This screencast provide detailed instructions on how to develop OSGi-enabled Java EE Applications using GlassFish and Eclipse which will be delivered as a 2-hrs tutorial at the EclipseCon 2011.

You can download the required software and follow the detailed instructions (PDF) along with this screencast. Enjoy the screencast in HD in the full-screen mode:

Here are some time lines in case you want to move around in the screencast:

Introduction & Software Installation 0:00
Exercise 1 (Simple OSGi Service and Client) 2:42
Exercise 2 (Web Application Bundle) 11:57
Exercise 3 (EJB OSGi Service) 27:28
References 40:10


Many thanks to Doug & Ankush for an extensive review of the instructions!

Let us know your feedback by posting a question to the GlassFish Forum.

Technorati: conf eclipsecon osgi javaee glassfish eclipse screencast

Sunday Mar 06, 2011

Oracle at Eclipse Con 2011: OSGi-enabled Java EE Applications using GlassFish Tutorial and Other Sessions

Oracle is a gold sponsor at Eclipse Con 2011.

Sahoo and I will give a 2-hours tutorial on Developing OSGi-enabled Java EE Applications using GlassFish (session #1987). We'll walk you through building OSGi bundles and show how they can leverage benefits of Java EE programming model using Eclipse and GlassFish.

Date ? : Mar 23, Wednesday
Time ? : 2 hours starting at 3:50 pm
Where ? : Stevens Creek

Please download the following software in order to maximize your participation in the tutorial:

  • JDK 1.6 U20+
  • Eclipse Helios for Java EE Bundle
  • Install “m2eclipse” plugin and “m2eclipse extension” plugins from “http://m2eclipse.codehaus.org”. Complete installation instructions are available here.
  • Download GlassFish 3.1 Open Source Edition, unzip the bundle, include “glassfish3/bin” in the PATH.
  • Download Maven 2.2.1 and unzip. Configure Maven 2.2.1 in Eclipse - In “Eclipse”, “Preferences...” menu, search for
    “maven”, select “Installations”, click on “Add...”, and select the location of unzipped Maven 2.2.1 directory.

Here are some other pointers for the over all conference ...

There is also an Android/iPhone app for Eclipse Con and a plenty of receptions to attend :-)

See the complete list of sessions, panels, and tutorials from Oracle here.

Technorati: conf eclipsecon oracle osgi javaee glassfish

Tuesday Mar 01, 2011

TOTD #157: GlassFish 3.1 Blogs & Screencasts

GlassFish 3.1 was released yesterday ... yay!

This Tip Of The Day (TOTD) will provide the list of blogs/screencasts produced by the GlassFish team:

  1. Connecting Securely to GlassFish via JMX (Prasad)
  2. Securing Administration in GlassFish Server 3.1 - 1: Admin Authentication (Tim)
  3. Securing Administration in GlassFish Server 3.1 - 2: Remote Administration (Tim)
  4. Securing Administration in GlassFish Server 3.1 - 3: Admin Message Encryption (Tim)
  5. Whats New in Metro 2.1 Security (Kumar)
  6. Customizing generated Java Web Start JNLP for app clients in GlassFish Server 3.1 (Tim)
  7. Single Sign-on Using the GlasFish 3.1 OAM Security Provider (Kumar)
  8. Metro 2.1 in GlassFish 3.1 (Fabian)
  9. Tracing SQL Queries & Monitoring (Shalini)
  10. Statement Leak Detection and Reclaim (Shalini)
  11. Statement Cache Monitoring (Shalini)
  12. Application based Connection Pool Monitoring (Shalini)
  13. Performance Tuner in Oracle GlassFish Server 3.1 (Jennifer)
  14. GlassFish 3.1: Clusters with SSH (Joe)
  15. Automatic Starting Implementation Details for GlassFish 3.1 (Byron)
  16. Huge Perfomance Improvement (Byron)
  17. A Taste of Monitoring in GlassFish 3.1 (Byron)
  18. Automatic Starting of Servers in GlassFish 3.1 (Byron)
  19. Monitoring Data - How to Open the Firehose (Byron)
  20. GlassFish 3.1 Scripting of Monitoring Data for Clusters and Instances (Byron)
  21. How to make GlassFish 3.1 Platform Services survive logoff (Byron)
  22. GlassFish 3.1 est là! (Alexis)
  23. Troubleshooting SSH in GlassFish 3.1 (Jennifer)
  24. GlassFish 3.1 and create-local-instance (Jennifer)
  25. GlassFish 3.1 and Manual Synchronization (Jennifer)
  26. Application-scoped Resources (Jagadish)
  27. Transparent JDBC connection Pool Re-configuration in GlassFish 3.1 (Jagadish)
  28. What's New in GlassFish V31. Security (Kumar)
  29. Moving On Up: Upgrading to GlassFish 3.1 (Bobby)
  30. GlassFish 3.1 Overview (Nazrul)
  31. GlassFish 3.1 and NetBeans 7.0 (Vince)
  32. GlassFish 3.1 and Deployment (Hong)
  33. State of the Cluster With Get-Health Command (Bobby)
  34. GlassFish 3.1: From Installation to Running Application in a Cluster (Anissa)
  35. GlassFish 3.1: New Features in Admin Console (Anissa)
  36. change-master-password command in GlassFish 3.1 (Bhakti)
  37. RESTful GlassFish Monitoring (Jason)
  38. GlassFish 3.1 Windows SSH Setup (Elena)
  39. IIOP Changes in GlassFish 3.1 (Ken)
  40. GlassFish 3.1 Automatic Domain Backup (Chris)
  41. Shoal 1.5.29 released - GlassFish 3.1's runtime dynamic clustering service (Shreedhar)
  42. GlassFish OSE 3.1 is out with WebSocket support included (Justin)
  43. GlassFish 3.1 with Metro 2.1 is Out (Marek)
  44. CDI Support in GlassFish 3.1 (Siva)
  45. Whats new in GlassFish 3.1 Performance (Scott)
  46. New Release: GlassFish Server 3.1: Read All About It! (Paul)
  47. Load Balancing Feature in GlassFish 3.1 (Kshitiz)
  48. GlassFish 3.1: using the master password and managing instances (Carla)
  49. GlassFish Server Load Balancer Plugin Installation & Setup (John)
  50. Quick Introduction to Embeddability of GlassFish Open Source Edition 3.1 (Bhavanishankar)
  51. Enhancements to JMS Clustering in GlassFish (Satish)
  52. Validating Multicast Transport: Where did my instances go ? (Bobby)
  53. Debugging GlassFish REST Requests (Jason)
  54. High Availability Single Sign On in GlassFish 3.1 (Shing Wai)
  55. Adding Users to a GlassFish Realm via REST (Jason)
  56. Getting started with Maven Plugin of Embedded GlassFish Server Open Source Edition 3.1 (Bhavanishankar)
  57. Managing GlassFish JDBC Resources using REST (Jason)

Check out the complete set of videos at GlassFishVideos@youtube.

For a more comprehensive list of blogs (including several from the community members), refer to The Aquarium.

Technorati: totd glassfish javaee blogs screencast

Sunday Feb 27, 2011

"Miles To Go" thanks GlassFish Community!

GlassFish 3.1 is just about a few hours away ... the bow has been placed!

This release is the countless hours of work put by the developers, testers, project/people management, docs, partners, and last but not the least, and the most important the active community users who gave us constant feedback. I certainly feel privileged to be with the team when we delivered the very first version of "Reference Implementation" back in 1999. And also enjoy the floor with most of the GlassFish team and the ability to have hallway/whiteboard discussions with them other than participating in the daily jokes ;-) I'm merely a spokesperson of all these brilliant folks and just blow the horn all around the world. With GlassFish 3.1 out the door, this is going to get much more exciting!

On the eve of GlassFish 3.1 launch, I thought of sharing how this blog has traveled around the world promoting Java EE and GlassFish.

This blog has visited the following cities so far ...

Amsterdam, Atlanta, Bengaluru, Beijing, Berlin, Brasilia, Budapest, Chennai, Chicago, Dallas, Delhi, Fortaleza, Hyderabad, Kansas City, Las Vegas, London, Malmo, Milan, Minneapolis, Montreal, Mountain View, New York City, Orlando, Portland, Porto Alegre, Pune, Reston, Rome, San Francisco, San Jose, Santa Clara, Sao Paolo, Seattle, Singapore, Sofia, St Louis, Stockholm, Toronto, Turku, Salt Lake City, Vejle, Vitoria, Wisconsin, Zurich, ...


View Cities Visited by "Miles To Go..." in a larger map

Spoken at the following Java User Groups ...

  1. Berlin-Brandenburg JUG (Aug 2008)
  2. Brasilia DFJUG (Sep 2008)
  3. CEJUG, Fortaleza (2010)
  4. Dallas JUG (Nov 2008)
  5. ES JUG, Espirito Santo (Sep 2008)
  6. Javagruppen (2011)
  7. London Java Community (2010)
  8. Oakland Java SIG (Oct 2010)
  9. RS JUG, Brazil (2009)
  10. San Francisco JUG (Aug 2010, May 2009)
  11. Silicon Valley JUG (Aug 2008)
  12. SouJava, Brazil (2009)
  13. Taguatinga DFJUG (Sep 2008)
  14. Utah JUG (Jul 2008)

Spoken, Attended, Engaged with community at the following conferences

  1. acts_as_conference (Feb 2008)
  2. Ajax World (2008)
  3. Bay Area JUG Roundup (2010)
  4. Cloud Computing Expo (2010)
  5. DevIgnition (2010)
  6. DevNexus (2010)
  7. Eclipse Demo Camp (2009)
  8. EclipseCon (2009)
  9. FISL (2010, 2009)
  10. FOSS.IN (Dec 2007)
  11. Google Developer Day (May 2007)
  12. IndicThreads (2010, 2009)
  13. Java2Days (2010)
  14. Java EE / GlassFish Workshops
    1. 2 day in Budapest - Jan 2011
    2. 7 hrs at San Francsico JUG - Aug 2010
    3. 3 hrs at Dallas Tech Fest
    4. 8 hrs at Milwaukee - Mar 2009
    5. Day long at Santa Clara - Mar 2009
    6. 4 hrs at JavaMUG - Feb 2010
    7. 4 hrs at Delhi University - Dec 2007
    8. 3 hrs in Seattle/Toronto/Montreal - Nov 2007
    9. 4 hrs in Chicago - Oct 2007
    10. 4 hrs in Minneapols - Oct 2007
  15. Javagruppen (2011)
  16. Javali (2009)
  17. JavaOne (2010, 2009, 2008, 2007, 2006, 2005)
  18. JFall (2009)
  19. JavaOne Brazil (2010)
  20. JFokus (2011)
  21. Mashup Camp (Jul 2007)
  22. Oracle User Group Leaders Summit (2011)
  23. Microsoft Web Services Interoperathon (Nov 2005, Mar 2006)
  24. MySQL Users Conference (2009)
  25. Oracle Open World (2010, 2009)
  26. Oredev (2010)
  27. Rails Conf (2009, 2007)
  28. Rails Conf Europe (2008, 2007)
  29. Rich Web Experience (2010, 2007)
  30. RightScale User Meetup (2009)
  31. Ruby Conf India (2010)
  32. Silicon Valley Code Camp (2010, 2009, 2008, 2007)
  33. Sun Tech Days
    1. Hyderabad 2010
    2. Singapore 2009
    3. Sao Paolo 2008
    4. Hyderabad 2008
    5. Beijing 2007
    6. Rome 2007
    7. Milan 2007
    8. Atlanta Jan 2007
  34. UberConf (2010)
  35. Spark IT (2010)
  36. Jazoon (2010)
  37. Dallas Tech Fest (2010)
  38. JAX London (2010)
  39. OTN Developer Day (New York City 2010)
  40. Silicon Valley Rails Meetup (2009)
  41. Super Happy Dev House 30 (Feb 2009)
  42. The Server Side Java Symposium (2008, 2007)
  43. SD West (Mar 2008)
  44. South Bay Ruby Meetup (Jan 2008)
  45. Web 2.0 Conference & Expo (Jan 2008)
  46. Vaadin Meetup (2011)
  47. WS-I Plenary (Summer 2005)

And in order to stay healthy, did outdoor running in the following cities (while attending a conference) ...

  1. Spree River, Berlin
  2. Singapore River, Singapore
  3. River Danube, Budapest
  4. Las Vegas, USA
  5. Bussum, Netherlands
  6. Rome, Italy
  7. Mercuripe beach, Fortaleza
  8. Ft Lauderdale Beach, USA
  9. Denver, USA
  10. Üetliberg, Zurich
  11. Stockholm, Sweden
  12. Porto Alegre, Brazil

And here are some statistics on page visits/views for this blog ...



Over a 1,000,000 page visits by audience from 30,658 cities cities from 215 countries/territories ...

Thank you GlassFish!

Thank you for reading the content on this blog and please keep those suggestions coming! I'm here to serve your needs :-)

There are still a tons of cities to visit...
Plenty of JUGs to spread the fever ...
Loads of conferences to speak ...
And miles to go before I sleep.

Technorati: milestogo glassfish javaee blogs googleanalytics stats

Monday Jan 17, 2011

Java EE Day @ JAX San Jose 2011

After conducting multiple conferences, primarily in Europe, and some in other parts of the world, for many years, JAX is now coming to the USA as well. And that too right in the heart of Silicon Valley, in the downtown San Jose.

The Call for Papers ends on Jan 21 and allows you to submit papers in several different tracks such as Java Core, Java Enterprise, JSF Summit, Web Tech, Agile Tools & ALM, Cloud, Mobile, and many others. There will be a Java EE day as part of the conference so please submit your sessions today and make sure to mark them to be included in the Java EE track.

What are we looking ?

  • Are you passionate about any or all Java EE 6 technologies and using them to solve your business problems ?
  • Are you building CDI extensions ? Any creative or radical usage of CDI ?
  • Are you using PrimeFaces or any other JSF 2-compliant libraries, in conjunction with rest of the Java EE 6 stack ?
  • Are you using EJB-in-a-WAR packaging, web.xml-free Servlets, RESTful Web services using JAX-RS or any other ease-of-use features from Java EE 6 in your applications ?
  • Any production tips on going live with Java EE 6 ?
  • Any migration experience from properietary frameworks to Java EE 6 ?
  • Any migration experience from previous versions of J2EE 1.4 and Java EE 5 to Java EE 6 ?
  • Would you like to participate in a panel discussion ?
  • Are you one of the spec leads and would like to share your perspective ?
  • Any other wild ideas around Java EE ? :-)

Don't wait, submit your papers now!

When ? Jun 20-23, 2011

Where ? San Jose Convention Center (right in the downtown)

Follow @jaxconf for the latest updates!

Jun 21st also marks the beginning of summer in the US and where else would you want to be other than sunny California to celebrate it :-)

Technorati: conf jaxconf sanjose javaee

Monday Oct 04, 2010

Screencast #32: OSGi-enabled Java EE Applications using NetBeans and GlassFish

OSGi provides the benefit of modularity, dependency management, service dynamism, and others. Java EE provides persistence, security, transaction management and other similar services. The Enterprise Expert Group in OSGi Alliance defines how to mix and match the Java EE APIs in OSGi. The Release 4 Version 4.2 of Enterprise Specification defines how several Java EE specifications such as JPA, JNDI, JMX, and WAR file specification can work with OSGi and levarage its benefits.

Sahoo & Siva gave a talk at JavaOne 2010 explaining the approach and advantages of writing such applications, their slides are available below:

This 6-part screencast shows how to develop OSGi-enabled Java EE applications using NetBeans and deploy them on GlassFish. The screencast creates a simple OSGi service which is invoked by OSGi client. The same OSGi service is then invoked by Web Application Bundle (WAB) client that is a Web Application + OSGi bundle, a.k.a hybrid application. The OSGi service is then replaced by an EJB-based service using Java Persistence API. This shows how OSGi client and service can seamlessly interoperate with Java EE counterparts.

Specifically, the different parts show:

1. How to create a parent POM project
2. API and Service OSGi Bundle
3. Client OSGi Bundle invoking an OSGi Service
4. Web Application Bundle (WAB) client invoking an OSGi service
5. Client OSGi bundle invoking EJB service
6. Conclusion and other possible extensions

This entire exercise was scheduled as S313522 hands-on lab at JavaOne 2010 but could not be conducted because of technical difficulties. We hope you are able to follow the steps mentioned below and benefit from it.

Please download and install NetBeans 6.9.1 and download the following zip files before attempting the exercise:

  1. GlassFish 3.1 b20 Web Profile
  2. GlassFish OSGi Feature Pack for 3.1 b20
  3. S313522 Detailed Docs + Solutions

If you are using a different build of GlassFish then the OSGi Feature Pack can be downloaded by executing the following script in "glassfish/modules/autostart" directory and giving the build number as the first parameter:

curl -C - -O http://download.java.net/maven/glassfish/org/glassfish/osgi-http/3.1-b$1/osgi-http-3.1-
b$1.jar
curl -C - -O http://download.java.net/maven/glassfish/org/glassfish/osgi-platforms/felix-webconsole-
extension/3.1-b$1/felix-webconsole-extension-3.1-b$1.jar
curl -C - -O http://download.java.net/maven/glassfish/org/glassfish/osgi-jpa/3.1-b$1/osgi-jpa-3.1-b$
1.jar
curl -C - -O http://download.java.net/maven/glassfish/org/glassfish/osgi-ejb-container/3.1-b$1/osgi-
ejb-container-3.1-b$1.jar
curl -C - -O http://download.java.net/maven/glassfish/org/glassfish/admingui/glassfish-osgi-console-
plugin/3.1-b$1/glassfish-osgi-console-plugin-3.1-b$1.jar
curl -C - -O http://www.reverse.net/pub/apache/felix/org.apache.felix.webconsole-3.1.2.jar

A typical execution of this script might look like:

./gf-osgi-fp.sh 20
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 27522  100 27522    0     0  74967      0 --:--:-- --:--:-- --:--:--  120k
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  6795  100  6795    0     0  17811      0 --:--:-- --:--:-- --:--:-- 24068
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 24342  100 24342    0     0  59168      0 --:--:-- --:--:-- --:--:--  108k
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 16145  100 16145    0     0  72180      0 --:--:-- --:--:-- --:--:--  186k
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 18724  100 18724    0     0  35921      0 --:--:-- --:--:-- --:--:-- 48785
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  602k  100  602k    0     0   636k      0 --:--:-- --:--:-- --:--:--  748k

Enjoy the video!


How are you using OSGi and Java EE together ? What other OSGi features would you like to see in GlassFish ?


Technorati: screencast javaone osgi javaee netbeans glassfish

Wednesday Sep 22, 2010

S313522: Instructions for OSGi-enabled Java EE Applications Hands-on Lab at JavaOne 2010

This blog provides instructions on how to follow S313522 (Hands-on Lab on OSGi-enabled Java EE Applications) that was conducted at JavaOne 2010 earlier today.

  1. Download and Install NetBeans 6.9.1.
  2. Download and Unzip GlassFish 3.1 b20 Web Profile.
  3. Start GlassFish as "asadmin start-domain" and Database as "asadmin start-database" from "glassfishv3/glassfish/bin" directory.
  4. Go to "glassfishv3/glassfish/modules/autostart" directory and execute the following script:
    #!/bin/sh -x
    wget http://download.java.net/maven/glassfish/org/glassfish/osgi-http/3.1-b20/osgi-http-3.1-b20.jar
    wget http://download.java.net/maven/glassfish/org/glassfish/osgi-platforms/felix-webconsole-extensio
    n/3.1-b20/felix-webconsole-extension-3.1-b20.jar
    wget http://download.java.net/maven/glassfish/org/glassfish/osgi-jpa/3.1-b20/osgi-jpa-3.1-b20.jar
    wget http://download.java.net/maven/glassfish/org/glassfish/osgi-ejb-container/3.1-b20/osgi-ejb-cont
    ainer-3.1-b20.jar
    wget http://download.java.net/maven/glassfish/org/glassfish/admingui/glassfish-osgi-console-plugin/3
    .1-b20/glassfish-osgi-console-plugin-3.1-b20.jar
    wget http://www.reverse.net/pub/apache//felix/org.apache.felix.webconsole-3.1.2.jar
    This is going to download the required OSGi bundles.

Refer to detailed docs and completed solutions to get started. A detailed screencast highlighting the exact set of steps will be available next week.

Technorati: conf javaone handson osgi javaee glassfish netbeans

Monday Jun 21, 2010

Uber Conf 2010 - Day 4 Report - OSGi/Java EE in GlassFish and Getting Started with Clojure


Uber Conf Day 4 (Day 3, 2, and 1) started with yet another 10 miler with fellow attendees in 1 hr 18 mins and 7:49 pace. It was slightly slower than the day before - guess physical exhaustion was setting in ;-) Here are the mile splits:

Thanks to Andy for showing how to turn on the Auto-Lap feature in Garmin 305 ... really handy!

I gave a talk on how GlassFish provides a great execution environment for deploying OSGi, Java EE, and hybrid applications easily. The slides are given below:

The remainder of the day was spent in Clojure track by Stuart Halloway. Next are some basic notes for getting started with Clojure:

Why Clojure ?

  • Power (hosted on jvm)
  • Robustness (functional)
  • Concurrency (identity, state, time)
  • Abstraction (OO done right)
  • Focus (lisp)

Together, these features add up to simplicity. Simplicity means

  • absence of incidental complexity
  • sufficient to meet your design constraints

Simplicity does not mean

  • Familiarity has nothing to do with simplicity
  • its not superficial, goes to the bone (e.g. only simpler syntax is just a sugar wrapper, look for the supported idioms)
  • does not mean easy, its very hard to be simple

Lot of code in Clojure is not about "set" something, its about invoke a function on it.

How to get started ?

Download the latest stable release or cutting edge build. The Clojure REPL (Read-Evaluate-Print Loop) is the easiest way to run a Clojure program as shown below:

~/tools/clojure/clojure-1.1.0 >java -cp clojure.jar clojure.main
Clojure 1.1.0
user=> (print "Hello World")
Hello Worldnil
user=> \^D

OR

~/tools/clojure/jun7 >java -cp clojure.jar clojure.main
Clojure 1.2.0-master-SNAPSHOT
user=> (print "Hello World")
Hello Worldnil
user=> \^D

Notice, the first fragment shows how to run REPL using the latest stable release and the second fragment shows the same using the cutting edge build. "Ctrl+D" exits the REPL shell. Stuart mentioned that the Clojure community stays on the cutting edge build most of the times.

Alternatively, you can also clone "labrepl" from "http://github.com/relevance/labrepl" which is an environment for exploring the Clojure language. It also provides complete instructions for getting started with NetBeans/Enclojure, Eclipse/Counterclockwise, Maven, Max/Linux command line, Windows command line, IDEA/La Clojure, and Emacs.

Configuring Clojure in NetBeans using the Enclojure plugin with NetBeans 6.9 gives the following error:

but works easily with NetBeans 6.8. The IDE seem to support REPL, Java/Clojure integration, syntax highlighting, brace/paren/bracket matching, code navigation, debugger and lots of interesting features.

Here is a typical REPL getting started session with NetBeans and Enclojure:

Here are some equivalent syntax with Java:

Semantic Java Clojure
new new Widget("foo") (Widget. "foo")
Access static members Math.PI Math/PI
Access instance members rnd.nextInt() (.nextInt rnd)
Chaining access person.getAddress().getZipCode() (.. person getAddress getZipCode)
  • "defn" is a symbol so no new syntax for adding a method.
  • \^ introduces metadata for the next symbol, "greet" in this case. You can put metadata anywhere.
  • "clojure.core" is the core of Clojure's implementation
  • "javadoc" knows the default JDK javadocs, can make a local copy and/or extend it
  • "show" is Java reflection
  • "dir", "show", "source" are promoted from community version to the bleeding edge build.
  • Source is not always exposed
  • [1 2 3] Call the function 1 with arguments 2 & 3.
  • '(1 2 3) don't evaluate it and print as is, just tick it.
  • Idiomatically Clojure requires less parentheses than Java
  • Every single function in Clojure is Runnable and Callable

  • Java interop is simple, wrapper-free (raw), performant, complete

Compojure is a small, open source Web framework for Clojure based upon Ring (similar to Python's WSGI and Ruby's Rack). Otherwise Clojure apps are deployed as a JAR file.

A subsequent blog will show how to deploy a simple Clojure JAR file and a simple web app using Compojure on GlassFish.

And finally, here are my top-10 reasons (in no particular order) that I'd like to attend UberConf next year:

  1. Long 90 minute sessions
  2. Lots of hands-on workshops
  3. Fun Run as part of the formal agenda
  4. Beautiful location (Westin Westminster) with lots of running trails
  5. Great food (breakfast + lunch + dinner)
  6. Small attendance so intimate discussions with speakers
  7. Great set of speakers
  8. Rarely see session hopping
  9. Pure technology, no product pitching
  10. Swags are nice - bracelet-style USB stick with all the presos, 2 different tee-shirts, fancy folder and some additional goodies for speakers

See ya next year, hopefully!

Check out the complete set of pictures at:

Technorati: conf uberconf denver clojure compojure glassfish netbeans javaee osgi

Monday Jun 14, 2010

Über Conf Day 1 Trip Report

Jay Zimmerman kick started the 200th No Fluff Just Stuff event and Day 1 of Über Conf earlier today. This event is focused on alpha-geeks, with more access to speakers, more hands-on workshops, longer hours, and attendees from 45 different states.

Cliff Click gave a great keynote talking about Challenges and Directions in Java Virtual Machines. Here are some key points from his talk:

  • Hardware, Operating Systems, and JVM are ready for concurrent processing; Tools, Languages, IDEs, etc are not.
  • Background compilation, Concurrent GC, Introspection and continuous profiling are some opportunities for multi-core (2-4) machines.
  • Application level parallelism - JDK libraries are really useful, thread pools, pipelines of pools. No support for self-tuning and auto-sizing pipeline of thread pools.
  • Data parallelism is recommended for 4-32 core CPUs - Big data, small code, small code with lots of repetition, realm of scientific computing (weather, simulation, nuclear reactor, etc)
  • For 64-100 chips - Clustering on a chip, multiple applications communicating via pipes, GC fixed mallocs, parallelism at all levels (queues, caches, DB access, processor, ...)
  • Java concurrency is not right most times because of the lack of knowledge, not because of language features
  • Software Transactional Memory (STM) is replace existing locak with transaction boundaries, Step towards declarative program #1 issue while debugging other concurrent programs - "they can't name the shared variable"
  • Other performance pitfalls - Debugging, performance, Performance Anomalies
  • Suggestions for concurrent programming - Scala, Clojure, X10, JVSTM + Data modeling

The conference started on a positive note on a personal self with complimentary upgrade to first class in the flight and yet another complimentary upgrade to high-floor room in the hotel. I forgot my Garmin 305 USB connector but found another runner who has it, so nice!

Tomorrow morning starts with a 5K run and then Java EE 6 / GlassFish 3 talk at 10:30am in Westminster 1. The interesting part is that this is the first conference, at least I'm aware of, with a 5K run as part of the formal agenda. The hotel certainly has a lots of running trails near by and I did a 4 miler in the mile-high city. Looking forward to longer distance running on Wednesday and Thursday. The piano and magician during the evening reception added a good fun to the entire mix.

Now get ready to be physically and mentally exhausted!

Here are some pictures captured from today:

And here is the evolving photo album so far:

Technorati: conf uberconf denver glassfish javaee

Monday May 31, 2010

TOTD #139: Asynchronous Request Processing using Servlets 3.0 and Java EE 6

Server resources are always valuable and should be used conservatively. Consider a Servlet that has to wait for a JDBC connection to be available from the pool, receiving a JMS message or reading a resource from the file system. Waiting for a "long running" process to completely blocks the thread - waiting, sitting and doing nothing - not an optimal usage of your server resources. Servlets 3.0 introduces the ability to asynchronously process requests such that the control (or thread) is returned back to the container to perform other tasks while waiting for the long running process to complete. The request processing continues in the same thread after after the response from the long running process is returned or or may be dispatched to a new resource from within the long running process. A typical use case for long running process is a Chat Application.

The asynchronous behavior need to be explicitly enabled on a Servlet. This is achieved by adding "asyncSupported" attribute on @WebServlet as shown below:

@WebServlet(name="AsyncServlet", urlPatterns={"/AsyncServlet"}, asyncSupported=true)
public class AsyncServlet extends HttpServlet {

The asynchronous processing can then be started in a separate thread using "startAsync" method on the request. This method returns "AsyncContext" which represents the execution context of the asynchronous request. The asynchronous request can then be completed by calling AsyncContext.complete (explicit) or dispatching to another resource (implicit). The container completes the invocation of asynchronous request in the later case.

Lets say the long running process is implemented as:

class MyAsyncService implements Runnable {
    AsyncContext ac;

    public MyAsyncService(AsyncContext ac) {
        this.ac = ac;
    }

    @Override
    public void run() {
        System.out.println("Some long running process in \\"MyAsyncService\\"");
    }
}

Note this is running in a separate thread. This service can be invoked from the original servlet as:
AsycnContext ac = request.startAsync();

The service may also be started as:

ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
executor.execute(new MyAsyncService(ac));

The ScheduledThreadPoolExecutor usage is recommended as it makes the thread management easier.

A listener can be associated with the AsyncContext to get notified of when the async request is complete, timed out, or resulted in an error. This can be achieved as:

ac.addListener(new AsyncListener() {

    @Override
    public void onComplete(AsyncEvent event) throws IOException {
        System.out.println("onComplete.");
    }

    . . .
});

A more complete code for the above fragment is given below. The "onComplete" method is used to clean up resources created during async processing.

The asynchronous request processing can be either completed in "run" method of "MyAsyncService" by invoking "AsycnContext.complete" as shown below:

@Override
public void run() {
    System.out.println("Some long running process in \\"MyAsyncService\\"");
    ac.complete();
}

or dispatched to a different resource as:

@Override
public void run() {
    System.out.println("Some long running process in \\"MyAsyncService\\"");
    ac.dispatch("/response.jsp");
}

Lets take a look at our complete code:

@WebServlet(name="AsyncServlet", urlPatterns={"/AsyncServlet"}, asyncSupported=true)
public class AsyncServlet extends HttpServlet {
   
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try {
            System.out.println("Starting doGet");
            AsyncContext ac = request.startAsync();
            ac.addListener(new AsyncListener() {

                @Override
                public void onComplete(AsyncEvent event) throws IOException {
                    System.out.println("onComplete");
                }

                @Override
                public void onTimeout(AsyncEvent event) throws IOException {
                    System.out.println("onTimeout");
                }

                @Override
                public void onError(AsyncEvent event) throws IOException {
                    System.out.println("onError");
                }

                @Override
                public void onStartAsync(AsyncEvent event) throws IOException {
                    System.out.println("onStartAsync");
                }
            });

            System.out.println("Do some stuff in doGet ...");


            // Start another service
            ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
            executor.execute(new MyAsyncService(ac));

            System.out.println("Some more stuff in doGet ...");
        } finally { 
        }
    }

    class MyAsyncService implements Runnable {
        AsyncContext ac;

        public MyAsyncService(AsyncContext ac) {
            this.ac = ac;
            System.out.println("Dispatched to " + "\\"MyAsyncService\\"");
        }

        @Override
        public void run() {
            System.out.println("Some long running process in \\"MyAsyncService\\"");
            ac.complete();
        }
    }
} 

Invoking the GET operation of this Servlet shows the following sequence of statements in GlassFish server log:

INFO: Starting doGet
INFO: Dispatched to "MyAsyncService"
INFO: Doing some stuff in doGet ...
INFO: Some more in doGet ...
INFO: Some long running process in "MyAsyncService"
INFO: onComplete

The first statement marks the beginning of "doGet", the second statement indicates that the request is dispatched to the long running
"MyAsyncService", the third and fourth statement indicates that the response returned back to "doGet" for normal request processing. Finally fifth and sixth statement shows that now the asynchronous request is getting processed and is completed.

Clean and simple!

A request may be dispatched from Asynchronous servlet to Synchronous but other way around is illegal. The section 2.3.3.3 in the Servlets 3.0 specification provides an introduction to the Asynchronous Processing in Servlets 3.0.

The asynchronous behavior is available in the Servlet Filter as well.

The complete code used in this blog can be downloaded here. A fully working sample of a Chat Application using Servlets 3.0 can be seen here.

Technorati: totd glassfish v3 servlets javaee asynchronous comet

Tuesday May 18, 2010

TOTD #137: Asynchronous EJB, a light-weight JMS solution - Feature-rich Java EE 6

One of the new features introduced in Enterprise Java Beans 3.1 (JSR 318)  is asynchronous invocation of a business method. This allows the control to return to the client before the container dispatches the instance to a bean. The asynchronous operations can return a "Future<V>" that allow the client to retrieve a result value, check for exceptions, or attempt to cancel any in-progress invocations.

The "@Asynchronous" annotation is used to mark a specific (method-level) or all (class-level) methods of the bean as asynchronous. Here is an example of a stateless session bean that is tagged as asynchronous at the class-level:

@Stateless
@Asynchronous
public class SimpleAsyncEJB {

    public Future<Integer> addNumbers(int n1, int n2) {
        Integer result;

        result = n1 + n2;
        try {
            // simulate JPA queries + reading file system
            Thread.currentThread().sleep(2000);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }

        return new AsyncResult(result);
    }
}

The method signature returns "Future<Integer>" and the return type is "AsyncResult(Integer)". The "AsyncResult" is a new class introduced in EJB 3.1 that wraps the result of an asynchronous method as a Future object. Under the covers, the value is retrieved and sent to the client. Adding any new methods to this class will automatically make them asynchronous as well.

The 2 second sleep simulates server side processing of the response which may involve querying the database or reading some information from the filesystem.

This EJB can be easily injected in a Servlet using the normal way:

@EJB SimpleAsyncEJB ejb;

This business method can be invoked in the "doGet" method of a Servlet as:

PrintWriter out = response.getWriter();
try {
    Future<Integer> future = ejb.addNumbers(10, 20);
    print(out, "Client is working ...");
    Thread.currentThread().sleep(1000);

    if (!future.isDone()) {
        print(out, "Response not ready yet ...");
    }

    print(out, "Client is working again ...");
    Thread.currentThread().sleep(1000);

    if (!future.isDone()) {
        print(out, "Response not ready yet ...");
    }

    print(out, "Client is still working ...");
    Thread.currentThread().sleep(1000);

    if (!future.isDone()) {
        print(out, "Response not ready yet ...");
    } else {
        print(out, "Response is now ready");
    }

    Integer result = future.get();

    print(out, "The result is: " + result);
} catch (InterruptedException ex) {
    ex.printStackTrace();
} catch (ExecutionException ex) {
    ex.printStackTrace();
} finally { 
    out.close();
}

The control is returned to the client right after the the EJB business method is invoked and does not wait for the business method execution to finish. The methods on "Future" API are used to query if the result is available. The "Thread.sleep()" for 1 second simulate that client can continue working and possibly check for results at a regular interval. The "print" is a convenience method that prints the string to "response.getWriter" and flushes the output so that it can be instantly displayed instead of getting buffered. Invoking this "doGet" shows the following output:

1274142978365: Client is working ...
1274142979365: Response not ready yet ...
1274142979365: Client is working again ...
1274142980366: Response not ready yet ...
1274142980366: Client is still working ...
1274142981366: Response is now ready
1274142981366: The result is: 30

The client transaction context does not and security context do propagate from the client to the asynchronous business method.

Up until now, any kind of asynchrony in the EJB required to use the Message Driven Beans which in turn required some JMS setup. Introduction of this feature allows you to easily incorporate asynchrony in your EJB applications.

Try this and other Java EE 6 features in GlassFish Server Open Source Edition 3 or Oracle GlassFish Server today!

The complete source code used in this blog can be downloaded here.

Technorati: totd javaee ejb asynchronous glassfish v3

Monday May 17, 2010

TOTD #136: Default Error Page using Servlets 3.0 - Improved productivity using Java EE 6

Servlets 2.x allowed to create a mapping between an HTTP error code or an exception type to the path of a resource in the Web application. This is achieved by specifying an "error-page" element in the "web.xml". The element definition looks like:

So any HTTP error code or an exception thrown within the application can be mapped to a resource bundled with the application. Here is a sample:

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

Adding the above fragment in "web.xml" of an application will display "error-404.jsp" page to the client if a non-existing resource is accessed. This mapping can be easily done for other HTTP status codes as well by adding other <error-page> elements.

Similarly, <exception-type> element can be used to map an exception to a resource in the web application. This allows fine-grained mapping of errors from your web application to custom pages.

Starting with Servlets 3.0, <error-code> and <exception-type> elements are optional. An <error-page> without any <exception-type> and <error-code> will be considered as the webapp's default error page, and will act as a "catch-all" for any error codes or exception types. It will be an error if a web.xml contains more than one such default error page.

A default error page may be overridden for specific exception types and error codes. For example:

     <error-page>
       <location>/error-default.jsp</location>
     </error-page>

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

Any response with a status code other than 404 will be error-dispatched to /default.jsp, while a 404 response will be error-dispatched to /error-404.jsp.

So if the Servlet code looks like:

@WebServlet(name="HelloServlet", urlPatterns={"/HelloServlet"})
public class HelloServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, 
                         HttpServletResponse response) throws IOException {
        String type = (String)request.getParameter("type");

        if (type == null) {
            response.getWriter().print("hello world"); 
            return;
        }

        if (type.equals("helloex")) {   
          throw new HelloException();
        } else if (type.equals("ncdfe")) {
            throw new NoClassDefFoundError();
        } else {
            throw new NullPointerException();
        }
    }
}

And the "web.xml" looks like:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <error-page>
       <exception-type>java.lang.NoClassDefFoundError</exception-type>
       <location>/error-ncdfe.jsp</location>
    </error-page>
    <error-page>
       <exception-type>server.HelloException</exception-type>
       <location>/error-helloex.jsp</location>
    </error-page>
    <error-page>
       <error-code>404</error-code>
       <location>/error-404.jsp</location>
    </error-page>
    <error-page>
       <location>/error-default.jsp</location>
    </error-page>
</web-app>

Lets say the directory structure looks like:

WEB-INF/classes/
WEB-INF/classes/server/
WEB-INF/classes/server/HelloException.class
WEB-INF/classes/server/HelloServlet.class
WEB-INF/web.xml
error-404.jsp
error-default.jsp
error-helloex.jsp
error-ncdfe.jsp

and this application is deployed as "DefaultErrorPage.war". Then here is a table of the page that gets displayed when the URL mentioned in the first column is accessed:

URL Response Comment
http://localhost:8080/DefaultErrorPage/HelloServlet "hello world" Expected result
http://localhost:8080/DefaultErrorPage/HelloServlet2 error-404.jsp HTTP 404
http://localhost:8080/DefaultErrorPage/HelloServlet?type=ncdfe error-ncdfe.jsp System exception
http://localhost:8080/DefaultErrorPage/HelloServlet?type=helloex error-helloex.jsp User exception
http://localhost:8080/DefaultErrorPage/HelloServlet?type error-default.jsp Catch-all exception


Try this and other Java EE 6 features in GlassFish Server Open Source Edition 3 or Oracle GlassFish Server today!

The complete source code used in this blog can be downloaded here.

The default setting in Chrome is to show suggestions to navigate to other parts of the website or search with Google. This can be easily disabled by Chrome -> Preferences -> Under the Hood and deselecting "Show suggestions for navigation errors" in Privacy section. This is explained in detail here.

Technorati: totd javaee glassfish v3 servlet default error

Tuesday May 11, 2010

TOTD #135: JSF2 Composite Components using NetBeans IDE - lightweight Java EE 6

NetBeans IDE provide comprehensive feature set to build applications using Java Server Faces 2 (JSR 314). This Tip Of The Day (TOTD) explains how to create JSF composite components using wizards provided by the NetBeans IDE.

The JSF2 specification, section 3.6 defines composite components as:

A tree of "UIComponent" instances, rooted at a top level component, that can be thought of and used as a single component in a view. The component hierarchy of this subtree is described in the composite component defining page.

This definition is good from the specification perspective but can help with some layman explanation. Essentially, a composite component is what it says - a composition of two or more components such that it behaves like a single component. For example, consider four components in a panel grid where 2 components are "h:outputText" to display prompts and other 2 are "h:inputText" to receive input from the user. The composite components allow all of these components (1 panel grid + 2 "h:inputText" + 2 "h:outputText") packaged as a single component.

Resource Handling and Facelets, both features newly introduced in the JSF2 specification, makes the creation of composite component much easier. The Resource Handling defines a standard location for bundling resources in a web application and Facelets defines a cleaner templating language that enables composition. In technical terms:

A composite component is any Facelet markup file that resides inside of a resource library.

Lets create a simple Web application using JSF 2 that accepts a username/password and displays it in a new page. The application is first created using the traditional "h:inputText" and "h:outputText" elements and is then converted to use a composite component.

Before we dig into composite component creation using JSF2, here are the steps listed to create one using JSF 1.2:

  1. Implement UIComponent subclass
  2. Markup rendering code in Renderer
  3. Register your component and renderer in faces-config.xml
  4. Implement your JSP tag
  5. And the TLD

There is Java code involved, sub-classing from JSF classes, deployment descriptor editing in "faces-config.xml", declaring TLDs and then implementing the JSP tag. Creating a composite component in JSF 1.2 was quite a chore and spread all over. There are lots of files

With that background, lets see what it takes us to create a composite component using JSF2.

The CDI backing bean for the application looks like:

package server;

import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

@Named("simplebean")
@RequestScoped
public class SimpleBean {
    String name;
    String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

The "index.xhtml" Facelet markup file looks like:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:h="http://java.sun.com/jsf/html">
  <h:head>
    <title>Enter Name &amp; Password</title>
  </h:head>
  <h:body>
    <h1>Enter Name &amp; Password</h1>
    <h:form>
      <h:panelGrid columns="2">
        <h:outputText value="Name:"/>
        <h:inputText value="#{simplebean.name}" title="name" 
                     id="name" required="true"/>
        <h:outputText value="Password:"/>
        <h:inputText value="#{simplebean.password}" title="password" 
                     id="password" required="true"/>
      </h:panelGrid>
      <h:commandButton action="/old?u=http%3A%2F%2Fblogs.oracle.com%2Farungupta%2Ftags%2Fshow&y=1999" value="submit"/>
    </h:form>
  </h:body>
</html>


And the "show.xhtml" Facelet markup looks like:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html">
  <h:head>
    <title>Show Name &amp; Password</title>
  </h:head>
  <h:body>
    <h1>Show Name &amp; Password</h1>
    <h:panelGrid columns="2">
      <h:outputText value="Name:"/>
      <h:outputText value="#{simplebean.name}" />
      <h:outputText value="Password:"/>
      <h:outputText value="#{simplebean.password}" />
    </h:panelGrid>
  </h:body>
</html>



Now select the <panelGrid> fragment in "index.xhtml" as shown below:

Right-click and select "Convert To Composite Component ..." and specify the values as given in the wizard below:

Note, most of the values are default and only the "File Name:" is changed. After clicking on "Finish" in the wizard, the updated page looks like:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:ez="http://java.sun.com/jsf/composite/ezcomp">
  <h:head>
    <title>Enter Name &amp; Password</title>
  </h:head>
  <h:body>
    <h1>Enter Name &amp; Password</h1>
    <h:form>
      <ez:username-password/>
      <h:commandButton action="/old?u=http%3A%2F%2Fblogs.oracle.com%2Farungupta%2Ftags%2Fshow&y=1999" value="submit"/>
    </h:form>
  </h:body>
</html>

The namspace/prefix "http://java.sun.com/jsf/composite/ezcomp" is added to the markup page. <ez:username-password> is the composite component used instead of those multiple components. The namespace prefix, "ez", and the tag name, "username-password", are chosen based upon the values entered in the wizard.

The JSF 2 specification, section 3.6.1.4 defines that:

The occurrence of the string “http://java.sun.com/jsf/composite/” in a Facelet XML namespace declaration means that whatever follows that last “/” is taken to be the name of a resource library.

The resource library location is relative to the Facelet markup file that is using it. So in our case, all the code is rightly encapsulated in the "resources/ezcomp/username-password.xhtml" file as:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml"
     xmlns:cc="http://java.sun.com/jsf/composite"
     xmlns:h="http://java.sun.com/jsf/html">

    <!-- INTERFACE -->
    <cc:interface>
    </cc:interface>

    <!-- IMPLEMENTATION -->
    <cc:implementation>
      <h:panelGrid columns="2">
        <h:outputText value="Name:"/>
        <h:inputText value="#{simplebean.name}" title="name"
                   id="name" required="true"/>
        <h:outputText value="Password:"/>
        <h:inputText value="#{simplebean.password}" title="password"
                   id="password" required="true"/>
      </h:panelGrid>
 </cc:implementation>
</html>

Notice, the composite component name matches the Facelet markup file name. The markup file lives in "resources/ezcomp" directory as indicated by the namespace value.

<cc:interface> defines metadata that describe the characteristics of component, such as supported attributes, facets, and attach points for event listeners. <cc:implementation> contains the markup substituted for the composite component.

The "index.xhtml" page is using the composite component and is conveniently called the using page. Similarly the "username-password.xhtml" page is defining the composite component and is conveniently called the defining page. In short, creating composite components in JSF2 requires the following steps:

  1. Move the required tags to a separate Facelet markup file, "defining page", in the "resources" directory
  2. Declare the namespace/prefix derived from "http://java.sun.com/jsf/composite" and the directory name
  3. Refer the composite component in the "using page".

Much simpler and cleaner than JSF 1.2. Are you using JSF 2 composite components ?

The entire source code used in this blog can be downloaded here.

JSF 2 implementation is bundled with GlassFish Server Open Source Edition, try it today!

Technorati: totd glassfish v3 netbeans jsf2 javaee composite components ajax

Monday May 10, 2010

TOTD #134: Interceptors 1.1 in Java EE 6 - What and How ?

TOTD #129 explained Managed Beans 1.0, this Tip Of The Day (TOTD) attempts to explain the basics of Interceptors 1.1 - a "new" specification introduced in the Java EE 6.

The specification is not entirely new as the concept is borrowed from the EJB 3.0 specification and abstracted at a higher level so that it can be more generically applied to a broader set of specifications in the platform. Interceptors do what they say - they intercept on invocations and lifecycle events on an associated target class. Basically, interceptor is a class whose methods are invoked when business methods on the target class are invoked and/or lifecycle events such as methods that create/destroy the bean occur. Interceptors are typically used to implement cross-cutting concerns like logging, auditing, and profiling.

Contexts and Dependency Injection (CDI, aka JSR 299) uses the concept defined by Interceptors 1.1 and adds the notion of interceptors binding.

Let see some code to make it all clear.

Each interceptor require at least one interceptor binding to associate with the target class. An interceptor binding is defined as:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;

@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface MyInterceptorBinding {
}

And then the interceptor is defined as:

import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

@Interceptor
@MyInterceptorBinding
public class MyInterceptor {

    @AroundInvoke
    public Object intercept(InvocationContext context) throws Exception {
        System.out.println("before interception");
        Object result = context.proceed();
        System.out.println("after interception");

        return result;
    }
}

The "@AroundInvoke" annotation (can be only one per interceptor) on a method in the interceptor class ensures that this method is invoked around the business method interception. This will be more clear after the program flow is explained later. Multiple interceptors can be chained and the flow/outcome may be diverted in any of them using "InvocationContext".

The associated target bean looks like:

. . .
import javax.interceptor.Interceptors;

@ManagedBean(value="mybean")
@Interceptors(MyInterceptor.class)
public class MyManagedBean {
    @PostConstruct
    public void setupResources() {
        // setup your resources
        System.out.println("Setting up resources ...");
    }

    . . .

}

The only missing part on the server-side is enabling bean discovery by adding an empty "beans.xml" as:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

Notice, there is no need to explicitly mention <interceptors> in "beans.xml". Multiple interceptors on a bean can be easily defined as:

@ManagedBean(value="mybean")
@Interceptors({MyInterceptor.class, MyInterceptor2.class})
public class MyManagedBean {

Lets see how this bean and interceptor can be used. Create a Servlet as:

@WebServlet(name="TestServlet", urlPatterns={"/TestServlet"})
public class TestServlet extends HttpServlet {

Inject a bean as ...

@Inject
MyManagedBean bean;

and then invoke the bean's method in "doGet" or "doPost" methods of the servlet as:

String result = bean.sayHello("Duke");

Notice that @Inject is used to inject the managed bean and bean discovery is enabled by adding an empty "beans.xml". This ensures that CDI inject works as expected and all the interceptors are invoked as well. Another alternative is to inject the bean using @Resource but "beans.xml" need to be removed in order for the interceptors to be invoked. So inject your bean using @Inject + "beans.xml" or @Resource. The recommended approach is to use @Inject + "beans.xml" as CDI might be used in other parts of your applications as well.

If 2 interceptors, each with a separate interceptor binding, managed bean class, and the servlet is included in a web application then the directory structure will look like:

./META-INF
./META-INF/MANIFEST.MF
./WEB-INF
./WEB-INF/beans.xml
./WEB-INF/classes
./WEB-INF/classes/server
./WEB-INF/classes/server/MyInterceptor.class
./WEB-INF/classes/server/MyInterceptor2.class
./WEB-INF/classes/server/MyInterceptorBinding.class
./WEB-INF/classes/server/MyInterceptorBinding2.class
./WEB-INF/classes/server/MyManagedBean.class
./WEB-INF/classes/server/TestServlet.class

If there are "System.out.println"s inserted at relevant positions in the interceptor and the Servlet code, then the code flow looks like:

Before Intercept
Before Intercept2
sayHello
After Intercept2
After Intercept
processRequest

"Before XXX" messages are printed by a method from the interceptors, in the order of chaining, before "context.proceed" is invoked in all the interceptors. "sayHello" method is invoked from the "doGet" or "doPost" method in the Servlet. "After XXX" messages are printed from the interceptors after "context.proceed" method is invoked, this time in the reverse order of chain. And finally "processRequest" method is invoked again from the "doGet" or "doPost" method in the Servlet.

The complete source code for the sample explained above can be downloaded here.

Technorati: javaee glassfish v3 managedbeans interceptors cdi ejb servlet

About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, and a community guy who works for Oracle Corp.

Search
Recent Posts
Top Tags
Categories
Archives
« May 2011
SunMonTueWedThuFriSat
1
2
3
4
5
6
7
8
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    
       
Today
News
Blogroll

No bookmarks in folder

Menu
Feeds