Wednesday, March 30, 2016

A simple Json Demo (2)

Building up on the previous demo, I enriched my samples with a method that returns a Json array.

After doing a bit of research, I came up with this solution: my method returns a JsonArray:


...
@GET
@Path("testArray")
@Produces({MediaType.APPLICATION_JSON})
public JsonArray testArray4() throws Exception {

    JsonArray value = Json.createArrayBuilder()
            .add(Json.createObjectBuilder()
                    .add("firstName", "Barak")
                    .add("lastName", "Obama"))
            .add(Json.createObjectBuilder()
                    .add("firstName", "Bill")
                    .add("lastName", "Clinton"))
            .build();
    return value;
}
...

It is available under http://localhost:8080/demoRest/demo/testArray

Note that the deployment occurs using the exploded war of IntelliJ on Glassfish 4.1, which allows defining a custom context root under "/". Otherwise, the *.war file being (oddly) DemoBean_war.war, the URL would be http://localhost:8080/DemoBean_war/demoRest/demo/testArray.

I first made diverse other attempts, which all failed because of the internal binding that takes place during Json processing: using a list of dtos, a list of JsonObject, or a list of dtos wrapped in a GenericEntity: all attempt failed with diverse errors in relations with the libraries available on the server:

java.lang.NoClassDefFoundError: 
  javax/xml/parsers/ParserConfigurationException
java.lang.NoClassDefFoundError: 
  Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper
java.lang.ClassNotFoundException: 
  javax.xml.parsers.ParserConfigurationException not found by org.eclipse.persistence.moxy



The solution using a Json Array proved to be working on Glassfish 4.1.1

I found some information about incompatibilities in Jersey Libs of Glasshfish 4.1.1 on the Jersey Jira, but none helped me solving the problems.

I found a hint in Adam's Bien Blog for returning a list of objects with JAX-RS, but this didn't solve the problems that occured when running on Glassfish. 

I also could not deploy successfully the examples on JBoss, but did not investigate further.









Monday, March 28, 2016

A simple, simple json and rest demo

I created a simple demonstration of a Rest - application, based on the examples from the Java EE Tutorial.

My demo just returns a Json object.

I used IntelliJ, configuring module facets for library dependencies.

I did not use any maven for build or dependency management.

Deployment is done on a local Glassfish instance.

Project configuration IntelliJ

Project settings use the facets EJB, Web and Java EE application. Libraries : ejb 3.2, javax.json.processing-1.0, JAX-RS.

Code

Code consists of 2 classes : one application - Class (that inherits from javax.ws.rs.core.Application), and one implementation class, where the json processing takes place, and with the rest annotations.

Application class

package org.nstern.demos.rest;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/demoRest")
  public class RestDemoApplication extends Application {
}

Implementing class

package org.nstern.demos.rest;

import javax.json.Json;
import javax.json.JsonObject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

@Path("/demo")
public class RestDemoResource {

    @Context    private UriInfo context;

    public RestDemoResource(){}

    @GET    
    @Path("test")
    @Produces({MediaType.APPLICATION_JSON})
    public String testBean() {
        return "123456789";
    }

    @GET    
    @Path("testJson")
    @Produces({MediaType.APPLICATION_JSON})
    public JsonObject testJson() {

        JsonObject model = Json.createObjectBuilder()
                .add("firstName", "Duke")
                .add("lastName", "Java")
                .build();

        return model;
    }
}

Deployment and calling the Rest methods

Artefact is configured in IntelliJ in the Glassfish config (war exploded). I defined a custom context root to avoid cumbersome URLs.

I call the rest method using Chrome advanced rest client:

The two urls are :
http://localhost:8080/demoRest/demo/test
http://localhost:8080/demoRest/demo/testJson

Summary, remarks

I had to struggle before finding out that if I don't define a custom context root, the application will use a strange root URL  - like "http://localhost:8080/demoBean_war_exploded/etc.*"

I found a useful hint about generating artefacts (*.war file) on this blog. (This is pure handling of IntelliJ).

Not that this application has no web.xml

Wednesday, March 23, 2016

How to validate an input field with Angular JS

Angular JS offers a very simple way to validate an entry into an input field with a regular expression with the ng-pattern attribute.

I had to change a behavior of an input field in an application: special characters like 'ä', 'ö', 'ü' were not allowed, but should have.

The interesting thing is that the pattern can be assigned dynamically.

Here is the setup:

for a static pattern, I use a variable (vm.regex) in my controller.

(function () {
    var valApp = angular.module("valApp", []);
    valApp.controller("ListCtrl", ListController);
    function ListController() {
        var vm = this;
        vm.regex ='\\d+';
        ...
    }
})();

... and in the view, the attribute ng-pattern references this variable: 


<div class="container" ng-app="valApp">
  <div class="row" ng-controller="ListCtrl as ctrl">
    <form name="myForm">
      <div class="span4">
          <p>
            <label>Field1:</label>
            <input name="field1" 
            type="text" 
            ng-model="ctrl.item.field1" 
            ng-pattern="'\\d'"/>
          </p>
          <p>
            <label>Field2:</label>
            <input name="field2" 
            type="text" 
            ng-model="ctrl.item.field2" 
            ng-pattern="ctrl.regex"/>
          </p>
      </div>
    </form>
  </div>
</div>

Now, the pattern to allow characters with "Umlauten" (ä,ü,ö) is as follows:

[a-zA-Z0-9öüäÖÜÄ]+