Commit 474feab1 authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
## Example files for the title:
# RESTful Web Services, by Leonard Richardson
[![RESTful Web Services, by Leonard Richardson](http://akamaicovers.oreilly.com/images/9780596529260/cat.gif)](https://www.safaribooksonline.com/library/view/title/9780596529260//)
The following applies to example files from material published by O’Reilly Media, Inc. Content from other publishers may include different rules of usage. Please refer to any additional usage rights explained in the actual example files or refer to the publisher’s website.
O'Reilly books are here to help you get your job done. In general, you may use the code in O'Reilly books in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from our books does not require permission. Answering a question by citing our books and quoting example code does not require permission. On the other hand, selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Incorporating a significant amount of example code from our books into your product's documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN.
If you think your use of code examples falls outside fair use or the permission given here, feel free to contact us at <permissions@oreilly.com>.
Please note that the examples are not production code and have not been carefully testing. They are provided "as-is" and come with no warranty of any kind.
using System;
using System.IO;
using System.Net;
using System.Xml.XPath;
public class DeliciousApp {
static string user = "username";
static string password = "password";
static Uri uri = new Uri("https://api.del.icio.us/v1/posts/recent");
static void Main(string[] args) {
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri);
request.Credentials = new NetworkCredential(user, password);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
XPathDocument xml = new
XPathDocument(response.GetResponseStream());
XPathNavigator navigator = xml.CreateNavigator();
foreach (XPathNavigator node in navigator.Select("/posts/post")) {
string description = node.GetAttribute("description","");
string href = node.GetAttribute("href","");
Console.WriteLine(description + ": " + href);
}
}
}
See ch7/ for the Restlet implementation of the del.icio.us clone bookmark program.
// DeliciousApp.java
import java.io.*;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
/**
* A command-line application that fetches bookmarks from del.icio.us
* and prints them to strandard output.
*/
public class DeliciousApp
{
public static void main(String[] args)
throws HttpException, IOException, ParserConfigurationException,
SAXException, XPathExpressionException
{
if (args.length != 2)
{
System.out.println("Usage: java -classpath [CLASSPATH] "
+ "DeliciousApp [USERNAME] [PASSWORD]");
System.out.println("[CLASSPATH] - Must contain commons-codec, " +
"commons-logging, and commons-httpclient");
System.out.println("[USERNAME] - Your del.icio.us username");
System.out.println("[PASSWORD] - Your del.icio.us password");
System.out.println();
System.exit(-1);
}
// Set the authentication credentials.
Credentials creds = new UsernamePasswordCredentials(args[0], args[1]);
HttpClient client = new HttpClient();
client.getState().setCredentials(AuthScope.ANY, creds);
// Make the HTTP request.
String url = "https://api.del.icio.us/v1/posts/recent";
GetMethod method = new GetMethod(url);
client.executeMethod(method);
InputStream responseBody = method.getResponseBodyAsStream();
// Turn the response entity-body into an XML document.
DocumentBuilderFactory docBuilderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder =
docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(responseBody);
method.releaseConnection();
// Hit the XML document with an XPath expression to get the list
// of bookmarks.
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList bookmarks = (NodeList)xpath.evaluate("/posts/post", doc,
XPathConstants.NODESET);
// Iterate over the bookmarks and print out each one.
for (int i = 0; i < bookmarks.getLength(); i++)
{
NamedNodeMap bookmark = bookmarks.item(i).getAttributes();
String description = bookmark.getNamedItem("description")
.getNodeValue();
String uri = bookmark.getNamedItem("href").getNodeValue();
System.out.println(description + ": " + uri);
}
System.exit(0);
}
}
/*
* Copyright 2005-2007 Noelios Consulting.
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License"). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the license at
* http://www.opensource.org/licenses/cddl1.txt See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at http://www.opensource.org/licenses/cddl1.txt If
* applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*/
package org.restlet.example.book.rest.ch2;
import org.restlet.Client;
import org.restlet.data.Protocol;
import org.restlet.data.Reference;
import org.restlet.data.Response;
import org.restlet.resource.DomRepresentation;
import org.w3c.dom.Node;
/**
* Searching the web with Yahoo!'s web service using XML.
*
* @author Jerome Louvel (contact@noelios.com)
*/
public class Example2_1a {
static final String BASE_URI = "http://api.search.yahoo.com/WebSearchService/V1/webSearch";
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("You need to pass a term to search");
} else {
// Fetch a resource: an XML document full of search results
String term = Reference.encode(args[0]);
String uri = BASE_URI + "?appid=restbook&query=" + term;
Response response = new Client(Protocol.HTTP).get(uri);
DomRepresentation document = response.getEntityAsDom();
// Use XPath to find the interesting parts of the data structure
String expr = "/ResultSet/Result/Title";
for (Node node : document.getNodes(expr)) {
System.out.println(node.getTextContent());
}
}
}
}
/*
* Copyright 2005-2007 Noelios Consulting.
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License"). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the license at
* http://www.opensource.org/licenses/cddl1.txt See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at http://www.opensource.org/licenses/cddl1.txt If
* applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*/
package org.restlet.example.book.rest.ch2;
import org.restlet.Client;
import org.restlet.data.Protocol;
import org.restlet.data.Reference;
import org.restlet.data.Response;
import org.restlet.resource.DomRepresentation;
import org.w3c.dom.Node;
/**
* Searching the web with Yahoo!'s web service using XML. This version is
* namespace aware.
*
* @author Jerome Louvel (contact@noelios.com)
*/
public class Example2_1b {
static final String BASE_URI = "http://api.search.yahoo.com/WebSearchService/V1/webSearch";
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("You need to pass a term to search");
} else {
// Fetch a resource: an XML document full of search results
String term = Reference.encode(args[0]);
String uri = BASE_URI + "?appid=restbook&query=" + term;
Response response = new Client(Protocol.HTTP).get(uri);
DomRepresentation document = response.getEntityAsDom();
// Associate the namespace with the prefix y
document.setNamespaceAware(true);
document.putNamespace("y", "urn:yahoo:srch");
// Use XPath to find the interesting parts of the data structure
String expr = "/y:ResultSet/y:Result/y:Title/text()";
for (Node node : document.getNodes(expr)) {
System.out.println(node.getTextContent());
}
}
}
}
/*
* Copyright 2005-2007 Noelios Consulting.
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License"). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the license at
* http://www.opensource.org/licenses/cddl1.txt See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at http://www.opensource.org/licenses/cddl1.txt If
* applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*/
package org.restlet.example.book.rest.ch2;
import org.restlet.Client;
import org.restlet.data.ChallengeResponse;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Method;
import org.restlet.data.Protocol;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.DomRepresentation;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
/**
* Getting your list of recent bookmarks on del.icio.us.
*
* @author Jerome Louvel (contact@noelios.com)
*/
public class Example2_5 {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err
.println("You need to pass your del.icio.us user name and password");
} else {
// Create a authenticated request
Request request = new Request(Method.GET,
"https://api.del.icio.us/v1/posts/recent");
request.setChallengeResponse(new ChallengeResponse(
ChallengeScheme.HTTP_BASIC, args[0], args[1]));
// Fetch a resource: an XML document with your recent posts
Response response = new Client(Protocol.HTTPS).handle(request);
DomRepresentation document = response.getEntityAsDom();
// Use XPath to find the interesting parts of the data structure
for (Node node : document.getNodes("/posts/post")) {
NamedNodeMap attrs = node.getAttributes();
String desc = attrs.getNamedItem("description").getNodeValue();
String href = attrs.getNamedItem("href").getNodeValue();
System.out.println(desc + ": " + href);
}
}
}
}
/*
* Copyright 2005-2007 Noelios Consulting.
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License"). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the license at
* http://www.opensource.org/licenses/cddl1.txt See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at http://www.opensource.org/licenses/cddl1.txt If
* applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*/
package org.restlet.example.book.rest.ch2;
import org.json.JSONArray;
import org.json.JSONObject;
import org.restlet.Client;
import org.restlet.data.Protocol;
import org.restlet.data.Reference;
import org.restlet.data.Response;
import org.restlet.ext.json.JsonRepresentation;
/**
* Searching the web with Yahoo!'s web service using JSON.
*
* @author Jerome Louvel (contact@noelios.com)
*/
public class Example2_9 {
static final String BASE_URI = "http://api.search.yahoo.com/WebSearchService/V1/webSearch";
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("You need to pass a term to search");
} else {
// Fetch a resource: a JSON document full of search results
String term = Reference.encode(args[0]);
String uri = BASE_URI + "?appid=restbook&output=json&query=" + term;
Response response = new Client(Protocol.HTTP).get(uri);
JSONObject json = new JsonRepresentation(response.getEntity())
.toJsonObject();
// Navigate within the JSON document to display the titles
JSONObject resultSet = json.getJSONObject("ResultSet");
JSONArray results = resultSet.getJSONArray("Result");
for (int i = 0; i < results.length(); i++) {
System.out.println(results.getJSONObject(i).getString("Title"));
}
}
}
}
/*
* Copyright 2005-2007 Noelios Consulting.
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License"). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the license at
* http://www.opensource.org/licenses/cddl1.txt See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at http://www.opensource.org/licenses/cddl1.txt If
* applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*/
package org.restlet.example.book.rest.ch3;
import java.util.ArrayList;
import java.util.List;
import org.restlet.data.Response;
import org.restlet.resource.DomRepresentation;
import org.w3c.dom.Node;
/**
* Amazon S3 client application. Returns a list of buckets.
*
* @author Jerome Louvel (contact@noelios.com)
*/
public class S3App extends S3Authorized {
public static void main(String... args) {
for (S3Bucket bucket : new S3App().getBuckets()) {
System.out.println(bucket.getName() + " : " + bucket.getUri());
}
}
public List<S3Bucket> getBuckets() {
List<S3Bucket> result = new ArrayList<S3Bucket>();
// Fetch a resource: an XML document with our list of buckets
Response response = authorizedGet(HOST);
DomRepresentation document = response.getEntityAsDom();
// Use XPath to find the bucket names
for (Node node : document.getNodes("//Bucket/Name")) {
result.add(new S3Bucket(node.getTextContent()));
}
return result;
}
}
/*
* Copyright 2005-2007 Noelios Consulting.
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License"). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the license at
* http://www.opensource.org/licenses/cddl1.txt See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at http://www.opensource.org/licenses/cddl1.txt If
* applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*/
package org.restlet.example.book.rest.ch3;
import org.restlet.Client;
import org.restlet.data.ChallengeResponse;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Method;
import org.restlet.data.Protocol;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
/**
* Amazon S3 client. Support class handling authorized requests.
*
* @author Jerome Louvel (contact@noelios.com)
*/
public class S3Authorized {
public final static String PUBLIC_KEY = "0F9DBXKB5274JKTJ8DG2";
public final static String PRIVATE_KEY = "GuUHQ086WawbwvVl3JPl9JIk4VOtLcllkvIb0b7w";
public final static String HOST = "https://s3.amazonaws.com/";
private static Response handleAuthorized(Method method, String uri,
Representation entity) {
// Send an authenticated request
Request request = new Request(method, HOST, entity);
request.setChallengeResponse(new ChallengeResponse(
ChallengeScheme.HTTP_AWS, PUBLIC_KEY, PRIVATE_KEY));
return new Client(Protocol.HTTPS).handle(request);
}
public static Response authorizedHead(String uri) {
return handleAuthorized(Method.HEAD, uri, null);
}
public static Response authorizedGet(String uri) {
return handleAuthorized(Method.GET, uri, null);
}
public static Response authorizedPut(String uri, Representation entity) {
return handleAuthorized(Method.PUT, uri, entity);
}
public static Response authorizedDelete(String uri) {
return handleAuthorized(Method.DELETE, uri, null);
}
}
/*
* Copyright 2005-2007 Noelios Consulting.
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License"). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the license at
* http://www.opensource.org/licenses/cddl1.txt See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at http://www.opensource.org/licenses/cddl1.txt If
* applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*/
package org.restlet.example.book.rest.ch3;
import java.util.ArrayList;
import java.util.List;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.DomRepresentation;
import org.w3c.dom.Node;
/**
* Amazon S3 bucket.
*
* @author Jerome Louvel (contact@noelios.com)
*/
public class S3Bucket extends S3Authorized {
private String name;
private boolean truncated;
public S3Bucket(String name) {
this.name = name;
}
/**
* Stores this bucket on S3. Analagous to ActiveRecord::Base#save, which
* stores an object in the database.
*/
public Status save() {
return authorizedPut(getUri(), null).getStatus();
}
/**
* Deletes this bucket.
*/
public Status delete() {
return authorizedDelete(getUri()).getStatus();
}
/**
* Get the objects in this bucket: all of them, or some subset.
*
* If S3 decides not to return the whole bucket/subset, the second return
* value will be set to true. To get the rest of the objects, you'll need to
* manipulate the subset options.
*
* Subset options are :Prefix, :Marker, :Delimiter, :MaxKeys. For details,
* see the S3 docs on "Listing Keys".
*
* @return The objects in this nucket.
*/
public List<S3Object> getObjects(String prefix, String marker,
String delimiter, Integer maxKeys) {
List<S3Object> result = new ArrayList<S3Object>();
// Construct the request URI by appending optional listing keys
StringBuilder uri = new StringBuilder().append(getUri());
String suffix = "?";
if (prefix != null) {
uri.append(suffix).append("prefix=").append(prefix);
suffix = "&";
}
if (marker != null) {
uri.append(suffix).append("marker=").append(marker);
suffix = "&";