Hot questions for Using GlassFish in json

Question:

According to my project Provider org.glassfish.json.JsonProviderImpl not found I dont understand why it is complaining about glassfish as I am using a different library for json:

...
        <dependencies>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.0.1</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.websocket</groupId>
                <artifactId>javax.websocket-api</artifactId>
                <version>1.1</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.json</groupId>
                <artifactId>javax.json-api</artifactId>
                <version>1.0</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.36</version>
            </dependency>
        </dependencies>
...

Any idea about how can I use my Json library and avoid to use glassfish?


Answer:

The problem is that javax.json-api only contains the API (interfaces) and no implementation.

If your server comes with a pre-bundled implementation this should work, but if not you can add the following dependency to get an implementation:

<dependency>
  <groupId>org.glassfish</groupId>
  <artifactId>javax.json</artifactId>
  <version>1.0.4</version>
</dependency>

Question:

I've tried to make a rest app that returns me a list of recipes, the count method works but the when I try to get one or all of them it gives me this error

javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.util.ServiceConfigurationError: javax.json.bind.spi.JsonbProvider: Provider org.eclipse.yasson.JsonBindingProvider not found

I do have

<dependency>
            <groupId>org.eclipse</groupId>
            <artifactId>yasson</artifactId>
            <version>1.0</version>
</dependency>

in my pom.xml

Function looks like this

    @GET
    @Path("/{id : \\d+}")
    @Produces(APPLICATION_JSON)
    public Response getBook(@PathParam("id") @Min(1) int id) {
        Recipe recipe = recipeRepository.findOneByID(id);

        if (recipe == null)
            return Response.status(Response.Status.NOT_FOUND).build();

        return Response.ok(recipe).build();
    }

This is the function returning the recipe by ID

public Recipe findOneByID(int id) {
        return entitymanager.find(Recipe.class, id);

    }

And the recipe has the following attributes

@Id
private int id;

private String complexity;

private int cookingTime;

private String description;

private int estimatedTime;

private String imageUrl;

private String information;

private boolean isPromoted;

private int preparationTime;

private float servings;

private String title;

private String type;

//bi-directional many-to-one association to Allergen
@OneToMany(mappedBy="recipe")
private List<Allergen> allergens;

//bi-directional many-to-one association to Ingredient
@OneToMany(mappedBy="recipe")
private List<Ingredient> ingredients;

//bi-directional many-to-one association to Mediaitem
@OneToMany(mappedBy="recipe")
private List<Mediaitem> mediaitems;

//bi-directional many-to-one association to Nutritionvalue
@OneToMany(mappedBy="recipe")
private List<Nutritionvalue> nutritionvalues;

//bi-directional many-to-one association to Step
@OneToMany(mappedBy="recipe")
private List<Step> steps;

Any hint would be a huge help. I've spent half a day trying to fix this


Answer:

If you are running this on GlassFish 5.0-b11 or higher, then you need to remove your dependency on Yasson (since Yasson is already included in GlassFish 5 nightly builds after b11), but you should specify a dependency on the JSON-B 1.0 API (and probably JSON-P 1.1 really) because there is no Java EE 8 umbrella dependency available yet to encompass all of the Java EE 8 specs.

Remove Yasson and add these:

<dependency>
    <groupId>javax.json.bind</groupId>
    <artifactId>javax.json.bind-api</artifactId>
    <version>1.0</version>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
    <scope>provided</scope>
</dependency>

Note that they need to have <scope>provided</scope>, since GlassFish 5 is providing the implementation, and you don't want Maven to build the libraries into your app.

If you are using GlassFish 5.0-b10 or lower, then you need to specify these same dependencies as well as the Yasson dependency in your pom.xml above, since Yasson is the implementation and that needs to be present:

<dependency>
    <groupId>javax.json.bind</groupId>
    <artifactId>javax.json.bind-api</artifactId>
    <version>1.0</version>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>yasson</artifactId>
    <version>1.0</version>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
    <scope>compile</scope>
</dependency>

I have also explicitly added the <scope>compile</scope> here, since that is the default if no scope is provided. It's sometimes useful to be explicit about this since you may want to move this project to GlassFish 5 in the future and the scope would need to be changed and the Yasson dependency removed completely.

Source: http://json-b.net/getting-started.html

Question:

I have a Maven jersey server that sends json objects to my JavaFX client, in my server I have model classes that have strings and int and in the client model class I tried to use Stringproperty and IntegerProperty (for the bind use and I have proper getter and setters(setter = name.set("example"), getter = return name.get)) but when I do I get

Both front and backend have JSON as mediatype and when I change client modelclass variables to String and Int everything works as expected.I want to find a way to keep the property of strings and int for the bind method, I tried to google but no one else seems to have had this problem, does anyone know what can solve this and let me use property of variables

I caught the exception as processingException e

e.getCause(): null

e.getMessage():

MessageBodyReader not found for media type=application/json, type=interface java.util.List, genericType=java.util.List<models.Users>.
[org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:207), org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:139), org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1109), org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:853), org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:812), org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:309), org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:813), org.glassfish.jersey.client.JerseyInvocation.access$600(JerseyInvocation.java:90), org.glassfish.jersey.client.JerseyInvocation$3.call(JerseyInvocation.java:693), org.glassfish.jersey.internal.Errors.process(Errors.java:315), org.glassfish.jersey.internal.Errors.process(Errors.java:297), org.glassfish.jersey.internal.Errors.process(Errors.java:228), org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:422), org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:689), org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:405), org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:301), Repository.UserRepo.getUsers(UserRepo.java:55), cleaner.Cleaner.start(Cleaner.java:35), com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863), com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326), com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295), java.security.AccessController.doPrivileged(Native Method), com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294), com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95), com.sun.glass.ui.win.WinApplication._runLoop(Native Method), com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191), java.lang.Thread.run(Thread.java:745)]

When I run get method with postman the backend works, so that tells me it something with client.

client: glassfish 4.1 Jersey 2.5.1 (JAX-RS RI) javax.ws.rs-api-2.0.1

server: glassfish 4.1 jersey 2.26-b03

Thanks in advance!


Answer:

Add the following dependency to your client to provide a MessageBodyReader implementation that knows how to deserialize an incoming JSON string to an instance of Users.

<dependency> 
  <groupId>com.fasterxml.jackson.jaxrs</groupId> 
  <artifactId>jackson-jaxrs-json-provider</artifactId> 
  <version>2.4.4</version> 
</dependency>

Question:

Suppose I want to create JSON and store it in String using Java JSON Streaming API. For that purpose I create ByteArrayOutputStream (BAOS) and JsonGenerator on top of it.

ByteArrayOutputStream collector = new ByteArrayOutputStream();
JsonGenerator jsonGenerator = Json.createGenerator(collector);

After a while, when I'm done with it, I take String from BAOS and supposed to release all resources. As follows from BAOS close method implementation

public void close() throws IOException {
}

it does nothing. close method of JsonGenerator, however, not only closes underlying stream, but also flushes buffer and recycles a buffer pool (frankly speaking, I have no idea of what latter means). I doubt that JsonGenerator buffers data when writes it to BAOS. But, it will take some time from me to investigate it further, so I hope someone already knows: does it make sense to close generator, or doesn't. Note I use Glassfish implementation of javax.json.


Answer:

Ok. I checked JsonGeneratorImpl source code. And I have to say that I really need to close it. First of all, JsonGeneratorImpl receives buffer from BufferPoolImpl here:

public final char[] take() {
    char[] t = (char[])getQueue().poll();
    if (t == null)
        return new char[4096];
    return t;
}

And when we call close we put it back:

public final void recycle(char[] t)
{
    getQueue().offer(t);
}

It doesn't make a lot sense if you create jsonGenerator like I do in question:

JsonGenerator jsonGenerator = Json.createGenerator(collector);

Because in that case, each newly created generator will use its own instance of JsonProvider, and its own instance of buffer pool which will be collected by GC when I'll finish to work with generator. So its better to create JsonGeneratorFactory, because all generators created by this factory will share common buffer pool. And yes — in that case it's really better to close generator at the end. Another reason to close generator is that close method invokes flushBuffer method. And yes, generator uses buffer regardless of output stream type:

void writeChar(char c) {
    if (this.len >= this.buf.length) {
        flushBuffer();
    }
    this.buf[(this.len++)] = c;
}

So the final answer is yes. It always makes sense to close JsonGenerator in the end. UPDATE As @StephenC rightfully noted, there is another reason to close it, because it enforces check for not finished JSON:

if ((this.currentContext.scope != Scope.IN_NONE) || (this.currentContext.first)) {
  throw new JsonGenerationException(JsonMessages.GENERATOR_INCOMPLETE_JSON());
}

Question:

I made a restful service by netbeans from my localhost and I choose glassfish 4.1.1 as my webserver then I wanted to test it. it was working when it wanted to give me an xml response but when I tried to get an JSON response it gave me a 500 ERROR as below

GET RequestFailed RequestFailed --> Status: (500) 
Response: {

HTTP Status 500 - Internal Server Error


type Exception report

messageInternal Server Error

descriptionThe server encountered an internal error that prevented it from fulfilling this request.

exception 
javax.servlet.ServletException: javax.ejb.EJBException


root cause 
javax.ejb.EJBException


root cause 
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.1.v20150605-31e8258): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Error Code: 0


root cause 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.1.v20150605-31e8258): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Error Code: 0


root cause 
java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.


root cause 
javax.resource.spi.ResourceAllocationException: Error in allocating a connection. Cause: Connection could not be allocated because: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.


root cause 
com.sun.appserv.connectors.internal.api.PoolingException: Connection could not be allocated because: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.


root cause 
com.sun.appserv.connectors.internal.api.PoolingException: Connection could not be allocated because: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.


root cause 
com.sun.appserv.connectors.internal.api.PoolingException: Connection could not be allocated because: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.


root cause 
javax.resource.spi.ResourceAllocationException: Connection could not be allocated because: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.


root cause 
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.


root cause 
java.net.ConnectException: Connection refused: connect


note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.1.1 logs.


GlassFish Server Open Source Edition 4.1.1 

}

I searched on web and stack and see that it occursed because of eclipselink so I tested it with eclipselink 2.6.3 and 2.6.1 and reinstall my localhost but got errors again:

GET RequestFailed RequestFailed --> Status: (500) 
Response: {
HTTP Status 500 - Internal Server Error

type Exception report

messageInternal Server Error

descriptionThe server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper
root cause

org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper
root cause

java.lang.NoClassDefFoundError: Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.1.1 logs.

GlassFish Server Open Source Edition 4.1.1


}

sorry for my bad English language and thank you so much for putting your time for my problem even if just read it.


Answer:

The stacktrace shows that the code is failing with java.lang.NoClassDefFoundError

java.lang.NoClassDefFoundError: Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper

Make sure that org.eclipse.persistence.jaxb.BeanValidationHelper class dependecy is present during the runtime.

You can read more about NoClassDefFoundError @ How to solve java.lang.NoClassDefFoundError?

=========================================================================== Update:

It looks like there is a bug with GlassFish 4.1.1. The JIRA is still OPEN https://java.net/jira/browse/GLASSFISH-21440. There is one JIRA on Jersey as well https://java.net/jira/browse/JERSEY-2888. At the end, they have provided some workaround for the problem. Please verfiy with that workaround.

Question:

I have a maven java ee application

Path to the file is

~/Work/appname/WebContent/resources/json/menu.json

After deploying on glassfish file located here:

~/Tools/glassfish4/glassfish/domains/domain1/applications/appname/resources/json/menu.json

In this file stores menu in json format. I need to do basic crud (create, read, update, delete) operations with this file.

I've tried to get file like this:

InputStream inputStream  = ModulMenuUtil.class.getClassLoader().getResourceAsStream("/menu.json");

I get a NullPointerException. I don't know how to get path to this file. Please help me.


Answer:

Make sure your json folder and the file are placed under src/main/resources.

Try the following:

this.getClass().getClassLoader().getResourceAsStream("json/menu.json");

or (not recommended)

Thread.currentThread().getContextClassLoader().getResourceAsStream("json/menu.json");

If both methods don't work you can also try to put the file in the root of your src folder.

See also:

  • Where to place and how to read configuration resource files in servlet based application?
  • getClassLoader().getResourceAsStream("../resources/config.properties") returns null
  • file path in WebApplication using GlassFish
  • Why does getResource return null
  • getResourceAsStream() is always returning null

Question:

Using Jersey with the same code and testing in Glassfish 3.1.2 and 4.1.2 have different result output. Here is the code :

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public ArrayList<Lenovo> getList(@DefaultValue("0") @QueryParam("limit") final int limit,
                                    @DefaultValue("0") @QueryParam("offset") final int offset,
                                    @DefaultValue("0") @QueryParam("id") final int id,
                                    @DefaultValue("") @QueryParam("series") final String series) {

        DBBase obj = new Lenovo(id, series);
        DBSearch dbs = new DBSearch(limit, offset, obj);

        return bl.getList(dbs);
    }

JSON output from glassfish 3.1.2 :

    {
      "Lenovo": [
        {
          "id": "1",
          "series": "X220"
        },
        {
          "id": "12",
          "series": "X230"
        } 
      ]
    }

JSON Output from Glassfish 4.1.2 :

    [
      { 
        "id": "1",
        "series": "x220"
      },
      { 
        "id": "2",
        "series": "x230"
      }
    ]

Get data from database and return object.

    ArrayList<Agama> rtn = new ArrayList<Lenovo>();

    ResultSet rs = stmt.executeQuery(sql.toString());

        while (rs.next()) {
            rtn.add(new Lenovo(rs));
        }

    return rtn;

Lenovo Object :

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlRootElement(namespace="Lenovo")
    @XmlType(name = "Lenovo", propOrder = { 
        "id", 
        "series" 
    })

    public class Lenovo extends DBBase {
        int id;
        String series;

        private void setValues(ResultSet rs) {
            try {
                id = rs.getInt("id");
                series = rs.getString("series");
            } catch (SQLException ex) {
                ErisHelper.logger.error("Err>" + ex.getMessage(), ex);
            }
        }

    }

I've tried to using java platform JDK 1.6, 1.7 both of GLassfish and got the same result. How to get same JSON result output using same code in difference Glassfish version. Thanks.


Answer:

It's because they are using different serializers. Glassfish 3 is using some internal serializer. You can configure it to use Jackson 1, with just a web.xml configuration swtich, but still Glassfish 4 used MOXy by default, as its serializer.

Best thing to do, if you want the same behavior, is to just use the same serializer. You can add the following (Jackson 2) dependency

<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-json-provider</artifactId>
    <version>2.8.5</version>
</dependency>

If you're using web.xml for configuration, then just use the package scanning to pick up the providers.

In Glassfish 3

<init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>com.fasterxml.jackson.jaxrs.json</param-value>
</init-param>

In Glassfish 4

<init-param>
    <param-name>jersey.config.server.provider.packages</param-name>
    <param-value>com.fasterxml.jackson.jaxrs.json</param-value>
</init-param>

If you want the exception mappers, then you should also add the following package

<param-value>
    com.fasterxml.jackson.jaxrs.json,
    com.fasterxml.jackson.jaxrs.base   <----
</param-value>

If you're not using web.xml, ie. you're using an Application subclass, you should register the JacksonJaxbJsonProvider, and if you want the exception mappers, JsonMappingExceptionMapper, JsonParseExceptionMapper.

The last thing you need to do is to disabled MOXy in Glassfish 4. For this you can just set a property. In web.xml you can do

<init-param>
    <param-name>jersey.config.disableMoxyJson</param-name>
    <param-value>true</param-value>
</init-param>

If you're using an Application subclass, you can do

class MyApplication extends Application {
    @Override
    public Map<String, String> getProperties() {
        Map<String, String> props = new HashMap<>();
        props.put("jersey.config.disableMoxyJson", "true");
        return props;
    }
}

Question:

For days I am trying to get Glassfish 4.1.1 and Jersey working together. The tricky part is when there is communication via JSON.

I tried many solutions to get JSON data transfer working. Alas, still not working.

Glassfish and Jersey are 'standards', so I guess there is a standard way to combine these two? What is the correct way of configuring JSON?

Whenever I am starting to work with JSON, I get all kinds of errors. The last errors I get:

     2016-11-25T15:59:52.070+0100|Warning: StandardWrapperValve[Jersey Web Application]: Servlet.service() for servlet Jersey Web Application threw exception
java.lang.ClassNotFoundException: javax.xml.parsers.ParserConfigurationException not found by org.eclipse.persistence.moxy [228]
    at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1532)
    at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:75)
etc, etc. 

The maven dependencies are:

http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>nl.xyz</groupId>
<artifactId>GlassfishJerseyJson</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>GlassfishJerseyJson</name>

<build>
    <finalName>GlassfishJerseyJson</finalName>
    <plugins>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.1.1</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
                <!-- <webXml>src\main\webapp\WEB-INF\web.xml</webXml> -->
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.glassfish.maven.plugin</groupId>
            <artifactId>maven-glassfish-plugin</artifactId>
            <version>2.1</version>
            <configuration>
                <glassfishDirectory>${local.glassfish.home}</glassfishDirectory>
                <user>admin</user>
                <passwordFile>${local.glassfish.passfile}</passwordFile>
                <domain>
                    <name>domain1</name>
                    <httpPort>8080</httpPort>
                    <adminPort>4848</adminPort>
                </domain>
                <components>
                    <component>
                        <name>${project.artifactId}</name>
                        <artifact>target/${project.build.finalName}.war</artifact>
                    </component>
                </components>
                <debug>true</debug>
                <terse>false</terse>
                <echo>true</echo>
            </configuration>
        </plugin>
    </plugins>
</build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>javax</groupId> 
            <artifactId>javaee-web-api</artifactId> 
            <version>7.0</version> 
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId> 
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-json-provider</artifactId>
            <version>2.6.3</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.6.3</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>2.5.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
    <properties>
        <jersey.version>2.24.1</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

The JQuery call is:

function findResource() {
    $.ajax({
        type: 'GET',
        accepts: { json: "application/json, text/javascript" }, 
        dataType: "json",
        url: resourceURL, 
        success: function(data){
            alert( "Back from resource: name=" + data.name); 
        }, 
        error: function(jqXHR, textStatus, errorThrown){
            alert('Back from resource error: ' + textStatus + ' - Error: ' + errorThrown + " - Response: " + jqXHR.responseText);
        }
    });
}

Resource java file:

@Path("myresource")
public class MyResource {
     @GET
     @Produces( MediaType.APPLICATION_JSON)
     public Wine2 getIt() {
         Wine2 w = new Wine2();
         w.setId( 100);
         w.setCountry( "france");
         return w;
     }
} 

Configuration: option 1: web.xml (left the default first line out):

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>org.coenraets.cellar</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>
</web-app>

Configuration: option 2: MyApplication.java

import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;

public class MyApplication extends Application {
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> s = new HashSet<Class<?>>();
        s.add( MyResource.class);
        s.add( WineResource.class);
        return s;
    }
}

Answer:

Yesssss!!!! I found the complete answer.

The solution is by using the original (see above) maven libs ANd to change the following files in the GLASSFISH/modules folder to verion 2.5.0 (or similar):

  • org.eclipse.persistence.moxy.jar
  • org.eclipse.persistence.core.jar

The solution came via [this webpage][1] and similar sites.

In this post and others the org.eclipse.persistence.moxy.jar file in the $Glassfish/modules is replaced with the 2.5.0 version.

Question:

I got a problem consuming a web service with Angular from a client.

I have created a person.java class:

public class person {

    private String id;
    private String name;

    public person(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

The Rest service has the following function:

serviceTest.java

@Path("/service")
public class serviceTest{
    @GET
    @Path("/findall")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Person> findAll(){
        List <Person> result = new ArrayList<>();
        result.add(new Person("1", "Jason");
        result.add(new Person("2", "Kimberly");
        return result;
        }
    }

When I called the findAll() function, it returns the following JSON object:

[
    {
        "id": "1",
        "name": "Jason"    
    },

    {
        "id": "2",
        "name": "Kimberly"  
    }
]

Now, in the client I have the index.jsp where I call the service with angular.js in which I want to show the values in a table:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html ng-app="myapp">
<head>
    <title>$Title$</title>
    <script type="text/javascript" src="resources/javaScript/angular.min.js"></script>
</head>
<body ng-controller="personController">

<table cellpadding="2" cellspacing="2" border="1">
    <tr>
        <th>ID</th>
        <th>Name</th>
    </tr>
    <tr ng-repeat="pr in listPerson">
        <td>{{pr.id}}</td>
        <td>{{pr.name}}</td>
    </tr>
</table>

<script type="text/javascript">
    var myapp = angular.module('myapp', []);
    myapp.controller('personController', function ($scope, $http) {
        $http.get('http://localhost:8080/wsService/api/service/findall').success(function(data) {
            $scope.listPerson = data;
        });
    });

</script>    
</body>
</html>

When I execute java client and the index is loaded, nothing is show in the table:

Thanks in advance...


Answer:

Thank you all, I already did it...

I added a CORSFilter class to the web service:

public class CORSFilter implements Filter {

public CORSFilter() {
}

public void init(FilterConfig fConfig) throws ServletException {
}

public void destroy() {
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    ((HttpServletResponse) response).addHeader("Access-Control-Allow-Origin", "*");
    ((HttpServletResponse) response).addHeader("Access-Control-Allow-Credentials", "true");
    ((HttpServletResponse) response).addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE");
    ((HttpServletResponse) response).addHeader("Access-Control-Allow-Headers", "X-Requested-With");
    chain.doFilter(request, response);
}

}

And in the web.xml:

<filter>
    <filter-name>CORSFilter</filter-name>
    <filter-class>CORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CORSFilter</filter-name>
    <url-pattern>/api/*</url-pattern>
</filter-mapping>