Markus Eisele

About 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. Follow him on Twitter @myfear.

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.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


four − 3 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close