Enterprise Java

Test driving Java API for Processing JSON with GlassFish 4.0

Writing and contributing to a specification is one thing. Working with it and looking into real examples a pre-condition if you want to give valuable feedback. The latest promoted GlassFish builds contain the renaming to 4.0 and I thought it might be a good time to give the Java API for Processing JSON (JSON-P) a test drive.

Get Java EE 7 enabled GlassFish 4.0

First thing to do is to grab a copy of latest Java EE 7 enabled GlassFish 4.0 from the promoted builds. I am using the GlassFish Server Open Source Edition 4.0 (build 77) which seems to be quite stable. But in general, if you are trying this please keep in mind, that the promoted builds are basically development and unstable versions of
 
ongoing work for GlassFish 4.0. It wouldn’t make much sense to complain about them. Unzip the download into a suitable location. For a later step you need to update the JSON-P RI within the modules directory. Follow Arun’s Blog about getting and building the JSON-P RI and copy the jsonp~git\impl\target\javax.json-1.0-SNAPSHOT.jar to the glassfish4\glassfish\modules\javax.json.jar. Make sure to make a copy of the original in case you do something wrong in that step. If you are feeling uncomfortable with that you can also skip it and select a different dependency later on … The fact is, that the JSON-P API changed that much over the past few months, that the GlassFish included b02 isn’t appropriate anymore to show you anything. So, for now, we have to tweak it a bit. Afterwards you are all set to integrate your fresh GlassFish install into your favorite IDE which could be NetBeans.

Create a new Java EE 7 Projekt

The Java EE 7 archetype is located in the codehaus.org snapshot repository. In order to use it via NetBeans effectively you have to configure the repository on the ‘Services’ tab under ‘Maven Repositories’. The repository URL is https://nexus.codehaus.org/content/repositories/snapshots/. It might take a while to process the index. After that, proceed with the ‘New Project > Maven > Project from Archetype’ wizard and enter ‘webapp-javaee7’ into the search box. Select the 0.1-SNAPSHOT and click ‘Finish’. Alternatively you can always go with the following command line:

mvn -DarchetypeGroupId=org.codehaus.mojo.archetypes -DarchetypeArtifactId=webapp-javaee7 -DarchetypeVersion=0.1-SNAPSHOT -DarchetypeRepository=https://nexus.codehaus.org/content/repositories/snapshots/ -DgroupId=net.eisele.sample -DartifactId=javaee7-jsonp -Dversion=1.0-SNAPSHOT -Dpackage=net.eisele.javaee7jsonp -Darchetype.interactive=false --batch-mode --update-snapshots archetype:generate

Now open the project and edit the pom.xml. Change the scope of the javaee-web-api to provided and add the json-api dependency as shown below:

 <dependencies>
        <dependency>
            <groupId>javax.json</groupId>
            <artifactId>javax.json-api</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0-b72</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

Please make sure to use the version 1.0-SNAPSHOT and _not_ the officially documented 1.0-b02. We want to use the latest snapshot we build in the first paragraph with all the new APIs .If you decided not to go the ‘build it your own way’ you can simply use the 1.0-b04 from maven central. This also works. Please make sure to have exactly this order of dependencies. If not, you will use the old b02 which is included with the javaee-web-api dependency. Did someone say, Maven is easy? That’s it for now. Let’s create a simple JAX-RS endpoint.

Adding a JAX-RS Person Resource

First thing to do is to write the basic JAX-RS resource. You can do this via the NetBeans’ ‘RESTful Web Services from Pattern’ wizard or yourself by simply outlining a brief class like the following:

@Path('person')
public class PersonResource {
    public PersonResource() {
    }

    @GET
    @Produces('application/json')
    public String getJson() {
        return '[]';
    }

This class needs to be registered. You can either use Jerseys servlet mechanism to do this or register it yourself with the application specific ApplicationConfig:

@javax.ws.rs.ApplicationPath('webresources')
public class ApplicationConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<>();
        resources.add(net.eisele.javaee7jsonp.PersonResource.class);
        return resources;
    }
}

Wow .. that should be all for now. You should give it a test drive. Deploy it to your domain and try http://localhost:8080/javaee7-jsonp/webresources/person. It should simply print the empty brackets []. Now it is time to get some JSON-P into the mix.

Building JSON Objects with JSON-P

We are going to build a JSON representation of a person with the DOM-based API. Replace the return statement in the PersonResource with the following code:

 JsonObjectBuilder builder = Json.createObjectBuilder();
        builder.add('person', Json.createObjectBuilder()
                .add('firstName', 'Markus')
                .add('lastName', 'Eisele'));
        JsonObject result = builder.build();
        StringWriter sw = new StringWriter();
        try (JsonWriter writer = Json.createWriter(sw)) {
            writer.writeObject(result);
        }
        return sw.toString();

And now lets use my most favorite Chrome extension to look at what we’ve got:


It obviously works. Turning this the other way round would mean to read incoming JSON. This could look like the following:

        String json = '{\n'
                + '    \'person\': {\n'
                + '        \'firstName\': \'Markus\',\n'
                + '        \'lastName\': \'Eisele\'\n'
                + '    }\n'
                + '}';
        JsonReader jr = Json.createReader(new StringReader(json));
        JsonValue value = jr.readObject();
        jr.close();

Beside the DOM-API you also have a Streaming-API which uses a

JsonGenerator generator = Json.createGenerator(new FileWriter(..))

JsonParser parser = Json.createParser(new StringReader(...));

to generate and parse JSON. Have a look at the latest JavaDoc for a complete reference. Go ahead and test drive yourself.
 

Reference: Test driving Java API for Processing JSON with GlassFish 4.0 from our JCG partner Markus Eisele at the Enterprise Software Development with Java blog.

Markus Eisele

Markus is a Developer Advocate at Red Hat and focuses on JBoss Middleware. He is working with Java EE servers from different vendors since more than 14 years and talks about his favorite topics around Java EE on conferences all over the world. He has been a principle consultant and worked with different customers on all kinds of Java EE related applications and solutions. Beside that he has always been a prolific blogger, writer and tech editor for different Java EE related books. He is an active member of the German DOAG e.V. and it's representative on the iJUG e.V. As a Java Champion and former ACE Director he is well known in the community. Follow him on Twitter @myfear.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button