us.monoid.web
Class Resty

java.lang.Object
  extended by us.monoid.web.Resty
Direct Known Subclasses:
AbstractResource

public class Resty
extends Object

Main class. Use me! Use me! Resty is a small, convenient interface to talk to RESTful services. Basic usage is very simple: Create a Resty instance, use authenticate methode to add credentials (optional), then call one of the content type specific methods, like json(...), xml(...), text(...) or bytes(...). The idea is that the method name will convey the expected content type you can then operate on. Most static methods help you build content objects or queries with a compact syntax. Static methods like put(...) and delete() are used to implement the respective HTTP methods. A neat trick to save you typing is to use

import static us.monoid.web.Resty.*;

GETting an URL (as JSON):

new Resty().json(url);
POSTing to an URL (using multipart/form-data) and expecting JSON back:
new Resty().json(url, form(data("name", "Don Draper"), data("occupation", "Ad Man")));
PUTting content and expecting JSON back:

 new Resty().json(url, put(content(someJSON)));
 
DELETE a resource via URL expecting JSON back:
new Resty().json(url, delete());
Here is an example on how to use the geonames web service. It retrieves the json object (see json.org for details) and gets the name of a place from the zip code:
 
        Resty r = new Resty();
        Object name = r.json("http://ws.geonames.org/postalCodeLookupJSON?postalcode=66780&country=DE").get("postalcodes[0].placeName");
        assertEquals(name, "Rehlingen-Siersburg");
 
 
The return value is a resource with the data you requested AND a new Resty instance with the same set of options you initialized Resty with. Resty supports complex path queries to navigate into a json object. This is mainly used for extracting URIs to surf along a series of REST resources for web services following the HATEOS paradigm. Resty objects are not re-entrant. You can also specify options when creating a Resty instance. Well, currently there is one option to set the timeout for connections. But you can also create your own options! See Resty.Option for more info.

Author:
beders

Nested Class Summary
static class Resty.Option
          Base class for Resty options.
static class Resty.Proxy
          Option to set the proxy for a Resty instance.
static class Resty.Timeout
          Option to set a timeout.
 
Constructor Summary
Resty(Resty.Option... someOptions)
          Create an instance of Resty with the following list of options.
 
Method Summary
 void alwaysSend(String aHeader, String aValue)
          Deprecated.  
 void authenticate(String string, String aLogin, char[] charArray)
           
 void authenticate(URI aSite, String aLogin, char[] aPwd)
          Register this root URI for authentication.
 void authenticateForRealm(String realm, String aLogin, char[] charArray)
          Register a login password for the realm returned by the authorization challenge.
 BinaryResource bytes(String anUri)
          Get the resource specified by the uri and return a binary resource for it.
 BinaryResource bytes(String anUri, AbstractContent someContent)
          POST to the URI and get the resource as binary resource.
 BinaryResource bytes(URI anUri)
          Get the resource specified by the uri and return a binary resource for it.
 BinaryResource bytes(URI anUri, AbstractContent someContent)
          POST to the URI and get the resource as binary resource.
static Content content(byte[] bytes)
          Create a content object from a byte array.
static Content content(JSONObject someJson)
          Create a content object from JSON.
static Content content(String somePlainText)
          Create a content object from plain text.
static FormData data(String name, AbstractContent content)
          Create a form data entry for a multipart form with any kind of content type.
static FormData data(String name, String plainTextValue)
          Create a plain/text form data entry for a multipart form.
static AbstractContent delete()
          Tell Resty to delete the URL content on the server, resulting in a DELETE.
 void dontSend(String aHeader)
          Don't send a header that was formely added in the alwaysSend method.
static String enc(String unencodedString)
          Shortcut to URLEncoder.encode with UTF-8.
static us.monoid.web.mime.MultipartContent form(FormData... formData)
          Create form content to be sent as multipart/form-data.
static FormContent form(String query)
          Create form content as application/x-www-form-urlencoded (i.e.
 Resty identifyAsMozilla()
          Sets the User-Agent to identify as Mozilla/Firefox.
 Resty identifyAsResty()
          Sets the User-Agent to Resty.
static void ignoreAllCerts()
          Install a SSL socket factory which will trust all certificates.
 JSONResource json(String string)
          GET a URI given by string and parse the result as JSON.
 JSONResource json(String anUri, AbstractContent content)
           
 JSONResource json(URI anUri)
          GET a URI and parse the result as JSON.
 JSONResource json(URI anUri, AbstractContent requestContent)
          POST to a URI and parse the result as JSON
static JSONPathQuery path(String string)
          Create a JSONPathQuery to extract data from a JSON object.
static AbstractContent put(Content someContent)
          Tell Resty to replace the specified content on the server, resulting in a PUT operation instead of a POST operation.
 Resty setOptions(Resty.Option... someOptions)
          Set options if you missed your opportunity in the c'tor or if you want to change the options.
 void setProxy(String proxyhost, int proxyport)
          Set the proxy for this instance of Resty.
 TextResource text(String anUri)
          Get a plain text resource for the specified URI.
 TextResource text(String anUri, AbstractContent content)
          Get a plain text resource for the specified URI by POSTing to it.
 TextResource text(URI anUri)
          Get a plain text resource for the specified URI.
 TextResource text(URI anUri, AbstractContent content)
          Get a plain text resource for the specified URI by POSTing to it.
 void withHeader(String aHeader, String aValue)
          Tell Resty to send the specified header with each request done on this instance.
 XMLResource xml(String string)
          GET a URI given by string and parse the result as XML.
 XMLResource xml(String anUri, AbstractContent content)
           
 XMLResource xml(URI anUri)
          GET a URI and parse the result as XML.
 XMLResource xml(URI anUri, AbstractContent requestContent)
          POST to a URI and parse the result as XML
static XPathQuery xpath(String anXPathExpression)
          Create an XPathQuery to extract data from an XML document.
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Resty

public Resty(Resty.Option... someOptions)
Create an instance of Resty with the following list of options. Also, options are carried over to resources created by calls to json/text/binary etc. Use setOptions(Option...) to change options afterwards.

Method Detail

setOptions

public Resty setOptions(Resty.Option... someOptions)
Set options if you missed your opportunity in the c'tor or if you want to change the options.

Parameters:
someOptions - new set of options
Returns:

authenticate

public void authenticate(URI aSite,
                         String aLogin,
                         char[] aPwd)
Register this root URI for authentication. Whenever a URL is requested that starts with this root, the credentials given are used for HTTP AUTH. Note that currently authentication information is shared across all Resty instances. This is due to the shortcomings of the java.net authentication mechanism. This might change should Resty adopt HttpClient and is the reason why this method is not a static one.

Parameters:
aSite - the root URI of the site
aLogin - the login name
aPwd - the password. The array will not be internally copied. Whenever you null it, the password is gone within Resty

authenticate

public void authenticate(String string,
                         String aLogin,
                         char[] charArray)
Parameters:
string -
aLogin -
charArray -
See Also:
authenticate(URI, String, char[])

authenticateForRealm

public void authenticateForRealm(String realm,
                                 String aLogin,
                                 char[] charArray)
Register a login password for the realm returned by the authorization challenge. Use this method instead of authenticate in case the URL is not made available to the java.net.Authenticator class

Parameters:
realm - the realm (see rfc2617, section 1.2)
aLogin -
charArray -

identifyAsMozilla

public Resty identifyAsMozilla()
Sets the User-Agent to identify as Mozilla/Firefox. Otherwise a Resty specific User-Agent is used


identifyAsResty

public Resty identifyAsResty()
Sets the User-Agent to Resty. WHICH IS THE DEFAULT. Sorry for yelling.


json

public JSONResource json(String string)
                  throws IOException
GET a URI given by string and parse the result as JSON.

Parameters:
string - - the string to use as URI
Throws:
IOException
See Also:
for more docs

json

public JSONResource json(URI anUri)
                  throws IOException
GET a URI and parse the result as JSON.

Parameters:
anUri - the URI to request
Returns:
the JSONObject, wrapped in a neat JSONResource
Throws:
IOException

json

public JSONResource json(URI anUri,
                         AbstractContent requestContent)
                  throws IOException
POST to a URI and parse the result as JSON

Parameters:
anUri - the URI to visit
requestContent - the content to POST to the URI
Returns:
Throws:
IOException - if uri is wrong or no connection could be made or for 10 zillion other reasons

json

public JSONResource json(String anUri,
                         AbstractContent content)
                  throws IOException
Throws:
IOException
See Also:
Resty#json(URI, Content)

text

public TextResource text(URI anUri)
                  throws IOException
Get a plain text resource for the specified URI.

Parameters:
anUri - the URI to follow
Returns:
a plain text resource, if available
Throws:
IOException - if content type sent is not a plain text, if the connection could not be made and gazillion other reasons

text

public TextResource text(URI anUri,
                         AbstractContent content)
                  throws IOException
Get a plain text resource for the specified URI by POSTing to it.

Parameters:
anUri - the URI to follow
Returns:
a plain text resource, if available
Throws:
IOException - if content type sent is not a plain text, if the connection could not be made and gazillion other reasons

text

public TextResource text(String anUri)
                  throws IOException
Get a plain text resource for the specified URI.

Parameters:
anUri - the URI to follow
Returns:
a plain text resource, if available
Throws:
IOException - if content type sent is not a plain text, if the connection could not be made and gazillion other reasons

text

public TextResource text(String anUri,
                         AbstractContent content)
                  throws IOException
Get a plain text resource for the specified URI by POSTing to it.

Parameters:
anUri - the URI to follow
Returns:
a plain text resource, if available
Throws:
IOException - if content type sent is not a plain text, if the connection could not be made and gazillion other reasons

xml

public XMLResource xml(String string)
                throws IOException
GET a URI given by string and parse the result as XML.

Parameters:
string - - the string to use as URI
Throws:
IOException
See Also:
for more docs

xml

public XMLResource xml(URI anUri)
                throws IOException
GET a URI and parse the result as XML.

Parameters:
anUri - the URI to request
Returns:
the XML, wrapped in a neat XMLResource
Throws:
IOException

xml

public XMLResource xml(URI anUri,
                       AbstractContent requestContent)
                throws IOException
POST to a URI and parse the result as XML

Parameters:
anUri - the URI to visit
requestContent - the content to POST to the URI
Returns:
Throws:
IOException - if uri is wrong or no connection could be made or for 10 zillion other reasons

xml

public XMLResource xml(String anUri,
                       AbstractContent content)
                throws IOException
Throws:
IOException
See Also:
Resty#xml(URI, Content)

bytes

public BinaryResource bytes(String anUri)
                     throws IOException
Get the resource specified by the uri and return a binary resource for it.

Parameters:
anUri - the uri to follow
Returns:
Throws:
IOException

bytes

public BinaryResource bytes(URI anUri)
                     throws IOException
Get the resource specified by the uri and return a binary resource for it.

Parameters:
uri - the uri to follow
Returns:
Throws:
IOException

bytes

public BinaryResource bytes(String anUri,
                            AbstractContent someContent)
                     throws IOException
POST to the URI and get the resource as binary resource.

Parameters:
anUri - the uri to follow
Returns:
Throws:
IOException

bytes

public BinaryResource bytes(URI anUri,
                            AbstractContent someContent)
                     throws IOException
POST to the URI and get the resource as binary resource.

Parameters:
uri - the uri to follow
Returns:
Throws:
IOException

path

public static JSONPathQuery path(String string)
Create a JSONPathQuery to extract data from a JSON object. This is usually used to extract a URI and use it in json|text|xml(JSONPathQuery...) methods of JSONResource. Resty r = new Resty(); r.json(someUrl).json(path("path.to.url.in.json"));

Parameters:
string -
Returns:

xpath

public static XPathQuery xpath(String anXPathExpression)
                        throws XPathException
Create an XPathQuery to extract data from an XML document. This is usually used to extract a URI and use it in json|text|xml(XPathQuery...) methods. In this case, your XPath must result in a String value, i.e. it can't just extract an Element.

Parameters:
anXPathExpression - an XPath expression with result type String
Returns:
the query
Throws:
XPathException

content

public static Content content(JSONObject someJson)
Create a content object from JSON. Use this to POST the content to a URL.

Parameters:
someJson - the JSON to use
Returns:
the content to send

content

public static Content content(String somePlainText)
Create a content object from plain text. Use this to POST the content to a URL.

Parameters:
somePlainText - the plain text to send
Returns:
the content to send

content

public static Content content(byte[] bytes)
Create a content object from a byte array. Use this to POST the content to a URL with mime type application/octet-stream.

Parameters:
bytes - the bytes to send
Returns:
the content to send

form

public static FormContent form(String query)
Create form content as application/x-www-form-urlencoded (i.e. a=b&c=d&...)

Parameters:
query - the preformatted, properly encoded form data
Returns:
a content object to be useable for upload

form

public static us.monoid.web.mime.MultipartContent form(FormData... formData)
Create form content to be sent as multipart/form-data. Useful if you want to upload files or have tons of form data that looks really ugly in a URL.


data

public static FormData data(String name,
                            String plainTextValue)
Create a plain/text form data entry for a multipart form.

Parameters:
name - the name of the control of the form
plainTextValue - the plain text value
Returns:
the FormData part used in a multipart/form-data upload

data

public static FormData data(String name,
                            AbstractContent content)
Create a form data entry for a multipart form with any kind of content type.

Parameters:
name - the name of the control or variable in a form
content - the content to send
Returns:

enc

public static String enc(String unencodedString)
Shortcut to URLEncoder.encode with UTF-8.

Parameters:
unencodedString - the string to encode
Returns:
the URL encoded string, safe to be used in URLs

put

public static AbstractContent put(Content someContent)
Tell Resty to replace the specified content on the server, resulting in a PUT operation instead of a POST operation. Example use: r.json(uri, put(content("bubu")));


delete

public static AbstractContent delete()
Tell Resty to delete the URL content on the server, resulting in a DELETE. Example use: r.json(uri,delete());


alwaysSend

public void alwaysSend(String aHeader,
                       String aValue)
Deprecated. 

Tell Resty to send the specified header with each request done on this instance. These headers will also be sent from any resource object returned by this instance. I.e. chained calls will carry over the headers r.json(url).json(get("some.path.to.a.url")); Multiple headers of the same type are not supported (yet).

Parameters:
aHeader - the header to send
aValue - the value

withHeader

public void withHeader(String aHeader,
                       String aValue)
Tell Resty to send the specified header with each request done on this instance. These headers will also be sent from any resource object returned by this instance. I.e. chained calls will carry over the headers r.json(url).json(get("some.path.to.a.url")); Multiple headers of the same type are not supported (yet).

Parameters:
aHeader - the header to send
aValue - the value

dontSend

public void dontSend(String aHeader)
Don't send a header that was formely added in the alwaysSend method.

Parameters:
aHeader - the header to remove

ignoreAllCerts

public static void ignoreAllCerts()
Install a SSL socket factory which will trust all certificates. This is generally considered dangerous as you won't know if you are really talking to the server you think you are talking to. This is like your best friend using his Facebook account in an Apple store and forgetting to log out. This method should be called once and replaces the SSL factory for ALL HttpsURLConnections.


setProxy

public void setProxy(String proxyhost,
                     int proxyport)
Set the proxy for this instance of Resty. Note, that the proxy settings will be carried over to Resty instances created by this instance only if you used new Resty(Option.proxy(...))!

Parameters:
proxyhost - name of the host
proxyport - port to be used


Copyright © 2013. All Rights Reserved.