Monday Feb 18, 2013

JsonGenerator and JsonObjectBuilder - Streaming and Object API in Java API for JSON Processing (TOTD #205)


Java API for JSON Processing (JSR 353) cleared Public Review unanimously and is on its way to to standardization. There is still Proposed Final Draft and the final vote to come. As per the Java EE 7 schedule, the specification will be final on 4/15/2013. The implementation is already integrated in GlassFish 4 builds.

The API provides an Object Model (like DOM for XML) and Streaming API (like StAX for XML) to parse and generate JSON structure. Here is a table that provide code fragments for generating some common JSON:

JSON Object Model API Streaming API
{ }
JsonObject jsonObject =
     new JsonObjectBuilder().build();

new JsonWriter(System.out)
     .writeObject(jsonObject);

JsonGeneratorFactory factory =
     Json.createGeneratorFactory();

JsonGenerator gen =
     factory.createGenerator(System.out);

gen.writeStartObject().writeEnd();
{
  "apple":"red",
  "banana":"yellow"
}
new JsonObjectBuilder()
  .add("apple", "red")
  .add("banana", "yellow")
.build();
gen.writeStartObject()
     .write("apple", "red")
     .write("banana", "yellow")
   .writeEnd();
[
  { "apple":"red" },
  { "banana":"yellow" }
]
JsonArray jsonArray = new JsonArrayBuilder()
  .add(new JsonObjectBuilder()
          .add("apple","red"))

  .add(new JsonObjectBuilder()
          .add("banana","yellow"))

  .build();
gen.writeStartArray()
     .writeStartObject()
       .write("apple", "red")
     .writeEnd()
     .writeStartObject()
       .write("banana", "yellow")
     .writeEnd()
.writeEnd();
{
  "title":"The Matrix",
  "year":1999,
  "cast":[
    "Keanu Reaves",
    "Laurence Fishburne",
    "Carrie-Anne Moss"
  ]
}
new new JsonObjectBuilder()
  .add("title", "The Matrix")
  .add("year", 1999)
  .add("cast", new JsonArrayBuilder()
  .add("Keanu Reaves")
  .add("Laurence Fishburne")
  .add("Carrie-Anne Moss"))
.build();
gen.writeStartObject()
     .write("title", "The Matrix")
     .write("year", 1999)
     .writeStartArray("cast")
       .write("Keanu Reaves")
       .write("Laurence Fishburne")
       .write("Carrie-Anne Moss")
     .writeEnd()
   .writeEnd();

The source code for this sample can be downloaded here, try it with GlassFish 4 b76 or later.

Here are some more links for you to read further:

Wednesday Feb 13, 2013

@WebSocketClient in GlassFish 4 (TOTD #204)


Tyrus is the Reference Implementation for Java API for WebSocket (JSR 356) and is already integrated in GlassFish 4. The implementation is rapidly evolving and and adding support for different features already defined in the latest version of the specification.

The latest integration in GlassFish added support for creating Java-based WebSocket clients.

Any POJO can be made a WebSocket client by adding @WebSocketClient. A inbound message is received in a method annotated with @WebSocketMessage. Any method can be designated as lifecycle method by specifying @WebSocketOpen, @WebSocketClose, @WebSocketError. Here is a simple sample:

@WebSocketClient
public class MyClient {
@WebSocketOpen
public void onOpen(Session session) {
System.out.println("Connected to endpoint: " + session.getRemote());
try {
session.getRemote().sendString("Duke");
} catch (IOException ex) {
Logger.getLogger(MyClient.class.getName()).log(Level.SEVERE, null, ex);
}
}

@WebSocketMessage
public void processMessage(String message, Session session) {
System.out.println(getClass().getName() + ": " + message);
}
}

In this code, a message is sent to the connected WebSocket endpoint whenever the connection is initiated. An inbound message (coming from the server) is processed using processMessage method.

The endpoint code is pretty trivial:

@WebSocketEndpoint(value="/websocket", configuration=DefaultServerConfiguration.class)
public class MyEndpoint {

@WebSocketMessage
public String sayHello(String name) {
System.out.println(getClass().getName() + ": " + name);
return "Hello " + name;
}

}
The endpoint has a single method that receives the payload, appends a string and returns back as the response. Even though server is returning the response right away, the client views this as two separate messages, one outbound and the other one inbound. So any message-exchange-pattern such as request/response need to be specifically built using the application code. The configuration attribute, in this case, is optional and will be fixed in a subsequent release of Tyrus.

The client can bootstrap using Java SE or Java EE components as:

WebSocketContainer container = ContainerProvider.getWebSocketContainer();
String uri = "ws://localhost:8080" + request.getContextPath() + "/websocket";
container.connectToServer(MyClient.class, URI.create(uri));
The complete source code used in this Tip Of The Day (TOTD) is available here. It will run on the latest checked out version of GlassFish workspace, not a promoted build yet (bleeding edge eh ;-)

Please provide feedback on users@tyrus.java.net.

How are you going to use Java-based WebSocket client in your applications ?

Here are other Java EE 7 entries published on this blog so far:


Monday Feb 11, 2013

Create ManagedExecutorService, ManagedScheduledExecutorService, ManagedThreadFactory, ContextService in GlassFish 4 build 74 (TOTD #203)


Latest GlassFish 4 promoted build (74 at this time) has the first cut of Concurrency Utilities for Java EE (JSR 236) implementation integrated. An earlier blog provided an overview of the specification, lets see what can be actually done with this build.

This build introduce new commands to create ManagedExecutorService, ManagedScheduledExecutorService, ManagedThreadFactory, and ContextService.

A simple command execution as:

asadmin create-managed-executor-service concurrent/myExecutor
Managed executor service concurrent/myExecutor created successfully.
Command create-managed-executor-service executed successfully.

creates the configuration for a default ManagedExecutorService. Adding --help shows more details about the command:

create-managed-executor-service
    [--enabled=true]
    [--contextinfo=contextinfo]
    [--threadpriority=5]
    [--longrunningtasks=false]
    [--hungafterseconds=hungafterseconds]
    [--corepoolsize=0]
    [--maximumpoolsize=2147483647]
    [--keepaliveseconds=60]
    [--threadlifetimeseconds=0]
    [--taskqueuecapacity=2147483647]
    [--description=description]
    [--property=property]
    [--target=target]
    jndi_name

The created executor can then be injected into a Java EE component (say Servlet) as:

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

or looked up using JNDI as:

InitialContext ctx = new InitialContext();
ManagedExecutorService executor = (ManagedExecutorService) ctx.lookup("concurrent/myExecutor");

A task can be defined as:

public class MyRunnableTask implements Runnable {

private int id;

public MyRunnableTask(int id) {
this.id = id;
}

@Override
public void run() {
try {
System.out.format("%d (runnable): starting", id);
System.out.format("%d (runnable): sleeping 2 seconds", id);
Thread.sleep(2000);
System.out.format("%d (runnable): complete", id);
} catch (InterruptedException ex) {
Logger.getLogger(TestResourceServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Task can be submitted as:

Future<?> f = executor.submit(new MyRunnableTask(1));

OR

executor.execute(new MyRunnableTask(2));

A task may also be defined as:

public class MyCallableTask implements Callable<Product> {

private int id;

public MyCallableTask(int id) {
this.id = id;
}

@Override
public Product call() {
try {
System.out.format("%d (callable): starting", id);
System.out.format("%d (callable): sleeping 2 seconds", id);
Thread.sleep(2000);
System.out.format("%d (callable): complete", id);
} catch (InterruptedException ex) {
Logger.getLogger(TestResourceServlet.class.getName()).log(Level.SEVERE, null, ex);
}
return new Product(id);
}
}

where Product is a domain-specific class. In this case, the task is submited for execution as:

Future<Product> f2 = executor.submit(new MyCallableTask(3));
A ManagedScheduledExecutorService can be created as:

asadmin create-managed-scheduled-executor-service concurrent/myScheduledExecutor
Managed scheduled executor service concurrent/myScheduledExecutor created successfully.
Command create-managed-scheduled-executor-service executed successfully.

A ManagedThreadFactory can be created as:

asadmin create-managed-thread-factory concurrent/myThreadFactory
Managed thread factory concurrent/myThreadFactory created successfully.
Command create-managed-thread-factory executed successfully.

A ContextService can be created as:

asadmin create-context-service concurrent/myContextService
Context service concurrent/myContextService created successfully.
Command create-context-service executed successfully.

Note, this is the first integration and some of the options may not work. But you can definitely start playing around with basic stuff now.

The complete source code used in this Tip Of The Day (TOTD) is available here and will run on GlassFish 4 b74.

Friday Feb 08, 2013

Resource Library Contracts in JSF2.2 (TOTD #202)


JavaServer Faces 2 introduced Facelets as the default View Declaration Language. Facelets allows to create templates using XHTML and CSS that can be then used to provide a consistent look-and-feel across different pages of an application. JSF 2.2 defines Resource Library Contracts that allow facelet templates to be applied to an entire application in a reusable and interchangeable manner.

This Tip Of The Day (TOTD) will explain how you can leverage them in your web application.

The complete source code for this sample can be downloaded here. This will run on GlassFish build 72 + latest JSF 2.2.0 SNAPSHOT copied over "glassfish3/glassfish/modules/javax.faces.jar" file.

Consider the following WAR file:
index.xhtml
user/index.xhtml
contracts/blue/layout.css
contracts/blue/template.xhtml
contracts/red
contracts/red/layout.css
contracts/red/template.xhtml
WEB-INF/faces-config.xml

The application also has two pages - "index.xhtml" and "user/index.xhtml". All contracts reside in the "contracts" directory of the WAR. All templates and resources for a contract are in their own directory. For example, the structure above has two defined contracts "blue" and "red". Each contract has a "template.xhtml" and a CSS. Each template is called as "declared template". The "template.xhtml" has <ui:insert> tags called as "declared insertion points". CSS and other resources bundled in the directory are "declared resources". The "declared template", "declared insertion points", and "declared resources" together make the definition of the resource library contract. A template client needs to know the value of all three in order to use the contract.

In our case, templates have similar "ui:insert" sections and template clients will accordingly have "ui:define" sections. The difference will primarily be in the CSS. "index.xhtml" will refer to the template as:

<ui:composition template="/template.xhtml">
<ui:define name="content">
. . .
</ui:define>
</ui:composition>

The usage of the contracts is defined in "faces-config.xml" as:

<application>
<resource-library-contracts>
<contract-mapping>
<url-pattern>/user/*</url-pattern>
<contracts>blue</contracts>
</contract-mapping>
<contract-mapping>
<url-pattern>*</url-pattern>
<contracts>red</contracts>
</contract-mapping>
</resource-library-contracts>
</application>
A contract is applied based upon the URL pattern invoked. Based upon the configuration specified here, "red" contract will be applied to "faces/index.xhtml" and "red" contract will be applied to "faces/user/index.xhtml".

The template of the page can be changed dynamically as well. For example consider "index.xhtml" is updated as:

<f:view contracts="#{contractsBean.contract}">
<ui:composition template="/template.xhtml">

<ui:define name="content">
<a href="#{facesContext.externalContext.requestContextPath}/faces/user/index.xhtml">Go to</a> other contract
<p/>
Look at WEB-INF/faces-config.xml for contract configuration.
<p/><p/>
Choose a template:<br/>
<h:form>
<h:selectOneRadio value="#{contractsBean.contract}" layout="pageDirection" required="true">
<f:selectItem itemValue="red" itemLabel="red"/>
<f:selectItem itemValue="blue" itemLabel="blue"/>
</h:selectOneRadio>
<h:commandButton value="Apply" action="index" />
</h:form>
</ui:define>

</ui:composition>
</f:view>
The "ui:composition" is included in "f:view". An additional "contracts" attribute can bind to an EL. The value of this EL is populated from the radio button in the newly added form. Now you can choose a radio button, click on the "Apply" button and the new template will be applied to the page. The bean is very trivial:

@Named
@SessionScoped
public class ContractsBean implements Serializable {

String contract = "red";

public String getContract() {
return contract;
}

public void setContract(String contract) {
this.contract = contract;
}
}

This is a very powerful feature. Imagine providing different look-and-feel for your website and letting the user choose them, fun eh ?

Contracts may be packaged as a JAR file. Such a JAR file maybe bundled in "WEB-INF/lib" directory. Read section 2.7 for more details about the packaging requirement and a marker file that identifies the JAR to contain a contract.

In the specification ...
  • Section 10.1.3 provide background on the feature.
  • Section 2.7 provide formal definition of the feature.
  • Section 11.4.2.1 defines how the contracts are identified during application startup.
Create templates as JAR files and reuse them across different applications, enjoy!

Friday Feb 01, 2013

Java EE 7 Maven Archetype - Available in NetBeans (TOTD #201)


Want to create a Java EE 7 application using Maven ?

mvn -DarchetypeGroupId=org.codehaus.mojo.archetypes -DarchetypeArtifactId=webapp-javaee7 -DarchetypeVersion=0.1-SNAPSHOT -DarchetypeRepository=https://nexus.codehaus.org/content/repositories/snapshots/ -DgroupId=org.glassfish -DartifactId=javaee7-sample -Dversion=1.0-SNAPSHOT -Dpackage=org.glassfish.javaee7-sample -Darchetype.interactive=false --batch-mode --update-snapshots archetype:generate
[INFO] Scanning for projects...
Downloading: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-metadata.xml
Downloading: http://repo1.maven.org/maven2/org/codehaus/mojo/maven-metadata.xml
Downloaded: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-metadata.xml (11 KB at 42.6 KB/sec)
Downloaded: http://repo1.maven.org/maven2/org/codehaus/mojo/maven-metadata.xml (22 KB at 65.6 KB/sec)
Downloading: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-archetype-plugin/maven-metadata.xml
Downloaded: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-archetype-plugin/maven-metadata.xml (701 B at 4.3 KB/sec)
[INFO]                                                                        
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
Downloading: http://repo1.maven.org/maven2/org/codehaus/mojo/maven-metadata.xml
Downloading: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-metadata.xml
Downloaded: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-metadata.xml (11 KB at 64.9 KB/sec)
Downloaded: http://repo1.maven.org/maven2/org/codehaus/mojo/maven-metadata.xml (22 KB at 77.8 KB/sec)
Downloading: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-archetype-plugin/maven-metadata.xml
Downloaded: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-archetype-plugin/maven-metadata.xml (701 B at 3.1 KB/sec)
[INFO]
[INFO] >>> maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom <<<
[INFO]
[INFO] --- maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Batch mode
[INFO] Archetype defined by properties
Downloading: https://nexus.codehaus.org/content/repositories/snapshots/org/codehaus/mojo/archetypes/webapp-javaee7/0.1-SNAPSHOT/maven-metadata.xml
Downloaded: https://nexus.codehaus.org/content/repositories/snapshots/org/codehaus/mojo/archetypes/webapp-javaee7/0.1-SNAPSHOT/maven-metadata.xml (786 B at 0.5 KB/sec)
Downloading: https://nexus.codehaus.org/content/repositories/snapshots/org/codehaus/mojo/archetypes/webapp-javaee7/0.1-SNAPSHOT/maven-metadata.xml
Downloaded: https://nexus.codehaus.org/content/repositories/snapshots/org/codehaus/mojo/archetypes/webapp-javaee7/0.1-SNAPSHOT/maven-metadata.xml (786 B at 2.0 KB/sec)
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Archetype: webapp-javaee7:0.1-SNAPSHOT
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: org.glassfish
[INFO] Parameter: artifactId, Value: javaee7-sample
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Parameter: package, Value: org.glassfish.javaee7-sample
[INFO] Parameter: packageInPathFormat, Value: org/glassfish/javaee7-sample
[INFO] Parameter: package, Value: org.glassfish.javaee7-sample
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Parameter: groupId, Value: org.glassfish
[INFO] Parameter: artifactId, Value: javaee7-sample
[INFO] project created from Archetype in dir: /Users/arungup/code/workspaces/tmp/javaee7-sample
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.703s
[INFO] Finished at: Sat Feb 02 07:31:54 EET 2013
[INFO] Final Memory: 11M/125M
[INFO] ------------------------------------------------------------------------

That's it!

NetBeans Development Builds allows to create a Maven-based Java EE 7 web application now. wiki.netbeans.org/JavaEE7 provide a complete list of planned features. TOTD #199 provide some more details on the features currently working. Of course, this application will get deployed to GlassFish 4.

Wednesday Jan 30, 2013

GlassFish 4 Latest Builds, Zip, API, and Javadocs (TOTD #200)


Do you want a handy link to the latest GlassFish builds, zip bundles, Java EE 7 API jar or javadocs ?

Now they are available at download.java.net/glassfish/4.0/promoted!



The pattern is: download.java.net/glassfish/4.0/promoted/latest-*.

So download.java.net/glassfish/4.0/promoted/latest-glassfish.zip gives you the latest GlassFish zip bundle. Similarly download.java.net/glassfish/4.0/promoted/latest-javaee-api-javadoc.jar gives you the latest Java EE 7 javadocs and download.java.net/glassfish/4.0/promoted/latest-web-unix.sh gives you the latest Unix installer for Java EE 7 Web profile. These are all in turn link to the latest promoted build.

The complete set of promoted builds are available as usual at download.java.net/glassfish/4.0/promoted. And the nightly builds at download.java.net/glassfish/4.0/nightly.

What is your favorite location to download GlassFish builds ?

Tuesday Jan 29, 2013

Java EE 7 and NetBeans IDE - Early Support Available (TOTD #199)


NetBeans IDE provides the best out-of-the-box experience for Java EE development, deployment, and debugging. Early builds of NetBeans have already started providing support for Java EE 7 features such as
  • Registering GlassFish 4
  • Creating Java EE 7 application
  • Wizard for JAX-RS 2 Filters/Interceptors
  • Initial support for Faces Flow
  • Loading templates from a resource library
  • Non-persistent EJB timers in Web profile
  • Wizard for WebSocket endpoints
wiki.netbeans.org/JavaEE7 provide a complete list of features slated for the release and the builds can be downloaded from bertram2.netbeans.org:8080/job/web-main-javaee7. Here are some snapshots of the work completed so far.

Creating a Java EE 7 Web application and using GlassFish 4 server


Creating a WebSocket endpoint



Wizard for creating WebSocket endpoint


The generated code looks like:

@WebSocketEndpoint("/endpoint")
public class NewWSEndpoint {

@WebSocketMessage
public String onMessage(String message) {
return null;
}

}

Creating a JAX-RS 2 Filter


Wizard for creating a JAX-RS 2 Filter


By default it is a server-side filter but can be made client-side filter too.

Wizard for creating a JAX-RS 2 Interceptor



Creating a RESTful Java Client using JAX-RS 2 Client APIs



Wizard for creating a JAX-RS 2 Client


This is a very early work-in-progress so any feedback is welcome.

Download GlassFish 4.0 promoted build, register it with NetBeans IDE and take it for a test drive!

Monday Jan 28, 2013

JSF 2.2 Faces Flow - @FlowScoped, #{flowScope}, @FlowDefinition (TOTD #198)


JavaServer Faces 2.2 is more evolutionary than it is revolutionary. This is by design as JSF 2.0 added a whole bunch of new features as part of the Java EE 6 platform. The Preface 1 from the JSF 2.2 Public Review specification provides a list of changes between JSF 2.1 and 2.2. There are several changes coming in JSF 2.2 but the big ticket items are:
  • Faces Flow
  • Resource Library Contract
  • HTML5 Friendly Markup
This Tip Of The Day (TOTD) will explain Faces Flow. Section 7.5 and 11.4.3 in the specification introduce the feature.

Faces Flow provides an encapsulation of related views/pages with an application defined entry and exit points. For example, a check out cart can consist of cart page, credit card details page, shipping address page, and confirmation page. All these pages, along with required resources and beans, can be packaged together as a module which can then be reused in other applications.

Each flow has a well-defined entry and exit point that have been assigned some application specific meaning by the developer. Usually the objects in a faces flow are designed to allow the user to accomplish a task that requires input over a number of different views. In our case, the navigation between pages for selecting items, entering shipping address, credit card details, and confirmation page would make a flow. All the pages and objects that deal with the checking out process can be composed as modules. An application thus become a collection of flows instead of just views.

It takes the best part of other flow-based technologies such as ADF Task Flow, Spring Web Flow, and Apace MyFaces CODI and standardizes in JSF 2.2.

What is the need ?

Imagine a multi-page shopping cart with one page for selecting the items, a second page for shipping options, a third page for entering credit card details, and a fourth page for final confirmation. Managed Beans can be used to capture the data, session scope variables pass information between pages, button clicks can be used to invoke the business logic in backing EJBs, and (conditional) navigation rules can be defined to go from one page to another. There are a few issues with this approach:
  • This flow of sequence will typically be part of a bigger application. However an application, typically with several pages, is one large flow and everything is visible with no logical partitioning.
  • The flow of pages or views cannot be encapsulated as a logical unit and thus cannot be reused, e.g. incorporated into another bigger flow easily.
  • The lowest logical granularity is a page. The only way to invoke application logic is to tie it to a UI component activated by the user in a page. Business logic cannot be invoked without any user initiated action.
  • Same flow cannot be opened in multiple windows because session scoped variables are used to pass information between pages. CDI defines @ConversationScoped but that is only part of the solution.
  • There is no scope defined that can span multiple pages but less than a session.
Faces Flow provide a solution to the issues mentioned above.

What's new in JSF 2.2 for flows ?

The flow of application is no longer restricted to flow between pages but instead defined as flow between "nodes". There are five different types of nodes:
  • View: Any JSF page in the application
  • Method Call: Invoke application logic from flow graph via an EL
  • Switch: Navigation decisions in the flow graph based on boolean EL
  • Flow Call: Call another flow with parameters and receive return values
  • Flow Return: Return to the calling flow
The nodes define the entry and exit points of a flow.

Two new annotations are introduced:
  • @FlowScoped is a CDI scope that defines the scope of bean in the specified flow. This enables automatic activation/passivation of the bean when the scope is entered/exited.
  • @FlowDefinition is a class level annotation that allows the flow definition to be defined using the fluent FlowBuilder API.
A new EL object, #{flowScope}, for flow local storage is also introduced. This maps to facesContext.getApplication().getFlowHandler().getCurrentFlowScope().

How are flows packaged ?

Flows can be packaged in JAR files or in directories.

JAR packaging requires flows to be explicitly declared in META-INF/faces-config.xml in the JAR file. Flow nodes are packaged in META-INF/flows/<flowname> where <flowname> is a JAR directory entry whose name is identical to that of a flow id in the corresponding faces-config.xml. @FlowScoped and @FlowDefinition beans must be packaged in the JAR file and accompanied by META-INF/beans.xml.

A sample JAR file looks like:

META-INF/faces-config.xml
META-INF/flows/flow1/entry.xhtml
META-INF/flows/flow1/next.xhtml
META-INF/flows/flow1/end.xhtml
META-INF/flows/flow2/start.xhtml
META-INF/flows/flow2/next.xhtml
META-INF/flows/flow2/end.xhtml
META-INF/beans.xml
org/glassfish/sample/MyFlow1Bean.class
org/glassfish/sample/MyFlow2Bean.class
org/glassfish/sample/MyFlowDefintion.class
Flows packaged in directories use convention-over-configuration. The conventions are:
  • Every View Declaration Language file in that directory is a view node of that flow.
  • The start node of the flow is the view whose name is the same as the name of the flow.
  • Navigation among any of the views in the directory is considered to be within the flow.
  • Navigation to a view outside of that directory is considered to be an exit of the flow.
  • Optional <flowname>-flow.xml that represents the flow definition. The rules in this file overrides the conventions described above.

A sample directory looks like:

flow1/flow1.xhtml
flow1/flow1a.xhtml
flow1/flow1b.xhtml
flow2/flow2-flow.xml
flow2/flow2.xhtml
flow2/flow2a.xhtml
flow2/flow2b.xhtml
WEB-INF/...
Show me the code!

Lets try a sample now!

The source code for the two samples explained below can be downloaded here. A complete explanation of the sample including the code walk-through is shown in the video:



This will run on GlassFish 4.0 b72. For now, you'll need to replace glassfish/modules/javax.faces.jar with javax.faces-2.2.0-SNAPSHOT.jar and replacing glassfish/modules/javax.el.jar with javax-el-3.0-b03.jar. This JARs will soon be integrated in the GlassFish build. Ah, the joys of bleeding edge development!

Saturday Jan 26, 2013

Java EE 7 Maven Application (TOTD #197)

Did you know that Java EE 7 APIs are now published in maven ?

The complete set of coordinates are described here. So how do you build a simple Java EE 7 maven application ?

  1. Generate the ususal Java EE 6 maven application as:

    mvn -DarchetypeGroupId=org.codehaus.mojo.archetypes -DarchetypeArtifactId=webapp-javaee6 -DarchetypeVersion=1.5 -DarchetypeRepository=http://repo.maven.apache.org/maven2 -DgroupId=org.glassfish -DartifactId=hello-javaee7 -Dversion=1.0-SNAPSHOT -Dpackage=org.glassfish.hellojavaee7 -Darchetype.interactive=false --batch-mode archetype:generate
  2. In the generated pom.xml, replace
    <dependencies>
    <dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>6.0</version>
    <scope>provided</scope>
    </dependency>
    </dependencies>

    with

    <repositories>
    <repository>
    <id>Java EE 7</id>
    <url>https://maven.java.net/content/groups/promoted/</url>
    </repository>
    </repositories>

    <dependencies>
    <dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0-b72</version>
    </dependency>
    </dependencies>

    Notice, there is a new <version> of dependency for each GlassFish 4 promoted build. This may be simplified in the coming builds.

    The <artifactId> can be changed to javaee-web-api if your application requires Java EE 7 Web Profile API only.

And now all Java EE 7 APIs so far integrated in GlassFish are available in your application.

You can also include specific API JAR files explicitly in your project directly. The latest APIs are available in the format:

In general, you can replace "b72" in the URL with the latest promoted build number to get the latest artifacts. A simplified URL for the latest set of these artifacts is in the works!

What next ? Maven archetype and support in NetBeans coming soon!

Tuesday Jan 22, 2013

Default DataSource in Java EE 7: Lesser XML and More Defaults (TOTD #196)


Section E.5.5.20 in the Java EE 7 Platform specification defines a new Default Data Source that must be provided by a Java EE 7-compliant runtime. This pre-configured data source can be used by application for accessing the associated database. It is accessible to the application under the JNDI name:
java:comp/DefaultDataSource

This can be accessed in the application as:
@Resource(name="myDataSource", lookup="java:comp/DefaultDataSource")
DataSource myDS;

If the binding is not specified, the mapping of the reference will default to this default data source. So the above fragment is equivalent to:
@Resource(name="myDataSource")
DataSource myDS;

Section 8.2.1.5 in the JPA 2.1 specification says

If neither jta-data-source and non-jta-data-source elements are specified, the deployer must specify a JTA data source at deployment or a JTA data source must be provided by the container, and a JTA EntityManagerFactory will be created to correspond to it.

Per.book
This means a Java EE 7 application can have the following persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="myPU" transaction-type="JTA">
<jta-data-source>java:comp/DefaultDataSource</jta-data-source>
</persistence-unit>
</persistence>

This is semantically equivalent to:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="movieplex7PU" transaction-type="JTA"/>
</persistence>

Notice, no jta-data-source.

In both cases, the default data source will be provisioned and available to the application. In GlassFish 4, this is bound to the JDBC resource jdbc/__default.

And this can be verified by giving the command:
./bin/asadmin list-jdbc-resources
jdbc/sample
jdbc/__TimerPool
jdbc/__default
Command list-jdbc-resources executed successfully.

Lesser XML and more defaults makes Java EE 7 more lightweight and user friendly!

Download GlassFish 4.0 promoted build and try it today!

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
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today