Permalink
Browse files

added scala support

  • Loading branch information...
fehguy committed Sep 5, 2011
1 parent 7f3af74 commit 20e94c5f1758d05ac9f21a5af2e1c59d62d32549
Showing with 1,271 additions and 12 deletions.
  1. +23 −0 bin/generate-scala-lib.sh
  2. +35 −0 conf/scala/structure/src/main/java/com/wordnik/swagger/annotations/AllowableValues.java
  3. +29 −0 conf/scala/structure/src/main/java/com/wordnik/swagger/annotations/MethodArgumentNames.java
  4. +33 −0 conf/scala/structure/src/main/java/com/wordnik/swagger/annotations/Required.java
  5. +268 −0 conf/scala/structure/src/main/java/com/wordnik/swagger/common/APIInvoker.java
  6. +47 −0 conf/scala/structure/src/main/java/com/wordnik/swagger/common/SecurityHandler.java
  7. +38 −0 conf/scala/structure/src/main/java/com/wordnik/swagger/common/StringValue.java
  8. +100 −0 conf/scala/structure/src/main/java/com/wordnik/swagger/exception/APIException.java
  9. +54 −0 conf/scala/structure/src/main/java/com/wordnik/swagger/exception/APIExceptionCodes.java
  10. +31 −0 conf/scala/templates/EnumObject.st
  11. +63 −0 conf/scala/templates/ModelObject.st
  12. +136 −0 conf/scala/templates/ResourceObject.st
  13. +33 −0 conf/scala/templates/VersionChecker.st
  14. +36 −0 src/main/java/com/wordnik/swagger/codegen/FieldDefinition.java
  15. +13 −11 src/main/java/com/wordnik/swagger/codegen/LibraryCodeGenerator.java
  16. +10 −0 src/main/java/com/wordnik/swagger/codegen/ResourceMethod.java
  17. +11 −0 src/main/java/com/wordnik/swagger/codegen/config/DataTypeMappingProvider.java
  18. +5 −0 src/main/java/com/wordnik/swagger/codegen/config/as3/As3DataTypeMappingProvider.java
  19. +5 −0 src/main/java/com/wordnik/swagger/codegen/config/java/JavaDataTypeMappingProvider.java
  20. +200 −0 src/main/java/com/wordnik/swagger/codegen/config/scala/ScalaDataTypeMappingProvider.scala
  21. +93 −0 src/main/java/com/wordnik/swagger/codegen/config/scala/ScalaLibCodeGen.scala
  22. +7 −0 src/main/java/com/wordnik/swagger/codegen/resource/EndpointOperation.java
  23. +1 −1 src/main/java/com/wordnik/swagger/codegen/resource/ModelField.java
View
@@ -0,0 +1,23 @@
+#!/bin/bash
+if [ $# -ne 4 ]
+then
+ echo "Error in $0 - Invalid Argument Count"
+ echo "Syntax: $0 location_of_service api_key package_name library_root"
+ exit
+fi
+
+echo "" > classpath.txt
+for file in `ls lib`;
+ do echo -n 'lib/' >> classpath.txt;
+ echo -n $file >> classpath.txt;
+ echo -n ':' >> classpath.txt;
+done
+for file in `ls build`;
+ do echo -n 'build/' >> classpath.txt;
+ echo -n $file >> classpath.txt;
+ echo -n ':' >> classpath.txt;
+done
+
+export CLASSPATH=$(cat classpath.txt):conf/scala/templates
+export JAVA_OPTS="${JAVA_OPTS} -Dproperty=Xmx2g"
+scala $WORDNIK_OPTS $JAVA_CONFIG_OPTIONS $JAVA_OPTS -cp $CLASSPATH com.wordnik.swagger.codegen.config.scala.ScalaLibCodeGen "$@"
@@ -0,0 +1,35 @@
+/**
+ * Copyright 2011 Wordnik, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.wordnik.swagger.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 "";
+}
@@ -0,0 +1,29 @@
+/**
+ * Copyright 2011 Wordnik, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.wordnik.swagger.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 "";
+}
@@ -0,0 +1,33 @@
+/**
+ * Copyright 2011 Wordnik, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.wordnik.swagger.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 {
+
+}
@@ -0,0 +1,268 @@
+/**
+ * Copyright 2011 Wordnik, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.wordnik.swagger.common;
+
+import java.io.IOException;
+import java.lang.String;
+import java.util.Map;
+import java.util.List;
+import java.util.HashMap;
+import java.util.logging.Logger;
+
+import javax.ws.rs.core.MultivaluedMap;
+
+import com.wordnik.swagger.exception.APIException;
+import com.wordnik.swagger.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 method to initialize the api server settings and also handles the logic related to invoking the API server
+ * along with serealizing and deserializing input and output responses.
+ *
+ * This is also a Base class for all API classes
+ *
+ * @author ramesh
+ *
+ */
+public class APIInvoker {
+
+ private static String apiServer = "http://api.wordnik.com/v4";
+ private static SecurityHandler securityHandler = null;
+ 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";
+ public 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 securityHandler security handler responsible for populating necessary security invocation while making API server calls
+ * @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(SecurityHandler securityHandler, String apiServer, boolean enableLogging) {
+ setSecurityHandler(securityHandler);
+ 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 SecurityHandler setSecurityHandler() {
+ return securityHandler;
+ }
+
+ private static void setSecurityHandler(SecurityHandler aSecurityHandler) {
+ securityHandler = aSecurityHandler;
+ }
+
+ /**
+ * 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;
+ }
+
+ public static void setApiServer(String server) {
+ 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 security information
+ * based ons ecuroty handler
+ *
+ * @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.swagger.exception.APIException if the call to API server fails.
+ */
+ public static String invokeAPI(String resourceURL, String method, Map<String,
+ String> queryParams, Object postData) throws APIException {
+
+
+ Client apiClient = Client.create();
+
+ //check for app server values
+ 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++;
+ }
+ }
+ Map<String, String> headerMap = new HashMap<String, String>();
+ if(securityHandler != null){
+ securityHandler.populateSecurityInfo(resourceURL, headerMap);
+ }
+ WebResource aResource = apiClient.resource(resourceURL);
+
+
+ //set the required HTTP headers
+ Builder builder = aResource.type("application/json");
+ for(String key : headerMap.keySet()){
+ builder.header(key, headerMap.get(key));
+ }
+
+ ClientResponse clientResponse = null;
+ if(method.equals(GET)) {
+ clientResponse = builder.get(ClientResponse.class);
+ }else if (method.equals(POST)) {
+ clientResponse = builder.post(ClientResponse.class, serialize(postData));
+ }else if (method.equals(PUT)) {
+ clientResponse = builder.put(ClientResponse.class, serialize(postData));
+ }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 {
+ 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);
+ }
+ }
+
+
+ /**
+ * Overloaded method for returning the path value
+ * For a string value an empty value is returned if the value is null
+ * @param value
+ * @return
+ */
+ public static String toPathValue(String value) {
+ return value == null ? "" : value;
+ }
+
+ /**
+ * Overloaded method for returning a path value
+ * For a list of objects a comma separated string is returned
+ * @param objects
+ * @return
+ */
+ public static String toPathValue(List objects) {
+ StringBuilder out = new StringBuilder();
+ for(Object o: objects){
+ out.append(o.toString());
+ out.append(",");
+ }
+ if(out.indexOf(",") != -1) {
+ return out.substring(0, out.lastIndexOf(",") );
+ }
+ return out.toString();
+ }
+}
Oops, something went wrong.

0 comments on commit 20e94c5

Please sign in to comment.