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

Thursday Jul 05, 2012

Jersey 2 in GlassFish 4 - First Java EE 7 Implementation Now Integrated (TOTD #182)


The JAX-RS 2.0 specification released their Early Draft 3 recently. One of my earlier blogs explained as the features were first introduced in the very first draft of the JAX-RS 2.0 specification. Last week was another milestone when the first Java EE 7 specification implementation was added to GlassFish 4 builds.

Jakub blogged about Jersey 2 integration in GlassFish 4 builds. Most of the basic functionality is working but EJB, CDI, and Validation are still a TBD. Here is a simple Tip Of The Day (TOTD) sample to get you started with using that functionality.
  1. Create a Java EE 6-style Maven project

    mvn archetype:generate
    -DarchetypeGroupId=org.codehaus.mojo.archetypes
    -DarchetypeArtifactId=webapp-javaee6 -DgroupId=example
    -DartifactId=jersey2-helloworld -DarchetypeVersion=1.5
    -DinteractiveMode=false

    Note, this is still a Java EE 6 archetype, at least for now.
  2. Open the project in NetBeans IDE as it makes it much easier to edit/add the files. Add the following <repositories>

    <repositories>
    <repository>
    <id>snapshot-repository.java.net</id>
    <name>Java.net Snapshot Repository for Maven</name>
    <url>https://maven.java.net/content/repositories/snapshots/</url>
    <layout>default</layout>
    </repository>
    </repositories>

  3. Add the following <dependency>s

    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.10</version>
    <scope>test</scope>
    </dependency>
    <dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.0-m09</version>
    <scope>test</scope>
    </dependency>
    <dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.0-m05</version>
    <scope>test</scope>
    </dependency>
    The complete list of Maven coordinates for Jersey2 are available here. An up-to-date status of Jersey 2 can always be obtained from here.
  4. Here is a simple resource class:

    @Path("movies")
    public class MoviesResource {

    @GET
    @Path("list")
    public List<Movie> getMovies() {
    List<Movie> movies = new ArrayList<Movie>();

    movies.add(new Movie("Million Dollar Baby", "Hillary Swank"));
    movies.add(new Movie("Toy Story", "Buzz Light Year"));
    movies.add(new Movie("Hunger Games", "Jennifer Lawrence"));

    return movies;
    }
    }
    This resource publishes a list of movies and is accessible at "movies/list" path with HTTP GET. The project is using the standard JAX-RS APIs.

    Of course, you need the trivial "Movie" and the "Application" class as well. They are available in the downloadable project anyway.
  5. Build the project

    mvn package

    And deploy to GlassFish 4.0 promoted build 43 (download, unzip, and start as "bin/asadmin start-domain") as

    asadmin deploy --force=true target/jersey2-helloworld.war

  6. Add a simple test case by right-clicking on the MoviesResource class, select "Tools", "Create Tests", and take defaults. Replace the function "testGetMovies" to
    @Test
    public void testGetMovies() {
    System.out.println("getMovies");
    Client client = ClientFactory.newClient();
    List<Movie> movieList = client.target("http://localhost:8080/jersey2-helloworld/webresources/movies/list")
    .request()
    .get(new GenericType<List<Movie>>() {});
    assertEquals(3, movieList.size());
    }

    This test uses the newly defined JAX-RS 2 client APIs to access the RESTful resource.
  7. Run the test by giving the command "mvn test" and see the output as

    -------------------------------------------------------
    T E S T S
    -------------------------------------------------------
    Running example.MoviesResourceTest
    getMovies
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.561 sec

    Results :

    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

GlassFish 4 contains Jersey 2 as the JAX-RS implementation. If you want to use Jersey 1.1 functionality, then Martin's blog provide more details on that. All JAX-RS 1.x functionality will be supported using standard APIs anyway. This workaround is only required if Jersey 1.x functionality needs to be accessed.

The complete source code explained in this project can be downloaded from here.

Here are some pointers to follow

Provide feedback on Jersey 2 to users@jersey.java.net and JAX-RS specification to users@jax-rs-spec.java.net.

Monday Jun 18, 2012

WebSocket and Java EE 7 - Getting Ready for JSR 356 (TOTD #181)


WebSocket is developed as part of HTML 5 specification and provides a bi-directional, full-duplex communication channel over a single TCP socket. It provides dramatic improvement over the traditional approaches of Polling, Long-Polling, and Streaming for two-way communication. There is no latency from establishing new TCP connections for each HTTP message.

There is a WebSocket API and the WebSocket Protocol. The Protocol defines "handshake" and "framing". The handshake defines how a normal HTTP connection can be upgraded to a WebSocket connection. The framing defines wire format of the message. The design philosophy is to keep the framing minimum to avoid the overhead. Both text and binary data can be sent using the API.

WebSocket may look like a competing technology to Server-Sent Events (SSE), but they are not. Here are the key differences:
  1. WebSocket can send and receive data from a client. A typical example of WebSocket is a two-player game or a chat application. Server-Sent Events can only push data data to the client. A typical example of SSE is stock ticker or news feed. With SSE, XMLHttpRequest can be used to send data to the server.
  2. For server-only updates, WebSockets has an extra overhead and programming can be unecessarily complex. SSE provides a simple and easy-to-use model that is much better suited.
  3. SSEs are sent over traditional HTTP and so no modification is required on the server-side. WebSocket require servers that understand the protocol.
  4. SSE have several features that are missing from WebSocket such as automatic reconnection, event IDs, and the ability to send arbitrary events.
    1. The client automatically tries to reconnect if the connection is closed. The default wait before trying to reconnect is 3 seconds and can be configured by including "retry: XXXX\n" header where XXXX is the milliseconds to wait before trying to reconnect.
    2. Event stream can include a unique event identifier. This allows the server to determine which events need to be fired to each client in case the connection is dropped in between.
    3. The data can span multiple lines and can be of any text format as long as EventSource message handler can process it.
  5. WebSockets provide true real-time updates, SSE can be configured to provide close to real-time by setting appropriate timeouts.
OK, so all excited about WebSocket ? Want to convert your POJOs into WebSockets endpoint ?

websocket-sdk and GlassFish 4.0 is here to help!

The complete source code shown in this project can be downloaded here.

On the server-side, the WebSocket SDK converts a POJO into a WebSocket endpoint using simple annotations. Here is how a WebSocket endpoint will look like:

@WebSocket(path="/echo")
public class EchoBean {

@WebSocketMessage
public String echo(String message) {
return message + " (from your server)";
}
}

In this code
  1. "@WebSocket" is a class-level annotation that declares a POJO to accept WebSocket messages. The path at which the messages are accepted is specified in this annotation.
  2. "@WebSocketMessage" indicates the Java method that is invoked when the endpoint receives a message. This method implementation echoes the received message concatenated with an additional string.

The client-side HTML page looks like

<div style="text-align: center;">
<form action="">
<input onclick="send_echo()" value="Press me" type="button">
<input id="textID" name="message" value="Hello WebSocket!" type="text"><br>
</form>
</div>
<div id="output"></div>

WebSocket allows a full-duplex communication. So the client, a browser in this case, can send a message to a server, a WebSocket endpoint in this case. And the server can send a message to the client at the same time. This is unlike HTTP which follows a "request" followed by a "response". In this code, the "send_echo" method in the JavaScript is invoked on the button click. There is also a <div> placeholder to display the response from the WebSocket endpoint.

The JavaScript looks like:

<script language="javascript" type="text/javascript">
var wsUri = "ws://localhost:8080/websockets/echo";
var websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };

function init() {
output = document.getElementById("output");
}

function send_echo() {
websocket.send(textID.value);
writeToScreen("SENT: " + textID.value);
}

function onOpen(evt) {
writeToScreen("CONNECTED");
}

function onMessage(evt) {
writeToScreen("RECEIVED: " + evt.data);
}

function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}

function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}

window.addEventListener("load", init, false);
</script>

In this code
  1. The URI to connect to on the server side is of the format

    ws://<HOST>:<PORT>/websockets/<PATH>

    "ws" is a new URI scheme introduced by the WebSocket protocol. <PATH> is the path on the endpoint where the WebSocket messages are accepted. In our case, it is

    ws://localhost:8080/websockets/echo

    WEBSOCKET_SDK-1 will ensure that context root is included in the URI as well.
  2. WebSocket is created as a global object so that the connection is created only once. This object establishes a connection with the given host, port and the path at which the endpoint is listening.
  3. The WebSocket API defines several callbacks that can be registered on specific events. The "onopen", "onmessage", and "onerror" callbacks are registered in this case. The callbacks print a message on the browser indicating which one is called and additionally also prints the data sent/received.
  4. On the button click, the WebSocket object is used to transmit text data to the endpoint. Binary data can be sent as one blob or using buffering.
The HTTP request headers sent for the WebSocket call are:

GET ws://localhost:8080/websockets/echo HTTP/1.1
Origin: http://localhost:8080
Connection: Upgrade
Sec-WebSocket-Extensions: x-webkit-deflate-frame
Host: localhost:8080
Sec-WebSocket-Key: mDbnYkAUi0b5Rnal9/cMvQ==
Upgrade: websocket
Sec-WebSocket-Version: 13

And the response headers received are

Connection:Upgrade
Sec-WebSocket-Accept:q4nmgFl/lEtU2ocyKZ64dtQvx10=
Upgrade:websocket
(Challenge Response):00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00

The headers are shown in Chrome as shown below:


The complete source code shown in this project can be downloaded here.

The builds from websocket-sdk are integrated in GlassFish 4.0 builds. Would you like to live on the bleeding edge ? Then follow the instructions below to check out the workspace and install the latest SDK:

  1. Check out the source code

    svn checkout https://svn.java.net/svn/websocket-sdk~source-code-repository
  2. Build and install the trunk in your local repository as:

    mvn install
  3. Copy "./bundles/websocket-osgi/target/websocket-osgi-0.3-SNAPSHOT.jar" to "glassfish3/glassfish/modules/websocket-osgi.jar" in your GlassFish 4 latest promoted build. Notice, you need to overwrite the JAR file.
Anybody interested in building a cool application using WebSocket and get it running on GlassFish ? :-)

This work will also feed into JSR 356 - Java API for WebSocket.

On a lighter side, there seems to be less agreement on the name. Here are some of the options that are prevalent:
I prefer "WebSocket" as that seems to be most common usage and used by the W3C API as well. What do you use ?

Sunday Jul 10, 2011

TDC 2011 Trip Report


Keep reading for the conclusive blog entry on my Brazil trip. After FISL12, Java Noroeste, Brasilia, and Goiania the trip concluded with The Developers Conference 2011 (TDC) in Sao Paulo.


The TDC, as the name says, is a developer conference organized by Global Code, Brazil's largest trainer of Java developers and several other IT courses. They offer courses in Core Java, Web, Design Patterns, Java EE 6, Robotics, and several other topics and have offices all around Brazil. There were about 2000+ attendees over 5 days and spread across multiple tracks covering Java, Java EE, Web, Python, PHP, .NET, Ruby, Cloud, and several other topics.

I gave two talks and a NetBeans-driven hackathon. The slides for the presos are available below:





The first talk had about 200 attendees and the second one had approx 80 attendees. And the NetBeans-driven Java EE 6/GlassFish hackathon code can be downloaded here.

Yara Senger (one of the main organizers of the conference) was telling me that several attendees gave her extremely positive feedback about my talks, this is always good to know. She also told me that attendees from other tracks left their session to attend these talks. Here are couple of feedbacks from twitterverse #tdc2011:

#TDC2011 Palestra do @arungupta muito bom

@esdrasbb Indiano da Oracle = @arungupta? O cara é bom! #GlassfishGuy

I'm certainly looking forward to participate in TDC at other locations/times.

Check out some pictures from the TDC 2011 ....








And, as always, the complete album:



I'm certainly glad to be back home after being on the road for 15 days but it was a very enjoyable and a valuable experience!

Saturday Jul 02, 2011

FISL12 Trip Report - Special Appearance by "Javali" and "Code Monkey"


FISL is the biggest open source conference in Latin America and had about 7000 participants in the FISL 12 that concluded earlier this week. This was my third consecutive year (2010 and 2009) and as every year the conference was packed with lectures, workshops, demonstrations, booths, presentations, and lot more.

Anil Gaur, VP of Java EE Platform and GlassFish, gave a presentation on "Oracle GlassFish Server: A flexibly, light-weight, and production-ready Java EE 6". There were about 100 attendees in the theatre-style seating. The talk gave a great overview of the explosive growth happening in the GlassFish community on all fronts. It also gave an overview of how GlassFish is the first platform to provide clustering and high-availability for Java EE 6 applications with full commercial support from Oracle. The 2-instance session failover demo that I started to show in the talk did not work completely and my digging is still going on but here is a basic analysis so far.
  • The GlassFish High Availability depends on GMS which further relies on UDP Multicast (more details here). I've shown this demo on my previous machine (a Macbook) multiple times and in different configurations of with or without an IP address. But multicast is enabled by default on Macs. However Natty Narwhal does not seem to be configured that way, at least by default. And so even though I could create a cluster, the application with HA enabled could not be deployed. 
  • The GlassFish 3.1 Certification Matrix provides a complete list of supported platform and Ubutnu 10.10, not 11.04 (demo machine), is listed as a supported developer platform. There might be bugs in this newest release of Ubuntu or how Grizzly picks a network interface for binding when there is no bind interface address setup and the default interface (eth0) is not connected.
More details on how this will eventually get fixed in a later blog.

Other than that I gave two presentations on "The Java EE 7 Platform: Developing for the Cloud" and "Running your Java EE 6 Applications in the Cloud: and the slides are now available:


There were about 60+ attendees for the 9am talk on Java EE 7. Check out more details about the evolution of Java EE 7 at javaee-spec.java.net. All the component JSRs have their independent pages as well with the format: <component>-spec.java.net where <component> is "jpa", "ejb", "servlet" and "jsf".


The second preso turned out a lot more fun than originally planned with the two surprise co-speakers - "Javali" and "Code Monkey". The audience seem to enjoy the interesting conversation as part of the talk, pictures below. There is usual engaging with the community, talking to folks at the booth, explaining Oracle's open source strategy, and customer visits.

Also, check out Java Spotlight podcast #36 where Anil Gaur talks about GlassFish 3.1.

There were several other talks given by Oracle employees covering JDK 7, NetBeans, OpenJDK, MySQL and other open source offerings.

Check out some pictures from the event:

















And, as always, the evolving album:


See you next year!

Now on to Sao Jose do Rio Preto ...

Tuesday Mar 08, 2011

TOTD #158: Java EE 7 JSRs: JPA 2.1, JAX-RS 2.0, Servlets 3.1, EL 3.0, JMS 2.0, JSF 2.2, CDI 1.1, Bean Validation 1.1

Java EE 6 specifications were approved on Dec 1st 2009 and the corresponding binaries and TCK were released on Dec 10th 2009. Oracle GlassFish Server 3.1 added Clustering and High Availability capabilities to Java EE 6 applications, and many other features, and was released on Feb 28th 2011. Now the wheels are chugging along and several Java EE 7 JSRs have been filed. This Tip Of The Day (TOTD) provides a summary of propopsed features in each of the JSR (make sure to read the proposed JSR for the complete list) ...

Java EE 7 (JSR 342)

  • The main theme is to easily run applications on private or public clouds
  • Application metadata descriptor to describe PaaS execution environment such as multi-tenancy, resources sharing, quality-of-service, and dependencies between applications
  • Embrace latest standards like WebSocket, HTML5, JSON and have a standards-based API for each one of them
  • Remove inconsistencies between Managed Beans, EJB, Servlets, JSF, CDI, and JAX-RS
  • Inclusion of JAX-RS 2.0 in Web Profile
  • Technology Refresh for several existing technologies (more on this below) and possible inclusion of Concurrency Utilities for Java EE (JSR 236) and JCache (JSR 107)
  • Spec leads: Roberto Chinnici, Bill Shannon (Oracle)

JPA 2.1 (JSR 338)

  • Multi-tenancy
  • Support for stored procedures and vendor function
  • Update and Delete Critieria queries, JPQL <-> Critieria mapping
  • Support for schema generation
  • Persistence Context synchronization
  • Dynamic definition of PU
  • Additional event listeners
  • Approved by the JCP EC, watch the progress at jpa-spec@java.net, spec lead: Linda DeMichiel (Oracle)

JAX-RS 2.0 (JSR 339)

  • Client API - low level using builder pattern and a higher level on top of that
  • Hypermedia
  • MVC Pattern - Resource controller and pluggable viewing technology
  • Form or Query parameter validation using Bean Validation
  • Closer integration with @Inject, etc
  • Server-side asynchronous request processing
  • Server-side content negotiation
  • Approved by the JCP EC, watch progress at jax-rs-spec@java.net, spec leads: Roberto Chinnici, Marek Potociar (Oracle)

Servlets 3.1 (JSR 340)

  • Multi tenancy for security, session, resources, etc.
  • Asynchronous IO based on NIO2
  • Simplfiied asynchronous Servlets
  • Utilize Java EE concurrency utilities
  • Enable support for WebSockets
  • Spec leads: Shing Wai Chan, Rajiv Mordani (Oracle)

Expression Language 3.0 (JSR 341)

  • Separate ELContext into parsing and evaluation contexts
  • Customizable EL coercion rules
  • Reference static methods and members directly in EL expressions
  • Adding operators like equality, string concatenation, and sizeof etc.
  • Integration with CDI such as generating events before/during/after the expressions are evaluated
  • Spec lead: Kin-man Chung (Oracle)

Java Message Server 2.0 (JSR 343)

  • Ease of development
  • Remove/Clarify ambiguities in the existing specification
  • Integration with CDI
  • Clarification of the relationship between JMS and other Java EE specs
  • A new mandatory API to allow any JMS provider to be integrated with any Java EE container
  • Spec lead: Nigel Deakin (Oracle)

Java Server Faces 2.2 (JSR 344)

  • Ease of Development - make cc:interface in composite components optional, shorthand URLs for Facelet tag libraries, integration with CDI
  • Support implementation of Portlet Bridge 2.0 (JSR 329)
  • Support for HTML5 features, Flow management, Listener for page navigation events, and new components like FileUpload and BackButton
  • Spec lead: Ed Burns (Oracle)

CDI 1.1 (details - JSR TBD)

  • Global ordering of interceptors and decorators
  • API for managing built-in contexts
  • Embedded mode to startup outside Java EE container
  • Injection for static members such as loggers
  • Send Servlet events as CDI event
  • Spec lead: Pete Muir (RedHat)

Bean Validation 1.1 (details - JSR TBD)

  • Integration with other specs
    • JAX-RS: Validate parameters on HTTP calls
    • JAXB: Convert into XML schema descriptor
    • JPA: DDL Generation
  • Method level validation
  • Apply constrains on group collection
  • Spec lead: Emmanuel Bernard (RedHat)

JPA 2.1 and JAX-RS 2.0 are already approved by the JCP Executive Committee and others are going through a review ballot. And then the EG needs to be formed, specifications and implementations delivered so its a long road ahead. But hey, this group has delivered every time in the past and we'll do it again :-) And this time all the JSRs are run more transparently and some of the highlights on that front are:

  • Names of the EG members are publicly visible
  • EG business reported on publicly readable alias
  • Schedule is public, current and updated regularly
  • Public can read/write to a wiki to discuss the status so far
  • Discussion board on jcp.org
  • Public read-only issue tracker

Here is a latest slide deck I delivered at OTN Developer Day Boston last week giving a good mix of Java EE 6 and providing an insight into the future:

I expect this slide deck to stay current and add more details as they become available, so stay tuned ...

Technorati: totd javaee6 javaee7 glassfish jcp jsr

Monday Mar 07, 2011

OTN Developer Day Boston 2011 - Slides & Trip Report

OTN Developer Day Boston concluded last week with about 70 developers/architects/consultant attending 20 sessions in 4 tracks (Server, Desktop, Java SE Platform, Mobile & Embedded). I delivered 2 technical sessions + 2 hands-on labs.

The first session explained the value proposition of Java EE 6 and the key themes of ease-of-use, simplicity, and extensiblity. With several Java EE 7 JSRs recently released (more on this in a subsequent blog) I added several slides on each one of them. Jump to slide #34 in the following slide deck to see the highlights on upcoming feature set in Java EE 7.

This session was followed by a hands-on lab showcasing how EJB 3.1 + JAX-RS 1.1 can be used to build a simple web application. The second technical session of the day explained the recently released GlassFish 3.1 Clustering, High Availability, and a myriad of features to boost your Java EE 6 deployment. A comprehensive list of blogs will walk you through each and every feature in detail.

The GlassFish 3.1 slides are available below:

Boston 2011 OTN Developer Days - GlassFish 3.1

The last session of the day (for me) was another hands-on lab explaining how JSF 2 + CDI can be used effectively to create a compelling web application in a matter of few minutes. The last session in Server track was "Developer Experience, WebLogic Server, and Java EE 6" by Will Lyons. A replay of this and many other related talks from OTN Virtual Developer Day are available in a replay here.

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

I still need to locate my camera after the trip and so the pictures will have to wait this time :-)

Technorati: conf otn devdays boston javaee6 javaee7 glassfish

Tuesday Jan 11, 2011

JAX-RS 2.0 and JPA 2.1 JSRs filed ... Java EE 7 moves forward!

JSR 338 (JPA 2.1) and JSR 339 (JAX-RS 2.0) are the first formal steps in moving Java EE 7 platform forward!

The key features considered in scope of JPA 2.1 are:

  • Support for the use of custom types and transformation methods in object/relational mapping.
  • Support for the use of "fetch groups" and/or "fetch plans" to provide further control over data that is fetched, detached, copied, and/or used in merging.
  • Support for the specification of immutable attributes and readonly entities.
  • Support for user-configurable naming strategies for use in O/R mapping and metamodel generation.
  • More flexibility in the use of generated values; support for UUID generator type.
  • Additional mapping metadata to provide better standardization for schema generation.
  • Support for multitenancy.
  • Additional event listeners and callback methods; availability of entity manager to callbacks.
  • Methods for dirty detection.
  • Improved ability to control persistence context synchronization.
  • Additional unwrap methods to support use of vendor extensions.
  • Support for dynamic definition of persistence unit, including object/relational mapping information.
  • Extension of metamodel API to object/relational mapping information.
  • Improvements to the Java Persistence query language and criteria APIs

More details in JSR 338. Click here if you are interested in joining this Expert Group.

The key features considered in scope of JAX-RS 2.0 are:

  • Client API - a low-level using a builder pattern and a higher level leveraging the former one
  • Hypermedia processing on client and server
  • MVC architecture compatible with JAX-RS programming model
  • Integration with Bean Validation for parameter validation
  • Tighter integration with JSR 330 annotations, such as @Inject
  • Asynchronous request processing
  • Sophisiticated server-side content negotiation
  • More ease-of-development following DRY principles

More details in JSR 339. Click here if you are interested in joining this Expert Group. This Expert Group will have a public observer alias to monitor discussions.

The JSR ballot closes on Jan 24, 2011. After the JSRs are approved the Expert Groups start discussion on each and every item of the proposal. And you'll start seeing the promoted builds and integrations into GlassFish after that.

Stay tuned to hear details as Java EE 7 continues its march forward. In the meanwhile, you can download GlassFish 3.1 promoted build (soon to be final) that provides full Java EE 6 functionality along with centralized administration and high availability.

Technorati: javaee7 glassfish jaxrs jpa restful persistence

About

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

Stay Connected