Bookmark and Share

Google Samples

This sample contains the implementation of a two Google public Rest APIs: Search and Translate.

This example is more complex than the Twitter since Google wraps all API responses into a generic response format. To keep it simple we could have written the interface to return directly the google's response object with its nested payload, but we'll show here how to extract the payload and do some error checking before returning it.

NB: The following are partial mappings of the available services and their main purpose is to give a quick example of a real world use case scenario of CRest usage, thus the mappings may not reflect all the services offered by the API.

Search

This sample maps the legacy Google's Search REST API.

Below the mapped interface.

@EndPoint("http://ajax.googleapis.com")
@Path("ajax/services/search")
@QueryParam(value = "v", defaultValue = "1.0")
@ResponseHandler(GoogleResponseHandler.class)
public interface SearchService {

    @Path("web")
    SearchResult<Address> search(@QueryParam("q") String text);

}

And here's how to get an instance of the SearchService:

// Get a CRest instance. Should be done once.
CRest crest = CRest.getInstance();

// get a service instance
SearchService service = crest.build(SearchService.class);

// use it !
SearchResult<Address> results = service.search("codegist crest");

Translate

This sample maps the Google's Translate API v1, part of Google's Language REST API.

Below the mapped interface.

@EndPoint("http://ajax.googleapis.com")
@Path("ajax/services/language")
@QueryParam(value = "v", defaultValue = "1.0")
@ResponseHandler(GoogleResponseHandler.class)
public interface LanguageService {

    @Path("detect")
    LanguageGuess detectLanguage(@QueryParam("q") String text);

    @Path("translate")
    Translation translate(
            @QueryParam("q") String text,
            @QueryParam("langpair") @Serializer(LangPairSerializer.class) LangPair langPair);

}

And here's how to get an instance of the LanguageService:

// Get a CRest instance. Should be done once.
CRest crest = CRest.getInstance();

// get a service instance
SearchService service = crest.build(SearchService.class);

// use it !
LanguageGuess guess = service.detectLanguage("Guess it!");
Translation translation = service.translate("Translate me if you can!", new LangPair("en", "it"));

Response Handler

Here is the code for the custom response handling. As said, this class is not stricly necessary as we could have always returned the generic Response object with its nested payload for every method whatever happens, but this approach makes the interface looks better and less coupled to the google response format.

public class GoogleResponseHandler implements ResponseHandler {

    public final Object handle(org.codegist.crest.io.Response context) throws Exception {
        /* Marshall the response */
        Response res = context.to(Response.class, Types.newType(Response.class, context.getExpectedGenericType()));
        /* Check for google OK status */
        if (res.status == null || res.status == 200) {
            return res.data; /* Returns the nested payload */
        } else {
            throw new CRestException(res.details + " (status=" + res.status + ")"); /* Throw exception with google error details */
        }
    }

    /* ... Response inner-class declaration ... */
}

LangPair serializer

Here is the code needed to write a custom LangPair objects serializer

public class LangPairSerializer extends StringSerializer<LangPair> {

    private static final String FORMAT = "%s|%s";

    public String serialize(LangPair value, Charset charset) {
        return String.format(FORMAT, value.getFrom(), value.getTo());
    }

}

Model & Sources

The data model used by these samples hasn't been documented in this page as it only limits itself to plain java bean objects. The model have been deduced from the API response format and documentation and isn't guaranteed to reflect the full available model the API offers.

Do get a look at it, please refer to the sample source code HTML-based version.

This code is part of a project containing more sample, go to the project home page to get more information.