Lang package created for files to copy to generated folder

This commit is contained in:
Deepak Michael 2011-07-25 12:00:55 +05:30
parent 643971c011
commit ad1a670bef
12 changed files with 602 additions and 0 deletions

View File

@ -0,0 +1,19 @@
package com.wordnik.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation used to provide list of possible values
* @author ramesh
*
*/
@Target({ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AllowableValues {
String value() default "";
}

View File

@ -0,0 +1,13 @@
package com.wordnik.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodArgumentNames {
String value() default "";
}

View File

@ -0,0 +1,17 @@
package com.wordnik.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation used to indicate given property or field is required or not
* @author ramesh
*
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Required {
}

View File

@ -0,0 +1,11 @@
package com.wordnik.common;
/**
* Created by IntelliJ IDEA.
* User: ramesh
* Date: 7/5/11
* Time: 6:09 PM
* To change this template use File | Settings | File Templates.
*/
public class Size {
}

View File

@ -0,0 +1,22 @@
package com.wordnik.common;
/**
* Created by IntelliJ IDEA.
* User: ramesh
* Date: 4/12/11
* Time: 5:46 PM
* To change this template use File | Settings | File Templates.
*/
public class StringValue {
String word;
public String getWord() {
return word;
}
public void setWord(String value) {
this.word = value;
}
}

View File

@ -0,0 +1,15 @@
package com.wordnik.common;
/**
* This is a model class tht needs to be generated by the system.
* APIs use this class but REST documentation is not returning model object for this class, hence we created dummy version
* REMOVE this class after API documentation is fixed.
* @author ramesh
*
*/
public class WordListType {
public WordListType() {
}
}

View File

@ -0,0 +1,216 @@
package com.wordnik.common;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Logger;
import javax.ws.rs.core.MultivaluedMap;
import com.wordnik.exception.APIException;
import com.wordnik.exception.APIExceptionCodes;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.type.TypeReference;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.filter.LoggingFilter;
/**
* Provides way to initialize the communication with Wordnik API server.
* This is also a Base class for all API classes
* @author ramesh
*
*/
public class WordnikAPI {
private static String apiServer = "http://api.wordnik.com/v4";
private static String apiKey = "";
private static boolean loggingEnabled;
private static Logger logger = null;
protected static String POST = "POST";
protected static String GET = "GET";
protected static String PUT = "PUT";
protected static String DELETE = "DELETE";
protected static ObjectMapper mapper = new ObjectMapper();
static{
mapper.getDeserializationConfig().set(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.getSerializationConfig().set(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(SerializationConfig.Feature.WRITE_NULL_PROPERTIES, false);
mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
}
/**
* Initializes the API communication with required inputs.
* @param apiKey provide the key provided as part of registration
* @param apiServer Sets the URL for the API server. It is defaulted to the server
* used while building the driver. This value should be provided while testing the APIs against
* test servers or if there is any changes in production server URLs.
* @param enableLogging This will enable the logging using Jersey logging filter. Refer the following documentation
* for more details. {@link com.sun.jersey.api.client.filter.LoggingFilter}. Default output is sent to system.out.
* Create a logger ({@link java.util.logging.Logger} class and set using setLogger method.
*/
public static void initialize(String apiKey, String apiServer, boolean enableLogging) {
setApiKey(apiKey);
if(apiServer != null && apiServer.length() > 0) {
if(apiServer.substring(apiServer.length()-1).equals("/")){
apiServer = apiServer.substring(0, apiServer.length()-1);
}
setApiServer(apiServer);
}
loggingEnabled = enableLogging;
}
/**
* Set the logger instance used for Jersey logging.
* @param aLogger
*/
public static void setLogger(Logger aLogger) {
logger = aLogger;
}
/**
* Gets the API key used for server communication.
* This value is set using initialize method.
* @return
*/
public static String getApiKey() {
return apiKey;
}
private static void setApiKey(String apiKey) {
WordnikAPI.apiKey = apiKey;
}
/**
* Sets the URL for the API server. It is defaulted to the server used while building the driver.
* @return
*/
private static String getApiServer() {
return apiServer;
}
private static void setApiServer(String server) {
WordnikAPI.apiServer = server;
}
/**
* Invokes the API and returns the response as json string.
* This is an internal method called by individual APIs for communication. It sets the required HTTP headers
* based on API key and auth token.
* @param authToken - token that is received as part of authentication call. This is only needed for the calls that are secure.
* @param resourceURL - URL for the rest resource
* @param method - Method we should use for communicating to the back end.
* @param postObject - if the method is POST, provide the object that should be sent as part of post request.
* @return JSON response of the API call.
* @throws com.wordnik.exception.APIException if the call to API server fails.
*/
protected static String invokeAPI(String authToken, String resourceURL, String method, Map<String,
String> queryParams, Object postObject) throws APIException {
Client apiClient = Client.create();
//check for app key and server values
if(getApiKey() == null || getApiKey().length() == 0) {
String[] args = {getApiKey()};
throw new APIException(APIExceptionCodes.API_KEY_NOT_VALID, args);
}
if(getApiServer() == null || getApiServer().length() == 0) {
String[] args = {getApiServer()};
throw new APIException(APIExceptionCodes.API_SERVER_NOT_VALID, args);
}
//initialize the logger if needed
if(loggingEnabled) {
if(logger == null) {
apiClient.addFilter(new LoggingFilter());
}else{
apiClient.addFilter(new LoggingFilter(logger));
}
}
//make the communication
resourceURL = getApiServer() + resourceURL;
if(queryParams.keySet().size() > 0){
int i=0;
for(String paramName : queryParams.keySet()){
String symbol = "&";
if(i==0){
symbol = "?";
}
resourceURL = resourceURL + symbol + paramName + "=" + queryParams.get(paramName);
i++;
}
}
WebResource aResource = apiClient.resource(resourceURL);
// aResource.queryParams(queryParams);
//set the required HTTP headers
Builder builder = aResource.type("application/json");
builder.header("api_key", getApiKey());
if(authToken != null){
builder.header("auth_token", authToken);
}
ClientResponse clientResponse = null;
if(method.equals(GET)) {
clientResponse = builder.get(ClientResponse.class);
}else if (method.equals(POST)) {
clientResponse = builder.post(ClientResponse.class, serialize(postObject));
}else if (method.equals(PUT)) {
clientResponse = builder.put(ClientResponse.class, serialize(postObject));
}else if (method.equals(DELETE)) {
clientResponse = builder.delete(ClientResponse.class);
}
//process the response
if(clientResponse.getClientResponseStatus() == ClientResponse.Status.OK) {
String response = clientResponse.getEntity(String.class);
return response;
}else{
int responseCode = clientResponse.getClientResponseStatus().getStatusCode() ;
throw new APIException(responseCode, clientResponse.getEntity(String.class));
}
}
/**
* De-serialize the object from String to object of type input class name.
* @param response
* @param inputClassName
* @return
*/
public static Object deserialize(String response, Class inputClassName) throws APIException {
try {
System.out.println("Input :::::" + response);
Object responseObject = mapper.readValue(response, inputClassName);
return responseObject;
} catch (IOException ioe) {
String[] args = new String[]{response, inputClassName.toString()};
throw new APIException(APIExceptionCodes.ERROR_CONVERTING_JSON_TO_JAVA, args, "Error in coversting response json value to java object : " + ioe.getMessage(), ioe);
}
}
/**
* serialize the object from String to input object.
* @param input
* @return
*/
public static String serialize(Object input) throws APIException {
try {
if(input != null) {
return mapper.writeValueAsString(input);
}else{
return "";
}
} catch (IOException ioe) {
throw new APIException(APIExceptionCodes.ERROR_CONVERTING_JAVA_TO_JSON, "Error in coverting input java to json : " + ioe.getMessage(), ioe);
}
}
}

View File

@ -0,0 +1,11 @@
package com.wordnik.common;
/**
* This is super class of all the model classes.
* Any common attributes or methods across all model objects can be added here
* @author ramesh
*
*/
public class WordnikObject {
}

View File

@ -0,0 +1,131 @@
package com.wordnik.common.ext;
import com.wordnik.annotations.MethodArgumentNames;
import com.wordnik.common.WordnikAPI;
import com.wordnik.exception.APIException;
import com.wordnik.exception.APIExceptionCodes;
import com.wordnik.model.AudioFile;
import com.wordnik.model.FrequencySummary;
import org.codehaus.jackson.map.type.TypeFactory;
import org.codehaus.jackson.type.TypeReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class is written to provide implementations for some of the methods that are not possible from code generation.
* Example: For getting the word frequency we have the possiblity of to output bsed on the type of input, this will be
* difficult to model with code generation hence the overwriten calls is provided and the ode generation ignores
* these methods while generating the code.
* User: ramesh
* Date: 4/26/11
* Time: 7:51 AM
*/
public abstract class AbstractWordAPI extends WordnikAPI {
/**
* Fetches audio metadata for a word.
*
* The metadata includes a time-expiring fileUrl which allows reading the audio file directly from the API.
* Currently only audio pronunciations from the American Heritage Dictionary in mp3 format are supported.
*
* @param word Word to get audio for.
* @param useCanonical Use the canonical form of the word.
* @param limit Maximum number of results to return
*
* @return GetAudioOutput {@link com.wordnik.model.AudioFile}
* @throws com.wordnik.exception.APIException 400 - Invalid word supplied. 400 - Invalid word supplied.
*/
@MethodArgumentNames(value="word, useCanonical, limit")
public static List<AudioFile> getAudio(String word, String useCanonical, String limit) throws APIException {
//parse inputs
String resourcePath = "/word.{format}/{word}/audio";
resourcePath = resourcePath.replace("{format}","json");
String method = "GET";
Map<String, String> queryParams = new HashMap<String, String>();
if( useCanonical != null) {
queryParams.put("useCanonical", useCanonical);
}
if( limit != null) {
queryParams.put("limit", limit);
}
if( word != null) {
resourcePath = resourcePath.replace("{word}", word);
}
//make the API Call
String response = invokeAPI(null, resourcePath, method, queryParams, null);
//create output objects if the response has more than one object
if(response == null || response.length() == 0){
return null;
}
TypeReference ref = new TypeReference<List<AudioFile>>() { };
try {
List<AudioFile> responseObject = (List<AudioFile>)mapper.readValue(response, TypeFactory.type(ref));
return responseObject;
}catch(Exception e){
throw new APIException(APIExceptionCodes.ERROR_CONVERTING_JSON_TO_JAVA, e.getMessage());
}
}
/**
* Returns word usage over tim
*
* @param word Word to return
*
* @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns
* exactly what was requested.
*
* @param startYear Starting Year
*
* @param endYear Ending Year
*
* @return FrequencySummary {@link com.wordnik.model.FrequencySummary}
* @throws com.wordnik.exception.APIException 400 - Invalid word supplied. 404 - No results. 400 - Invalid word supplied. 404 - No results.
*/
@MethodArgumentNames(value="word, useCanonical, startYear, endYear")
public static FrequencySummary getWordFrequency(String word, String useCanonical, String startYear,
String endYear) throws APIException {
//parse inputs
String resourcePath = "/word.{format}/{word}/frequency";
resourcePath = resourcePath.replace("{format}","json");
String method = "GET";
Map<String, String> queryParams = new HashMap<String, String>();
if( useCanonical != null) {
queryParams.put("useCanonical", useCanonical);
}
if( startYear != null) {
queryParams.put("startYear", startYear);
}
if( endYear != null) {
queryParams.put("endYear", endYear);
}
if( word != null) {
resourcePath = resourcePath.replace("{word}", word);
}
//make the API Call
String response = invokeAPI(null, resourcePath, method, queryParams, null);
//create output objects if the response has more than one object
if(response == null || response.length() == 0){
return null;
}
FrequencySummary responseObject = (FrequencySummary)deserialize(response, FrequencySummary.class);
return responseObject;
}
}

View File

@ -0,0 +1,84 @@
package com.wordnik.exception;
import com.sun.jersey.api.client.ClientResponse;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.annotate.JsonProperty;
/**
* Exception that is thrown if there are any issues in invoking Wordnik API.
*
* Each exception carries a code and message. Code can be either HTTP error response code {@link com.sun.jersey.api.client.ClientResponse.Status}
* or The list of possible Wordnik exception code that are listed in the interface {@link APIExceptionCodes}.
* User: ramesh
* Date: 3/31/11
* Time: 9:27 AM
*/
public class APIException extends Exception {
private String message;
private int code;
private String[] args;
@JsonCreator
public APIException() {
}
public APIException(String message) {
super(message);
}
public APIException(int code) {
this.code = code;
}
public APIException(int code, String message, Throwable t) {
super(message, t);
this.message = message;
this.code = code;
}
public APIException(int code, String[] args, String message, Throwable t) {
super(message, t);
this.message = message;
this.code = code;
this.args = args;
}
public APIException(int code, String message) {
super(message);
this.message = message;
this.code = code;
}
public APIException(int code, String[] args, String message) {
super(message);
this.message = message;
this.code = code;
this.args = args;
}
public APIException(int code, String[] args) {
this.code = code;
this.args = args;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}

View File

@ -0,0 +1,38 @@
package com.wordnik.exception;
/**
* Lists all the possible exception codes
* @author ramesh
*
*/
public interface APIExceptionCodes {
/**
* System exception.
*/
public static final int SYSTEM_EXCEPTION = 0;
/**
* With Arguments as current key.
*/
public static final int API_KEY_NOT_VALID = 1000;
/**
* With arguments as current token value
*/
public static final int AUTH_TOKEN_NOT_VALID = 1001;
/**
* With arguments as input JSON and output class anme
*/
public static final int ERROR_CONVERTING_JSON_TO_JAVA = 1002;
/**
* With arguments as JAVA class name
*/
public static final int ERROR_CONVERTING_JAVA_TO_JSON = 1003;
public static final int ERROR_FROM_WEBSERVICE_CALL = 1004;
/**
* With arguments as current API server name
*/
public static final int API_SERVER_NOT_VALID = 1005;
}

View File

@ -0,0 +1,25 @@
package com.wordnik.exception;
/**
* Exception raised while generating code for java driver.
* User: ramesh
* Date: 3/31/11
* Time: 9:29 AM
*/
public class CodeGenerationException extends RuntimeException {
private String message;
public CodeGenerationException(String message){
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}