diff --git a/jersey-crud-example/.classpath b/jersey-crud-example/.classpath new file mode 100644 index 0000000..c169161 --- /dev/null +++ b/jersey-crud-example/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jersey-crud-example/.project b/jersey-crud-example/.project new file mode 100644 index 0000000..47e53d7 --- /dev/null +++ b/jersey-crud-example/.project @@ -0,0 +1,37 @@ + + + jersey-crud-example + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/jersey-crud-example/.settings/.jsdtscope b/jersey-crud-example/.settings/.jsdtscope new file mode 100644 index 0000000..2418123 --- /dev/null +++ b/jersey-crud-example/.settings/.jsdtscope @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/jersey-crud-example/.settings/org.eclipse.jdt.core.prefs b/jersey-crud-example/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..13b3428 --- /dev/null +++ b/jersey-crud-example/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,13 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/jersey-crud-example/.settings/org.eclipse.m2e.core.prefs b/jersey-crud-example/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/jersey-crud-example/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/jersey-crud-example/.settings/org.eclipse.wst.common.component b/jersey-crud-example/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..f21393c --- /dev/null +++ b/jersey-crud-example/.settings/org.eclipse.wst.common.component @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/jersey-crud-example/.settings/org.eclipse.wst.common.project.facet.core.xml b/jersey-crud-example/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..d74c55e --- /dev/null +++ b/jersey-crud-example/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/jersey-crud-example/.settings/org.eclipse.wst.jsdt.ui.superType.container b/jersey-crud-example/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100644 index 0000000..3bd5d0a --- /dev/null +++ b/jersey-crud-example/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/jersey-crud-example/.settings/org.eclipse.wst.jsdt.ui.superType.name b/jersey-crud-example/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100644 index 0000000..05bd71b --- /dev/null +++ b/jersey-crud-example/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/jersey-crud-example/.settings/org.eclipse.wst.validation.prefs b/jersey-crud-example/.settings/org.eclipse.wst.validation.prefs new file mode 100644 index 0000000..04cad8c --- /dev/null +++ b/jersey-crud-example/.settings/org.eclipse.wst.validation.prefs @@ -0,0 +1,2 @@ +disabled=06target +eclipse.preferences.version=1 diff --git a/jersey-crud-example/pom.xml b/jersey-crud-example/pom.xml new file mode 100644 index 0000000..bf827bb --- /dev/null +++ b/jersey-crud-example/pom.xml @@ -0,0 +1,88 @@ + + 4.0.0 + com.javadevelopersguide.jersey + jersey-crud-example + war + 0.0.1-SNAPSHOT + jersey-crud-example Maven Webapp + http://maven.apache.org + + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + + org.glassfish.jersey.core + jersey-server + ${jersey.version} + + + org.glassfish.jersey.containers + jersey-container-servlet + ${jersey.version} + + + + + org.glassfish.jersey.media + jersey-media-moxy + ${jersey.version} + + + + org.glassfish.jersey.inject + jersey-hk2 + ${jersey.version} + + + + + org.glassfish.jersey.core + jersey-client + ${jersey.version} + + + + org.slf4j + slf4j-log4j12 + 1.7.21 + + + + + jersey-crud-example + + + org.apache.maven.plugins + maven-war-plugin + + false + + + + maven-compiler-plugin + 2.0.2 + + 1.8 + 1.8 + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + 2.2 + + + + + + 2.26 + + + diff --git a/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/client/UserResourceClient.java b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/client/UserResourceClient.java new file mode 100644 index 0000000..b0981d0 --- /dev/null +++ b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/client/UserResourceClient.java @@ -0,0 +1,103 @@ +package com.javadevelopersguide.jersey.client; + +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.logging.LoggingFeature; + +import com.javadevelopersguide.jersey.model.User; + +public class UserResourceClient { + + public static void main(String[] args) { + // getUsers(); + // getUser(); + createUser(); + // updateUser(); + //deleteUser(); + } + + protected static ClientConfig createClientConfig() { + ClientConfig config = new ClientConfig(); + config.register(new LoggingFeature(Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 10000)); + return config; + } + + private static void getUsers() { + Client client = ClientBuilder.newClient(createClientConfig()); + + String entity = client.target("http://localhost:8080/jersey-crud-example/api").path("users") + .request(MediaType.APPLICATION_JSON).header("some-header", "true").get(String.class); + + System.out.println(entity); + } + + private static void getUser() { + Client client = ClientBuilder.newClient(); + + String entity = client.target("http://localhost:8080/jersey-crud-example/api").path("users").path("user/100") + .request(MediaType.APPLICATION_JSON).header("some-header", "true").get(String.class); + + System.out.println(entity); + } + + private static void createUser() { + Client client = ClientBuilder.newClient(createClientConfig()); + WebTarget webTarget = client.target("http://localhost:8080/jersey-crud-example/api").path("users"); + + User user = new User(); + user.setId(1); + user.setName("Ramesh"); + + Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); + Response response = invocationBuilder.post(Entity.entity(user, MediaType.APPLICATION_JSON)); + + System.out.println(response.getStatus()); + System.out.println(response.readEntity(String.class)); + } + + private static void updateUser() { + Client client = ClientBuilder.newClient(); + WebTarget webTarget = client.target("http://localhost:8080/jersey-crud-example/api").path("users") + .path("user/1"); + + User user = new User(); + user.setId(1); + user.setName("Ramesh"); + + Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); + Response response = invocationBuilder.put(Entity.entity(user, MediaType.APPLICATION_JSON)); + + String userJson = response.readEntity(String.class); + + System.out.println(response.getStatus()); + System.out.println(userJson); + } + + private static void deleteUser() { + + Client client = ClientBuilder.newClient(); + WebTarget webTarget = client.target("http://localhost:8080/jersey-crud-example/api").path("users") + .path("user/100"); + + User user = new User(); + user.setId(1); + user.setName("Ramesh"); + + Invocation.Builder invocationBuilder = webTarget.request(); + Response response = invocationBuilder.delete(); + + System.out.println(response.getStatus()); + System.out.println(response.readEntity(String.class)); + } +} diff --git a/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/config/AppResourceConfig.java b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/config/AppResourceConfig.java new file mode 100644 index 0000000..98e2772 --- /dev/null +++ b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/config/AppResourceConfig.java @@ -0,0 +1,22 @@ +package com.javadevelopersguide.jersey.config; + +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.ws.rs.ApplicationPath; + +import org.glassfish.jersey.logging.LoggingFeature; +// Deployment of a JAX-RS application using @ApplicationPath with Servlet 3.0 +// Descriptor-less deployment +import org.glassfish.jersey.server.ResourceConfig; + +@ApplicationPath("/api") +public class AppResourceConfig extends ResourceConfig { + + public AppResourceConfig() { + // if there are more than two packanges then separate them with semicolon + // exmaple : packages("org.foo.rest;org.bar.rest"); + packages("com.javadevelopersguide.jersey.resources"); + register(new LoggingFeature(Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 10000)); + } +} diff --git a/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/exception/ApiException.java b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/exception/ApiException.java new file mode 100644 index 0000000..117e545 --- /dev/null +++ b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/exception/ApiException.java @@ -0,0 +1,25 @@ +/** + * Copyright 2016 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.javadevelopersguide.jersey.exception; + +public class ApiException extends Exception{ + private int code; + public ApiException (int code, String msg) { + super(msg); + this.code = code; + } +} diff --git a/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/exception/BadRequestException.java b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/exception/BadRequestException.java new file mode 100644 index 0000000..58ff168 --- /dev/null +++ b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/exception/BadRequestException.java @@ -0,0 +1,25 @@ +/** + * Copyright 2016 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.javadevelopersguide.jersey.exception; + +public class BadRequestException extends ApiException{ + private int code; + public BadRequestException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/exception/NotFoundException.java b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/exception/NotFoundException.java new file mode 100644 index 0000000..84fb3b2 --- /dev/null +++ b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/exception/NotFoundException.java @@ -0,0 +1,25 @@ +/** + * Copyright 2016 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.javadevelopersguide.jersey.exception; + +public class NotFoundException extends ApiException { + private int code; + public NotFoundException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/exception/ResourceNotFoundException.java b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/exception/ResourceNotFoundException.java new file mode 100644 index 0000000..440d60c --- /dev/null +++ b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/exception/ResourceNotFoundException.java @@ -0,0 +1,12 @@ +package com.javadevelopersguide.jersey.exception; + +public class ResourceNotFoundException extends Exception{ + /** + * + */ + private static final long serialVersionUID = 1L; + + public ResourceNotFoundException(String message){ + super(message); + } +} diff --git a/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/model/APIResponse.java b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/model/APIResponse.java new file mode 100644 index 0000000..f47e506 --- /dev/null +++ b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/model/APIResponse.java @@ -0,0 +1,37 @@ +package com.javadevelopersguide.jersey.model; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class APIResponse { + private int errorCode; + private String message; + + public APIResponse(){ + + } + + public APIResponse(int errorCode, String message) { + super(); + this.errorCode = errorCode; + this.message = message; + } + + public int getErrorCode() { + return errorCode; + } + + public void setErrorCode(int errorCode) { + this.errorCode = errorCode; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + +} diff --git a/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/model/User.java b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/model/User.java new file mode 100644 index 0000000..df8348f --- /dev/null +++ b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/model/User.java @@ -0,0 +1,40 @@ +package com.javadevelopersguide.jersey.model; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class User { + private long id; + private String name; + private String email; + + public User() { + + } + + + public User(long id, String name, String email) { + super(); + this.id = id; + this.name = name; + this.email = email; + } + public long getId() { + return id; + } + public void setId(long id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } +} diff --git a/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/resources/CustomExceptionMapper.java b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/resources/CustomExceptionMapper.java new file mode 100644 index 0000000..bac5734 --- /dev/null +++ b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/resources/CustomExceptionMapper.java @@ -0,0 +1,53 @@ +package com.javadevelopersguide.jersey.resources; + +import java.util.HashMap; + +import javax.ws.rs.NotFoundException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +import com.javadevelopersguide.jersey.exception.BadRequestException; +import com.javadevelopersguide.jersey.exception.ResourceNotFoundException; +import com.javadevelopersguide.jersey.model.APIResponse; + +@Provider +public class CustomExceptionMapper { + + // -- Exception Mappers + @Provider + public static class ResourceNotFoundExceptionMapper implements ExceptionMapper { + + @Override + public Response toResponse(ResourceNotFoundException exception) { + return Response + .status(Status.NOT_FOUND) + .entity(new HashMap<>().put(Status.INTERNAL_SERVER_ERROR, exception.getMessage())).build(); + } + } + + @Provider + public static class BadRequestExceptionMapper implements ExceptionMapper { + + @Override + public Response toResponse(BadRequestException exception) { + return Response.status(Response.Status.BAD_REQUEST).entity( + "Code:" + Response.Status.BAD_REQUEST + ":" + exception.getMessage()).build(); + } + } + + @Provider + public static class NotFoundExceptionMapper implements ExceptionMapper { + + @Override + public Response toResponse(NotFoundException exception) { + Response r = exception.getResponse(); + return Response.status(r.getStatus()).entity( + new APIResponse(r.getStatus(),exception.getMessage())).build(); + } + } + +} + + diff --git a/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/resources/UserResource.java b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/resources/UserResource.java new file mode 100644 index 0000000..55fbbe1 --- /dev/null +++ b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/resources/UserResource.java @@ -0,0 +1,85 @@ +package com.javadevelopersguide.jersey.resources; + +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.InternalServerErrorException; +import javax.ws.rs.NotFoundException; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import com.javadevelopersguide.jersey.model.User; +import com.javadevelopersguide.jersey.services.UserService; + +@Path("/users") +public class UserResource { + + private UserService userService = new UserService(); + + @GET + @Produces(MediaType.APPLICATION_JSON) + public List fetchAll() { + return userService.fetchAll(); + } + + @GET + @Path("user/id/{id}") + @Produces(MediaType.APPLICATION_JSON) + public Response fetchBy(@PathParam("id") int id) { + User user = userService.fetchBy(id); + return Response.ok().entity(user).build(); + } + + @GET + @Path("user/{id}") + @Produces(MediaType.APPLICATION_JSON) + public Response get(@PathParam("id") int id) { + return Response.ok().entity(new User(100, "me", "me@gmail.com")).build(); + } + + + @GET + @Path("exception/{id}") + @Produces(MediaType.APPLICATION_JSON) + public Response exception(@PathParam("id") long id) { + throw new NotFoundException("Resource not found ::" + id); + } + + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public Response create(User user) { + // create notification + userService.create(user); + return Response.status(Status.CREATED).build(); + } + + @POST + @Path("request_exception") + public String exceptionInRequestFilter() { + throw new InternalServerErrorException(); // should not reach here + } + + @PUT + @Path("/user/{id}") + @Consumes(MediaType.APPLICATION_JSON) + public Response update(@PathParam("id") long id, User user) { + userService.update(user); + return Response.noContent().build(); + } + + @DELETE + @Path("/user/{id}") + public Response delete(@PathParam("id") long id) { + userService.delete(id); + return Response.status(202).entity("User deleted successfully !!").build(); + } +} diff --git a/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/services/UserService.java b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/services/UserService.java new file mode 100644 index 0000000..ccddb4e --- /dev/null +++ b/jersey-crud-example/src/main/java/com/javadevelopersguide/jersey/services/UserService.java @@ -0,0 +1,49 @@ +package com.javadevelopersguide.jersey.services; + +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.NotFoundException; + +import com.javadevelopersguide.jersey.model.User; + +public class UserService { + + private List users = new ArrayList(); + + public List fetchAll() { + + users.add(new User(100, "A", "demo@gmail.com")); + users.add(new User(101, "B", "demo1@gmail.com")); + users.add(new User(102, "C", "demo2@gmail.com")); + return users; + } + + public User fetchBy(long id) throws NotFoundException { + for (User user2 : fetchAll()) { + if (id == user2.getId()) { + return user2; + }else{ + throw new NotFoundException("Resource not found with Id :: " + id); + } + } + return null; + } + + public void create(User user) { + users.add(user); + } + + public void update(User user) { + for (User user2 : users) { + if (user.getId() == user2.getId()) { + users.remove(user2); + users.add(user); + } + } + } + + public void delete(long id) throws NotFoundException { + // delete operation + } +} diff --git a/jersey-crud-example/src/main/webapp/WEB-INF/web.xml b/jersey-crud-example/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..9f88c1f --- /dev/null +++ b/jersey-crud-example/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,7 @@ + + + + Archetype Created Web Application + diff --git a/jersey-crud-example/src/main/webapp/index.jsp b/jersey-crud-example/src/main/webapp/index.jsp new file mode 100644 index 0000000..c38169b --- /dev/null +++ b/jersey-crud-example/src/main/webapp/index.jsp @@ -0,0 +1,5 @@ + + +

Hello World!

+ + diff --git a/jersey-exception-mapping-example/.classpath b/jersey-exception-mapping-example/.classpath new file mode 100644 index 0000000..c169161 --- /dev/null +++ b/jersey-exception-mapping-example/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jersey-exception-mapping-example/.project b/jersey-exception-mapping-example/.project new file mode 100644 index 0000000..32f5181 --- /dev/null +++ b/jersey-exception-mapping-example/.project @@ -0,0 +1,37 @@ + + + jersey-exception-mapping-example + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/jersey-exception-mapping-example/.settings/.jsdtscope b/jersey-exception-mapping-example/.settings/.jsdtscope new file mode 100644 index 0000000..2418123 --- /dev/null +++ b/jersey-exception-mapping-example/.settings/.jsdtscope @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/jersey-exception-mapping-example/.settings/org.eclipse.jdt.core.prefs b/jersey-exception-mapping-example/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..13b3428 --- /dev/null +++ b/jersey-exception-mapping-example/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,13 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/jersey-exception-mapping-example/.settings/org.eclipse.m2e.core.prefs b/jersey-exception-mapping-example/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/jersey-exception-mapping-example/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/jersey-exception-mapping-example/.settings/org.eclipse.wst.common.component b/jersey-exception-mapping-example/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..2d94fa9 --- /dev/null +++ b/jersey-exception-mapping-example/.settings/org.eclipse.wst.common.component @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/jersey-exception-mapping-example/.settings/org.eclipse.wst.common.project.facet.core.xml b/jersey-exception-mapping-example/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..d74c55e --- /dev/null +++ b/jersey-exception-mapping-example/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/jersey-exception-mapping-example/.settings/org.eclipse.wst.jsdt.ui.superType.container b/jersey-exception-mapping-example/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100644 index 0000000..3bd5d0a --- /dev/null +++ b/jersey-exception-mapping-example/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/jersey-exception-mapping-example/.settings/org.eclipse.wst.jsdt.ui.superType.name b/jersey-exception-mapping-example/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100644 index 0000000..05bd71b --- /dev/null +++ b/jersey-exception-mapping-example/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/jersey-exception-mapping-example/.settings/org.eclipse.wst.validation.prefs b/jersey-exception-mapping-example/.settings/org.eclipse.wst.validation.prefs new file mode 100644 index 0000000..04cad8c --- /dev/null +++ b/jersey-exception-mapping-example/.settings/org.eclipse.wst.validation.prefs @@ -0,0 +1,2 @@ +disabled=06target +eclipse.preferences.version=1 diff --git a/jersey-exception-mapping-example/README.MD b/jersey-exception-mapping-example/README.MD new file mode 100644 index 0000000..2d7ddd3 --- /dev/null +++ b/jersey-exception-mapping-example/README.MD @@ -0,0 +1,44 @@ +http://localhost:8080/jersey-exception-mapping-example/resources/exception + + +Exception Mapping Example +========================= + +This example demonstrates how to create a custom exception mapping. There are described several common use-cases such as +`WebApplicationException`, custom exceptions and an exception mapper inheritance. + +The full description how to handle exception and map them to Response object can be found in Jersey User Guide, chapter +[WebApplicationException and Mapping Exceptions to Responses](https://jersey.java.net/documentation/latest/representations.html#d0e6567). + +Contents +-------- + +The mapping of the URI path space is presented in the following table: + +URI path | HTTP methods | Allowed Values | Description +----------------------------------------- | ------------- |-------------------------------------------- | ---------------- +**_/exception_** | GET | --- | returns "ping!" +**_/exception/webapplication_entity_** | POST | two numbers delimited by colons e.g. 1:201 | not handled by `WebApplicationExceptionMapper` (already has an entity in the exception) +**_/exception/webapplication_noentity_** | POST | e.g. 1:201 | handled by `WebApplicationExceptionMapper` +**_/exception/my_** | POST | e.g. 1:201 | handled by `MyExceptionMapper` +**_/exception/mysub_** | POST | e.g. 1:201 | handled by `MySubExceptionMapper` +**_/exception/mysubsub_** | POST | e.g. 1:201 | handled by `MySubExceptionMapper` +**_/exception/request_exception_** | POST | String "Request Exception" | not reached a resource method, processed by `ContainerRequestFilter` +**_/exception/response_exception_** | GET | --- | response handled and changed by `ContainerResponseFilter` + + +Application is based on Grizzly container (see `App`). Everything needed +(resources/providers) is registered in `ExceptionResource` and custom exceptions +along with mappers can be found in `Exceptions` class. + +Running the Example +------------------- + +Run the example as follows: + +> mvn clean compile exec:java + +This deploys the example using [Grizzly](http://grizzly.java.net/) container. + +- +- diff --git a/jersey-exception-mapping-example/pom.xml b/jersey-exception-mapping-example/pom.xml new file mode 100644 index 0000000..392b109 --- /dev/null +++ b/jersey-exception-mapping-example/pom.xml @@ -0,0 +1,58 @@ + + 4.0.0 + com.javadevelopersguide.jersey + jersey-exception-mapping-example + war + 0.0.1-SNAPSHOT + jersey-exception-mapping-example Maven Webapp + http://maven.apache.org + + + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + + org.glassfish.jersey.core + jersey-server + 2.7 + + + org.glassfish.jersey.containers + jersey-container-servlet + 2.7 + + + + jersey-exception-mapping-example + + + org.apache.maven.plugins + maven-war-plugin + + false + + + + maven-compiler-plugin + 2.0.2 + + 1.8 + 1.8 + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + 2.2 + + + + + diff --git a/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/config/JerseyServletContainerConfig.java b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/config/JerseyServletContainerConfig.java new file mode 100644 index 0000000..ac38dcd --- /dev/null +++ b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/config/JerseyServletContainerConfig.java @@ -0,0 +1,17 @@ +package com.javadevelopersguide.jersey.config; + +import javax.ws.rs.ApplicationPath; + +// Deployment of a JAX-RS application using @ApplicationPath with Servlet 3.0 +// Descriptor-less deployment +import org.glassfish.jersey.server.ResourceConfig; + +@ApplicationPath("resources") +public class JerseyServletContainerConfig extends ResourceConfig { + public JerseyServletContainerConfig() { + + // if there are more than two packanges then separate them with semicolon + // exmaple : packages("org.foo.rest;org.bar.rest"); + packages("com.javadevelopersguide.jersey.helloworld;com.javadevelopersguide.jersey.resources"); + } +} diff --git a/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/helloworld/HelloWorldResource.java b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/helloworld/HelloWorldResource.java new file mode 100644 index 0000000..9a6b470 --- /dev/null +++ b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/helloworld/HelloWorldResource.java @@ -0,0 +1,14 @@ +package com.javadevelopersguide.jersey.helloworld; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +@Path("/") +public class HelloWorldResource { + + @GET + @Path("helloworld") + public String helloworld(){ + return "Helloworld !!!!"; + } +} diff --git a/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/ApiResponse.java b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/ApiResponse.java new file mode 100644 index 0000000..2b66b5c --- /dev/null +++ b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/ApiResponse.java @@ -0,0 +1,84 @@ +/** + * Copyright 2016 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.javadevelopersguide.jersey.resources; + +import javax.xml.bind.annotation.XmlTransient; + +@javax.xml.bind.annotation.XmlRootElement +public class ApiResponse { + public static final int ERROR = 1; + public static final int WARNING = 2; + public static final int INFO = 3; + public static final int OK = 4; + public static final int TOO_BUSY = 5; + + int code; + String type; + String message; + + public ApiResponse(){} + + public ApiResponse(int code, String message){ + this.code = code; + switch(code){ + case ERROR: + setType("error"); + break; + case WARNING: + setType("warning"); + break; + case INFO: + setType("info"); + break; + case OK: + setType("ok"); + break; + case TOO_BUSY: + setType("too busy"); + break; + default: + setType("unknown"); + break; + } + this.message = message; + } + + @XmlTransient + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/CustomExceptionMapper.java b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/CustomExceptionMapper.java new file mode 100644 index 0000000..1e0f975 --- /dev/null +++ b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/CustomExceptionMapper.java @@ -0,0 +1,19 @@ +package com.javadevelopersguide.jersey.resources; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +@Provider +public class CustomExceptionMapper implements ExceptionMapper { + + @Override + public Response toResponse(ResourceNotFoundException exception) { + return Response + .status(Status.NOT_FOUND) + .entity(new ApiResponse(ApiResponse.ERROR, exception + .getMessage())).build(); + } + +} diff --git a/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/CustomExceptionResource.java b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/CustomExceptionResource.java new file mode 100644 index 0000000..2e17f6c --- /dev/null +++ b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/CustomExceptionResource.java @@ -0,0 +1,27 @@ +package com.javadevelopersguide.jersey.resources; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import com.javadevelopersguide.jersey.resources.exception.BadRequestException; + +@Path("customexception/") +public class CustomExceptionResource { + + @GET + @Path("notfound") + @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public String notfound() throws ResourceNotFoundException { + throw new ResourceNotFoundException("Resource not found exception."); + } + + @GET + @Path("badrequest") + @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public String badrequest() throws BadRequestException { + throw new BadRequestException(400, "Bad Request Exception."); + } + +} diff --git a/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/ExceptionResource.java b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/ExceptionResource.java new file mode 100644 index 0000000..18aeb78 --- /dev/null +++ b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/ExceptionResource.java @@ -0,0 +1,181 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2010-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey.resources; + +import java.io.IOException; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.InternalServerErrorException; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; + +import org.glassfish.jersey.server.ContainerRequest; + +import com.javadevelopersguide.jersey.resources.Exceptions.MyException; +import com.javadevelopersguide.jersey.resources.Exceptions.MySubException; +import com.javadevelopersguide.jersey.resources.Exceptions.MySubSubException; +import com.javadevelopersguide.jersey.resources.exception.BadRequestException; + +/** + * ExceptionResource class. + * + * @author Santiago.PericasGeertsen at oracle.com + */ +@Path("exception") +@Consumes("text/plain") +@Produces("text/plain") +public class ExceptionResource { + + @Provider + static class MyResponseFilter implements ContainerResponseFilter { + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { + System.out.println("MyResponseFilter.postFilter() enter"); + responseContext.setEntity( + responseContext.getEntity() + ":" + getClass().getSimpleName(), null, MediaType.TEXT_PLAIN_TYPE); + System.out.println("MyResponseFilter.postFilter() exit"); + } + } + + @Provider + static class WebApplicationExceptionFilter implements ContainerRequestFilter, ContainerResponseFilter { + + @Override + public void filter(ContainerRequestContext context) throws IOException { + System.out.println("WebApplicationExceptionFilter.preFilter() enter"); + + String path = ((ContainerRequest) context).getRequestUri().getPath(); + if (path.endsWith("request_exception") && context.hasEntity() && ((ContainerRequest) context) + .readEntity(String.class).equals("Request Exception")) { + throw new WebApplicationException(Response.Status.OK); + } + System.out.println("WebApplicationExceptionFilter.preFilter() exit"); + } + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { + System.out.println("WebApplicationExceptionFilter.postFilter() enter"); + if (responseContext.hasEntity() && responseContext.getEntity().equals("Response Exception")) { + throw new WebApplicationException(Response.Status.OK); + } + System.out.println("WebApplicationExceptionFilter.postFilter() exit"); + } + } + + @GET + public String pingMe() { + return "ping!"; + } + + @POST + @Path("webapplication_entity") + public String testWebApplicationExceptionEntity(String s) { + String[] tokens = s.split(":"); + assert tokens.length == 2; + int statusCode = Integer.valueOf(tokens[1]); + Response r = Response.status(statusCode).entity(s).build(); + throw new WebApplicationException(r); + } + + @POST + @Path("webapplication_noentity") + public String testWebApplicationExceptionNoEntity(String s) { + String[] tokens = s.split(":"); + assert tokens.length == 2; + int statusCode = Integer.valueOf(tokens[1]); + Response r = Response.status(statusCode).build(); + throw new WebApplicationException(r); + } + + @POST + @Path("my") + public String testMyException(String s) { + String[] tokens = s.split(":"); + assert tokens.length == 2; + int statusCode = Integer.valueOf(tokens[1]); + Response r = Response.status(statusCode).build(); + throw new MyException(r); + } + + @POST + @Path("mysub") + public String testMySubException(String s) { + String[] tokens = s.split(":"); + assert tokens.length == 2; + int statusCode = Integer.valueOf(tokens[1]); + Response r = Response.status(statusCode).build(); + throw new MySubException(r); + } + + @POST + @Path("mysubsub") + public String testMySubSubException(String s) { + String[] tokens = s.split(":"); + assert tokens.length == 2; + int statusCode = Integer.valueOf(tokens[1]); + Response r = Response.status(statusCode).build(); + throw new MySubSubException(r); + } + + @POST + @Path("request_exception") + public String exceptionInRequestFilter() { + throw new InternalServerErrorException(); // should not reach here + } + + @GET + @Path("response_exception") + public String exceptionInResponseFilter() { + return "Response Exception"; + } + +} diff --git a/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/Exceptions.java b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/Exceptions.java new file mode 100644 index 0000000..64db784 --- /dev/null +++ b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/Exceptions.java @@ -0,0 +1,116 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2010-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey.resources; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +/** + * Exceptions class. + * + * @author Santiago.Pericas-Geertsen at oracle.com + */ +public class Exceptions { + + // -- Exceptions + public static class MyException extends RuntimeException { + + private Response response; + + public MyException(Response response) { + this.response = response; + } + + public Response getResponse() { + return response; + } + } + + public static class MySubException extends MyException { + + public MySubException(Response response) { + super(response); + } + } + + public static class MySubSubException extends MySubException { + + public MySubSubException(Response response) { + super(response); + } + } + + // -- Exception Mappers + @Provider + public static class MyExceptionMapper implements ExceptionMapper { + + @Override + public Response toResponse(MyException exception) { + Response r = exception.getResponse(); + return Response.status(r.getStatus()).entity( + "Code:" + r.getStatus() + ":" + exception.getMessage()).build(); + } + } + + @Provider + public static class MySubExceptionMapper implements ExceptionMapper { + + @Override + public Response toResponse(MySubException exception) { + Response r = exception.getResponse(); + return Response.status(r.getStatus()).entity( + "Code:" + r.getStatus() + ":" + exception.getMessage()).build(); + } + } + + @Provider + public static class WebApplicationExceptionMapper implements ExceptionMapper { + + @Override + public Response toResponse(WebApplicationException exception) { + Response r = exception.getResponse(); + return Response.status(r.getStatus()).entity("Code:" + r.getStatus() + ":" + + exception.getMessage()).build(); + } + } +} diff --git a/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/ResourceNotFoundException.java b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/ResourceNotFoundException.java new file mode 100644 index 0000000..22e4f18 --- /dev/null +++ b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/ResourceNotFoundException.java @@ -0,0 +1,12 @@ +package com.javadevelopersguide.jersey.resources; + +public class ResourceNotFoundException extends Exception{ + /** + * + */ + private static final long serialVersionUID = 1L; + + public ResourceNotFoundException(String message){ + super(message); + } +} diff --git a/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/SampleExceptionMapper.java b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/SampleExceptionMapper.java new file mode 100644 index 0000000..9f922d1 --- /dev/null +++ b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/SampleExceptionMapper.java @@ -0,0 +1,58 @@ +/** + * Copyright 2016 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.javadevelopersguide.jersey.resources; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +import com.javadevelopersguide.jersey.resources.exception.ApiException; +import com.javadevelopersguide.jersey.resources.exception.BadRequestException; +import com.javadevelopersguide.jersey.resources.exception.NotFoundException; + +@Provider +public class SampleExceptionMapper implements ExceptionMapper { + public Response toResponse(Exception exception) { + if (exception instanceof javax.ws.rs.WebApplicationException) { + javax.ws.rs.WebApplicationException e = (javax.ws.rs.WebApplicationException) exception; + return Response + .status(e.getResponse().getStatus()) + .entity(new ApiResponse(e.getResponse().getStatus(), + exception.getMessage())).build(); + } else if (exception instanceof NotFoundException) { + return Response + .status(Status.NOT_FOUND) + .entity(new ApiResponse(ApiResponse.ERROR, exception + .getMessage())).build(); + } else if (exception instanceof BadRequestException) { + return Response + .status(Status.BAD_REQUEST) + .entity(new ApiResponse(ApiResponse.ERROR, exception + .getMessage())).build(); + } else if (exception instanceof ApiException) { + return Response + .status(Status.BAD_REQUEST) + .entity(new ApiResponse(ApiResponse.ERROR, exception + .getMessage())).build(); + } else { + return Response.status(500) + .entity(new ApiResponse(500, "something bad happened")) + .build(); + } + } +} \ No newline at end of file diff --git a/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/exception/ApiException.java b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/exception/ApiException.java new file mode 100644 index 0000000..12f0fa3 --- /dev/null +++ b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/exception/ApiException.java @@ -0,0 +1,25 @@ +/** + * Copyright 2016 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.javadevelopersguide.jersey.resources.exception; + +public class ApiException extends Exception{ + private int code; + public ApiException (int code, String msg) { + super(msg); + this.code = code; + } +} diff --git a/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/exception/BadRequestException.java b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/exception/BadRequestException.java new file mode 100644 index 0000000..599a1e1 --- /dev/null +++ b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/exception/BadRequestException.java @@ -0,0 +1,25 @@ +/** + * Copyright 2016 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.javadevelopersguide.jersey.resources.exception; + +public class BadRequestException extends ApiException{ + private int code; + public BadRequestException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/exception/NotFoundException.java b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/exception/NotFoundException.java new file mode 100644 index 0000000..bed5224 --- /dev/null +++ b/jersey-exception-mapping-example/src/main/java/com/javadevelopersguide/jersey/resources/exception/NotFoundException.java @@ -0,0 +1,25 @@ +/** + * Copyright 2016 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.javadevelopersguide.jersey.resources.exception; + +public class NotFoundException extends ApiException { + private int code; + public NotFoundException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/jersey-exception-mapping-example/src/main/webapp/WEB-INF/web.xml b/jersey-exception-mapping-example/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..9f88c1f --- /dev/null +++ b/jersey-exception-mapping-example/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,7 @@ + + + + Archetype Created Web Application + diff --git a/jersey-exception-mapping-example/src/main/webapp/index.jsp b/jersey-exception-mapping-example/src/main/webapp/index.jsp new file mode 100644 index 0000000..c38169b --- /dev/null +++ b/jersey-exception-mapping-example/src/main/webapp/index.jsp @@ -0,0 +1,5 @@ + + +

Hello World!

+ + diff --git a/jersey-helloworld-example/.classpath b/jersey-helloworld-example/.classpath new file mode 100644 index 0000000..2784a1b --- /dev/null +++ b/jersey-helloworld-example/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jersey-helloworld-example/.project b/jersey-helloworld-example/.project new file mode 100644 index 0000000..4bef9fd --- /dev/null +++ b/jersey-helloworld-example/.project @@ -0,0 +1,37 @@ + + + jersey-helloworld-example + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/jersey-helloworld-example/.settings/.jsdtscope b/jersey-helloworld-example/.settings/.jsdtscope new file mode 100644 index 0000000..f179e11 --- /dev/null +++ b/jersey-helloworld-example/.settings/.jsdtscope @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/jersey-helloworld-example/.settings/org.eclipse.jdt.core.prefs b/jersey-helloworld-example/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..45a6e0e --- /dev/null +++ b/jersey-helloworld-example/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.5 diff --git a/jersey-helloworld-example/.settings/org.eclipse.m2e.core.prefs b/jersey-helloworld-example/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/jersey-helloworld-example/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/jersey-helloworld-example/.settings/org.eclipse.wst.common.component b/jersey-helloworld-example/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..26ac6a1 --- /dev/null +++ b/jersey-helloworld-example/.settings/org.eclipse.wst.common.component @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/jersey-helloworld-example/.settings/org.eclipse.wst.common.project.facet.core.xml b/jersey-helloworld-example/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..d74c55e --- /dev/null +++ b/jersey-helloworld-example/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/jersey-helloworld-example/.settings/org.eclipse.wst.jsdt.ui.superType.container b/jersey-helloworld-example/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100644 index 0000000..3bd5d0a --- /dev/null +++ b/jersey-helloworld-example/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/jersey-helloworld-example/.settings/org.eclipse.wst.jsdt.ui.superType.name b/jersey-helloworld-example/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100644 index 0000000..05bd71b --- /dev/null +++ b/jersey-helloworld-example/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/jersey-helloworld-example/.settings/org.eclipse.wst.validation.prefs b/jersey-helloworld-example/.settings/org.eclipse.wst.validation.prefs new file mode 100644 index 0000000..04cad8c --- /dev/null +++ b/jersey-helloworld-example/.settings/org.eclipse.wst.validation.prefs @@ -0,0 +1,2 @@ +disabled=06target +eclipse.preferences.version=1 diff --git a/jersey-helloworld-example/pom.xml b/jersey-helloworld-example/pom.xml new file mode 100644 index 0000000..77ea276 --- /dev/null +++ b/jersey-helloworld-example/pom.xml @@ -0,0 +1,57 @@ + + 4.0.0 + com.javadevelopersguide.jersey + jersey-helloworld-example + war + 0.0.1-SNAPSHOT + jersey-helloworld-example Maven Webapp + http://maven.apache.org + + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + + org.glassfish.jersey.core + jersey-server + 2.7 + + + org.glassfish.jersey.containers + jersey-container-servlet + 2.7 + + + + jersey-helloworld-example + + + org.apache.maven.plugins + maven-war-plugin + + false + + + + maven-compiler-plugin + 2.0.2 + + 1.8 + 1.8 + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + 2.2 + + + + + diff --git a/jersey-helloworld-example/src/main/java/com/javadevelopersguide/jersey/config/AppResourceConfig.java b/jersey-helloworld-example/src/main/java/com/javadevelopersguide/jersey/config/AppResourceConfig.java new file mode 100644 index 0000000..51d0c9c --- /dev/null +++ b/jersey-helloworld-example/src/main/java/com/javadevelopersguide/jersey/config/AppResourceConfig.java @@ -0,0 +1,14 @@ +package com.javadevelopersguide.jersey.config; + +import javax.ws.rs.ApplicationPath; + +import org.glassfish.jersey.server.ResourceConfig; + +@ApplicationPath("resources") +public class AppResourceConfig extends ResourceConfig { + public AppResourceConfig() { + // if there are more than two packanges then separate them with semicolon + // exmaple : packages("org.foo.rest;org.bar.rest"); + packages("com.javadevelopersguide.jersey.helloworld"); + } +} diff --git a/jersey-helloworld-example/src/main/java/com/javadevelopersguide/jersey/helloworld/HelloWorldResource.java b/jersey-helloworld-example/src/main/java/com/javadevelopersguide/jersey/helloworld/HelloWorldResource.java new file mode 100644 index 0000000..5245f3a --- /dev/null +++ b/jersey-helloworld-example/src/main/java/com/javadevelopersguide/jersey/helloworld/HelloWorldResource.java @@ -0,0 +1,15 @@ +package com.javadevelopersguide.jersey.helloworld; + +import javax.ws.rs.GET; + +import javax.ws.rs.Path; + +@Path("/") +public class HelloWorldResource { + + @GET + @Path("helloworld") + public String helloworld(){ + return "Helloworld !!!!"; + } +} diff --git a/jersey-helloworld-example/src/main/webapp/WEB-INF/web.xml b/jersey-helloworld-example/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..9f88c1f --- /dev/null +++ b/jersey-helloworld-example/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,7 @@ + + + + Archetype Created Web Application + diff --git a/jersey-helloworld-example/src/main/webapp/index.jsp b/jersey-helloworld-example/src/main/webapp/index.jsp new file mode 100644 index 0000000..c38169b --- /dev/null +++ b/jersey-helloworld-example/src/main/webapp/index.jsp @@ -0,0 +1,5 @@ + + +

Hello World!

+ + diff --git a/jersey-java8-example/.classpath b/jersey-java8-example/.classpath new file mode 100644 index 0000000..c169161 --- /dev/null +++ b/jersey-java8-example/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jersey-java8-example/.project b/jersey-java8-example/.project new file mode 100644 index 0000000..ac7fab4 --- /dev/null +++ b/jersey-java8-example/.project @@ -0,0 +1,37 @@ + + + jersey-java8-example + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/jersey-java8-example/.settings/.jsdtscope b/jersey-java8-example/.settings/.jsdtscope new file mode 100644 index 0000000..f179e11 --- /dev/null +++ b/jersey-java8-example/.settings/.jsdtscope @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/jersey-java8-example/.settings/org.eclipse.jdt.core.prefs b/jersey-java8-example/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..13b3428 --- /dev/null +++ b/jersey-java8-example/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,13 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/jersey-java8-example/.settings/org.eclipse.m2e.core.prefs b/jersey-java8-example/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/jersey-java8-example/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/jersey-java8-example/.settings/org.eclipse.wst.common.component b/jersey-java8-example/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..5a115a9 --- /dev/null +++ b/jersey-java8-example/.settings/org.eclipse.wst.common.component @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/jersey-java8-example/.settings/org.eclipse.wst.common.project.facet.core.xml b/jersey-java8-example/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..d74c55e --- /dev/null +++ b/jersey-java8-example/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/jersey-java8-example/.settings/org.eclipse.wst.jsdt.ui.superType.container b/jersey-java8-example/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100644 index 0000000..3bd5d0a --- /dev/null +++ b/jersey-java8-example/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/jersey-java8-example/.settings/org.eclipse.wst.jsdt.ui.superType.name b/jersey-java8-example/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100644 index 0000000..05bd71b --- /dev/null +++ b/jersey-java8-example/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/jersey-java8-example/.settings/org.eclipse.wst.validation.prefs b/jersey-java8-example/.settings/org.eclipse.wst.validation.prefs new file mode 100644 index 0000000..04cad8c --- /dev/null +++ b/jersey-java8-example/.settings/org.eclipse.wst.validation.prefs @@ -0,0 +1,2 @@ +disabled=06target +eclipse.preferences.version=1 diff --git a/jersey-java8-example/pom.xml b/jersey-java8-example/pom.xml new file mode 100644 index 0000000..5f4ff6f --- /dev/null +++ b/jersey-java8-example/pom.xml @@ -0,0 +1,59 @@ + + 4.0.0 + com.javadevelopersguide.jersey + jersey-helloworld-example + war + 0.0.1-SNAPSHOT + jersey-helloworld-example Maven Webapp + http://maven.apache.org + + + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + + org.glassfish.jersey.core + jersey-server + 2.7 + + + org.glassfish.jersey.containers + jersey-container-servlet + 2.7 + + + + jersey-helloworld-example + + + org.apache.maven.plugins + maven-war-plugin + + false + + + + maven-compiler-plugin + 2.0.2 + + 1.8 + 1.8 + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + 2.2 + + + + + + diff --git a/jersey-java8-example/readme b/jersey-java8-example/readme new file mode 100644 index 0000000..8dcb4fe --- /dev/null +++ b/jersey-java8-example/readme @@ -0,0 +1,4 @@ +Lambda expression +http://localhost:8080/jersey-java8-example/java8/lambdas/12 + +http://localhost:8080/jersey-java8-example/java8/default-method \ No newline at end of file diff --git a/jersey-java8-example/src/main/java/com/javadevelopersguide/jersey/config/Java8Application.java b/jersey-java8-example/src/main/java/com/javadevelopersguide/jersey/config/Java8Application.java new file mode 100644 index 0000000..5cd960d --- /dev/null +++ b/jersey-java8-example/src/main/java/com/javadevelopersguide/jersey/config/Java8Application.java @@ -0,0 +1,21 @@ +package com.javadevelopersguide.jersey.config; + +import javax.ws.rs.ApplicationPath; + +// Deployment of a JAX-RS application using @ApplicationPath with Servlet 3.0 +// Descriptor-less deployment +import org.glassfish.jersey.server.ResourceConfig; + +@ApplicationPath("java8") +public class Java8Application extends ResourceConfig { + public Java8Application() { + + // if there are more than two packanges then separate them with semicolon + // exmaple : packages("org.foo.rest;org.bar.rest"); + packages("com.javadevelopersguide.jersey.java8"); + + // Resources. + //register(DefaultMethodResource.class); + //register(LambdaResource.class); + } +} diff --git a/jersey-java8-example/src/main/java/com/javadevelopersguide/jersey/java8/DefaultMethodInterface.java b/jersey-java8-example/src/main/java/com/javadevelopersguide/jersey/java8/DefaultMethodInterface.java new file mode 100644 index 0000000..cd817b5 --- /dev/null +++ b/jersey-java8-example/src/main/java/com/javadevelopersguide/jersey/java8/DefaultMethodInterface.java @@ -0,0 +1,63 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2015-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey.java8; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +/** + * Example interface containing resource methods in form of Java8's default methods. + * + */ +public interface DefaultMethodInterface { + + @GET + default String root() { + return "interface-root"; + } + + @GET + @Path("path") + default String path() { + return "interface-path"; + } +} + diff --git a/jersey-java8-example/src/main/java/com/javadevelopersguide/jersey/java8/DefaultMethodResource.java b/jersey-java8-example/src/main/java/com/javadevelopersguide/jersey/java8/DefaultMethodResource.java new file mode 100644 index 0000000..77df4e0 --- /dev/null +++ b/jersey-java8-example/src/main/java/com/javadevelopersguide/jersey/java8/DefaultMethodResource.java @@ -0,0 +1,20 @@ +package com.javadevelopersguide.jersey.java8; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; + +/** + * JAX-RS resource inheriting some resource method implementations from the implemented interface. + * + */ +@Path("default-method") +@Produces("text/plain") +public class DefaultMethodResource implements DefaultMethodInterface { + + @GET + @Path("class") + public String fromClass() { + return "class"; + } +} diff --git a/jersey-java8-example/src/main/java/com/javadevelopersguide/jersey/java8/LambdaResource.java b/jersey-java8-example/src/main/java/com/javadevelopersguide/jersey/java8/LambdaResource.java new file mode 100644 index 0000000..9750edd --- /dev/null +++ b/jersey-java8-example/src/main/java/com/javadevelopersguide/jersey/java8/LambdaResource.java @@ -0,0 +1,61 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2015-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey.java8; + +import java.util.Collections; + +import java.util.stream.Collectors; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + +/** + * JAX-RS resource using Java SE 8 lambdas. + * + */ +@Path("lambdas/{p}") +public class LambdaResource { + @GET + public String getLambdaResult(@PathParam("p") String p) { + return Collections.singleton(p).stream().map(v -> v + "-lambdaized").collect(Collectors.joining()); + } +} diff --git a/jersey-java8-example/src/main/webapp/WEB-INF/web.xml b/jersey-java8-example/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..9f88c1f --- /dev/null +++ b/jersey-java8-example/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,7 @@ + + + + Archetype Created Web Application + diff --git a/jersey-java8-example/src/main/webapp/index.jsp b/jersey-java8-example/src/main/webapp/index.jsp new file mode 100644 index 0000000..c38169b --- /dev/null +++ b/jersey-java8-example/src/main/webapp/index.jsp @@ -0,0 +1,5 @@ + + +

Hello World!

+ + diff --git a/jersey-jpa-bookmark-example/.classpath b/jersey-jpa-bookmark-example/.classpath new file mode 100644 index 0000000..2784a1b --- /dev/null +++ b/jersey-jpa-bookmark-example/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jersey-jpa-bookmark-example/.project b/jersey-jpa-bookmark-example/.project new file mode 100644 index 0000000..c0282fb --- /dev/null +++ b/jersey-jpa-bookmark-example/.project @@ -0,0 +1,37 @@ + + + jersey-jpa-bookmark-example + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/jersey-jpa-bookmark-example/.settings/.jsdtscope b/jersey-jpa-bookmark-example/.settings/.jsdtscope new file mode 100644 index 0000000..2418123 --- /dev/null +++ b/jersey-jpa-bookmark-example/.settings/.jsdtscope @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/jersey-jpa-bookmark-example/.settings/org.eclipse.jdt.core.prefs b/jersey-jpa-bookmark-example/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..45a6e0e --- /dev/null +++ b/jersey-jpa-bookmark-example/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.5 diff --git a/jersey-jpa-bookmark-example/.settings/org.eclipse.m2e.core.prefs b/jersey-jpa-bookmark-example/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/jersey-jpa-bookmark-example/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/jersey-jpa-bookmark-example/.settings/org.eclipse.wst.common.component b/jersey-jpa-bookmark-example/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..656e331 --- /dev/null +++ b/jersey-jpa-bookmark-example/.settings/org.eclipse.wst.common.component @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/jersey-jpa-bookmark-example/.settings/org.eclipse.wst.common.project.facet.core.xml b/jersey-jpa-bookmark-example/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..d74c55e --- /dev/null +++ b/jersey-jpa-bookmark-example/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/jersey-jpa-bookmark-example/.settings/org.eclipse.wst.jsdt.ui.superType.container b/jersey-jpa-bookmark-example/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100644 index 0000000..3bd5d0a --- /dev/null +++ b/jersey-jpa-bookmark-example/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/jersey-jpa-bookmark-example/.settings/org.eclipse.wst.jsdt.ui.superType.name b/jersey-jpa-bookmark-example/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100644 index 0000000..05bd71b --- /dev/null +++ b/jersey-jpa-bookmark-example/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/jersey-jpa-bookmark-example/.settings/org.eclipse.wst.validation.prefs b/jersey-jpa-bookmark-example/.settings/org.eclipse.wst.validation.prefs new file mode 100644 index 0000000..04cad8c --- /dev/null +++ b/jersey-jpa-bookmark-example/.settings/org.eclipse.wst.validation.prefs @@ -0,0 +1,2 @@ +disabled=06target +eclipse.preferences.version=1 diff --git a/jersey-jpa-bookmark-example/README.MD b/jersey-jpa-bookmark-example/README.MD new file mode 100644 index 0000000..3e6db60 --- /dev/null +++ b/jersey-jpa-bookmark-example/README.MD @@ -0,0 +1,115 @@ + + +Bookmark Example +================ + +This example demonstrates how to use JPA in the backend. The example is +based on bookmark example from the [RESTful Web +Services](http://www.oreilly.com/catalog/9780596529260/) book, which was +inspired by the [http://del.icio.us/](http://del.icio.us/v1) web +service. + +A bookmark web application is presented that is capable of maintaining +users and their bookmarks. + +Contents +-------- + +The mapping of the URI path space is presented in the following table: + +URI path | Resource class | HTTP methods | Notes +--------------------------------------- | ------------------- | ----------------------------------------------------- | -------------------------------------------------------- +**_/users_** | UsersResource | GET | Returns a list of users. +**_/users/{userid}_** | UserResource | GET, PUT (used also for creating new users), DELETE | Returns user details +**_/users/{userid}/bookmarks_** | BookmarksResource | GET, POST | Returns a list of bookmarks for actual user resource. +**_/users/{userid}/bookmarks/{bmid}_** | BookmarkResource | GET, PUT, DELETE | Returns bookmark uri and a long and short description. + +Running the Example +------------------- + +Bookmark example runs on Glassfish 3.x application servers +([https://javaee.github.io/glassfish/](https://javaee.github.io/glassfish/)) and needs a +running JavaDB +() +instance for underlying data (it comes along with GlassFish). + +Presuming, you have installed Glassfish 3.1 `AS_HOME` variable should +point to your glassfish installation directory. + +#### Building And Starting The Bookmark Service + +If `.asadminpass` file is missing at your home directory, you will need +to run the following command to get it created + + $AS_HOME/bin/asadmin start-domain + $AS_HOME/bin/asadmin login + +You then build and run the example by + + mvn package + $AS_HOME/bin/asadmin start-domain + $AS_HOME/bin/asadmin start-database + $AS_HOME/bin/asadmin create-jdbc-connection-pool \ + --datasourceclassname org.apache.derby.jdbc.ClientDataSource \ + --restype javax.sql.DataSource \ + --property "portnumber=1527:password=REST:user=REST:serverName=localhost:databaseName=BookmarkDB:connectionAttributes=;create\=true" bookmarkPool + $AS_HOME/bin/asadmin create-jdbc-resource --connectionpoolid bookmarkPool jdbc/bookmarkSample + $AS_HOME/bin/asadmin deploy target/bookmark.war + +**Notice:** On Windows: you might need +to replace asadmin with asadmin.bat. Also, because it seems there are +some issues with copy-pasting backslashes, you will also need to use the +following one-liner instead of the above mentioned complex command: + + asadmin create-jdbc-connection-pool --datasourceclassname org.apache.derby.jdbc.ClientDataSource --restype javax.sql.DataSource --property "portnumber=1527:password=REST:user=REST:serverName=localhost:databaseName=BookmarkDB:connectionAttributes=;create\=true" bookmarkPool + +and make sure you do not miss the backslash (\\) in `create\=true` part. + +#### Test Client Running + + mvn test -Djersey.config.test.container.factory=org.glassfish.jersey.test.external.ExternalTestContainerFactory -Djersey.config.test.logging.enable=true -Djersey.config.test.logging.dumpEntity=true -Djersey.config.test.container.port=8080 -Ptest + +Links +----- + + \ No newline at end of file diff --git a/jersey-jpa-bookmark-example/pom.xml b/jersey-jpa-bookmark-example/pom.xml new file mode 100644 index 0000000..a37aa3c --- /dev/null +++ b/jersey-jpa-bookmark-example/pom.xml @@ -0,0 +1,79 @@ + + 4.0.0 + com.javadevelopersguide.jersey + jersey-jpa-bookmark-example + war + 0.0.1-SNAPSHOT + jersey-jpa-bookmark-example Maven Webapp + http://maven.apache.org + + + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + + org.glassfish.jersey.core + jersey-server + 2.7 + + + org.glassfish.jersey.containers + jersey-container-servlet + 2.7 + + + + + javax.persistence + persistence-api + 1.0.2 + + + + org.glassfish.jersey.media + jersey-media-json-jettison + 2.7 + + + + javax.transaction + jta + 1.1 + provided + + + + + jersey-jpa-bookmark-example + + + org.apache.maven.plugins + maven-war-plugin + + false + + + + maven-compiler-plugin + 2.0.2 + + 1.8 + 1.8 + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + 2.2 + + + + + diff --git a/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/MyApplication.java b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/MyApplication.java new file mode 100644 index 0000000..a81d15d --- /dev/null +++ b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/MyApplication.java @@ -0,0 +1,60 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2012-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey; + +import javax.ws.rs.ApplicationPath; + +import org.glassfish.jersey.jettison.JettisonFeature; +import org.glassfish.jersey.server.ResourceConfig; + +import com.javadevelopersguide.jersey.resource.UsersResource; + +/** + * @author Michal Gajdos + */ +@ApplicationPath("/") +public class MyApplication extends ResourceConfig { + + public MyApplication() { + registerClasses(UsersResource.class); + register(new JettisonFeature()); + } +} diff --git a/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/entity/BookmarkEntity.java b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/entity/BookmarkEntity.java new file mode 100644 index 0000000..3b7ec33 --- /dev/null +++ b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/entity/BookmarkEntity.java @@ -0,0 +1,290 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2010-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey.entity; + +import java.io.Serializable; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +/** + * Entity class BookmarkEntity. + * + * @author Jakub Podlesak (jakub.podlesak at oracle.com) + */ +@Entity +@Table(name = "BOOKMARKS") +@NamedQueries({ + @NamedQuery(name = "BookmarkEntity.findByUserid", + query = "SELECT b FROM BookmarkEntity b WHERE b.bookmarkEntityPK.userid = :userid"), + @NamedQuery(name = "BookmarkEntity.findByBmid", + query = "SELECT b FROM BookmarkEntity b WHERE b.bookmarkEntityPK.bmid = :bmid"), + @NamedQuery(name = "BookmarkEntity.findByUri", query = "SELECT b FROM BookmarkEntity b WHERE b.uri = :uri"), + @NamedQuery(name = "BookmarkEntity.findByUpdated", query = "SELECT b FROM BookmarkEntity b WHERE b.updated = :updated"), + @NamedQuery(name = "BookmarkEntity.findByLdesc", query = "SELECT b FROM BookmarkEntity b WHERE b.ldesc = :ldesc"), + @NamedQuery(name = "BookmarkEntity.findBySdesc", query = "SELECT b FROM BookmarkEntity b WHERE b.sdesc = :sdesc") +}) +@SuppressWarnings("UnusedDeclaration") +public class BookmarkEntity implements Serializable { + + /** + * EmbeddedId primary key field + */ + @EmbeddedId + protected BookmarkEntityPK bookmarkEntityPK; + + @Column(name = "URI", nullable = false) + private String uri; + + @Column(name = "UPDATED") + @Temporal(TemporalType.TIMESTAMP) + private Date updated; + + @Column(name = "LDESC") + private String ldesc; + + @Column(name = "SDESC") + private String sdesc; + + @JoinColumn(name = "USERID", referencedColumnName = "USERID", insertable = false, updatable = false) + @ManyToOne + private UserEntity userEntity; + + /** + * Creates a new instance of BookmarkEntity + */ + public BookmarkEntity() { + } + + /** + * Creates a new instance of BookmarkEntity with the specified values. + * + * @param bookmarkEntityPK the bookmarkEntityPK of the BookmarkEntity + */ + public BookmarkEntity(BookmarkEntityPK bookmarkEntityPK) { + this.bookmarkEntityPK = bookmarkEntityPK; + } + + /** + * Creates a new instance of BookmarkEntity with the specified values. + * + * @param bookmarkEntityPK the bookmarkEntityPK of the BookmarkEntity + * @param uri the uri of the BookmarkEntity + */ + public BookmarkEntity(BookmarkEntityPK bookmarkEntityPK, String uri) { + this.bookmarkEntityPK = bookmarkEntityPK; + this.uri = uri; + } + + /** + * Creates a new instance of BookmarkEntityPK with the specified values. + * + * @param bmid the bmid of the BookmarkEntityPK + * @param userid the userid of the BookmarkEntityPK + */ + public BookmarkEntity(String bmid, String userid) { + this.bookmarkEntityPK = new BookmarkEntityPK(bmid, userid); + } + + /** + * Gets the bookmarkEntityPK of this BookmarkEntity. + * + * @return the bookmarkEntityPK + */ + public BookmarkEntityPK getBookmarkEntityPK() { + return this.bookmarkEntityPK; + } + + /** + * Sets the bookmarkEntityPK of this BookmarkEntity to the specified value. + * + * @param bookmarkEntityPK the new bookmarkEntityPK + */ + public void setBookmarkEntityPK(BookmarkEntityPK bookmarkEntityPK) { + this.bookmarkEntityPK = bookmarkEntityPK; + } + + /** + * Gets the uri of this BookmarkEntity. + * + * @return the uri + */ + public String getUri() { + return this.uri; + } + + /** + * Sets the uri of this BookmarkEntity to the specified value. + * + * @param uri the new uri + */ + public void setUri(String uri) { + this.uri = uri; + } + + /** + * Gets the updated of this BookmarkEntity. + * + * @return the updated + */ + public Date getUpdated() { + return this.updated; + } + + /** + * Sets the updated of this BookmarkEntity to the specified value. + * + * @param updated the new updated + */ + public void setUpdated(Date updated) { + this.updated = updated; + } + + /** + * Gets the ldesc of this BookmarkEntity. + * + * @return the ldesc + */ + public String getLdesc() { + return this.ldesc; + } + + /** + * Sets the ldesc of this BookmarkEntity to the specified value. + * + * @param ldesc the new ldesc + */ + public void setLdesc(String ldesc) { + this.ldesc = ldesc; + } + + /** + * Gets the sdesc of this BookmarkEntity. + * + * @return the sdesc + */ + public String getSdesc() { + return this.sdesc; + } + + /** + * Sets the sdesc of this BookmarkEntity to the specified value. + * + * @param sdesc the new sdesc + */ + public void setSdesc(String sdesc) { + this.sdesc = sdesc; + } + + /** + * Gets the userEntity of this BookmarkEntity. + * + * @return the userEntity + */ + public UserEntity getUserEntity() { + return this.userEntity; + } + + /** + * Sets the userEntity of this BookmarkEntity to the specified value. + * + * @param userEntity the new userEntity + */ + public void setUserEntity(UserEntity userEntity) { + this.userEntity = userEntity; + } + + /** + * Returns a hash code value for the object. This implementation computes + * a hash code value based on the id fields in this object. + * + * @return a hash code value for this object. + */ + @Override + public int hashCode() { + int hash = 0; + hash += (this.bookmarkEntityPK != null ? this.bookmarkEntityPK.hashCode() : 0); + return hash; + } + + /** + * Determines whether another object is equal to this BookmarkEntity. The result is + * true if and only if the argument is not null and is a BookmarkEntity object that + * has the same id field values as this object. + * + * @param object the reference object with which to compare + * @return true if this object is the same as the argument; + * false otherwise. + */ + @Override + public boolean equals(Object object) { + // TODO: Warning - this method won't work in the case the id fields are not set + if (!(object instanceof BookmarkEntity)) { + return false; + } + BookmarkEntity other = (BookmarkEntity) object; + return !(this.bookmarkEntityPK != other.bookmarkEntityPK && (this.bookmarkEntityPK == null || !this.bookmarkEntityPK + .equals(other.bookmarkEntityPK))); + } + + /** + * Returns a string representation of the object. This implementation constructs + * that representation based on the id fields. + * + * @return a string representation of the object. + */ + @Override + public String toString() { + return "BookmarkEntity{" + + "bookmarkEntityPK=" + bookmarkEntityPK + + '}'; + } +} diff --git a/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/entity/BookmarkEntityPK.java b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/entity/BookmarkEntityPK.java new file mode 100644 index 0000000..5c28de1 --- /dev/null +++ b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/entity/BookmarkEntityPK.java @@ -0,0 +1,171 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2010-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey.entity; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Embeddable; + +/** + * Primary Key class BookmarkEntityPK for entity class BookmarkEntity. + * + * @author Jakub Podlesak (jakub.podlesak at oracle.com) + */ +@SuppressWarnings("UnusedDeclaration") +@Embeddable +public class BookmarkEntityPK implements Serializable { + + @Column(name = "USERID", nullable = false) + private String userid; + + @Column(name = "BMID", nullable = false) + private String bmid; + + /** + * Creates a new instance of BookmarkEntityPK + */ + public BookmarkEntityPK() { + } + + /** + * Creates a new instance of BookmarkEntityPK with the specified values. + * + * @param bmid the bmid of the BookmarkEntityPK + * @param userid the userid of the BookmarkEntityPK + */ + public BookmarkEntityPK(String bmid, String userid) { + this.bmid = bmid; + this.userid = userid; + } + + /** + * Gets the userid of this BookmarkEntityPK. + * + * @return the userid + */ + public String getUserid() { + return this.userid; + } + + /** + * Sets the userid of this BookmarkEntityPK to the specified value. + * + * @param userid the new userid + */ + public void setUserid(String userid) { + this.userid = userid; + } + + /** + * Gets the bmid of this BookmarkEntityPK. + * + * @return the bmid + */ + public String getBmid() { + return this.bmid; + } + + /** + * Sets the bmid of this BookmarkEntityPK to the specified value. + * + * @param bmid the new bmid + */ + public void setBmid(String bmid) { + this.bmid = bmid; + } + + /** + * Returns a hash code value for the object. This implementation computes + * a hash code value based on the id fields in this object. + * + * @return a hash code value for this object. + */ + @Override + public int hashCode() { + int hash = 0; + hash += (this.bmid != null ? this.bmid.hashCode() : 0); + hash += (this.userid != null ? this.userid.hashCode() : 0); + return hash; + } + + /** + * Determines whether another object is equal to this BookmarkEntityPK. The result is + * true if and only if the argument is not null and is a BookmarkEntityPK object that + * has the same id field values as this object. + * + * @param object the reference object with which to compare + * @return true if this object is the same as the argument; + * false otherwise. + */ + @Override + @SuppressWarnings("StringEquality") + public boolean equals(Object object) { + // TODO: Warning - this method won't work in the case the id fields are not set + if (!(object instanceof BookmarkEntityPK)) { + return false; + } + + BookmarkEntityPK other = (BookmarkEntityPK) object; + if (this.bmid != other.bmid && (this.bmid == null || !this.bmid.equals(other.bmid))) { + return false; + } + if (this.userid != other.userid && (this.userid == null || !this.userid.equals(other.userid))) { + return false; + } + + return true; + } + + /** + * Returns a string representation of the object. This implementation constructs + * that representation based on the id fields. + * + * @return a string representation of the object. + */ + @Override + public String toString() { + return "BookmarkEntityPK{" + + "userid='" + userid + '\'' + + ", bmid='" + bmid + '\'' + + '}'; + } +} diff --git a/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/entity/UserEntity.java b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/entity/UserEntity.java new file mode 100644 index 0000000..212f395 --- /dev/null +++ b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/entity/UserEntity.java @@ -0,0 +1,250 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2010-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey.entity; + +import java.io.Serializable; +import java.util.Collection; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +/** + * Entity class UserEntity. + * + * @author Jakub Podlesak (jakub.podlesak at oracle.com) + */ +@SuppressWarnings("UnusedDeclaration") +@Entity +@Table(name = "USERS") +@NamedQueries({ + @NamedQuery(name = "UserEntity.findByUserid", query = "SELECT u FROM UserEntity u WHERE u.userid = :userid"), + @NamedQuery(name = "UserEntity.findByPassword", query = "SELECT u FROM UserEntity u WHERE u.password = :password"), + @NamedQuery(name = "UserEntity.findByUsername", query = "SELECT u FROM UserEntity u WHERE u.username = :username"), + @NamedQuery(name = "UserEntity.findByEmail", query = "SELECT u FROM UserEntity u WHERE u.email = :email") +}) +public class UserEntity implements Serializable { + + @Id + @Column(name = "USERID", nullable = false) + private String userid; + + @Column(name = "PASSWORD", nullable = false) + private String password; + + @Column(name = "USERNAME") + private String username; + + @Column(name = "EMAIL") + private String email; + + @OneToMany(cascade = CascadeType.ALL, mappedBy = "userEntity") + private Collection bookmarkEntityCollection; + + /** + * Creates a new instance of UserEntity + */ + public UserEntity() { + } + + /** + * Creates a new instance of UserEntity with the specified values. + * + * @param userid the userid of the UserEntity + */ + public UserEntity(String userid) { + this.userid = userid; + } + + /** + * Creates a new instance of UserEntity with the specified values. + * + * @param userid the userid of the UserEntity + * @param password the password of the UserEntity + */ + public UserEntity(String userid, String password) { + this.userid = userid; + this.password = password; + } + + /** + * Gets the userid of this UserEntity. + * + * @return the userid + */ + public String getUserid() { + return this.userid; + } + + /** + * Sets the userid of this UserEntity to the specified value. + * + * @param userid the new userid + */ + public void setUserid(String userid) { + this.userid = userid; + } + + /** + * Gets the password of this UserEntity. + * + * @return the password + */ + public String getPassword() { + return this.password; + } + + /** + * Sets the password of this UserEntity to the specified value. + * + * @param password the new password + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * Gets the username of this UserEntity. + * + * @return the username + */ + public String getUsername() { + return this.username; + } + + /** + * Sets the username of this UserEntity to the specified value. + * + * @param username the new username + */ + public void setUsername(String username) { + this.username = username; + } + + /** + * Gets the email of this UserEntity. + * + * @return the email + */ + public String getEmail() { + return this.email; + } + + /** + * Sets the email of this UserEntity to the specified value. + * + * @param email the new email + */ + public void setEmail(String email) { + this.email = email; + } + + /** + * Gets the bookmarkEntityCollection of this UserEntity. + * + * @return the bookmarkEntityCollection + */ + public Collection getBookmarkEntityCollection() { + return this.bookmarkEntityCollection; + } + + /** + * Sets the bookmarkEntityCollection of this UserEntity to the specified value. + * + * @param bookmarkEntityCollection the new bookmarkEntityCollection + */ + public void setBookmarkEntityCollection(Collection bookmarkEntityCollection) { + this.bookmarkEntityCollection = bookmarkEntityCollection; + } + + /** + * Returns a hash code value for the object. This implementation computes + * a hash code value based on the id fields in this object. + * + * @return a hash code value for this object. + */ + @Override + public int hashCode() { + int hash = 0; + hash += (this.userid != null ? this.userid.hashCode() : 0); + return hash; + } + + /** + * Determines whether another object is equal to this UserEntity. The result is + * true if and only if the argument is not null and is a UserEntity object that + * has the same id field values as this object. + * + * @param object the reference object with which to compare + * @return true if this object is the same as the argument; + * false otherwise. + */ + @SuppressWarnings("StringEquality") + @Override + public boolean equals(Object object) { + // TODO: Warning - this method won't work in the case the id fields are not set + if (!(object instanceof UserEntity)) { + return false; + } + + UserEntity other = (UserEntity) object; + + return !(this.userid != other.userid && (this.userid == null || !this.userid.equals(other.userid))); + } + + /** + * Returns a string representation of the object. This implementation constructs + * that representation based on the id fields. + * + * @return a string representation of the object. + */ + @Override + public String toString() { + return "UserEntity{" + + "userid='" + userid + '\'' + + '}'; + } +} diff --git a/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/exception/ExtendedNotFoundException.java b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/exception/ExtendedNotFoundException.java new file mode 100644 index 0000000..1034796 --- /dev/null +++ b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/exception/ExtendedNotFoundException.java @@ -0,0 +1,54 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2012-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey.exception; + +import javax.ws.rs.NotFoundException; +import javax.ws.rs.core.Response; + +/** + * @author Michal Gajdos + */ +public class ExtendedNotFoundException extends NotFoundException { + + public ExtendedNotFoundException(final String message) { + super(Response.status(Response.Status.NOT_FOUND).entity(message).build()); + } +} diff --git a/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/resource/BookmarkResource.java b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/resource/BookmarkResource.java new file mode 100644 index 0000000..4549b1a --- /dev/null +++ b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/resource/BookmarkResource.java @@ -0,0 +1,138 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2010-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey.resource; + +import java.util.Date; + +import javax.persistence.EntityManager; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; + +import com.javadevelopersguide.jersey.entity.BookmarkEntity; +import com.javadevelopersguide.jersey.entity.BookmarkEntityPK; +import com.javadevelopersguide.jersey.entity.UserEntity; +import com.javadevelopersguide.jersey.exception.ExtendedNotFoundException; +import com.javadevelopersguide.jersey.util.tx.TransactionManager; +import com.javadevelopersguide.jersey.util.tx.Transactional; + +/** + * @author Jakub Podlesak (jakub.podlesak at oracle.com) + * @author Paul Sandoz + * @author Michal Gajdos + */ +public class BookmarkResource { + + UriInfo uriInfo; // actual uri info provided by parent resource + EntityManager em; // entity manager provided by parent resource + + BookmarkEntity bookmarkEntity; + + /** + * Creates a new instance of UserResource + */ + public BookmarkResource(UriInfo uriInfo, EntityManager em, UserEntity userEntity, String bmid) { + this.uriInfo = uriInfo; + this.em = em; + bookmarkEntity = em.find(BookmarkEntity.class, new BookmarkEntityPK(bmid, userEntity.getUserid())); + if (null == bookmarkEntity) { + throw new ExtendedNotFoundException("bookmark with userid=" + + userEntity.getUserid() + " and bmid=" + + bmid + " not found\n"); + } + bookmarkEntity.setUserEntity(userEntity); + } + + @GET + @Produces(MediaType.APPLICATION_JSON) + public JSONObject getBookmark() { + return asJson(); + } + + @PUT + @Consumes(MediaType.APPLICATION_JSON) + public void putBookmark(JSONObject jsonEntity) throws JSONException { + + bookmarkEntity.setLdesc(jsonEntity.getString("ldesc")); + bookmarkEntity.setSdesc(jsonEntity.getString("sdesc")); + bookmarkEntity.setUpdated(new Date()); + + TransactionManager.manage(new Transactional(em) { + public void transact() { + em.merge(bookmarkEntity); + } + }); + } + + @DELETE + public void deleteBookmark() { + TransactionManager.manage(new Transactional(em) { + public void transact() { + UserEntity userEntity = bookmarkEntity.getUserEntity(); + userEntity.getBookmarkEntityCollection().remove(bookmarkEntity); + em.merge(userEntity); + em.remove(bookmarkEntity); + } + }); + } + + public JSONObject asJson() { + try { + return new JSONObject().put("userid", bookmarkEntity.getBookmarkEntityPK().getUserid()) + .put("sdesc", bookmarkEntity.getSdesc()) + .put("ldesc", bookmarkEntity.getLdesc()) + .put("uri", bookmarkEntity.getUri()); + } catch (JSONException je) { + return null; + } + } + + public String toString() { + return bookmarkEntity.getBookmarkEntityPK().getUserid(); + } +} diff --git a/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/resource/BookmarksResource.java b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/resource/BookmarksResource.java new file mode 100644 index 0000000..ba6ef0f --- /dev/null +++ b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/resource/BookmarksResource.java @@ -0,0 +1,138 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2010-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey.resource; + +import java.net.URI; +import java.util.Collection; +import java.util.Date; + +import javax.persistence.EntityManager; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; + +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; + +import com.javadevelopersguide.jersey.entity.BookmarkEntity; +import com.javadevelopersguide.jersey.util.tx.TransactionManager; +import com.javadevelopersguide.jersey.util.tx.Transactional; + +/** + * @author Jakub Podlesak (jakub.podlesak at oracle.com) + * @author Paul Sandoz + * @author Michal Gajdos + */ +public class BookmarksResource { + + UriInfo uriInfo; // actual uri info + EntityManager em; // entity manager provided by parent resource + + UserResource userResource; // parent user resource + + /** + * Creates a new instance of BookmarksResource + */ + public BookmarksResource(UriInfo uriInfo, EntityManager em, UserResource userResource) { + this.uriInfo = uriInfo; + this.em = em; + this.userResource = userResource; + } + + public Collection getBookmarks() { + return userResource.getUserEntity().getBookmarkEntityCollection(); + } + + @Path("{bmid: .+}") + public BookmarkResource getBookmark(@PathParam("bmid") String bmid) { + return new BookmarkResource(uriInfo, em, userResource.getUserEntity(), bmid); + } + + @GET + @Produces(MediaType.APPLICATION_JSON) + public JSONArray getBookmarksAsJsonArray() { + JSONArray uriArray = new JSONArray(); + for (BookmarkEntity bookmarkEntity : getBookmarks()) { + UriBuilder ub = uriInfo.getAbsolutePathBuilder(); + URI bookmarkUri = ub + .path(bookmarkEntity.getBookmarkEntityPK().getBmid()) + .build(); + uriArray.put(bookmarkUri.toASCIIString()); + } + return uriArray; + } + + @POST + @Consumes(MediaType.APPLICATION_JSON) + public Response postForm(JSONObject bookmark) throws JSONException { + final BookmarkEntity bookmarkEntity = new BookmarkEntity(getBookmarkId(bookmark.getString("uri")), + userResource.getUserEntity().getUserid()); + + bookmarkEntity.setUri(bookmark.getString("uri")); + bookmarkEntity.setUpdated(new Date()); + bookmarkEntity.setSdesc(bookmark.getString("sdesc")); + bookmarkEntity.setLdesc(bookmark.getString("ldesc")); + userResource.getUserEntity().getBookmarkEntityCollection().add(bookmarkEntity); + + TransactionManager.manage(new Transactional(em) { + public void transact() { + em.merge(userResource.getUserEntity()); + } + }); + + URI bookmarkUri = uriInfo.getAbsolutePathBuilder() + .path(bookmarkEntity.getBookmarkEntityPK().getBmid()) + .build(); + return Response.created(bookmarkUri).build(); + } + + private String getBookmarkId(String uri) { + return uri; + } +} diff --git a/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/resource/UserResource.java b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/resource/UserResource.java new file mode 100644 index 0000000..f9ae2ee --- /dev/null +++ b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/resource/UserResource.java @@ -0,0 +1,161 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2010-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey.resource; + +import javax.persistence.EntityManager; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; + +import com.javadevelopersguide.jersey.entity.UserEntity; +import com.javadevelopersguide.jersey.exception.ExtendedNotFoundException; +import com.javadevelopersguide.jersey.util.tx.TransactionManager; +import com.javadevelopersguide.jersey.util.tx.Transactional; + +/** + * @author Jakub Podlesak (jakub.podlesak at oracle.com) + * @author Paul Sandoz + * @author Michal Gajdos + */ +public class UserResource { + + String userid; // userid from url + UserEntity userEntity; // appropriate jpa user entity + + UriInfo uriInfo; // actual uri info provided by parent resource + EntityManager em; // entity manager provided by parent resource + + /** + * Creates a new instance of UserResource + */ + public UserResource(UriInfo uriInfo, EntityManager em, String userid) { + this.uriInfo = uriInfo; + this.userid = userid; + this.em = em; + userEntity = em.find(UserEntity.class, userid); + } + + @Path("bookmarks/") + public BookmarksResource getBookmarksResource() { + if (null == userEntity) { + throw new ExtendedNotFoundException("userid " + userid + " does not exist!"); + } + return new BookmarksResource(uriInfo, em, this); + } + + @GET + @Produces("application/json") + public JSONObject getUser() throws JSONException { + if (null == userEntity) { + throw new ExtendedNotFoundException("userid " + userid + "does not exist!"); + } + return new JSONObject().put("userid", userEntity.getUserid()) + .put("username", userEntity.getUsername()) + .put("email", userEntity.getEmail()) + .put("password", userEntity.getPassword()) + .put("bookmarks", uriInfo.getAbsolutePathBuilder().path("bookmarks").build()); + } + + @PUT + @Consumes("application/json") + public Response putUser(JSONObject jsonEntity) throws JSONException { + + String jsonUserid = jsonEntity.getString("userid"); + + if ((null != jsonUserid) && !jsonUserid.equals(userid)) { + return Response.status(409).entity("userids differ!\n").build(); + } + + final boolean newRecord = (null == userEntity); // insert or update ? + + if (newRecord) { // new user record to be inserted + userEntity = new UserEntity(); + userEntity.setUserid(userid); + } + userEntity.setUsername(jsonEntity.getString("username")); + userEntity.setEmail(jsonEntity.getString("email")); + userEntity.setPassword(jsonEntity.getString("password")); + + if (newRecord) { + TransactionManager.manage(new Transactional(em) { + public void transact() { + em.persist(userEntity); + } + }); + return Response.created(uriInfo.getAbsolutePath()).build(); + } else { + TransactionManager.manage(new Transactional(em) { + public void transact() { + em.merge(userEntity); + } + }); + return Response.noContent().build(); + } + } + + @DELETE + public void deleteUser() { + if (null == userEntity) { + throw new ExtendedNotFoundException("userid " + userid + "does not exist!"); + } + TransactionManager.manage(new Transactional(em) { + public void transact() { + em.remove(userEntity); + } + }); + } + + public String toString() { + return userEntity.getUserid(); + } + + public UserEntity getUserEntity() { + return userEntity; + } +} diff --git a/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/resource/UsersResource.java b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/resource/UsersResource.java new file mode 100644 index 0000000..767f498 --- /dev/null +++ b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/resource/UsersResource.java @@ -0,0 +1,101 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2010-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey.resource; + +import java.net.URI; +import java.util.List; + +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceUnit; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; + +import org.codehaus.jettison.json.JSONArray; + +import com.javadevelopersguide.jersey.entity.UserEntity; + +/** + * @author Jakub Podlesak (jakub.podlesak at oracle.com) + */ +@Path("/users/") +public class UsersResource { + + @Context + UriInfo uriInfo; + + @PersistenceUnit(unitName = "BookmarkPU") + EntityManagerFactory emf; + + /** + * Creates a new instance of Users. + */ + public UsersResource() { + } + + @SuppressWarnings("unchecked") + public List getUsers() { + return emf.createEntityManager().createQuery("SELECT u from UserEntity u").getResultList(); + } + + @Path("{userid}/") + public UserResource getUser(@PathParam("userid") String userid) { + return new UserResource(uriInfo, emf.createEntityManager(), userid); + } + + @GET + @Produces("application/json") + public JSONArray getUsersAsJsonArray() { + JSONArray uriArray = new JSONArray(); + for (UserEntity userEntity : getUsers()) { + UriBuilder ub = uriInfo.getAbsolutePathBuilder(); + URI userUri = ub + .path(userEntity.getUserid()) + .build(); + uriArray.put(userUri.toASCIIString()); + } + return uriArray; + } +} diff --git a/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/util/tx/TransactionManager.java b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/util/tx/TransactionManager.java new file mode 100644 index 0000000..3cebd27 --- /dev/null +++ b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/util/tx/TransactionManager.java @@ -0,0 +1,84 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2010-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey.util.tx; + +import javax.ws.rs.WebApplicationException; + +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.transaction.SystemException; +import javax.transaction.UserTransaction; + +/** + * @author Paul Sandoz + */ +public final class TransactionManager { + + public static void manage(Transactional t) { + UserTransaction utx = getUtx(); + try { + utx.begin(); + if (t.joinTransaction) { + t.em.joinTransaction(); + } + t.transact(); + utx.commit(); + } catch (Exception e) { + try { + utx.rollback(); + } catch (SystemException se) { + throw new WebApplicationException(se); + } + throw new WebApplicationException(e); + } finally { + t.em.close(); + } + } + + private static UserTransaction getUtx() { + try { + InitialContext ic = new InitialContext(); + return (UserTransaction) ic.lookup("java:comp/UserTransaction"); + } catch (NamingException ne) { + throw new WebApplicationException(ne); + } + } +} diff --git a/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/util/tx/Transactional.java b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/util/tx/Transactional.java new file mode 100644 index 0000000..ddac4c6 --- /dev/null +++ b/jersey-jpa-bookmark-example/src/main/java/com/javadevelopersguide/jersey/util/tx/Transactional.java @@ -0,0 +1,63 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2010-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey.util.tx; + +import javax.persistence.EntityManager; + +/** + * @author Paul Sandoz + */ +public abstract class Transactional { + + EntityManager em; + boolean joinTransaction; + + public Transactional(EntityManager em, boolean joinTransaction) { + this.em = em; + this.joinTransaction = joinTransaction; + } + + public Transactional(EntityManager em) { + this(em, true); + } + + public abstract void transact(); +} diff --git a/jersey-jpa-bookmark-example/src/main/resources/META-INF/persistence.xml b/jersey-jpa-bookmark-example/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000..bafe004 --- /dev/null +++ b/jersey-jpa-bookmark-example/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,55 @@ + + + + + + oracle.toplink.essentials.PersistenceProvider + + + + + + + + + diff --git a/jersey-jpa-bookmark-example/src/main/webapp/WEB-INF/web.xml b/jersey-jpa-bookmark-example/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..69caa9b --- /dev/null +++ b/jersey-jpa-bookmark-example/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,72 @@ + + + + + + com.javadevelopersguide.jersey.MyApplication + org.glassfish.jersey.servlet.ServletContainer + + javax.ws.rs.Application + com.javadevelopersguide.jersey.MyApplication + + + unit:BookmarkPU + persistence/bookmark + + 1 + + + com.javadevelopersguide.jersey.MyApplication + /resources/* + + + + persistence/bookmark + BookmarkPU + + + UserTransaction + javax.transaction.UserTransaction + Container + + diff --git a/jersey-jpa-bookmark-example/src/main/webapp/index.jsp b/jersey-jpa-bookmark-example/src/main/webapp/index.jsp new file mode 100644 index 0000000..c38169b --- /dev/null +++ b/jersey-jpa-bookmark-example/src/main/webapp/index.jsp @@ -0,0 +1,5 @@ + + +

Hello World!

+ + diff --git a/jersey-json-moxy/.classpath b/jersey-json-moxy/.classpath new file mode 100644 index 0000000..c169161 --- /dev/null +++ b/jersey-json-moxy/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jersey-json-moxy/.project b/jersey-json-moxy/.project new file mode 100644 index 0000000..d00ae61 --- /dev/null +++ b/jersey-json-moxy/.project @@ -0,0 +1,37 @@ + + + jersey-json-moxy + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/jersey-json-moxy/.settings/.jsdtscope b/jersey-json-moxy/.settings/.jsdtscope new file mode 100644 index 0000000..2418123 --- /dev/null +++ b/jersey-json-moxy/.settings/.jsdtscope @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/jersey-json-moxy/.settings/org.eclipse.jdt.core.prefs b/jersey-json-moxy/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..13b3428 --- /dev/null +++ b/jersey-json-moxy/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,13 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/jersey-json-moxy/.settings/org.eclipse.m2e.core.prefs b/jersey-json-moxy/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/jersey-json-moxy/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/jersey-json-moxy/.settings/org.eclipse.wst.common.component b/jersey-json-moxy/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..2583542 --- /dev/null +++ b/jersey-json-moxy/.settings/org.eclipse.wst.common.component @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/jersey-json-moxy/.settings/org.eclipse.wst.common.project.facet.core.xml b/jersey-json-moxy/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..d74c55e --- /dev/null +++ b/jersey-json-moxy/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/jersey-json-moxy/.settings/org.eclipse.wst.jsdt.ui.superType.container b/jersey-json-moxy/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100644 index 0000000..3bd5d0a --- /dev/null +++ b/jersey-json-moxy/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/jersey-json-moxy/.settings/org.eclipse.wst.jsdt.ui.superType.name b/jersey-json-moxy/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100644 index 0000000..05bd71b --- /dev/null +++ b/jersey-json-moxy/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/jersey-json-moxy/.settings/org.eclipse.wst.validation.prefs b/jersey-json-moxy/.settings/org.eclipse.wst.validation.prefs new file mode 100644 index 0000000..04cad8c --- /dev/null +++ b/jersey-json-moxy/.settings/org.eclipse.wst.validation.prefs @@ -0,0 +1,2 @@ +disabled=06target +eclipse.preferences.version=1 diff --git a/jersey-json-moxy/README.MD b/jersey-json-moxy/README.MD new file mode 100644 index 0000000..712f133 --- /dev/null +++ b/jersey-json-moxy/README.MD @@ -0,0 +1,75 @@ + + +MOXy JAX-RS JSON Provider Example +================================= + +This example demonstrates how to produce/consume JSON representations from Java objects. + +Contents +-------- + +The mapping of the URI path space is presented in the following table: + +URI path | Resource class | HTTP method +-------------- | ---------------- | ------------- +**_/test_** | JsonResource | GET +**_/test_** | JsonResource | POST + +(See JsonResourceTest for more details.) + +Running the Example +------------------- + +Run the example as follows: + +> mvn clean compile exec:java + +This deploys the example using [Grizzly](http://grizzly.java.net/) + +A [WADL description](http://wadl.java.net/#spec) may be accessed at the URL: + +- + +The resource is available at + +- \ No newline at end of file diff --git a/jersey-json-moxy/pom.xml b/jersey-json-moxy/pom.xml new file mode 100644 index 0000000..249081b --- /dev/null +++ b/jersey-json-moxy/pom.xml @@ -0,0 +1,65 @@ + + 4.0.0 + com.javadevelopersguide.jersey + jersey-json-moxy + war + 0.0.1-SNAPSHOT + jersey-json-moxy Maven Webapp + http://maven.apache.org + + + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + + org.glassfish.jersey.media + jersey-media-moxy + 2.26 + + + + + org.glassfish.jersey.core + jersey-server + 2.7 + + + org.glassfish.jersey.containers + jersey-container-servlet + 2.7 + + + + + jersey-json-moxy + + + org.apache.maven.plugins + maven-war-plugin + + false + + + + maven-compiler-plugin + 2.0.2 + + 1.8 + 1.8 + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + 2.2 + + + + diff --git a/jersey-json-moxy/src/main/java/com/javadevelopersguide/jersey/config/JerseyServletContainerConfig.java b/jersey-json-moxy/src/main/java/com/javadevelopersguide/jersey/config/JerseyServletContainerConfig.java new file mode 100644 index 0000000..a23ba03 --- /dev/null +++ b/jersey-json-moxy/src/main/java/com/javadevelopersguide/jersey/config/JerseyServletContainerConfig.java @@ -0,0 +1,30 @@ +package com.javadevelopersguide.jersey.config; + +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.ext.ContextResolver; + +import org.glassfish.jersey.moxy.json.MoxyJsonConfig; +// Deployment of a JAX-RS application using @ApplicationPath with Servlet 3.0 +// Descriptor-less deployment +import org.glassfish.jersey.server.ResourceConfig; + +@ApplicationPath("resources") +public class JerseyServletContainerConfig extends ResourceConfig { + public JerseyServletContainerConfig() { + + // if there are more than two packanges then separate them with semicolon + // exmaple : packages("org.foo.rest;org.bar.rest"); + packages("com.javadevelopersguide.jersey.helloworld;com.javadevelopersguide.jersey.jsonmoxy"); + } + + /* public ContextResolver createMoxyJsonResolver() { + final MoxyJsonConfig moxyJsonConfig = new MoxyJsonConfig(); + Map namespacePrefixMapper = new HashMap(1); + namespacePrefixMapper.put("http://www.w3.org/2001/XMLSchema-instance", "xsi"); + moxyJsonConfig.setNamespacePrefixMapper(namespacePrefixMapper).setNamespaceSeparator(':'); + return moxyJsonConfig.resolver(); + }*/ +} diff --git a/jersey-json-moxy/src/main/java/com/javadevelopersguide/jersey/helloworld/HelloWorldResource.java b/jersey-json-moxy/src/main/java/com/javadevelopersguide/jersey/helloworld/HelloWorldResource.java new file mode 100644 index 0000000..9a6b470 --- /dev/null +++ b/jersey-json-moxy/src/main/java/com/javadevelopersguide/jersey/helloworld/HelloWorldResource.java @@ -0,0 +1,14 @@ +package com.javadevelopersguide.jersey.helloworld; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +@Path("/") +public class HelloWorldResource { + + @GET + @Path("helloworld") + public String helloworld(){ + return "Helloworld !!!!"; + } +} diff --git a/jersey-json-moxy/src/main/java/com/javadevelopersguide/jersey/jsonmoxy/JsonResource.java b/jersey-json-moxy/src/main/java/com/javadevelopersguide/jersey/jsonmoxy/JsonResource.java new file mode 100644 index 0000000..0d8b3af --- /dev/null +++ b/jersey-json-moxy/src/main/java/com/javadevelopersguide/jersey/jsonmoxy/JsonResource.java @@ -0,0 +1,68 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2012-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey.jsonmoxy; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +/** + * @author Pavel Bucek (pavel.bucek at oracle.com) + */ +@Path("test") +public class JsonResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + public TestBean createSimpleBean() { + return new TestBean("a", 1, 1L); + } + + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public TestBean roundTrip(TestBean s) { + return s; + } +} diff --git a/jersey-json-moxy/src/main/java/com/javadevelopersguide/jersey/jsonmoxy/TestBean.java b/jersey-json-moxy/src/main/java/com/javadevelopersguide/jersey/jsonmoxy/TestBean.java new file mode 100644 index 0000000..673a245 --- /dev/null +++ b/jersey-json-moxy/src/main/java/com/javadevelopersguide/jersey/jsonmoxy/TestBean.java @@ -0,0 +1,101 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2012-2017 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://oss.oracle.com/licenses/CDDL+GPL-1.1 + * or LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package com.javadevelopersguide.jersey.jsonmoxy; + +public class TestBean { + + public String a; + public int b; + public long c; + + public TestBean() { + } + + public TestBean(String a, int b, long c) { + this.a = a; + this.b = b; + this.c = c; + } + + public String getA() { + return a; + } + + public int getB() { + return b; + } + + public long getC() { + return c; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + TestBean that = (TestBean) o; + + if (b != that.b) { + return false; + } + if (c != that.c) { + return false; + } + if (a != null ? !a.equals(that.a) : that.a != null) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = a != null ? a.hashCode() : 0; + result = 31 * result + b; + result = 31 * result + (int) (c ^ (c >>> 32)); + return result; + } +} diff --git a/jersey-json-moxy/src/main/webapp/WEB-INF/web.xml b/jersey-json-moxy/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..9f88c1f --- /dev/null +++ b/jersey-json-moxy/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,7 @@ + + + + Archetype Created Web Application + diff --git a/jersey-json-moxy/src/main/webapp/index.jsp b/jersey-json-moxy/src/main/webapp/index.jsp new file mode 100644 index 0000000..c38169b --- /dev/null +++ b/jersey-json-moxy/src/main/webapp/index.jsp @@ -0,0 +1,5 @@ + + +

Hello World!

+ + diff --git a/jersey-logging-server-client-example/.classpath b/jersey-logging-server-client-example/.classpath new file mode 100644 index 0000000..2784a1b --- /dev/null +++ b/jersey-logging-server-client-example/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jersey-logging-server-client-example/.project b/jersey-logging-server-client-example/.project new file mode 100644 index 0000000..8e985f0 --- /dev/null +++ b/jersey-logging-server-client-example/.project @@ -0,0 +1,37 @@ + + + jersey-logging-server-client-example + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/jersey-logging-server-client-example/.settings/.jsdtscope b/jersey-logging-server-client-example/.settings/.jsdtscope new file mode 100644 index 0000000..2418123 --- /dev/null +++ b/jersey-logging-server-client-example/.settings/.jsdtscope @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/jersey-logging-server-client-example/.settings/org.eclipse.jdt.core.prefs b/jersey-logging-server-client-example/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..45a6e0e --- /dev/null +++ b/jersey-logging-server-client-example/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.5 diff --git a/jersey-logging-server-client-example/.settings/org.eclipse.m2e.core.prefs b/jersey-logging-server-client-example/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/jersey-logging-server-client-example/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/jersey-logging-server-client-example/.settings/org.eclipse.wst.common.component b/jersey-logging-server-client-example/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..92e78bc --- /dev/null +++ b/jersey-logging-server-client-example/.settings/org.eclipse.wst.common.component @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/jersey-logging-server-client-example/.settings/org.eclipse.wst.common.project.facet.core.xml b/jersey-logging-server-client-example/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..d74c55e --- /dev/null +++ b/jersey-logging-server-client-example/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/jersey-logging-server-client-example/.settings/org.eclipse.wst.jsdt.ui.superType.container b/jersey-logging-server-client-example/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100644 index 0000000..3bd5d0a --- /dev/null +++ b/jersey-logging-server-client-example/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/jersey-logging-server-client-example/.settings/org.eclipse.wst.jsdt.ui.superType.name b/jersey-logging-server-client-example/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100644 index 0000000..05bd71b --- /dev/null +++ b/jersey-logging-server-client-example/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/jersey-logging-server-client-example/.settings/org.eclipse.wst.validation.prefs b/jersey-logging-server-client-example/.settings/org.eclipse.wst.validation.prefs new file mode 100644 index 0000000..04cad8c --- /dev/null +++ b/jersey-logging-server-client-example/.settings/org.eclipse.wst.validation.prefs @@ -0,0 +1,2 @@ +disabled=06target +eclipse.preferences.version=1 diff --git a/jersey-logging-server-client-example/pom.xml b/jersey-logging-server-client-example/pom.xml new file mode 100644 index 0000000..84fa54e --- /dev/null +++ b/jersey-logging-server-client-example/pom.xml @@ -0,0 +1,88 @@ + + 4.0.0 + com.javadevelopersguide.jersey + jersey-logging-server-client-example + war + 0.0.1-SNAPSHOT + jersey-logging-server-client-example Maven Webapp + http://maven.apache.org + + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + + org.glassfish.jersey.core + jersey-server + ${jersey.version} + + + org.glassfish.jersey.containers + jersey-container-servlet + ${jersey.version} + + + + + org.glassfish.jersey.media + jersey-media-moxy + ${jersey.version} + + + + org.glassfish.jersey.inject + jersey-hk2 + ${jersey.version} + + + + + org.glassfish.jersey.core + jersey-client + ${jersey.version} + + + + org.slf4j + slf4j-log4j12 + 1.7.21 + + + + + jersey-logging-server-client-example + + + org.apache.maven.plugins + maven-war-plugin + + false + + + + maven-compiler-plugin + 2.0.2 + + 1.8 + 1.8 + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + 2.2 + + + + + + 2.26 + + + diff --git a/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/client/UserResourceClient.java b/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/client/UserResourceClient.java new file mode 100644 index 0000000..3609817 --- /dev/null +++ b/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/client/UserResourceClient.java @@ -0,0 +1,33 @@ +package com.javadevelopersguide.jersey.client; + +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.core.MediaType; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.logging.LoggingFeature; + +public class UserResourceClient { + + public static void main(String[] args) { + getUsers(); + } + protected static ClientConfig createClientConfig() { + ClientConfig config = new ClientConfig(); + config.register(new LoggingFeature(Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 10000)); + return config; + } + + private static void getUsers() { + Client client = ClientBuilder.newClient(createClientConfig()); + + String entity = client.target("http://localhost:8080/jersey-logging-server-client-example/resources").path("users") + .request(MediaType.APPLICATION_JSON).header("some-header", "true").get(String.class); + + System.out.println(entity); + } + +} diff --git a/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/config/AppResourceConfig.java b/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/config/AppResourceConfig.java new file mode 100644 index 0000000..842bda4 --- /dev/null +++ b/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/config/AppResourceConfig.java @@ -0,0 +1,18 @@ +package com.javadevelopersguide.jersey.config; + +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.ws.rs.ApplicationPath; + +import org.glassfish.jersey.logging.LoggingFeature; +import org.glassfish.jersey.server.ResourceConfig; + +@ApplicationPath("resources") +public class AppResourceConfig extends ResourceConfig { + public AppResourceConfig() { + packages("com.javadevelopersguide.jersey.resources"); + register(new LoggingFeature(Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), + Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 10000)); + } +} diff --git a/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/model/APIResponse.java b/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/model/APIResponse.java new file mode 100644 index 0000000..f47e506 --- /dev/null +++ b/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/model/APIResponse.java @@ -0,0 +1,37 @@ +package com.javadevelopersguide.jersey.model; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class APIResponse { + private int errorCode; + private String message; + + public APIResponse(){ + + } + + public APIResponse(int errorCode, String message) { + super(); + this.errorCode = errorCode; + this.message = message; + } + + public int getErrorCode() { + return errorCode; + } + + public void setErrorCode(int errorCode) { + this.errorCode = errorCode; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + +} diff --git a/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/model/User.java b/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/model/User.java new file mode 100644 index 0000000..df8348f --- /dev/null +++ b/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/model/User.java @@ -0,0 +1,40 @@ +package com.javadevelopersguide.jersey.model; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class User { + private long id; + private String name; + private String email; + + public User() { + + } + + + public User(long id, String name, String email) { + super(); + this.id = id; + this.name = name; + this.email = email; + } + public long getId() { + return id; + } + public void setId(long id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } +} diff --git a/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/resources/HelloWorldResource.java b/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/resources/HelloWorldResource.java new file mode 100644 index 0000000..488d804 --- /dev/null +++ b/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/resources/HelloWorldResource.java @@ -0,0 +1,15 @@ +package com.javadevelopersguide.jersey.resources; + +import javax.ws.rs.GET; + +import javax.ws.rs.Path; + +@Path("/") +public class HelloWorldResource { + + @GET + @Path("helloworld") + public String helloworld(){ + return "Helloworld !!!!"; + } +} diff --git a/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/resources/UserResource.java b/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/resources/UserResource.java new file mode 100644 index 0000000..e1a70a0 --- /dev/null +++ b/jersey-logging-server-client-example/src/main/java/com/javadevelopersguide/jersey/resources/UserResource.java @@ -0,0 +1,25 @@ +package com.javadevelopersguide.jersey.resources; + +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import com.javadevelopersguide.jersey.model.User; + +@Path("/users") +public class UserResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + public List fetchAll() { + List users = new ArrayList(); + users.add(new User(100, "A", "demo@gmail.com")); + users.add(new User(101, "B", "demo1@gmail.com")); + users.add(new User(102, "C", "demo2@gmail.com")); + return users; + } +} diff --git a/jersey-logging-server-client-example/src/main/webapp/WEB-INF/web.xml b/jersey-logging-server-client-example/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..9f88c1f --- /dev/null +++ b/jersey-logging-server-client-example/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,7 @@ + + + + Archetype Created Web Application + diff --git a/jersey-logging-server-client-example/src/main/webapp/index.jsp b/jersey-logging-server-client-example/src/main/webapp/index.jsp new file mode 100644 index 0000000..c38169b --- /dev/null +++ b/jersey-logging-server-client-example/src/main/webapp/index.jsp @@ -0,0 +1,5 @@ + + +

Hello World!

+ +