BAEL-3091: The Prototype Pattern in Java (changed code based on valid comments from a reader)

This commit is contained in:
Vivek Balasubramaniam
2019-10-29 22:27:15 +05:30
parent db85c8f275
commit d3d5b060e7
20517 changed files with 1642290 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
## RESTEasy
This module contains articles about RESTEasy.
### Relevant Articles:
- [A Guide to RESTEasy](https://www.baeldung.com/resteasy-tutorial)
- [RESTEasy Client API](https://www.baeldung.com/resteasy-client-tutorial)
- [CORS in JAX-RS](https://www.baeldung.com/cors-in-jax-rs)
+149
View File
@@ -0,0 +1,149 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>resteasy</artifactId>
<version>1.0</version>
<name>resteasy</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- core library -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-servlet-initializer</artifactId>
<version>${resteasy.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>${resteasy.version}</version>
</dependency>
<!-- Optional library -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>${resteasy.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>${resteasy.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
</dependencies>
<build>
<finalName>RestEasyTutorial</finalName>
<plugins>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<type>embedded</type>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntTest.java</exclude>
</excludes>
<includes>
<include>**/*LiveTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>false</wait>
</configuration>
<executions>
<execution>
<id>start-server</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop-server</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<resteasy.version>3.0.19.Final</resteasy.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
</properties>
</project>
@@ -0,0 +1,36 @@
package com.baeldung.client;
import com.baeldung.model.Movie;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
@Path("/movies")
public interface ServicesInterface {
@GET
@Path("/getinfo")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
Movie movieByImdbId(@QueryParam("imdbId") String imdbId);
@GET
@Path("/listmovies")
@Produces({ "application/json" })
List<Movie> listMovies();
@POST
@Path("/addmovie")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
Response addMovie(Movie movie);
@PUT
@Path("/updatemovie")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
Response updateMovie(Movie movie);
@DELETE
@Path("/deletemovie")
Response deleteMovie(@QueryParam("imdbId") String imdbId);
}
@@ -0,0 +1,18 @@
package com.baeldung.filter;
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
public class CORSFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
}
}
@@ -0,0 +1,66 @@
package com.baeldung.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "movie", propOrder = { "imdbId", "title" })
public class Movie {
protected String imdbId;
protected String title;
public Movie(String imdbId, String title) {
this.imdbId = imdbId;
this.title = title;
}
public Movie() {}
public String getImdbId() {
return imdbId;
}
public void setImdbId(String imdbId) {
this.imdbId = imdbId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Movie movie = (Movie) o;
if (imdbId != null ? !imdbId.equals(movie.imdbId) : movie.imdbId != null)
return false;
return title != null ? title.equals(movie.title) : movie.title == null;
}
@Override
public int hashCode() {
int result = imdbId != null ? imdbId.hashCode() : 0;
result = 31 * result + (title != null ? title.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Movie{" +
"imdbId='" + imdbId + '\'' +
", title='" + title + '\'' +
'}';
}
}
@@ -0,0 +1,95 @@
package com.baeldung.server;
import com.baeldung.model.Movie;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Path("/movies")
public class MovieCrudService {
private Map<String, Movie> inventory = new HashMap<String, Movie>();
@GET
@Path("/")
@Produces({ MediaType.TEXT_PLAIN })
public Response index() {
return Response.status(200).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Credentials", "true")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD").entity("").build();
}
@GET
@Path("/getinfo")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Movie movieByImdbId(@QueryParam("imdbId") String imdbId) {
System.out.println("*** Calling getinfo for a given ImdbID***");
if (inventory.containsKey(imdbId)) {
return inventory.get(imdbId);
} else
return null;
}
@POST
@Path("/addmovie")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response addMovie(Movie movie) {
System.out.println("*** Calling addMovie ***");
if (null != inventory.get(movie.getImdbId())) {
return Response.status(Response.Status.NOT_MODIFIED).entity("Movie is Already in the database.").build();
}
inventory.put(movie.getImdbId(), movie);
return Response.status(Response.Status.CREATED).build();
}
@PUT
@Path("/updatemovie")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response updateMovie(Movie movie) {
System.out.println("*** Calling updateMovie ***");
if (null == inventory.get(movie.getImdbId())) {
return Response.status(Response.Status.NOT_MODIFIED)
.entity("Movie is not in the database.\nUnable to Update").build();
}
inventory.put(movie.getImdbId(), movie);
return Response.status(Response.Status.OK).build();
}
@DELETE
@Path("/deletemovie")
public Response deleteMovie(@QueryParam("imdbId") String imdbId) {
System.out.println("*** Calling deleteMovie ***");
if (null == inventory.get(imdbId)) {
return Response.status(Response.Status.NOT_FOUND).entity("Movie is not in the database.\nUnable to Delete")
.build();
}
inventory.remove(imdbId);
return Response.status(Response.Status.OK).build();
}
@GET
@Path("/listmovies")
@Produces({ "application/json" })
public List<Movie> listMovies() {
return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new));
}
}
@@ -0,0 +1,32 @@
package com.baeldung.server;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@ApplicationPath("/rest")
public class RestEasyServices extends Application {
private Set<Object> singletons = new HashSet<Object>();
public RestEasyServices() {
singletons.add(new MovieCrudService());
}
@Override
public Set<Object> getSingletons() {
return singletons;
}
@Override
public Set<Class<?>> getClasses() {
return super.getClasses();
}
@Override
public Map<String, Object> getProperties() {
return super.getProperties();
}
}
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,13 @@
<?xml version="1.0"?>
<jboss-deployment-structure>
<deployment>
<exclude-subsystems>
<subsystem name="resteasy"/>
</exclude-subsystems>
<exclusions>
<module name="javaee.api"/><module name="javax.ws.rs.api"/>
<module name="org.jboss.resteasy.resteasy-jaxrs"/>
</exclusions>
<local-last value="true"/>
</deployment>
</jboss-deployment-structure>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 4.2//EN" "http://www.jboss.org/j2ee/dtd/jboss-web_4_2.dtd">
<jboss-web>
</jboss-web>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>RestEasy Example</display-name>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
</web-app>
+16
View File
@@ -0,0 +1,16 @@
function call(url, type, data) {
var request = $.ajax({
url : url,
method : "GET",
data : (data) ? JSON.stringify(data) : "",
dataType : type
});
request.done(function(resp) {
console.log(resp);
});
request.fail(function(jqXHR, textStatus) {
console.log("Request failed: " + textStatus);
});
};
@@ -0,0 +1,178 @@
package com.baeldung.server;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import javax.naming.NamingException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import org.apache.commons.io.IOUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.client.ServicesInterface;
import com.baeldung.model.Movie;
public class RestEasyClientLiveTest {
public static final UriBuilder FULL_PATH = UriBuilder.fromPath("http://127.0.0.1:8082/RestEasyTutorial/rest");
Movie transformerMovie = null;
Movie batmanMovie = null;
ObjectMapper jsonMapper = null;
@Before
public void setup() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException {
jsonMapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
jsonMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
jsonMapper.setDateFormat(sdf);
try (InputStream inputStream = new RestEasyClientLiveTest().getClass().getResourceAsStream("./movies/transformer.json")) {
final String transformerMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
transformerMovie = jsonMapper.readValue(transformerMovieAsString, Movie.class);
} catch (final Exception e) {
e.printStackTrace();
throw new RuntimeException("Test is going to die ...", e);
}
try (InputStream inputStream = new RestEasyClientLiveTest().getClass().getResourceAsStream("./movies/batman.json")) {
final String batmanMovieAsString = String.format(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
batmanMovie = jsonMapper.readValue(batmanMovieAsString, Movie.class);
} catch (final Exception e) {
throw new RuntimeException("Test is going to die ...", e);
}
}
@Test
public void testListAllMovies() {
final ResteasyClient client = new ResteasyClientBuilder().build();
final ResteasyWebTarget target = client.target(FULL_PATH);
final ServicesInterface proxy = target.proxy(ServicesInterface.class);
Response moviesResponse = proxy.addMovie(transformerMovie);
moviesResponse.close();
moviesResponse = proxy.addMovie(batmanMovie);
moviesResponse.close();
final List<Movie> movies = proxy.listMovies();
System.out.println(movies);
}
@Test
public void testMovieByImdbId() {
final String transformerImdbId = "tt0418279";
final ResteasyClient client = new ResteasyClientBuilder().build();
final ResteasyWebTarget target = client.target(FULL_PATH);
final ServicesInterface proxy = target.proxy(ServicesInterface.class);
final Response moviesResponse = proxy.addMovie(transformerMovie);
moviesResponse.close();
final Movie movies = proxy.movieByImdbId(transformerImdbId);
System.out.println(movies);
}
@Test
public void testAddMovie() {
final ResteasyClient client = new ResteasyClientBuilder().build();
final ResteasyWebTarget target = client.target(FULL_PATH);
final ServicesInterface proxy = target.proxy(ServicesInterface.class);
Response moviesResponse = proxy.addMovie(batmanMovie);
moviesResponse.close();
moviesResponse = proxy.addMovie(transformerMovie);
if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) {
System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus());
}
moviesResponse.close();
System.out.println("Response Code: " + moviesResponse.getStatus());
}
@Test
public void testAddMovieMultiConnection() {
final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
final ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
final ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
final ResteasyWebTarget target = client.target(FULL_PATH);
final ServicesInterface proxy = target.proxy(ServicesInterface.class);
final Response batmanResponse = proxy.addMovie(batmanMovie);
final Response transformerResponse = proxy.addMovie(transformerMovie);
if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) {
System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus());
}
if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) {
System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus());
}
batmanResponse.close();
transformerResponse.close();
cm.close();
}
@Test
public void testDeleteMovie() {
final ResteasyClient client = new ResteasyClientBuilder().build();
final ResteasyWebTarget target = client.target(FULL_PATH);
final ServicesInterface proxy = target.proxy(ServicesInterface.class);
Response moviesResponse = proxy.addMovie(batmanMovie);
moviesResponse.close();
moviesResponse = proxy.deleteMovie(batmanMovie.getImdbId());
if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) {
System.out.println(moviesResponse.readEntity(String.class));
throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus());
}
moviesResponse.close();
System.out.println("Response Code: " + moviesResponse.getStatus());
}
@Test
public void testUpdateMovie() {
final ResteasyClient client = new ResteasyClientBuilder().build();
final ResteasyWebTarget target = client.target(FULL_PATH);
final ServicesInterface proxy = target.proxy(ServicesInterface.class);
Response moviesResponse = proxy.addMovie(batmanMovie);
moviesResponse.close();
batmanMovie.setTitle("Batman Begins");
moviesResponse = proxy.updateMovie(batmanMovie);
if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) {
System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus());
}
moviesResponse.close();
System.out.println("Response Code: " + moviesResponse.getStatus());
}
}
@@ -0,0 +1,4 @@
{
"title": "Batman",
"imdbId": "tt0096895"
}
@@ -0,0 +1,4 @@
{
"title": "Transformers",
"imdbId": "tt0418279"
}