Wednesday Dec 26, 2012

Simple JMS 2.0 Sample - @JMSDestinationDefinition and Synchronous Message Receive: TOTD #191


JMS 2.0 Early Draft - Simplified API Sample Code explained some of the changes that are made in JMS 2.0 to "catch up" with all the changes in the Java SE and EE platform over the past few years. The main goals of JMS 2.0 are:
  • Changes to improve ease-of-development
  • Clarification of relationship between JMS and other Java EE specifications
  • Definition of a new mandatory API to allow any JMS provider to be integrated with any other Java EE Application Server
  • Other enhancements as requested by the community
This Tip Of The Day (TOTD) will explain a simple sample showing how to send a message and receive it synchronously. The complete source code for the sample can be downloaded here.

This is a Stateless EJB that has a single method to send a message.

@Stateless
public class MessageSender {

@Inject
JMSContext context;

@Resource(mappedName="java:global/jms/myQueue")
Queue queue;

public void sendMessage(String message) {
context.createProducer().send(queue, message);
}
}
In this code:
  • JMSContext is a new interface introduced in the simplified API in JMS 2.0. This combines in a single object the functionality of two separate objects from the JMS 1.1 API: a Connection and a Session.

    A JMSContext may be injected in the Java EE web and EJB containers using the @Inject annotation. A JMSContext created in this way is described as being container-managed. A container-managed JMSContext will be closed automatically by the container. Applications running in the Java EE web and EJB containers are not permitted to create more than one active session on a connection. This allows to combine them in a single object offering a simpler API. This is the recommended way for creating JMS context in Java EE applications.

    A JMSContext may be created by calling one of the createContext methods on a ConnectionFactory. A JMSContext that is created this way is described as being application-managed. An application-managed JMSContext must be closed when no longer needed by calling its close method. Applications running in a Java SE environment or in the Java EE application client container are permitted to create multiple active sessions on the same connection. This allows the same physical connection to be used in multiple threads simultaneously. The createContext method is recommended to create JMSContext in such applications.
  • The Java EE Platform requires a preconfigured JMS ConnectionFactory accessible to the application under the JNDI name:
    java:comp/DefaultJMSConnectionFactory
    The annotation @JMSConnectionFactory may be used to specify the JNDI lookup name of the ConnectionFactory used to create the JMSContext as:
    @Inject
    @JMSConnectionFactory("java:comp/DefaultJMSConnectionFactory")
    JMSContext context;
    If no lookup name is specified or the @JMSConnectionFactory is omitted then the platform default JMS connection factory will be used. The above code fragment is equivalent to:
    @Inject
    JMSContext context;
  • @Resource defines a dependency on a resource needed by the application. In this case, it specifies the JNDI name of the destination to which the message needs to be sent.
  • When an application needs to send messages it uses the createProducer method to create JMSProducer which provides methods to configure and send messages. The various setProperty methods are used to set property on the message being sent. There are several other methods like setPriority, setDeliveryDelay, and setTimeToLive to set other quality-of-service attributes for the message being sent.

    Messages may be sent synchronously or asynchronously. Synchronous messages are sent using one of the send methods. Asynchronous messages are sent using setAsync method and assigning a CompletionListener. When the message has been successfully sent the JMS provider invokes the callback method onCompletion on the CompletionListener object. If the message is not sent for some reason or an acknowledgement from the remote JMS server is not received then onException callback method is called. An asynchronous send is not permitted in a Java EE application.

This is a Stateless EJB that has a single method to receive the message synchronously.

@Stateless
public class MessageReceiverSync {

@Inject
private JMSContext context;

@Resource(mappedName="java:global/jms/myQueue")
Queue myQueue;

public String receiveMessage() {
String message = context.createConsumer(myQueue).receiveBody(String.class, 1000);
return "Received " + message;
}
}

In this code:
  • JMSContext referring to the preconfigured JMS ConnectionFactory is injected by the container.
  • @Resource defines a dependency on the JMS destination on which the message is received.
  • When an application needs to receive messages it uses one of the several createConsumer or createDurableConsumer methods to create a JMSConsumer. createConsumer creates a non-durable subscription on the specified destination. This means that a client will only see the messages published on the destination when the subscriber is active. If the subscriber is not active, it is missing messages published on the destination. createDurableConsumer creates an unshared durable subscription of a specified topic and creates a consumer on that subscription. This allows the subscriber will receive all messages published on a topic, including the ones published when there is no active consumer associated with it. The JMS provider retains a record of this durable subscription and ensures that all messages from the topic's publishers are retained until they are delivered to, and acknowledged by, a consumer on this durable subscription or until they have expired.

    A JMSConsumer provides methods to receive messages either synchronously or asynchronously. receive methods are used for synchronous delivery of the messages. A MessageListener object may be registered with the client for asynchronous delivery of the messages. onMessage method of the MessageListener object are called as messages are received. Asynchronous delivery of messages will not work until MQ-264 is fixed.
Next is a Servlet that ties all the pieces together. It defines the JMS Destination and send and receive the message using the previously defined EJBs.

@JMSDestinationDefinition(name = "java:global/jms/myQueue",
resourceAdapterName = "jmsra",
className = "javax.jms.Queue",
destinationName="queue1234",
description="My Queue")
@WebServlet(urlPatterns = {"/TestServlet"})
public class TestServlet extends HttpServlet {

@EJB MessageSender sender;

@EJB MessageReceiverSync receiver;


void doGet(HttpServletRequest request, HttpServletResponse response) {
. . .
String m = "Hello there";
sender.sendMessage(m);
out.format("Message sent: %1$s.<br>", m);
out.println("Receiving message...<br>");
String message = receiver.receiveMessage();
out.println("Message received: " + message);
. . .
}
In this code:
  • @JMSDestinationDefinition defines the JMS destination. The name attribute defines the JNDI name of the destination being defined, destinationName attribute defines the name of the queue or topic, and className attribute defines the JMS destination implementation class name.
  • doGet method uses the injected EJBs to send and receive the message.
The complete source code for the sample can be downloaded here. "mvn package" and deploy the generated WAR file.

Download GlassFish 4 build 68 onwards and try this sample today!

The latest progress on JMS 2.0 can be tracked at:

Help us make JMS 2.0 better, simpler, easier to use. Join users@jms-spec and contribute!

Friday Dec 21, 2012

JavaOne 2013 Russia, India, China, USA: Save the Date


JavaOne

Moscow, Russia: April 23-24, 2013*

Hyderabad, India: May 8-9, 2013*

Shanghai, China: Jul 23-25, 2013*

San Francisco, USA: Sep 22-26, 2013*

* The dates are subject to change.

Venue, Agenda, CFP, and other details to come later.

Did you know that recording of all Technical Sessions from JavaOne San Francisco 2012 is available ? Watch them there!


Wednesday Dec 19, 2012

Adopt-a-JSR for Java EE 7 - Getting Started


Adopt-a-JSR is an initiative started by JUG leaders to encourage JUG members to get involved in a JSR, in order to increase grass roots participation. This allows JUG members to provide early feedback to specifications before they are finalized in the JCP. The standards in turn become more complete and developer-friendly after getting feedback from a wide variety of audience. adoptajsr.org provide more details about the logistics and benefits for you and your JUG. A similar activity was conducted for OpenJDK as well. Markus Eisele also provide a great introduction to the program (in German).

Java EE 7 (JSR 342) is scheduled to go final in Q2 2013. There are several new JSRs that are getting included in the platform (e.g. WebSocket, JSON, and Batch), a few existing ones are getting an overhaul (e.g. JAX-RS 2 and JMS 2), and several other getting minor updates (e.g. JPA 2.1 and Servlets 3.1). Each Java EE 7 JSR can leverage your expertise and would love your JUG to adopt a JSR.

What does it mean to adopt a JSR ?
  1. Your JUG is going to identify a particular JSR, or multiple JSRs, that is of interest to the JUG members. This is mostly done by polling/discussing on your local JUG members list.
  2. Your JUG will download and review the specification(s) and javadocs for clarity and completeness. The complete set of Java EE 7 specifications, their download links, and EG archives are listed here. glassfish.org/adoptajsr provide specific areas where different specification leads are looking for feedback.
  3. Your JUG can then think of a sample application that can be built using the chosen specification(s). An existing use case (from work or a personal hobby project) may be chosen to be implemented instead. This is where your creativity and uniqueness comes into play.
Most of the implementations are already integrated in GlassFish 4 and others will be integrated soon. You can also explore integration of multiple technologies and provide feedback on the simplicity and ease-of-use of the programming model. Especially look for integration with existing Java EE technologies and see if you find any discrepancies. Report any missing features that may be included in future release of the specification.

The most important part is to provide feedback by filing bugs on the corresponding spec or RI project. Any thing that is not clear either in the spec or implementation should be filed as a bug. This is what will ensure that specification and implementation leads are getting the required feedback and improving the quality of the final deliverable of the JSR.

How do I get started ?

A simple way to get started can be achieved by following S.M.A.R.T. as explained below.

Specific Identify who all will be involved ? What would you like to accomplish ? For example, even though building a sample app will provide real-world validity of the API but because of time constraints you may identify that reviewing the specification and javadocs only can be accomplished. Establish a time frame by which the activities need to be complete.
Measurable Define a success for metrics. For example, this could be the number of bugs filed. Remember, quality of bugs is more important that quantity of bugs. Define your end goal, for example, reviewing 4 chapters of the specification or completing the sample application. Create a dashboard that will highlight your JUG's contribution to this effort.
Attainable Make sure JUG members understand the time commitment required for providing feedback. This can vary based upon the level of involvement (any is good!) and the number of specifications picked. adoptajsr.org defines different categories of involvement. Once again, any level of involvement is good. Just reviewing a chapter, a section, or javadocs for your usecase is helpful.
Relevant Pick JSRs that JUG members are willing and able to work. If the JUG members are not interested then they might loose motivation half-way through. The "able" part is tricky as you can always stretch yourself and learn a new skill ;-)
Time-bound Define a time table of activities with clearly defined tasks. A tentative time table may look like:

Dec 25: Discuss and agree upon the specifications with JUG
Jan 1: Start Adopt-a-JSR for Java EE 7
Jan 15: Initial spec reading complete. Keep thinking through the application that will be implemented.
Jan 22: Early design of the sample application is ready
Jan 29: JUG members agree upon the application
Next 4 weeks: Implement the application

Of course, you'll need to alter this based upon your commitment. Maintaining an activity dashboard will help you monitor and track the progress.

Make sure to keep filing bugs through out the process!

12 JUGs from around the world (SouJava, Campinas JUG, Chennai JUG, London Java Community, BeJUG, Morocco JUG, Peru JUG, Indonesia JUG, Congo JUG, Silicon Valley JUG, Madrid JUG, and Houston JUG) have already adopted one of the Java EE 7 JSRs. I'm already helping some JUGs bootstrap and would love to help your JUG too.

What are you waiting for ?



Tuesday Dec 18, 2012

What's new in Servlet 3.1 ? - Java EE 7 moving forward


Servlet 3.0 was released as part of Java EE 6 and made huge changes focused at ease-of-use. The idea was to leverage the latest language features such as annotations and generics and modernize how Servlets can be written. The web.xml was made as optional as possible. Servet 3.1 (JSR 340), scheduled to be part of Java EE 7, is an incremental release focusing on couple of key features and some clarifications in the specification.

The main features of Servlet 3.1 are explained below:
  • Non-blocking I/O - Servlet 3.0 allowed asynchronous request processing but only traditional I/O was permitted. This can restrict scalability of your applications. Non-blocking I/O allow to build scalable applications. TOTD #188 provide more details about how non-blocking I/O can be done using Servlet 3.1.
  • HTTP protocol upgrade mechanism - Section 14.42 in the HTTP 1.1 specification (RFC 2616) defines an upgrade mechanism that allows to transition from HTTP 1.1 to some other, incompatible protocol. The capabilities and nature of the application-layer communication after the protocol change is entirely dependent upon the new protocol chosen. After an upgrade is negotiated between the client and the server, the subsequent requests use the new chosen protocol for message exchanges. A typical example is how WebSocket protocol is upgraded from HTTP as described in Opening Handshake section of RFC 6455.

    The decision to upgrade is made in Servlet.service method. This is achieved by adding a new method: HttpServletRequest.upgrade and two new interfaces: javax.servlet.http.HttpUpgradeHandler and javax.servlet.http.WebConnection.

    TyrusHttpUpgradeHandler shows how WebSocket protocol upgrade is done in Tyrus (Reference Implementation for Java API for WebSocket).
  • Security enhancements
    • Applying run-as security roles to #init and #destroy methods
    • Session fixation attack by adding HttpServletRequest.changeSessionId and a new interface HttpSessionIdListener. You can listen for any session id changes using these methods.
    • Default security semantic for non-specified HTTP method in <security-constraint>
    • Clarifying the semantics if a parameter is specified in the URI and payload
  • Miscellaneous
    • ServletResponse.reset clears any data that exists in the buffer as well as the status code, headers. In addition, Servlet 3.1 will also clears the state of calling getServletOutputStream or getWriter.
    • ServletResponse.setCharacterEncoding: Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.
    • Relative protocol URL can be specified in HttpServletResponse.sendRedirect. This will allow a URL to be specified without a scheme. That means instead of specifying "http://anotherhost.com/foo/bar.jsp" as a redirect address, "//anotherhost.com/foo/bar.jsp" can be specified. In this case the scheme of the corresponding request will be used.
    • Clarification in HttpServletRequest.getPart and .getParts without multipart configuration.
    • Clarification that ServletContainerInitializer is independent of metadata-complete and is instantiated per web application.

A complete replay of What's New in Servlet 3.1: An Overview from JavaOne 2012 can be seen here (click on CON6793_mp4_6793_001 in Media).

Each feature will be added to the JSR subject to EG approval. You can share your feedback to users@servlet-spec.java.net.

Here are some more references for you:

Several features have already been integrated in GlassFish 4 Promoted Builds. Have you tried any of them ?

Here are some other Java EE 7 primers published so far:


And of course, more on their way! Do you want to see any particular one first ?

Wednesday Dec 12, 2012

WebSocket Samples in GlassFish 4 build 66 - javax.websocket.* package: TOTD #190


This blog has published a few blogs on using JSR 356 Reference Implementation (Tyrus) integrated in GlassFish 4 promoted builds.
  • TOTD #183: Getting Started with WebSocket in GlassFish
  • TOTD #184: Logging WebSocket Frames using Chrome Developer Tools, Net-internals and Wireshark
  • TOTD #185: Processing Text and Binary (Blob, ArrayBuffer, ArrayBufferView) Payload in WebSocket
  • TOTD #186: Custom Text and Binary Payloads using WebSocket
  • TOTD #189: Collaborative Whiteboard using WebSocket in GlassFish 4
The earlier blogs created a WebSocket endpoint as:
import javax.net.websocket.annotations.WebSocketEndpoint;

@WebSocketEndpoint("websocket")
public class MyEndpoint {
. . .
Based upon the discussion in JSR 356 EG, the package names have changed to javax.websocket.*. So the updated endpoint definition will look like:
import javax.websocket.WebSocketEndpoint;

@WebSocketEndpoint("websocket")
public class MyEndpoint {
. . .
The POM dependency is:
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.0-b09</version>
</dependency>

And if you are using GlassFish 4 build 66, then you also need to provide a dummy EndpointFactory implementation as:
import javax.websocket.WebSocketEndpoint;

@WebSocketEndpoint(value="websocket", factory=MyEndpoint.DummyEndpointFactory.class)
public class MyEndpoint {
 . . .   
class DummyEndpointFactory implements EndpointFactory {
    @Override
public Object createEndpoint() { return null; }
  }
}
This is only interim and will be cleaned up in subsequent builds. But I've seen couple of complaints about this already and so this deserves a short blog.

Have you been tracking the latest Java EE 7 implementations in GlassFish 4 promoted builds ?

Monday Dec 10, 2012

JavaOne Latin America 2012 is a wrap!


Third JavaOne in Latin America (2010, 2011) is now a wrap!

Like last year, the event started with a Geek Bike Ride. I could not attend the bike ride because of pre-planned activities but heard lots of good comments about it afterwards. This is a great way to engage with JavaOne attendees in an informal setting. I highly recommend you joining next time!

JavaOne Blog provides a a great coverage for the opening keynotes. I talked about all the great set of functionality that is coming in the Java EE 7 Platform. Also shared the details on how Java EE 7 JSRs are willing to take help from the Adopt-a-JSR program.

glassfish.org/adoptajsr bridges the gap between JUGs willing to participate and looking for areas on where to help. The different specification leads have identified areas on where they are looking for feedback. So if you are JUG is interested in picking a JSR, I recommend to take a look at glassfish.org/adoptajsr and jump on the bandwagon.




The main attraction for the Tuesday evening was the GlassFish Party. The party was packed with Latin American JUG leaders, execs from Oracle, and local community members. Free flowing food and beer/caipirinhas acted as great lubricant for great conversations. Some of them were considering the migration from Spring -> Java EE 6 and replacing their primary app server with GlassFish. Locaweb, a local hosting provider sponsored a round of beer at the party as well. They are planning to come with Java EE hosting next year and GlassFish would be a logical choice for them ;)








I heard lots of positive feedback about the party afterwards. Many thanks to Bruno Borges for organizing a great party!

Check out some more fun pictures of the party!

Next day, I gave a presentation on "The Java EE 7 Platform: Productivity and HTML 5" and the slides are now available:




With so much new content coming in the plaform:
  • Java Caching API (JSR 107)
  • Concurrency Utilities for Java EE (JSR 236)
  • Batch Applications for the Java Platform (JSR 352)
  • Java API for JSON (JSR 353)
  • Java API for WebSocket (JSR 356)

And JAX-RS 2.0 (JSR 339) and JMS 2.0 (JSR 343) getting major updates, there is definitely lot of excitement that was evident amongst the attendees. The talk was delivered in the biggest hall and had about 200 attendees.

Also spent a lot of time talking to folks at the OTN Lounge.

The JUG leaders appreciation dinner in the evening had its usual share of fun.






Day 3 started with a session on "Building HTML5 WebSocket Apps in Java". The slides are now available:


The room was packed with about 150 attendees and there was good interaction in the room as well. A collaborative whiteboard built using WebSocket was very well received. The following tweets made it more worthwhile:

A WebSocket speek, by @ArunGupta, was worth every hour lost in transit. #JavaOneBrasil2012, #JavaOneBr
@arungupta awesome presentation about WebSockets :)

The session was immediately followed by the hands-on lab "Developing JAX-RS Web Applications Utilizing Server-Sent Events and WebSocket". The lab covers JAX-RS 2.0, Jersey-specific features such as Server-Sent Events, and a WebSocket endpoint using JSR 356. The complete self-paced lab guide can be downloaded from here.

The lab was planned for 2 hours but several folks finished the entire exercise in about 75 mins. The wonderfully written lab material and an added incentive of Java EE 6 Pocket Guide did the trick ;-)






I also spoke at "The Java Community Process: How You Can Make a Positive Difference". It was really great to see several JUG leaders talking about Adopt-a-JSR program and other activities that attendees can do to participate in the JCP. I shared details about Adopt a Java EE 7 JSR as well.




The community keynote in the evening was looking fun but I had to leave in between to go through the peak Sao Paulo traffic time :)

Enjoy the complete set of pictures in the album:



Wednesday Dec 05, 2012

Concurrency Utilities for Java EE Early Draft (JSR 236)


Concurrency Utilities for Java EE is being worked as JSR 236 and has released an Early Draft. It provides concurrency capabilities to Java EE application components without compromising container integrity. Simple (common) and advanced concurrency patterns are easily supported without sacrificing usability.

Using Java SE concurrency utilities such as java.util.concurrent API, java.lang.Thread and java.util.Timer in a Java EE application component such as EJB or Servlet are problematic since the container and server have no knowledge of these resources. The JSR 236 enables concurrency largely by extending the Concurrency Utilities API developed under JSR-166. This also allows a consistency between Java SE and Java EE concurrency programming model. The threads so spawned are provided and managed by the container.

There are four main programming interfaces available:
  • ManagedExecutorService
  • ManagedScheduledExecutorService
  • ContextService
  • ManagedThreadFactory

ManagedExecutorService is a managed version of java.util.concurrent.ExecutorService. The implementations of this interface are provided by the container and accessible using JNDI reference:

<resource-env-ref>
  <resource-env-ref-name>
    concurrent/BatchExecutor
  </resource-env-ref-name>
  <resource-env-ref-type>
    javax.enterprise.concurrent.ManagedExecutorService
  </resource-env-ref-type>
<resource-env-ref>

and available as:

@Resource(name="concurrent/BatchExecutor")
ManagedExecutorService executor;

Its recommended to bind the JNDI references in the java:comp/env/concurrent subcontext.

The asynchronous tasks that need to be executed need to implement java.lang.Runnable or java.util.concurrent.Callable interface as:

public class MyTask implements Runnable {
public void run() {
// business logic goes here
}
}

OR

public class MyTask2 implements Callable<Date> {
  public Date call() {
// business logic goes here
  }
}

The task is then submitted to the executor using one of the submit method that return a Future instance. The Future represents the result of the task and can also be used to check if the task is complete or wait for its completion.

Future<String> future = executor.submit(new MyTask(), String.class);
. . .
String result = future.get();

The task would run on a separate thread provided and managed by the container.

Another example to submit tasks is:

class MyTask implements Callable<Long> { . . . }
class MyTask2 implements Callable<Date> { . . . }

ArrayList<Callable> tasks = new ArrayList<();
tasks.add(new MyTask());
tasks.add(new MyTask2());
List<Future<Object>> result = executor.invokeAll(tasks);

The ManagedExecutorService may be configured for different properties such as:

  • Hung Task Threshold: Time in milliseconds that a task can execute before it is considered hung
  • Pool Info
    • Core Size: Number of threads to keep alive
    • Maximum Size: Maximum number of threads allowed in the pool
    • Keep Alive: Time to allow threads to remain idle when # of threads > Core Size
    • Work Queue Capacity: # of tasks that can be stored in inbound buffer
  • Thread Use: Application intend to run short vs long-running tasks, accordingly pooled or daemon threads are picked

The specification does not mandate any configuration attributes. The above mentioned properties are only examples and may not be supported by all application servers.

ManagedScheduledExecutorService adds delay and periodic task running capabilities to ManagedExecutorService. The implementations of this interface are provided by the container and accessible using JNDI reference:

<resource-env-ref>
  <resource-env-ref-name>
    concurrent/BatchExecutor
  </resource-env-ref-name>
  <resource-env-ref-type>
    javax.enterprise.concurrent.ManagedExecutorService
  </resource-env-ref-type>
<resource-env-ref>

and available as:

@Resource(name="concurrent/timedExecutor")
ManagedExecutorService executor;

And then the tasks are submitted using submit, invokeXXX or scheduleXXX methods.

ScheduledFuture<?> future = executor.schedule(new MyTask(), 5, TimeUnit.SECONDS);

This will create and execute a one-shot action that becomes enabled after 5 seconds of delay.

More control is possible using one of the newly added methods:

MyTaskListener implements ManagedTaskListener {
  public void taskStarting(...) { . . . }
  public void taskSubmitted(...) { . . . }
  public void taskDone(...) { . . . }
  public void taskAborted(...) { . . . } }
ScheduledFuture<?> future =
executor.schedule(new MyTask(),
5,
TimeUnit.SECONDS,
new MyTaskListener());

Here, ManagedTaskListener is used to monitor the state of a task's future.

ManagedThreadFactory provides a method for creating threads for execution in a managed environment. A simple usage is:

@Resource(name="concurrent/myThreadFactory")
ManagedThreadFactory factory;
. . .
Thread thread = factory.newThread(new Runnable() { . . . });

concurrent/myThreadFactory is a JNDI resource.

There is lot of interesting content in the Early Draft, download it, and read yourself. The implementation will be made available soon and also be integrated in GlassFish 4 as well.

Some references for further exploration ...

About

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


Java EE 7 Samples

Stay Connected

Search

Archives
« December 2012 »
SunMonTueWedThuFriSat
      
1
2
3
4
6
7
8
9
11
13
14
15
16
17
20
22
23
24
25
27
28
29
30
31
     
Today