Instantly share code, notes, and snippets.

Embed
What would you like to do?
Setup for Jersey 1.19.1 RESTful Interface in Netbeans

Setup for Jersey 1.19.1 RESTful Interface in Netbeans

License: CC BY 4.0

Florian Thiery M.Sc.

Römisch-Germanisches Zentralmuseum (RGZM)

i3mainz - Institut für Raumbezogene Informations- und Messtechnik

package restconfig;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;
public class CORSFilter implements ContainerResponseFilter {
@Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
response.getHttpHeaders().add("Access-Control-Allow-Origin", "*");
response.getHttpHeaders().add("Access-Control-Allow-Methods", "GET");
response.getHttpHeaders().add("Access-Control-Allow-Headers", "Content-Type, Accept, Accept-Encoding");
response.getHttpHeaders().add("Access-Control-Allow-Credentials", "false");
return response;
}
}
package rest;
import errorlog.Logging;
import restconfig.ResponseGZIP;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.simple.JSONObject;
@Path("/")
public class GenericResource {
@GET
@Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
public Response getEmptyJSON(@HeaderParam("Accept-Encoding") String acceptEncoding, @HeaderParam("Accept") String acceptHeader) {
try {
return ResponseGZIP.setResponse(acceptEncoding, new JSONObject().toJSONString(), Response.Status.OK);
} catch (Exception e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(Logging.getMessageJSON(e, "rest.GenericResource"))
.header("Content-Type", "application/json;charset=UTF-8").build();
}
}
}
package restconfig;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.ws.rs.NameBinding;
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface Gzip {}
package restconfig;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
@Provider
@Gzip
public class GZIPWriterInterceptor implements WriterInterceptor {
@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
final OutputStream outputStream = context.getOutputStream();
context.setOutputStream(new GZIPOutputStream(outputStream));
context.proceed();
}
}
package errorlog;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class Logging {
public static String getMessageJSON(Exception exception, String endClass) {
// START BUILD JSON
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JSONObject jsonobj_error = new JSONObject(); // {}
JSONObject jsonobj_error_data = new JSONObject(); // {}
JSONArray jsonarray_element = new JSONArray();
for (StackTraceElement element : exception.getStackTrace()) {
JSONObject errMessage = new JSONObject();
errMessage.put("class", element.getClassName());
errMessage.put("method", element.getMethodName());
errMessage.put("line", element.getLineNumber());
jsonarray_element.add(errMessage);
if (element.getClassName().equals(endClass)) {
break;
}
}
// get error code
String code = "";
String userMessage = "";
if (exception.toString().contains("NullPointerException")) {
code = "1";
userMessage = "some value is not available";
} else if (exception.toString().contains("ValidateJSONObjectException")) {
code = "2";
String[] ex = exception.toString().split(": ");
userMessage = "validate JSON object exception: " + ex[1];
}
// output
jsonobj_error.put("errors", jsonobj_error_data);
jsonobj_error_data.put("internalMessage", exception.toString());
jsonobj_error_data.put("userMessage", userMessage);
jsonobj_error_data.put("code", code);
jsonobj_error_data.put("developerInfo", jsonarray_element);
// OUTPUT AS pretty print JSON
return gson.toJson(jsonobj_error);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<properties>
<jersey.version>1.19.1</jersey.version>
</properties>
<dependencies>
<!-- Tests -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- json -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.3.0</version>
</dependency>
<!-- Jersey 1.19.1 -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>${jersey.version}</version>
</dependency>
</dependencies>
</project>
package restconfig;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
public class ResponseGZIP {
public static Response setResponse(String acceptEncoding, String output, Response.Status ResponseCode) {
if (acceptEncoding.contains("gzip")) {
// set outputstream
final String OUTSTRING_FINAL = output;
StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream output) throws IOException, WebApplicationException {
try {
output = GZIP(OUTSTRING_FINAL, output);
} catch (Exception e) {
System.out.println(e.toString());
}
}
};
return Response.status(ResponseCode).entity(stream)
.header("Content-Type", "application/json;charset=UTF-8").header("Content-Encoding", "gzip").build();
} else {
return Response.status(ResponseCode).entity(output)
.header("Content-Type", "application/json;charset=UTF-8").build();
}
}
private static OutputStream GZIP(String input, OutputStream baos) throws IOException {
try (GZIPOutputStream gzos = new GZIPOutputStream(baos)) {
gzos.write(input.getBytes("UTF-8"));
} catch (Exception e) {
System.out.println(e.toString());
}
return baos;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<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>API</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>rest</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>restconfig.CORSFilter</param-value>
</init-param>
<!-- http://javaevangelist.blogspot.de/2012/01/jersey-tip-of-day-use-gzip-compression.html-->
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
<param-value>com.sun.jersey.api.container.filter.GZIPContentEncodingFilter</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>com.sun.jersey.api.container.filter.GZIPContentEncodingFilter</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>API</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment