Miles to go …

November 22, 2010

TOTD #151: Transactional Interceptors using CDI – Extensible Java EE 6

Filed under: glassfish, javaee — arungupta @ 4:19 pm

One of the questions often asked in recently, and I’ve been wondering too, is how to enable transactions using CDI Interceptors. This Tip Of The Day (TOTD) will share some basic piece of code on how to author a CDI interceptor that enable transactions. TOTD #134 provide more details about interceptors.

Lets jump to the code straight away. Lets look at the transaction interceptor binding code:

package org.glassfish.samples;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;

@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({METHOD, TYPE})
public @interface TxInterceptorBinding {
}

And the actual interceptor:

package org.glassfish.samples;

import javax.annotation.Resource;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.transaction.UserTransaction;

@TxInterceptorBinding @Interceptor
public class TxInterceptor {
    @Resource UserTransaction tx;

    @AroundInvoke
    public Object manageTransaction(InvocationContext context) throws Exception {
        tx.begin();
        System.out.println("Starting transaction");
        Object result = context.proceed();
        tx.commit();
        System.out.println("Committing transaction");

        return result;
    }
}

This interceptor is injecting a "UserTransaction" and sandwiching the business method invocation between start and end of trnasaction. This interceptor is not dealing with any rollback scenarios or exception handling and so will need to be modified for a real-life scenario.

"beans.xml" looks like:

<?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">
  <interceptors>
    <class>org.glassfish.samples.TxInterceptor</class>
  </interceptors>
</beans>

This basically enables the interceptor.

With all the plumbing code now ready, lets use this interceptor on our application code as:

package org.glassfish.samples;

@TxInterceptorBinding
public class ShoppingCart {
    public void checkOut() {
        System.out.println("Checking out");
    }
}

The important part is "@TxInterceptorBinding" as a class-level annotation. Now this ShoppingCart can be injected in any Java EE resource such as:

@Inject ShoppingCart shoppingCart;

such as in a Servlet. Now invoking the servlet shows the following sequence of code in the server log:

INFO: Starting transaction
INFO: Checking out
INFO: Committing transaction

That’s it folks!

The code for this sample application can be downloaded from here. Just download and unzip the code, open the project in NetBeans (tried with 7.0 beta) and run it on GlassFish or any other Java EE 6-compliant container.

If you are using EJBs in a WAR, which is now allowed per Java EE 6, then you can certainly leverage all the annotation-driven transactions within your web application instead of maintaining your own interceptor-driven transactions. A similar approach can be used for security as well.

How are you dealing with transactions in your web application – using CDI-based interceptors or let the container manage it all for you ?

Technorati: totd cdi javaee6 glassfish interceptors transactions

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

Screencast #35: JDK 7 Project Coin Features in NetBeans IDE 7.0 Beta

Filed under: netbeans — arungupta @ 12:45 pm

NetBeans IDE 7.0 Beta was released last week – download here. JDK 7 build 118 was released last week as well – download here. The New and Noteworthy page of NetBeans 7.0 highlights the support for some of the Project Coin features. This screencast highlights how to get started with JDK 7 in NetBeans IDE and use some of the Project Coin features, specifically:

  • Strings in switch
  • Binary integer literals and underscores in numeric literals
  • Multi-catch
  • Improved type inference for generic instance creation (diamond operator)
  • Automatic resource management

Enjoy!

Share feedback about Project Coin at coin-dev and about NetBeans at NetBeans Forums.

Technorati: screencast netbeans jdk7 project coin

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

November 19, 2010

Java EE 6 & GlassFish @ JavaOne Brazil & CEJUG

Filed under: glassfish, netbeans — arungupta @ 8:53 pm

The first ever JavaOne outside the USA is going to be in Brazeeeeel from Dec 7-9th … yeeeee haw! Java EE 6 & GlassFish will have a strong presence there in terms of technical sessions, general session, exhibitor floor, hands-on labs, and of course you’ll find us all around the hallways.

Here is a quick summary of different Java EE 6 related sessions …

When ? Where ? What ? Speaker ?
Tuesday
11:45 – 12:30pm
Salon 2 S319438
HK2: Oracle WebLogic Serve, Oracle GlassFish Server, and Beyond
Jerome Dochez

Wednesday
10:15 – 11am

Salon 1 S313557
The Java EE 6 Programming Model Explained: How to Write Better Applications
Jerome Dochez
Wednesday
10:15 – 11am
Salon 2 S313431
Java Persistence API 2.0: An Overview
Ludovic Champenois
Wednesday
11:15 – 12pm
Salon 1 S314168
What’s New in Enterprise JavaBean Technology
Arun Gupta
Wednesday
1:30 – 2:15pm
Salon 3 S313265
Advanced Java API for RESTful Web Services (JAX-RS)
Chuk-Munn Lee
Wednesday
2:30 – 3:15pm
Salon 3 S320002
Creating RESTful Web Services using JAX-RS
Ludovic Champenois
Thursday
10:10:45
Salon 1 S313189
Complete Tools Coverage for the Java EE 6 Platform
Ludovic Champenois
Thursday
11:15 – 12:00pm
Salon 1 S320004
Hyperproductive JavaServer Faces 2.0
Arun Gupta
Thursday
2:00 – 2:45pm
Salon 1 S313937
Using Contexts and Dependency Injection (CDI) in the Java EE Ecosystem
Jerome Dochez
Thursday
4:15 – 5:00
Salon 1 S320003
Servlet 3.0 Extensible, Asynchronous and Easy to Use
Arun Gupta
Thursday
4:15 – 6:00pm
Salon 4 S314285
Using Oauth with RESTful Web Services (Hands-on Lab)
Chuk-Munn Lee
Thursday
4:15 – 6:00pm
Salon 6 S313277
Beginning with the Java EE 6 Platform (Hands-on Lab)
Ludovic Champenois
& Gang

And prior to JavaOne, I’ll also be speaking at CEJUG on Java EE 6.

Looking forward to enjoy Caipirinha, Churrascaria, Guarana, Brazilian coffee, beautiful beaches, and my first summer time visit to Brazil :-) Where will I see you ?

For the first time travelers to Brazil, here are some travel tips and 4 things not to miss in Brazil.

Technorati: conf javaone brazil javaee6 glassfish brazil cejug

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

November 18, 2010

TOTD #150: Collection of GlassFish, NetBeans, JPA, JSF, JAX-WS, EJB, Jersey, MySQL, Rails, Eclipse, and OSGi tips

This is the 150th tip published on this blog so decided to make it a collection of all the previous ones. Here is a tag cloud (created from wordle.net/create) from title of all the tips:

As expected GlassFish is the most prominent topic. And then there are several entries on NetBeans, JRuby/Rails, several Java EE 6 technologies like JPA, JAX-WS, JAX-RS, EJB, and JSF, and more entries on Eclipse, OSGi and some other tecnhologies too. Here is a complete collection of all the tips published so far:

  • #149: How to clean IntelliJ cache, preferences, etc on Mac OS X ?
  • #148: JPA2 Metamodel Classes in NetBeans 7.0 – Writing type-safe Criteria API
  • #147: Java Server Faces 2.0 Composite Components using NetBeans – DRY your code
  • #146: Understanding the EJB 3.1 Timer service in Java EE 6 – Programmatic, Deployment Descriptor, @Schedule
  • #145: CDI Events – a light-weight producer/consumer in Java EE 6
  • #144: CDI @Produces for container-managed @Resource
  • #143: Retrieve Twitter user timeline using using Jersey and OAuth
  • #142: GlassFish 3.1 – SSH Provisioning and Start/Stop instance/cluster on local/remote machines
  • #141: Running GlassFish 3.1 on Ubuntu 10.04 AMI on Amazon EC2
  • #140: Moving GlassFish Installation – Referenced file does not exist "osgi-main.jar"
  • #139: Asynchronous Request Processing using Servlets 3.0 and Java EE 6
  • #138: GlassFish 3.1 Milestone 1 – Clustering and Application Versioning Demos
  • #137: Asynchronous EJB, a light-weight JMS solution – Feature-rich Java EE 6
  • #136: Default Error Page using Servlets 3.0 – Improved productivity using Java EE 6
  • #135: JSF2 Composite Components using NetBeans IDE – lightweight Java EE 6
  • #134: Interceptors 1.1 in Java EE 6 – What and How ?
  • #133: JPA2 (JPQL & Criteria), JavaDB, and embedded GlassFish – perfect recipe for testing
  • #132: Servlets 3.0 in Embedded GlassFish Reloaded – lightweight Java EE 6
  • #131: Dynamic OSGi services in GlassFish – Using ServiceTracker
  • #130: Invoking a OSGi service from a JAX-WS Endpoint – OSGi and Enterprise Java
  • #129: Managed Beans 1.0 in Java EE 6 – What and How ?
  • #128: EJBContainer.createEJBContainer: Embedded EJB using GlassFish v3
  • #127: Embedding GlassFish in an existing OSGi runtime – Eclipse Equinox
  • #126: Creating an OSGi bundles using Eclipse and deploying in GlassFish
  • #125: Creating an OSGi bundles using NetBeans and deploying in GlassFish
  • #124: OSGi Declarative Services in GlassFish – Accessed from a Java EE client
  • #124: Using CDI + JPA with JAX-RS and JAX-WS
  • #123: f:ajax, Bean Validation for JSF, CDI for JSF and JPA 2.0 Criteria API – all in one Java EE 6 sample application
  • #122: Creating a JPA Persistence Unit using NetBeans 6.8
  • #121: JDBC resource for MySQL and Oracle sample database in GlassFish v3
  • #120: Deployment Descriptor-free Java EE 6 application using JSF 2.0 + EJB 3.1 + Servlets 3.0
  • #119: Telnet to GlassFish v3 with NetBeans 6.8 – "Could not open connection to the host"
  • #118: Managing OSGi bundles in GlassFish v3 – asadmin, filesystem, telnet console, web browser, REST, osgish
  • #117: Invoke a JAX-WS Web service from a Rails app deployed in GlassFish
  • #116: GlassFish v3 Administration using JavaFX front-end – JNLP available
  • #115: GlassFish in Eclipse – Integrated Bundle, Install Stand-alone or Update Existing plugin
  • #114: How to enable Java Console in Mac OS X, Windows, … ?
  • #113: JavaFX front-end for GlassFish v3 Administration – Using REST interface
  • #112: Exposing Oracle database tables as RESTful entities using JAX-RS, GlassFish, and NetBeans
  • #111: Rails Scaffold for a pre-existing table using Oracle and GlassFish
  • #110: JRuby on Rails application using Oracle on GlassFish
  • #109: How to convert a JSF managed bean to JSR 299 bean (Web Beans) ?
  • #108: Java EE 6 web application (JSF 2.0 + JPA 2.0 + EJB 3.1) using Oracle, NetBeans, and GlassFish
  • #107: Connect to Oracle database using NetBeans
  • #106: How to install Oracle Database 10g on Mac OS X (Intel) ?
  • TOTD #105: GlassFish v3 Monitoring – How to monitor a Rails app using asadmin, JavaScript, jConsole, REST ?
  • #104: Popular Ruby-on-Rails applications on GlassFish v3 – Redmine, Typo, Substruct
  • #103: GlassFish v3 with different OSGi runtimes – Felix, Equinox, and Knoplerfish
  • #102: Java EE 6 (Servlet 3.0 and EJB 3.1) wizards in Eclipse
  • #101: Applying Servlet 3.0/Java EE 6 “web-fragment.xml” to Lift – Deploy on GlassFish v3
  • #100: Getting Started with Scala Lift on GlassFish v3
  • #99: Creating a Java EE 6 application using MySQL, JPA 2.0 and Servlet 3.0 with GlassFish Tools Bundle for Eclipse
  • #98: Create a Metro JAX-WS Web service using GlassFish Tools Bundle for Eclipse
  • #97: GlassFish Plugin with Eclipse 3.5
  • #96: GlassFish v3 REST Interface to Monitoring and Management – JSON, XML, and HTML representations
  • #95: EJB 3.1 + Java Server Faces 2.0 + JPA 2.0 web application – Getting Started with Java EE 6 using NetBeans 6.8 M1 & GlassFish v3
  • #94: A simple Java Server Faces 2.0 + JPA 2.0 application – Getting Started with Java EE 6 using NetBeans 6.8 M1 & GlassFish v3
  • #93: Getting Started with Java EE 6 using NetBeans 6.8 M1 & GlassFish v3 – A simple Servlet 3.0 + JPA 2.0 app
  • #92: Session Failover for Rails applications running on GlassFish
  • #91: Applying Java EE 6 "web-fragment.xml" to Apache Wicket – Deploy on GlassFish v3
  • #90: Migrating from Wicket 1.3.x to 1.4 – "Couldn’t load DiskPageStore index from file" error
  • #89: How to add pagination to an Apache Wicket application
  • #88: How add pagination to Rails – will_paginate
  • #87: How to fix the error undefined method `new’ for "Rack::Lock":String caused by Warbler/JRuby-Rack ?
  • #86: Getting Started with Apache Wicket on GlassFish
  • #85: Getting Started with Django Applications on GlassFish v3
  • #84: Using Apache + mod_proxy_balancer to load balance Ruby-on-Rails running on GlassFish
  • #83: Eclipse Tools Bundle for GlassFish 1.0 – Now Available!
  • #82: Getting Started with Servlet 3.0 and EJB 3.1 in Java EE 6 using NetBeans 6.7
  • #81: How to use nginx to load balance a cluster of GlassFish Gem ?
  • #80: Sinatra CRUD application using Haml templates with JRuby and GlassFish Gem
  • #79: Getting Started with Sinatra applications on JRuby and GlassFish Gem
  • #78: GlassFish, EclipseLink, and MySQL efficient pagination using LIMIT
  • #77: Running Seam examples with GlassFish
  • #76: JRuby 1.2, Rails 2.3, GlassFish Gem 0.9.3, ActiveRecord JDBC Adapter 0.9.1 – can they work together ?
  • #75: Getting Started with Grails using GlassFish v3 Embedded
  • #74: JRuby and GlassFish Integration Test #5: JRuby 1.2.0 RC2 + Rails 2.x.x + GlassFish + Redmine
  • #73: JRuby and GlassFish Integration Test #4: JRuby 1.2.0 RC2 + Rails 2.2.x + GlassFish v2 + Warbler
  • #72: JRuby and GlassFish Integration Test #3: JRuby 1.2.0 RC2 + Rails 2.2.x + GlassFish v3
  • #71: JRuby and GlassFish Integration Test #2: JRuby 1.2.0 RC1 + Rails 2.2.x + GlassFish v3 Prelude
  • #70: JRuby and GlassFish Integration Test# 1: JRuby 1.2.0 RC1 + Rails 2.2.x + GlassFish Gem
  • #69: GlassFish High Availability/Clustering using Sun Web Server + Load Balancer Plugin on Windows Vista
  • #68: Installing Zones in Open Solaris 2008/11 on Virtual Box
  • #67: How to front-end a GlassFish Cluster with Apache + mod_jk on Mac OSX Leopard ?
  • #66: GlassFish Eclipse Plugin 1.0.16 – Install v3 Prelude from the IDE
  • #65: Windows 7 Beta 1 Build 7000 on Virtual Box: NetBeans + Rails + GlassFish + MySQL
  • #64: OpenSolaris 2008/11 using Virtual Box
  • #63: jmx4r gem – How to manage/monitor your Rails/Merb applications on JRuby/GlassFish ?
  • #62: How to remotely manage/monitor your Rails/Merb applications on JRuby/GlassFish using JMX API ?
  • #61: How to locally manage/monitor your Rails/Merb applications on JRuby/GlassFish using JMX ?
  • #60: Configure MySQL 6.0.x-alpha to NetBeans 6.5
  • #59: How to add Twitter feeds to blogs.sun.com ? + Other Twitter Tools
  • #58: Jersey and GlassFish – how to process POST requests ?
  • #57: Jersey Client API – simple and easy to use
  • #56: Simple RESTful Web service using Jersey and Embeddable GlassFish – Text and JSON output
  • #55: How to build GlassFish v3 Gem ?
  • #54: Java Server Faces with Eclipse IDE
  • #53: Scaffold in Merb using JRuby/GlassFish
  • #52: Getting Started with Merb using GlassFish Gem
  • #51: Embedding Google Maps in Java Server Faces using GMaps4JSF
  • #50: Mojarra 2.0 EDR2 is now available – Try them with GlassFish v3 and NetBeans 6.5
  • #49: Converting a JSF 1.2 application to JSF 2.0 – @ManagedBean
  • #48: Converting a JSF 1.2 application to JSF 2.0 – Facelets and Ajax
  • #47: Getting Started with Mojarra 2.0 nightly on GlassFish v2
  • #46: Facelets with Java Server Faces 1.2
  • #45: Ajaxifying Java Server Faces using JSF Extensions
  • #44: JDBC Connection Pooling for Rails on GlassFish v3
  • #43: GlassFish v3 Build Flavors
  • #42: Hello JavaServer Faces World with NetBeans and GlassFish
  • #41: How I created transparent logo of GlassFish using Gimp ?
  • #40: jQuery Autcomplete widget with MySQL, GlassFish, NetBeans
  • #39: Prototype/Script.aculo.us Autcomplete widget with MySQL, GlassFish, NetBeans
  • #38: Creating a MySQL Persistence Unit using NetBeans IDE
  • #37: SQLite3 with Ruby-on-Rails on GlassFish Gem
  • #36: Writing First Test for a Rails Application
  • #35: Rails Database Connection on Solaris
  • #34: Using Felix Shell with GlassFish
  • #33: Building GlassFish v3 Workspace
  • #32: Rails Deployment on GlassFish v3 from NetBeans IDE
  • #31: CRUD Application using Grails – Hosted on GlassFish and MySQL
  • #30: CRUD Application using Grails – Hosted on Jetty and HSQLDB
  • #29: Enabling "Available Plugins" tab in NetBeans IDE
  • #28: Getting Started with Rails 2.0 Scaffold
  • #27: Configurable Multiple Ruby Platforms in NetBeans 6.1 M1
  • #26: Overriding Database Defaults in Rails 2.0.2
  • #25: Rails application with PostgreSQL database using NetBeans
  • #24: Getting Started with Rails 2.0.x in JRuby 1.0.3 and JRuby 1.1RC1
  • #23: JavaFX Client invoking a Metro endpoint
  • #22: Java SE client for a Metro endpoint
  • #21: Metro 1.1 with GlassFish v2 UR1 and NetBeans 6
  • #20: How to create a new jMaki widget ?
  • #19: How to Add Metro Quality-of-Service to Contract-First Endpoint ?
  • #18: How to Build The GlassFish v3 Gem for JRuby ?
  • #17: Backing Up your Blog Posts on Roller
  • #16: Optimizing Metro Stubs by locally packaging the WSDL
  • #15: Delete/Update Row from Database using jMaki Data Table
  • #14: How to generate JRuby-on-Rails Controller on Windows (#9893)
  • #13: Setup Mongrel for JRuby-on-Rails applications on Windows
  • #12: Invoking a Java EE 5 Web service endpoint from JRuby
  • #11: Setup Mongrel cluster for JRuby-on-Rails applications on Unix
  • #10: Consuming JSON and XML representations generated by a Jersey endpoint in a jMaki Table widget
  • #9: Using JDBC connection pool/JNDI name from GlassFish in Rails Application
  • #8: Generating JSON using JAXB annotations in Jersey
  • #7: Switch between JRuby and CRuby interpreter in NetBeans 6
  • #6: Difference between Ruby Gem and Rails Plugin
  • #5: Loading data from beans in jMaki widgets
  • #4: How to convert a Session EJB to a Web service ?
  • #3: Using JavaDB with JRuby on Rails
  • #2: Change the endpoint address on a pre-generated Web services Stub
  • #1: SOAP Messaging Logging in Metro

Just for fun, here is another tag cloud:

You can access all the tips here. And keep those suggestions coming!

Technorati: totd glassfish netbeans jpa jsf jaxws jersey mysql rails osgi eclipse

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

Screencast #34: GlassFish 3.1 Clustering, High Availability and Centralized Administration

Filed under: glassfish — arungupta @ 12:47 pm

Two main themes of GlassFish 3.1 are: High Availability and Centralized Administration. This screencast demonstrates how to create a 2-instance cluster on a single machine using web-based Administration Console, deploy the canonical clusterjsp application, and show session fail-over capabilities in GlassFish 3.1.

From download to testing an application with high availability … all in under 10 minutes … enjoy!

A future screencast will show how to create multiple nodes on different machines, with 1 or more instance on each node, and all of them front-ended with a load balancer.

Technorati: screencast glassfish clustering highavailability

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

November 10, 2010

Oredev 2010 Trip Report

Filed under: glassfish — arungupta @ 2:11 pm

Oracle is a silver sponsor sponsor of Oredev 2010 and there were several talks by Oracle speakers. There are about 1300 attendees so its a fairly big conference, probably the biggest developer gathering in the Nordic countries. The conference had a pretty wide variety of topics from Java, .NET, Agile, Smart Phones, Web Development, and others. The conference venue itself used to be a slaughterhouse and you can imagine it easily accommodated 1300 attendees :)

I gave a hands-on workshop on "Deep Dive Hands-on in Java EE 6" and the slides are now available:

Deep Dive Hands-on in Java EE 6 – Oredev 2010

There were about 15 participants and most of them were very interactive which is the real fun part! As part of the lab we coded samples for most of the Java EE 6 new/updated technologies such as:

  • Managed Beans 1.0
  • Interceptors 1.1
  • Servlets 3.0
  • Enterprise Java Beans 3.1
  • Contexts & Dependency Injection 1.0
  • Java Server Faces 2.0
  • Java Persistence API 2.0
  • Bean Validation 1.0
  • Java API for RESTful Web services 1.1

The fun part that most of the attendees got their code working along with me. Anyway, the sample code built during the lab is also available here.

I also gave a presentation on "Using the latest Java Persistence API 2.0 Features" and the slide deck is available below:

Using the latest Java Persistence API 2.0 features

There were about 50 attendees in this talk. It basically explained the new features in JPA 2 such as improved O/R mapping in Java, expanded JPQL, Metamodel, type-safe Criteria API, support for Bean Validation, standard configuration options, and many other options. And then showed how NetBeans can easily generate JPA entities from a database and also generate canonical metamodel classes. As in the workshop, the audience was very interactive and gave some good suggestions for JPA 2.

Day 1 keynote was by Dr Jeff Norris (JPL, Pasadena) who talked about three pillars of Mission Critical Agility – Vision, Risk, and Commitment. His presentation showed how Alexander Graham Bell had a great vision and risked everything he had to meet that vision. He showed a great demo using augmented reality, probably one of the finest ones I’ve seen in recent conferences. The keynotes are conducted in a big theater-style hall, that probably makes it fourth conference in Europe (along with Devoxx, Jazoon, and JavaZone) to be conducted in a theater. I wonder if this is a European thing cause I’ve yet to see a conference in the US going that way ;-)

One of the cool tracks in the conference is Xtra(ck) which has topics like Undesrtanding Hypnosis, Photographic Composition and Creativity, Effective public speaking skills, and some other good ones. I attended the hypnosis session earlier today and Lina Esa (the instructor) talked about unconsious, sub-conscious, and conscious mind and how they can be controlled with hypnosis. She is going to have a practice session on Friday but I’m flying out earlier :(

The closing keynote on Day 1 was by Henrik Kniberg where he talked about how visualizing software, by means of pictures,  diagrams, and otherwise, can drive collaboration and process improvement. He is also linked it very nicely with personal life as a means to release stress and keep the work-life balance.

Other than that there were lots of fun activities planned …

  • Skinny dipping in the close-to-freezing ocean after sitting in the 85 degrees sauna was quite a unique and cultural experience.
  • Dinner at Ribersborgs Kallabdhus after the hot-and-cold-bath was definitely very welcome.
  • The meet-and-greet at at Magnus’s house before the speakers’ dinner was very welcoming. Enjoyed Glögg, with traditional raisins and almonds, in this freaking cold weather.
  • The speakers’ dinner in a formal setup at Malmo city hall with opening speech by deputy mayor of Malmo was quite an overwhelming experience. I tried black soup (made out of boiled pigs’ blood) there and not sure if I really liked it but the ambience was superb ;-)

There are other fun activities planned over the next couple of days. Here are some pics from the event:

And the complete album:

I would’ve loved to stay longer and engage with the wonderful attendees but fever, cough, and cold is making me pre-pone my flight by a day.

I plan to come back again next year, see ya in 2011!

Technorati: conf oredev sweden glassfish javaee6 jpa2 netbeans 2010

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

November 4, 2010

OTN Developer Days 2010, New York City Trip Report

Filed under: glassfish — arungupta @ 10:38 pm

OTN Developer Days kicked off this morning in the heart of New York City in the Millennium Broadway hotel. About 200 developers attended 20 sessions + hands-on labs divided in four tracks – Server, Desktop, Mobile, and Embedded. I think that was a pretty good turnout knowing that this was a weekday and kept raining all day.

I delivered 2 sessions + 3 hands-on labs (yes, back-to-back) in the Server track. There were about approximately 80 attendees through out the day in the Server track. It was tiring speaking for pretty much the entire day but totally enjoyed the super interactive audience. The attendees were not aware to bring their own laptops so most could not try hands-on lab on their own. This will be fixed for subsequent events by including a reminder in the registration email. As a consequence I converted the hands-on lab sessions to code walk through where I built the entire sample and explained the code in detail. After initial hiccups the three hands-on workshops went smoothly. The workshops covered some of the key Java EE 6 technologies by building mini applications and combination of technologies was:

  • EJB 3.1 + JAX-RS 1.1
  • JSF 2 + CDI 1.0
  • Servlets 3.0 + JPA 2

The slides from the two sessions are available below:

OTN Developer Days – Java EE 6

OTN Developer Days – GlassFish

Here is some feedback from the audience on the delivered sessions + workshops:

Arun Gupta puts on a fine presentation. The man has been doing this for a while; and he knows the technology and related material quite well. Good Job Arun!

I thought Arun Gupta did an excellent job with his presentations. He was very prepared with his examples and was able to offer supplemental materials for the content.

Mr Arun Gupta is knowledgeable and thorough presenter. Pace of the presentation is good.

Excellent presentation with audience involvement.

Arun is obviously very knowledgeable. He gives good intro level of detail to understand concepts, and can answer detailed questions as well. Arun is well spoken and open for question of all types.

Demo were well done and the walk through were helpful especially since I did not bring a laptop.

Arun Gupta = Excellent and Knowledgeable

Excellent presentation, hats up!

Great seminar, great instructor! Exceeded my expectation by a lot!

For fun, one of the feedback was …

Just do this kind of FREE seminars on WEEKEND.

As always there is always is room for improvement so I take that feedback close to my heart as well. Thank you everybody for attending the session and providing the feedback!

And as always, some pictures …

And the complete photo album:

If you are interested in attending in one of these workshops, check out the locations of OTN Developer Days worldwide.

2 down (Cloud Expo and OTN Dev Days) and 5 more to go (Oredev, Rich Web Expo, DegIgnition, CEJUG, JavaOne Brazil) in the next 5 weeks.

Where will I see you ?

Technorati: conf oracletechnet otn devdays newyorkcity javaee6 glassfish

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

October 29, 2010

TOTD #148: JPA2 Metamodel Classes in NetBeans 7.0 – Writing type-safe Criteria API

Filed under: glassfish, javaee, netbeans — arungupta @ 10:32 am

NetBeans 7.0 M2 was released recently. There are several Java EE related improvements in this release:

  • Find usages of managed beans (JSF/CDI) and their properties
  • PrimeFaces is now available as an integrated JSF component library
  • Wizard for creating Bean Validation constraint
  • CDI Qualifier creation editor hint
  • Cleaned up Inspect Observer/Producer for CDI events
  • Generation of Bean Validation annotations for Entities

and some others. One of the features that is not much spoken about is the automatic generation of JPA 2 Metamodel classes from Entity classes. This Tip Of The Day (TOTD) will explain how to generate these classes and use them for writing type-safe JPA2 Criteria queries.

The JPA2 Metamodel classes capture the metamodel of the persistent state and relationships of the managed classes of a persistence unit. This abstract persistence schema is then used to author the type-safe queries using Critieria API. The canonical metamodel classes can be generated statically using an annotation processor following the rules defined by the specification. The good thing is that no extra configuration is required to generate these metamodel classes. NetBeans IDE automatically generates the canonical metamodel classes using the EclipseLink Canonical Model Generator. There are two ways these metamodel classes are generated in NetBeans:

  1. Pre-configured when Entity Classes are generated from a Database using the wizards. TOTD #122 provide more details on that. The actual metamodel classes are generated when the project is build using "Clean and Build", "Deploy" or some other related target.
  2. Explicitly configured by right-clicking on the project, "Properties", "Libraries", "Processor", "Add Library…", and select "EclipseLink(JPA 2.0)" and "EclipseLink-ModelGen(JPA 2.0)" libraries and click on "Add Library" as shown below.

This TOTD will use the "Manufacturer" table from the pre-configured "jdbc/sample" JDBC resource in NetBeans and GlassFish. It will create a simple 2-page application where the first page (index.xhtml) accepts a Manufacturer name and the second page (show.xhtml) displays some details about that manufacturer.

  1. Create a NetBeans Web project with the title "CriteriaMetamodel", make sure to enable CDI and Java Server Faces during the creation.
  2. Create "Manufacturer" JPA entity by using the pre-configured "jdbc:derby://localhost:1527/sample" database connection and using the MANUFACTURER table. Notice that the generated manufacturer entity contains the bean validation constraints derived from the database schema, yet another new feature in 7.0 M2. More on this topic in a later blog.
  3. Generate the metamodel classes by right-clicking on the project and selecting "Clean and Build". The generated metamodel class looks like:

    package org.glassfish.samples.entities;
    import javax.annotation.Generated;
    import javax.persistence.metamodel.SingularAttribute;
    import javax.persistence.metamodel.StaticMetamodel;
    @Generated("EclipseLink-2.1.0.v20100614-r7608 @ Mon Oct 25 16:35:03 PDT 2010")
    @StaticMetamodel(Manufacturer.class)
    public class Manufacturer_ {
        public static volatile SingularAttribute addressline2;
        public static volatile SingularAttribute zip;
        public static volatile SingularAttribute phone;
        public static volatile SingularAttribute addressline1;
        public static volatile SingularAttribute fax;
        public static volatile SingularAttribute manufacturerId;
        public static volatile SingularAttribute email;
        public static volatile SingularAttribute name;
        public static volatile SingularAttribute state;
        public static volatile SingularAttribute city;
        public static volatile SingularAttribute rep;
    }
    

    This is shown as "Generated Sources" in NetBeans IDE as shown:

  4. Generate a new Java class "DatabaseBean" and mark it with "@javax.enterprise.inject.Model" annotation. This class will be the "backing bean" for the JSF pages and will have

    1. A field to accept the manufacturer’s name from "index.xhtml"
    2. A field to show information about the searched manufacturer in "show.xhtml"
    3. A business method "searchManufacturer" that searches the database for the given manufacturer’s name. This method will use the generated metamodel class and type-safe Criteria API to query the database.

    The complete source code for the class looks like:

    @PersistenceUnit EntityManagerFactory emf;
    
    String name;
    
    Manufacturer manufacturer;
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public Manufacturer getManufacturer() {
        return manufacturer;
    }
    
    public void searchManufacturer() {
        EntityManager em = emf.createEntityManager();
    
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery criteria = builder.createQuery(Manufacturer.class);
    
        // FROM clause
        Root root = criteria.from(Manufacturer.class);
    
        // SELECT clause
        criteria.select(root);
    
        // WHERE clause
        Predicate condition = builder.like(root.get(Manufacturer_.name),
                "%" + name + "%");
        criteria.where(condition);
    
        // FIRE query
        TypedQuery query = em.createQuery(criteria);
    
        // PRINT result
        List manufacturers = query.getResultList();
    
        if (manufacturers != null && manufacturers.size() > 0) {
            manufacturer = (Manufacturer)manufacturers.get(0);
        }
    }
    

    The business method returns the first manufacturer whose name contains the text entered in the textbox. No validation is performed in order to keep the business logic simple.

    Notice how "searchManufacturer" method is not using any String-based identifiers for constructing the query graph. This gives the complete type-safety for query construction and allows the errors to be detected much earlier.

  5. Edit the generated "index.xhtml" such that the content within <h:body> looks like:

    <h:form>
     <h:panelGrid columns="3">
     <h:outputText value="Name:" />
     <h:inputText value="#{databaseBean.name}" id="name"/>
     </h:panelGrid>
    
     <h:commandButton
        actionListener="#{databaseBean.searchManufacturer}"
        action="show"
        value="submit"/>
    </h:form>
    
    

    This page shows a text box and a submit button. The "searchManufacturer" method of the DatabaseBean is invoked when the "submit" button is clicked and passes the entered text in the "name"property of the DatabaseBean.

  6. Create a new XHTML page and name it "show.xhtml". Replace the generated boilerplate code with the code given below:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>Show Manufacturer's Detail</title>
      </head>
      <body>
        Name: #{databaseBean.manufacturer.name}<br/>
        Phone: #{databaseBean.manufacturer.phone}<br/>
        Address Line1: #{databaseBean.manufacturer.addressline1}<br/>
        Address Line2: #{databaseBean.manufacturer.addressline2}<br/>
     </body>
    </html>
    

Now you can deploy the application to GlassFish by usual means and access "http://localhost:8080/CriteriaMetamodel/faces/index.xhtml" which gets displayed as:

Enter some value as "S" in the text box and click on "Submit" to display the result as:

The complete source code for this sample can be downloaded here.

Now Criteria query is little verbose but it does give you the type-safety and was explicitly asked within the JPA Expert Group. It allows you to manipulate different parts of a query such as SELECT, FROM, and WHERE clauses and that too using the Java type system. This reminds me of Mr Potato Head :-)

This behavior can be achieved in JPQL but is available exclusively using String manipulation and the errors are not detected until runtime.

How are you using Criteria API ?

What use cases would you like to see solved in JPA2.next ?

Technorati: totd jpa2 criteria metamodel netbeans javaee6 glassfish

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

October 28, 2010

TOTD #147: Java Server Faces 2.0 Composite Components using NetBeans – DRY your code

Filed under: frameworks, glassfish, javaee, javaserverfaces, netbeans — arungupta @ 12:03 pm

The Java Server Faces 2.0 uses Facelets instead of JSP as the view declaration language. This allows "view" part of MVC to be completely written using XHTML and CSS only and all the business logic resides in the backing bean. This enables a cleaner separation of views with model and controller and thus follows the MVC design pattern in a more intuitive way. JSF 2 also defines how resources can be packaged, located, and rendered by JSF runtime within a web application.

Using these two features of Facelets and Resource Handling, JSF2 defines a composite component as a component that consists of one or more JSF components defined in a Facelet markup file that resides inside of a resource library. The composite component is defined in the defining page and used in the using page. The "defining page" defines the metadata (or parameters) using <cc:interface> and implementation using <cc:implementation> where "cc" is the prefix for "http://java.sun.com/jsf/composite" namespace. Future versions of the JSF 2 specification may relax the requirement to specify metadata as it can be derived from the implementation itself.

A composite component can be defined using JSF 1.2 as well but it requires a much deeper understanding of JSF lifecycle and also authoring multiple files. JSF2 really simplifies the authoring of composite components using just an XHTML file.

Code is king! This Tip Of The Day (TOTD) will explain how to convert an existing code fragment into a JSF2 composite component using NetBeans IDE.

Lets say a Facelet (index.xhtml) has the following code fragment:

<h:form>
    <h:panelGrid columns="3">
    <h:outputText value="Name:" />
    <h:inputText value="#{user.name}" id="name"/>
    <h:message for="name" style="color: red" />
    <h:outputText value="Password:" />
    <h:inputText value="#{user.password}" id="password"/>
    <h:message for="password" style="color: red" />
  </h:panelGrid>

  <h:commandButton actionListener="#{userService.register}"
                   id="loginButton" action="status" value="submit"/>
</h:form>

This fragment displays an HTML form with two text input boxes and a "submit" button. The two input boxes are bound to "user" bean and clicking on the button invokes "register" method of the "userService" bean.

Instead of repeating this code in multiple pages, its beneficial to convert this into a composite component and use the resulting tag instead of the complete fragment again. Why ?

  • Follows the DRY principle and allows to keep the code, that can be potentially be repeated at multiple places, in a single file.
  • It allows developers to author new components without any Java code or XML configuration.

How do you convert an existing code fragment to a composite component ? NetBeans makes it really easy.

In NetBeans IDE select the code fragment, right-click, "Refactor", "Convert to Composite Component…" as shown below:

In the next screen, change the filename to "loginPanel" and take every thing else as default as shown below:

and click on "Finish".

This will generate "web/resources/ezcomp/loginPanel.xhtml" and move the component definition to this file, aka "defining page" and 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:cc="http://java.sun.com/jsf/composite"
      xmlns:h="http://java.sun.com/jsf/html">

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

 <!-- IMPLEMENTATION -->
 <cc:implementation>
   <h:form>
     <h:panelGrid columns="3">
       <h:outputText value="Name:" />
       <h:inputText value="#{user.name}" id="name"/>
       <h:message for="name" style="color: red" />
       <h:outputText value="Password:" />
       <h:inputText value="#{user.password}" id="password"/>
       <h:message for="password" style="color: red" />
     </h:panelGrid>

     <h:commandButton actionListener="#{userService.register}"
                      id="loginButton" action="status" value="submit"/>
   </h:form>
</cc:implementation>
</html>

<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.

<cc:interface> is generated in the page but is empty and may be made optional in a subsequent release of the JSF specification.The "using page" will declare a new namespace as:

xmlns:ez="http://java.sun.com/jsf/composite/ezcomp"

and then replace the code fragment with:

<ez:loginPanel/>

The tag name for the new composite component is the same as the "defining page" file name. This enables "<ez:loginPanel/>" to be used instead of repeating that entire code fragment.

Now lets say that the code fragment need to pass different value expressions (instead of #{user.name}) and invoke a different method (instead of #{userService.register}) when submit button is clicked in different "using page"s. The "defining page" can then look like:

<!-- INTERFACE -->
<cc:interface>
  <cc:attribute name="name"/>
  <cc:attribute name="password"/>
  <cc:attribute name="actionListener"
      method-signature="void action(javax.faces.event.Event)"
      targets="ccForm:loginButton"/>
</cc:interface>

<!-- IMPLEMENTATION -->
<cc:implementation>
  <h:form id="ccForm">
  <h:panelGrid columns="3">
    <h:outputText value="Name:" />
    <h:inputText value="#{cc.attrs.name}" id="name"/>
    <h:message for="name" style="color: red" />
    <h:outputText value="Password:" />
    <h:inputText value="#{cc.attrs.password}" id="password"/>
    <h:message for="password" style="color: red" />
  </h:panelGrid>

  <h:commandButton id="loginButton"
                   action="status"
                   value="submit"/>
  </h:form>
</cc:implementation>

The changes are highlighted in bold and explained below:

  • All the parameters are explicitly specified in <cc:interface> for clarity. The third parameter has a "targets" attribute referrring to "ccForm:loginButton".
  • In <cc:implementation>

    • The <h:form> in has "id" attribute. This is required such that the button within the form can be explicitly referenced.
    • <h:inputText> is now using #{cc.attrs.xxx} instead of #{user.xxx}. #{cc.attrs} is a default EL expression that is available for composite component authors and provide access to attributes of the current composite component. In this case #{cc.attrs} has "name" and "password" defined as attributes.
    • "actionListener" is an attach point for event listener, defined as a "method-signature" and describes the signature of a method pointed to by the expression.
    • <h:commandButton> has "id" attribute so that it can be clearly identified within the <h:form>.

The "user", "password", and "actionListener" are then passed as required attributes in the "using page" as:

<ez:loginPanel
    name="#{user.name}"
    password="#{user.password}"
    actionListener="#{userService.register}"/>

Now the "using page" can pass different "backing beans" and business method to be invoked when "submit" button is invoked.

The complete source code for this TOTD can be downloaded here.

How 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!

I realized TOTD #135 already explains how to author composite components. Hey, but this TOTD provides new information on how to attach event listeners :-)

Technorati: totd javaee6 glassfish jsf2 composite component facelets

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

October 27, 2010

Java EE 6 & GlassFish at Cloud Computing Expo, OTN Developer Days, Oredev, Java EE 6 Workshops, JavaOne Brasil in next 2 months!

Filed under: glassfish, javaee — arungupta @ 2:58 pm

I’ll be speaking on Java EE 6 & GlassFish at several events around the world in the next couple of months and here is a quick summary …

Cloud Computing Expo Santa Clara, CA Nov 1-4 Taking your Java EE 6 Apps on the Cloud (2:25pm on 11/2) register now!
OTN Developer Days New York City, NY Nov 4 2 sessions + 3 Hands-on Lab (10am – 4:30pm), FREE, register now!
Oredev Malmo, Sweden Nov 8-12 Java EE 6 hands-on workshop (8:50am on Tuesday), JPA 2 session (5:40 on Wednesday), Run! (11:20am on Thursday), register now!
Java EE 6 & GlassFish Workshop Czech Republic Nov 22-23 Organized by Oracle University, register now!
Java EE 6 & GlassFish Workshop Hungary Nov 25-26 Organized by Oracle University, register now!
Devignition Reston, Virginia Dec 3 Java EE 6 & GlassFish 3 session (4:20pm), Panel (5:20pm), Organized by NovaJUG, register now!
CEJUG Fortaleza, Brazil Dec 4 Session, 8pm, registration page coming soon!
JavaOne Sao Paulo, Brazil Dec 7-9 Several sessions, hands-on labs, Technical General Session, JavaOne Brazil main page: English, Portuguese, Follow #javaonebrasil and @oracledobrasil.

Lots of travel over the next couple of months … New York City, Sweden, Czech Repbulic, Hungary, Reston, Fortaleza (Brazil), Sao Paulo.

Looking forward to meet several of you. Where will I see/run with you ?

Technorati: conf oracltechnet otn devdays newyorkcity oredev malmo sweden javaone brazil

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot
Older Posts »

The views expressed on this blog are my own and do not necessarily reflect the views of Oracle.
Powered by WordPress