package com.mycompany.restclientexam;
import java.util.Set;
import javax.ws.rs.core.Application;
@javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
try {
Class jsonProvider = Class.forName("org.glassfish.jersey.jackson.JacksonFeature");
// Class jsonProvider = Class.forName("org.glassfish.jersey.moxy.json.MoxyJsonFeature");
// Class jsonProvider = Class.forName("org.glassfish.jersey.jettison.JettisonFeature");
resources.add(jsonProvider);
// Add additional features such as support for Multipart.
Class multiPartFeature = Class.forName("org.glassfish.jersey.media.multipart.MultiPartFeature");
resources.add(multiPartFeature);
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
addRestResourceClasses(resources);
return resources;
}
/**
* Do not modify addRestResourceClasses() method.
* It is automatically populated with
* all resources defined in the project.
* If required, comment out calling this method in getClasses().
*/
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(com.mycompany.restclientexam.GenericResource.class);
resources.add(com.mycompany.restclientexam.PostResource.class);
resources.add(com.mycompany.restclientexam.SecureResource.class);
}
}
package com.mycompany.restclientexam;
import com.mycompany.restclientcommon.EmployeeBean;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
/**
* REST Web Service
*
* @author atsushi
*/
@Path("generic")
public class GenericResource {
@Context
private UriInfo context;
/**
* Creates a new instance of GenericResource
*/
public GenericResource() {
}
/**
* Retrieves representation of an instance of com.mycompany.restclientexam.GenericResource
* @param id
* @return an instance of java.lang.String
*/
@GET
@Path("search")
@Produces(MediaType.APPLICATION_XML)
public EmployeeBean searchEmployee(@QueryParam("id") long id) {
if (id == 123L) {
return new EmployeeBean(123L,"Takako","Accounting");
}
return new EmployeeBean(999L,"TEST_USER","TEST_DIVISION");
}
}
package com.mycompany.restclientcommon;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@XmlRootElement(name = "employee")
public class EmployeeBean {
private long id;
private String name;
private String dept;
}
<?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.mycompany</groupId>
<artifactId>RestClientCommon</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.6</version>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<!-- The maven-compiler-plugin is required
to expose lombok-bean outside the jar -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
[~]$ curl http://localhost:8080/RestClientExam/webresources/generic/search?id=123 | xmllint --format -
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
<dept>Accounting</dept>
<id>123</id>
<name>Takako</name>
</employee>
[~]$ curl http://localhost:8080/RestClientExam/webresources/generic/search?id=999 | xmllint --format -
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
<dept>TEST_DIVISION</dept>
<id>999</id>
<name>TEST_USER</name>
</employee>
<?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.mycompany</groupId>
<artifactId>RestClient</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>2.22.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.22.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>2.22.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.22.2</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>RestClientCommon</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
</project>
package com.mycompany.restclient;
import com.mycompany.restclientcommon.EmployeeBean;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.jaxb.internal.JaxbStringReaderProvider;
/**
* Jersey REST client generated for REST resource:GenericResource [generic]<br>
* USAGE:
* <pre>
* JerseyClient client = new JerseyClient();
* Object response = client.XXX(...);
* // do whatever with response
* client.close();
* </pre>
*
* @author atsushi
*/
public class JerseyClient {
private WebTarget webTarget;
private Client client;
private static final String BASE_URI = "http://localhost:8080/RestClientExam/webresources/generic";
public JerseyClient() {
ClientConfig config = new ClientConfig();
config.register(JaxbStringReaderProvider.class);
client = javax.ws.rs.client.ClientBuilder.newClient(config);
webTarget = client.target(BASE_URI);
}
public EmployeeBean search(long id) throws ClientErrorException {
WebTarget resource = webTarget.path("search").queryParam("id", id);
return resource
.request(javax.ws.rs.core.MediaType.APPLICATION_XML)
.get(EmployeeBean.class);
}
public void close() {
client.close();
}
}
package com.mycompany.restclient;
import com.mycompany.restclientcommon.EmployeeBean;
/**
* GET Example.
* @author atsushi
*/
public class Main {
public static void main(String[] args) {
JerseyClient client = new JerseyClient();
EmployeeBean bean = client.search(123L);
System.out.println(bean);
EmployeeBean bean2 = client.search(999L);
System.out.println(bean2);
}
}
EmployeeBean(id=123, name=Takako, dept=Accounting)
EmployeeBean(id=999, name=TEST_USER, dept=TEST_DIVISION)
WebTarget resource = webTarget.path("search/{id}");
return resource
.resolveTemplate("id", id)
.request(javax.ws.rs.core.MediaType.APPLICATION_XML)
.get(EmployeeBean.class);
package com.mycompany.restclient;
import com.mycompany.restclientcommon.EmployeeBean;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.jaxb.internal.JaxbStringReaderProvider;
/**
* Jersey REST client generated for REST resource:GenericResource [generic]<br>
* USAGE:
* <pre>
* NewJerseyClient client = new NewJerseyClient();
* Object response = client.XXX(...);
* // do whatever with response
* client.close();
* </pre>
*
* @author atsushi
*/
public class JerseyClient2 {
private WebTarget webTarget;
private Client client;
private static final String BASE_URI = "https://localhost:8181/RestClientExam/webresources/generic";
public JerseyClient2() {
ClientConfig config = new ClientConfig();
config.register(JaxbStringReaderProvider.class);
client = javax.ws.rs.client.ClientBuilder.newBuilder().sslContext(getSSLContext()).build();
webTarget = client.target(BASE_URI);
}
public EmployeeBean search(final long id) throws ClientErrorException {
WebTarget resource = webTarget.path("search").queryParam("id", id);
return resource.request(javax.ws.rs.core.MediaType.APPLICATION_XML).get(EmployeeBean.class);
}
public void close() {
client.close();
}
private HostnameVerifier getHostnameVerifier() {
return new HostnameVerifier() {
@Override
public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
return true;
}
};
}
private SSLContext getSSLContext() {
// for alternative implementation checkout org.glassfish.jersey.SslConfigurator
javax.net.ssl.TrustManager x509 = new javax.net.ssl.X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
return;
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
return;
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("SSL");
ctx.init(null, new javax.net.ssl.TrustManager[]{x509}, null);
} catch (java.security.GeneralSecurityException ex) {
}
return ctx;
}
}
package com.mycompany.restclient;
import com.mycompany.restclientcommon.EmployeeBean;
/**
* HTTPS Example.
* @author atsushi
*/
public class Main2 {
public static void main(String[] args) {
JerseyClient2 client = new JerseyClient2();
EmployeeBean bean = client.search(123L);
System.out.println(bean);
EmployeeBean bean2 = client.search(999L);
System.out.println(bean2);
}
}
EmployeeBean(id=123, name=Takako, dept=Accounting)
EmployeeBean(id=999, name=TEST_USER, dept=TEST_DIVISION)
package com.mycompany.restclient;
import com.mycompany.restclientcommon.EmployeeBean;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.glassfish.jersey.jaxb.internal.JaxbStringReaderProvider;
//import org.glassfish.jersey.client.filter.HttpBasicAuthFilter;
/**
* Jersey REST client generated for REST resource:GenericResource [generic]<br>
* USAGE:
* <pre>
* NewJerseyClient1 client = new NewJerseyClient1();
* Object response = client.XXX(...);
* // do whatever with response
* client.close();
* </pre>
*
* @author atsushi
*/
public class JerseyClient3 {
private WebTarget webTarget;
private Client client;
private static final String BASE_URI = "http://localhost:8080/RestClientExam/webresources/secure";
public JerseyClient3(String username, String password) {
ClientConfig config = new ClientConfig();
config.register(JaxbStringReaderProvider.class);
config.register(HttpAuthenticationFeature.basic(username, password));
client = javax.ws.rs.client.ClientBuilder.newClient(config);
webTarget = client.target(BASE_URI);
}
public EmployeeBean search(long id) throws ClientErrorException {
WebTarget resource = webTarget.path("search").queryParam("id", id);
return resource.request(javax.ws.rs.core.MediaType.APPLICATION_XML).get(EmployeeBean.class);
}
public void close() {
client.close();
}
}
package com.mycompany.restclient;
import com.mycompany.restclientcommon.EmployeeBean;
/**
* Basic Auth Example.
* @author atsushi
*/
public class Main3 {
public static void main(String[] args) {
JerseyClient3 client = new JerseyClient3("aho","password");
EmployeeBean bean = client.search(007L);
System.out.println(bean);
}
}
EmployeeBean(id=7, name=Bond, dept=MI6)
package com.mycompany.restclient;
import com.mycompany.restclientcommon.EmployeeBean;
import java.io.File;
import java.io.FileNotFoundException;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.jaxb.internal.JaxbStringReaderProvider;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
/**
* Jersey REST client generated for REST resource:PostResource [post]<br>
* USAGE:
* <pre>
* NewJerseyClient client = new NewJerseyClient();
* Object response = client.XXX(...);
* // do whatever with response
* client.close();
* </pre>
*
* @author atsushi
*/
public class JerseyClient4 {
private WebTarget webTarget;
private Client client;
private static final String BASE_URI = "http://localhost:8080/RestClientExam/webresources/post";
public JerseyClient4() {
ClientConfig config = new ClientConfig();
config.register(MultiPartFeature.class);
config.register(JaxbStringReaderProvider.class);
client = javax.ws.rs.client.ClientBuilder.newClient(config);
webTarget = client.target(BASE_URI);
}
public EmployeeBean search(long id) throws ClientErrorException {
WebTarget resource = webTarget.path("search");
Form form = new Form();
form.param("id",Long.toString(id));
return resource
.request(javax.ws.rs.core.MediaType.APPLICATION_XML)
.post(Entity.form(form), EmployeeBean.class);
}
public Response convert(String name, String sex, String photo) throws ClientErrorException, FileNotFoundException {
WebTarget resource = webTarget.path("convert");
MultiPart multiPart = new FormDataMultiPart()
.field("name", name)
.field("sex", sex)
.bodyPart(new FileDataBodyPart("photo", new File(photo)));
return resource
.request(javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM)
.post(Entity.entity(multiPart, multiPart.getMediaType()));
}
public void close() {
client.close();
}
}
package com.mycompany.restclient;
import com.mycompany.restclientcommon.EmployeeBean;
/**
* POST Example.
* @author atsushi
*/
public class Main4 {
public static void main(String[] args) {
JerseyClient4 client = new JerseyClient4();
EmployeeBean bean = client.search(123L);
System.out.println(bean);
EmployeeBean bean2 = client.search(999L);
System.out.println(bean2);
}
}
EmployeeBean(id=123, name=Takako, dept=Accounting)
EmployeeBean(id=999, name=TEST_USER, dept=TEST_DIVISION)
package com.mycompany.restclient;
import com.mycompany.restclientcommon.EmployeeBean;
import java.io.File;
import java.io.FileNotFoundException;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.jaxb.internal.JaxbStringReaderProvider;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
/**
* Jersey REST client generated for REST resource:PostResource [post]<br>
* USAGE:
* <pre>
* NewJerseyClient client = new NewJerseyClient();
* Object response = client.XXX(...);
* // do whatever with response
* client.close();
* </pre>
*
* @author atsushi
*/
public class JerseyClient4 {
private WebTarget webTarget;
private Client client;
private static final String BASE_URI = "http://localhost:8080/RestClientExam/webresources/post";
public JerseyClient4() {
ClientConfig config = new ClientConfig();
config.register(MultiPartFeature.class);
config.register(JaxbStringReaderProvider.class);
client = javax.ws.rs.client.ClientBuilder.newClient(config);
webTarget = client.target(BASE_URI);
}
public EmployeeBean search(long id) throws ClientErrorException {
WebTarget resource = webTarget.path("search");
Form form = new Form();
form.param("id",Long.toString(id));
return resource
.request(javax.ws.rs.core.MediaType.APPLICATION_XML)
.post(Entity.form(form), EmployeeBean.class);
}
public Response convert(String name, String sex, String photo) throws ClientErrorException, FileNotFoundException {
WebTarget resource = webTarget.path("convert");
MultiPart multiPart = new FormDataMultiPart()
.field("name", name)
.field("sex", sex)
.bodyPart(new FileDataBodyPart("photo", new File(photo)));
return resource
.request(javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM)
.post(Entity.entity(multiPart, multiPart.getMediaType()));
}
public void close() {
client.close();
}
}
package com.mycompany.restclient;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.core.Response;
/**
* Multipart POST & Recv Stream Example.
* @author atsushi
*/
public class Main5 {
public static void main(String[] args) {
try {
JerseyClient4 client = new JerseyClient4();
Response res = client.convert("Hanako", "female", "src/main/resources/440px-Lenna.png");
System.out.println(res.getStatus());
System.out.println(res.getHeaders());
// get contents
InputStream body = res.readEntity(InputStream.class);
File tmp = new File("/tmp/tmp.png");
tmp.createNewFile();
OutputStream out = new FileOutputStream(tmp);
byte[] buf = new byte[1024];
int len;
while ((len = body.read(buf)) > 0) {
out.write(buf,0,len);
}
out.close();
res.close();
} catch (ClientErrorException | IOException ex) {
Logger.getLogger(Main5.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
200
{Transfer-Encoding=[chunked],
Server=[GlassFish Server Open Source Edition 4.1],
Content-disposition=[attachment; filename=440px-Lenna.png],
Date=[Sun, 06 Mar 2016 16:02:37 GMT],
Content-Type=[application/octet-stream],
X-Powered-By=[Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition 4.1 Java/Oracle Corporation/1.8)]}