====== Lesson 5 - REST, Jersey client, mashup ====== ===== Lesson plan ===== * Mashups * Jersey Java client API * XML Parsers ===== Mashups ===== Short external talk on web mashup: [[http://www.slideshare.net/amba_slide/web-mashup|Mashup architecture]] ===== Jersey Java client API ===== One may want to create a programmatic REST client using JAVA. See the jersey documentation: [[https://jersey.java.net/documentation/latest/user-guide.html#client|Client API]] Adding the Maven dependency: org.glassfish.jersey.core jersey-client 2.22.1 Using the client API is very easy: Client orderClient = ClientBuilder.newClient(); WebTarget target = orderClient .target("http://localhost:8082/rest-client-api-example/resources/orders/{id}"); Response response = target .resolveTemplate("id", 1) // Resolves the {id} template .request(MediaType.APPLICATION_JSON) .get(); if(response.getStatus() == Status.OK.getStatusCode()){ Order order = (Order) response.readEntity(Order.class); System.out.println("Id: " + order.getId()); System.out.println("Name: " + order.getName()); System.out.println("Price: " + order.getPrice()); }else{ System.out.println(response.getStatus() + " " + response.getStatusInfo()); } ==== Parsing JSON ==== === Json-simple === Add the Maven dependency: com.googlecode.json-simple json-simple 1.1 Sample usage: //Server output in String String output = response.getEntity(String.class); final JSONObject jsonObj = (JSONObject) parser.parse( output ); if ( jsonObj != null && jsonObj.containsKey( "length" ) ) { System.out.println(jsonObj.get( "length" ).toString()); } === Google-gson === Using another JSON pareser: Maven: com.google.code.gson gson 2.2.4 compile Sample: [[http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/]] ==== XML parsing ==== Using the DOM XML Parser: http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/