This particular code for the service and client are nothing fancy, but I told the JUG members that I would publish it when I got a chance.
Code
The Apache Maven based projects were developed using the NetBeans 7 IDE and GlassFish 3.1.2. You will need to run the simple-xml-example project first before you can run the client application.The code for the projects can be downloaded here: simple-xml-example.zip and simple-xml-example-client.zip
ExampleResource.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | package com.bluelotussoftware.example; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; /** * Example REST Web Service * * @author John Yeary * @version 1.0 */ @Path ( "example" ) public class ExampleResource { /** * Creates a new instance of ExampleResource */ public ExampleResource() { } @GET @Produces (MediaType.APPLICATION_XML) public String getXml() { StringBuilder sb = new StringBuilder(); sb.append( "<?xml version='1.0'?><message>" ).append( "This is the message" ).append( "</message>" ); return sb.toString(); } @PUT @Consumes ({MediaType.APPLICATION_XML}) @Produces ({MediaType.APPLICATION_XML}) public String putXml(String content) { System.out.println(content); return content; } } |
SimpleXMLExampleClient.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | package com.bluelotussoftware.example; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; /** * Simple XML REST client. * * @author John Yeary * @version 1.0 */ public class SimpleXMLExampleClient { public static void main(String[] args) { ExampleResourceClient erc = new ExampleResourceClient(); System.out.println(erc.getXml()); String s = "<?xml version='1.0'?><message>My Personal message</message>" ; System.out.println(erc.putXml(s)); erc.close(); } static class ExampleResourceClient { private WebResource webResource; private Client client; public ExampleResourceClient() { com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig(); client = Client.create(config); webResource = client.resource(BASE_URI).path( "example" ); } public String getXml() throws UniformInterfaceException { WebResource resource = webResource; return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_XML).get(String.class); } public String putXml(Object requestEntity) throws UniformInterfaceException { return webResource.type(javax.ws.rs.core.MediaType.APPLICATION_XML).put(String.class, requestEntity); } public void close() { client.destroy(); } } } |
0 comments :
Post a Comment