Hot questions for Using Enterprise JavaBeans in json

Question:

I am working on Maven-EJB and want to convert a java object to JSON, I use Jackson jars lib but I got:

java.lang.ClassNotFoundException: com.fasterxml.jackson.core.Versioned

I added these dependencies in pom.xml file:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.4.0</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.4.0</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.4.0</version>
    </dependency>

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

    <dependency>
        <groupId>com.fasterxml.jackson.module</groupId>
        <artifactId>jackson-module-jaxb-annotations</artifactId>
        <version>2.4.0</version>
    </dependency>        
</dependencies>

in Java Facade I write this lines to convert:

String json = "";

    try {
         ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
         json = ow.writeValueAsString(userlist);
    } catch (JsonProcessingException e) {
        throw new BusinessException("error_json");
    }

and here is the imports:

import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter;

I checked the classpath and make a lot of clean and build but no way,,,the same exception appear!!

I am working on NetBeans8 and Java 1.7

Thanks in advance Mariam


Answer:

Thanks Couettos, it works, I checked the versions of application server and the maven jars then I downloaded the latest 2.4.0 jackson jars and upgrade the glassfish lib jars with the 2.4.0 version

Question:

I have tried to get the json object from android client in my Ejb Based Web application which used Restful api with jax-rs. But I'm unavailable to get the json object. It throw 404 error even I have match all the keyname with my entity class variable

My pojo class look like this:

@Entity
@Table(name = "events")
@NamedQueries({
    @NamedQuery(name = Event.FIND_ALL,query="Select e from Event e")
})
public class Event implements Serializable{

public static final String PREFIX="np.com.drose.data.modules.employee.domain.event.";
public static final String FIND_ALL=PREFIX+"FIND_ALL";

@Id
@GeneratedValue
private int eventId;

@Future
@Temporal(TemporalType.DATE)
private Date dateofEvent;

private String content;

private String header;

private String place;

private String specification;

public int getEventId() {
    return eventId;
}

public void setEventId(int eventId) {
    this.eventId = eventId;
}

public Date getDateofEvent() {
    return dateofEvent;
}

public void setDateofEvent(Date dateofEvent) {
    this.dateofEvent = dateofEvent;
}

public String getContent() {
    return content;
}

public void setContent(String content) {
    this.content = content;
}

public String getHeader() {
    return header;
}

public void setHeader(String header) {
    this.header = header;
}

public String getSpecification() {
    return specification;
}

public void setSpecification(String specification) {
    this.specification = specification;
}

public String getPlace() {
    return place;
}

public void setPlace(String place) {
    this.place = place;
}

}

and my Resources class look like this:

    @Path("secured")
    @Stateless
    public class EventAddResurces {
    @Inject
    EventServices eventServices;


    @POST
    @Path("/event/add")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.TEXT_PLAIN)
    public Response getResponse(Event event){
        this.eventServices.addEvent(event);
        return Response.ok().status(200).entity("Successfully added").build();
    }
}

Answer:

Use a library, such as Jackson's ObjectMapper, to serialize the Event object to JSON and save it in the database, e.g.

ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(event);
// Persist JSON string in database.

Question:

I have a problem with my EJB:

public class EntryResponseBuilder extends BaseResponseBuilder {
@EJB
private ApplicationCustomerCache applicationCustomerCache; //null

I have something like this in class that returns a JSON response.

@Singleton
@Startup
public class ApplicationCustomerCache {
    @EJB
    CustomerDao customerDao;
    private Map<Integer, Customer> customerMap;
    private Map<Integer, List<Customer>> applicationToCustomersMap;
    private static Logger log = Logger.getLogger(ApplicationCustomerCache.class);

    @PostConstruct
    public void initialize() {
        try {
            get();
        } catch (Exception e) {
            log.error("ApplicationCustomerCache.init()", e);
        }
    }

    private void get() throws SQLException {

And its working fine, except that when I try to get injection in EntryResponseBuilder, it's empty. One function before, it inject, where I have class with @Stateless. I've searched in Google, but I can not find any solution.


Answer:

Your dealing with two issues here:

  1. Your're trying to inject an instance of a bean on a POJO, which is not managed by the container;
  2. What's the EJB spec that you're following?

For both of them, I think the following answers can help you:

  • https://stackoverflow.com/a/3483720/1346996
  • https://stackoverflow.com/a/8138452/1346996

Question:

I'm using Eclipse Neon 3.6.3 and I have a Java EJB project where I try to use Json-Objects to evaluate the response from a REST-Service. I've imported JSONObject:

import org.json.JSONObject;

And added

json-20160810.jar

to the Build Path. After I deployed it on a Glassfish-Server (3.1.2) I get the following Error:

Caused by: java.lang.NoClassDefFoundError: org/json/JSONObject

Answer:

You probably can solve the problem by putting the JAR into the folder /glassfish3/glassfish/lib and restarting Glassfish.

A second solution would be to include the JAR in a WAR or EAR file for deployment. There are plenty of tutorials for that on the net, but I'm not sure what you need exactly for Eclipse.

Question:

I am working on the server side of a mobile application. One of the requirements I have is to implement the server using Java EE, JPA, EJB, and JSON.

I am new to Java EE but I did some reading and so far managed to build the business logic by implementing the Pojos and the EJBs of the project.

Where I am encountering difficulties is in figuring out how to expose my EJBs as a RESTful web service that can be consumed by the client side of the application. I could find some documentation and tutorials but all of it was related to building a backend for a website as opposed to mobile.

What are the best practices in exposing the business logic as a RESTful web service to a mobile application in a Java EE environment?


Answer:

I'm not sure what your app server is but with JavaEE 6 and 7, you can do this fairly easily. Take a look at this tutorial for a good starting point. In general, a simple service would look something like:

@Path("/login")
public class LoginService  {    

    @Consumes({MediaType.APPLICATION_JSON})
    @Produces({MediaType.APPLICATION_JSON})
    @POST
    public Response login(LoginRequest loginRequest) throws Exception {  
    // your code
    }

where LoginRequest in this case is simple Java POJO that has an equivalent in the JavaScript world.

Note that it doesn't matter what the client side is - the server just wants the JSON encoded object to come in and it can be a browser or a native mobile app.

A bit of an issue is how to initialize your app servers underlying Rest framework. Some use web.xml, some use a specially annotated class. That is a bit of a different question - let us know which app server you're using.