updated to 2.0

This commit is contained in:
Tony Tam 2012-08-24 15:27:08 -07:00
parent a33df3ac33
commit aa162b9393
70 changed files with 0 additions and 9717 deletions

View File

@ -1,151 +0,0 @@
/**
* 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.codegen;
import java.util.ArrayList;
import java.util.List;
public class FieldDefinition {
private String returnType;
private String name;
private String originalName;
private String initialization;
private List<String> importDefinitions = new ArrayList<String>();
private String collectionItemType;
private String collectionItemName;
private boolean hasListResponse;
private boolean hasMapResponse;
private boolean hasSetResponse;
private boolean hasDateResponse;
private boolean hasArrayResponse;
private boolean hasPrimitiveType;
public boolean isHasListResponse() {
return hasListResponse;
}
public void setHasListResponse(boolean hasListResponse) {
this.hasListResponse = hasListResponse;
}
public boolean isHasMapResponse() {
return hasMapResponse;
}
public void setHasMapResponse(boolean hasMapResponse) {
this.hasMapResponse = hasMapResponse;
}
public boolean isHasSetResponse() {
return hasSetResponse;
}
public void setHasSetResponse(boolean hasSetResponse) {
this.hasSetResponse = hasSetResponse;
}
public boolean isHasArrayResponse() {
return hasArrayResponse;
}
public void setHasArrayResponse(boolean hasArrayResponse) {
this.hasArrayResponse = hasArrayResponse;
}
public boolean isHasPrimitiveType() {
return hasPrimitiveType;
}
public void setHasPrimitiveType(boolean hasPrimitiveType) {
this.hasPrimitiveType = hasPrimitiveType;
}
public String getReturnType() {
return returnType;
}
public void setReturnType(String returnType) {
if(returnType.startsWith("List")){
hasListResponse = true;
}else if(returnType.startsWith("Set")){
hasSetResponse = true;
}else if(returnType.startsWith("Map")){
hasMapResponse = true;
}else if(returnType.startsWith("Array")){
hasArrayResponse = true;
}
this.returnType = returnType;
}
public String getOriginalName() {
return originalName;
}
public void setOriginalName(String originalName) {
this.originalName = originalName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInitialization() {
return initialization;
}
public void setInitialization(String initialization) {
this.initialization = initialization;
}
public List<String> getImportDefinitions() {
return importDefinitions;
}
public String getNameForMethod() {
return originalName.substring(0,1).toUpperCase() + originalName.substring(1);
}
public void setCollectionItemType(String collectionItemType) {
this.collectionItemType = collectionItemType;
}
public String getCollectionItemType() {
return collectionItemType;
}
public String getCollectionItemName() {
return collectionItemName;
}
public void setCollectionItemName(String collectionItemName) {
this.collectionItemName = collectionItemName;
}
public boolean isHasDateResponse() {
return hasDateResponse;
}
public void setHasDateResponse(boolean hasDateResponse) {
this.hasDateResponse = hasDateResponse;
}
}

View File

@ -1,577 +0,0 @@
/**
* 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.codegen;
import com.wordnik.swagger.codegen.api.SwaggerResourceDocReader;
import com.wordnik.swagger.codegen.config.*;
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider;
import com.wordnik.swagger.codegen.exception.CodeGenerationException;
import com.wordnik.swagger.codegen.resource.*;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* User: ramesh
* Date: 3/30/11
* Time: 6:59 PM
*/
public class LibraryCodeGenerator {
private static String VERSION_OBJECT_TEMPLATE = "VersionChecker";
private static String MODEL_OBJECT_TEMPLATE = "ModelObject";
private static String API_OBJECT_TEMPLATE = "ResourceObject";
private static final String ENUM_OBJECT_TEMPLATE = "EnumObject";
private static final String WRAPPER_OBJECT_TEMPLATE = "WrapperObject";
protected static final String PACKAGE_NAME = "packageName";
protected ApiConfiguration config = null;
protected LanguageConfiguration languageConfig = null;
protected ReservedWordMapper reservedWordMapper = new DefaultReservedWordMapper();
private SwaggerResourceDocReader apiMarshaller;
protected DataTypeMappingProvider dataTypeMappingProvider;
protected RulesProvider codeGenRulesProvider;
protected NamingPolicyProvider nameGenerator;
Logger logger = LoggerFactory.getLogger(LibraryCodeGenerator.class);
public LibraryCodeGenerator(){}
public LibraryCodeGenerator(String configPath){
initializeWithConfigPath(configPath);
}
protected void initializeWithConfigPath(String configPath){
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
final File configFile = new File(configPath);
this.setApiConfig(readApiConfiguration(configPath, mapper, configFile));
this.setCodeGenRulesProvider(readRulesProviderConfig(configPath, mapper, configFile));
this.setLanguageConfig( initializeLangConfig(readLanguageConfiguration(configPath, mapper, configFile)) );
}
public LibraryCodeGenerator(String apiServerURL, String apiKey, String modelPackageName, String apiPackageName,
String classOutputDir, String modelDirectory, String resourceDirectory, String libraryHome){
initialize(apiServerURL, apiKey, modelPackageName, apiPackageName, classOutputDir, modelDirectory, resourceDirectory, libraryHome);
}
public LibraryCodeGenerator(String apiServerURL, String apiKey, String modelPackageName, String apiPackageName,
String classOutputDir, String libraryHome){
this(apiServerURL, apiKey, modelPackageName, apiPackageName, classOutputDir, "model", "api", libraryHome);
}
protected void initialize(String apiServerURL, String apiKey, String modelPackageName, String apiPackageName,
String classOutputDir, String modelDirectory, String resourceDirectory, String libraryHome){
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ApiConfiguration aApiConfiguration = new ApiConfiguration();
aApiConfiguration.setApiKey(apiKey);
aApiConfiguration.setApiPackageName(apiPackageName);
aApiConfiguration.setModelPackageName(modelPackageName);
aApiConfiguration.setApiUrl(apiServerURL);
this.setApiConfig(aApiConfiguration);
CodeGenRulesProvider codeGenRules = new CodeGenRulesProvider();
this.setCodeGenRulesProvider(codeGenRules);
LanguageConfiguration aLanguageConfiguration = new LanguageConfiguration();
aLanguageConfiguration.setOutputDirectory(classOutputDir, modelDirectory, resourceDirectory);
aLanguageConfiguration.setLibraryHome(libraryHome);
initializeLangConfig(aLanguageConfiguration);
this.setLanguageConfig(aLanguageConfiguration);
}
protected void initialize(String apiServerURL, String apiKey, String modelPackageName, String apiPackageName,
String classOutputDir, String libraryHome){
initialize(apiServerURL, apiKey, modelPackageName, apiPackageName, classOutputDir, "model", "api", libraryHome);
}
/**
* Generate classes needed for the model and API invocation
*/
public void generateCode() {
apiMarshaller = new SwaggerResourceDocReader(this.config, this.getDataTypeMappingProvider(), this.getNameGenerator());
//read resources and get their documentation
List<Resource> resources = apiMarshaller.readResourceDocumentation();
preprocess(resources);
StringTemplateGroup aTemplateGroup = new StringTemplateGroup(languageConfig.getTemplateLocation());
aTemplateGroup.registerRenderer(String.class, new StringRenderer());
if(resources.size() > 0) {
generateVersionHelper(resources.get(0).getApiVersion(), aTemplateGroup);
}
generateModelClasses(resources, aTemplateGroup);
generateModelClassesForInput(resources, aTemplateGroup);
if(languageConfig.isModelEnumRequired()){
generateEnumForAllowedValues(resources, aTemplateGroup);
}
if(languageConfig.isOutputWrapperRequired()) {
generateOutputWrappers(resources, aTemplateGroup);
}
generateAPIClasses(resources, aTemplateGroup);
generateMiscClasses(resources, aTemplateGroup);
}
/**
* prepares the model for template generation
* @param resources
*/
protected void preprocess(List<Resource> resources) {
for(Resource resource: resources) {
for(Model model : resource.getModels()){
// apply keyword mapping
for(ModelField modelField : model.getFields()){
modelField.setName(reservedWordMapper.translate(modelField.getName()));
}
}
}
}
/**
* Generates version file based on the version number received from the doc calls. This version file is used
* while making the API calls to make sure Client and back end are compatible.
* @param version
*/
private void generateVersionHelper(String version, StringTemplateGroup templateGroup) {
StringTemplate template = templateGroup.getInstanceOf(languageConfig.getTemplateLocation()+"/"+VERSION_OBJECT_TEMPLATE);
template.setAttribute("apiVersion", version);
template.setAttribute(PACKAGE_NAME, config.getApiPackageName());
File aFile = new File(languageConfig.getResourceClassLocation() + this.getNameGenerator().getVersionCheckerClassName()
+ languageConfig.getClassFileExtension());
writeFile(aFile, template.toString(), "Version checker class");
}
/**
* Generates model classes. If the class is already generated then ignores the same.
*/
private void generateModelClasses(List<Resource> resources, StringTemplateGroup templateGroup) {
List<String> generatedClassNames = new ArrayList();
for(Resource resource: resources) {
for(Model model : resource.getModels()){
if(!generatedClassNames.contains(model.getName()) && !this.getCodeGenRulesProvider().isModelIgnored(model.getName())){
List<String> imports = new ArrayList<String>();
imports.addAll(this.config.getDefaultModelImports());
if(null == model.getFields() || model.getFields().size() == 0){
logger.warn("Model " + model.getName() + " doesn't have any properties");
} else {
for(ModelField param : model.getFields()){
param.setName(reservedWordMapper.translate(param.getName()));
for(String importDef : param.getFieldDefinition(this.getDataTypeMappingProvider(), config, nameGenerator, reservedWordMapper).getImportDefinitions()){
if(!imports.contains(importDef)){
imports.add(importDef);
}
}
}
StringTemplate template = templateGroup.getInstanceOf(languageConfig.getTemplateLocation()+"/"+MODEL_OBJECT_TEMPLATE);
template.setAttribute("model", model);
template.setAttribute("fields", model.getFields());
template.setAttribute("imports", imports);
template.setAttribute("annotationPackageName", languageConfig.getAnnotationPackageName());
template.setAttribute("extends", config.getDefaultModelBaseClass());
template.setAttribute("className", model.getGenratedClassName());
template.setAttribute(PACKAGE_NAME, config.getModelPackageName());
File aFile = new File(languageConfig.getModelClassLocation()+model.getGenratedClassName()+languageConfig.getClassFileExtension());
writeFile(aFile, template.toString(), "Model class");
generatedClassNames.add(model.getName());
}
}
}
}
generateWrapperClassForTestData(generatedClassNames, templateGroup);
}
/**
* Generates assembler classes if the API returns more than one object.
* @param resources
* @param templateGroup
*/
private void generateModelClassesForInput(List<Resource> resources, StringTemplateGroup templateGroup) {
List<String> generatedClasses = new ArrayList<String>();
for(Resource resource : resources) {
if(resource.getEndPoints() != null) {
for(Endpoint endpoint : resource.getEndPoints()){
if(endpoint.getOperations() != null) {
for(EndpointOperation operation : endpoint.getOperations()){
ResourceMethod method = operation.generateMethod(endpoint, resource, dataTypeMappingProvider, nameGenerator);
if(method.getInputModel() != null) {
Model model = method.getInputModel();
if(model != null){
if(!generatedClasses.contains(model.getName())) {
List<String> imports = new ArrayList<String>();
imports.addAll(this.config.getDefaultModelImports());
for(ModelField param : model.getFields()){
param.setName(reservedWordMapper.translate(param.getName()));
for(String importDef : param.getFieldDefinition(this.getDataTypeMappingProvider(), config, nameGenerator, reservedWordMapper).getImportDefinitions()){
if(!imports.contains(importDef)){
imports.add(importDef);
}
}
}
StringTemplate template = templateGroup.getInstanceOf(languageConfig.getTemplateLocation()+"/"+MODEL_OBJECT_TEMPLATE);
template.setAttribute("fields", model.getFields());
template.setAttribute("imports", imports);
template.setAttribute("extends", config.getDefaultModelBaseClass());
template.setAttribute("annotationPackageName", languageConfig.getAnnotationPackageName());
template.setAttribute("className", model.getGenratedClassName());
template.setAttribute(PACKAGE_NAME, config.getModelPackageName());
File aFile = new File(languageConfig.getModelClassLocation()+model.getGenratedClassName()+languageConfig.getClassFileExtension());
writeFile(aFile, template.toString(), "Input model class");
generatedClasses.add(model.getName());
}
}
}
}
}
}
}
}
}
/**
* Generates an Enum class for method params that have an allowed values list.
* @param resources
* @param templateGroup
*/
private void generateEnumForAllowedValues(List<Resource> resources, StringTemplateGroup templateGroup) {
List<String> generatedEnums = new ArrayList<String>();
StringTemplate template;
String valuePrefix, valueSuffix = "";
String enumName;
for(Resource resource: resources) {
if(resource.getEndPoints() != null) {
for(Endpoint endpoint : resource.getEndPoints()){
if(endpoint.getOperations() != null) {
for(EndpointOperation operation : endpoint.getOperations()){
//ResourceMethod method = operation.generateMethod(endpoint, resource, config);
if(operation.getParameters() != null){
for(ModelField operationParam : operation.getParameters()){
//skipping the case where there is just one item - TODO process case of allowableValue like '0 to 1000'
if(operationParam.getAllowableValues() != null && operationParam.getAllowableValues().getClass().isAssignableFrom(AllowableListValues.class)) {
if(!generatedEnums.contains(operationParam.getName())){
//generate enum
template = templateGroup.getInstanceOf(languageConfig.getTemplateLocation()+"/"+ENUM_OBJECT_TEMPLATE);
List<String> imports = new ArrayList<String>();
imports.addAll(this.config.getDefaultModelImports());
enumName = this.getNameGenerator().getEnumName(operationParam.getName());
template.setAttribute("className", enumName);
template.setAttribute("description", operationParam.getDescription());
template.setAttribute("enumValueType", this.getDataTypeMappingProvider().getClassType(operationParam.getDataType(), true));
for (String allowableValue : ((AllowableListValues)operationParam.getAllowableValues()).getValues()) {
if(operationParam.getDataType().equalsIgnoreCase("string")){
valuePrefix = valueSuffix = "\"";
}
else{
valuePrefix = valueSuffix = "";
};
String namePrefix = "";
if((isNameStartsWithInteger(allowableValue) && !canEnumNameStartsWithNumber()) || isEnumNumber(allowableValue) ){
namePrefix = "ENUM_";
}
template.setAttribute("values.{name,value}",
namePrefix+this.getNameGenerator().applyClassNamingPolicy(allowableValue.replaceAll("-","_")),
this.getNameGenerator().applyMethodNamingPolicy(valuePrefix.concat(allowableValue).concat(valueSuffix)));
}
template.setAttribute(PACKAGE_NAME, config.getModelPackageName());
File aFile = new File(languageConfig.getModelClassLocation() + enumName + languageConfig.getClassFileExtension());
writeFile(aFile, template.toString(), "Enum class");
generatedEnums.add(operationParam.getName());
}
}
}
}
}
}
}
}
}
}
private boolean isNameStartsWithInteger(String name) {
for(int i=0; i <= 9 ; i++){
if(name.startsWith(i+"")){
return true;
}
}
return false;
}
private boolean isEnumNumber(String name) {
try{
new Integer(name);
return true;
}catch(Throwable t){
return false;
}
}
private void generateOutputWrappers(List<Resource> resources, StringTemplateGroup templateGroup) {
List<String> generatedClasses = new ArrayList<String>();
StringTemplate template = templateGroup.getInstanceOf(languageConfig.getTemplateLocation()+"/"+WRAPPER_OBJECT_TEMPLATE);
if(template == null){
System.out.println("WrapperObject template not found to generate output wrappers");
return;
}
for(Resource resource: resources) {
if(resource.getEndPoints() != null) {
for(Endpoint endpoint : resource.getEndPoints()){
if(endpoint.getOperations() != null) {
for(EndpointOperation operation : endpoint.getOperations()){
ResourceMethod method = operation.generateMethod(endpoint, resource, dataTypeMappingProvider, nameGenerator);
if(codeGenRulesProvider.isModelIgnored( nameGenerator.applyMethodNamingPolicy( method.getReturnClassName() ))){
continue;
}
if(method.getListWrapperModel() != null) {
Model model = method.getListWrapperModel();
method.setReturnClassName(model.getName());
if(model != null){
if(!generatedClasses.contains(model.getName())) {
List<String> imports = new ArrayList<String>();
imports.addAll(this.config.getDefaultModelImports());
for(ModelField param : model.getFields()){
param.setName(reservedWordMapper.translate(param.getName()));
for(String importDef : param.getFieldDefinition(this.getDataTypeMappingProvider(), config, nameGenerator, reservedWordMapper).getImportDefinitions()){
if(!imports.contains(importDef)){
imports.add(importDef);
}
}
}
template = templateGroup.getInstanceOf(WRAPPER_OBJECT_TEMPLATE);
template.setAttribute("fields", model.getFields());
template.setAttribute("imports", imports);
template.setAttribute("extends", config.getDefaultModelBaseClass());
template.setAttribute("annotationPackageName", languageConfig.getAnnotationPackageName());
template.setAttribute("className", model.getGenratedClassName());
template.setAttribute(PACKAGE_NAME, config.getModelPackageName());
File aFile = new File(languageConfig.getModelClassLocation()+model.getGenratedClassName()+languageConfig.getClassFileExtension());
writeFile(aFile, template.toString(), "List wrapper model class");
generatedClasses.add(model.getName());
}
}
}
}
}
}
}
}
}
/**
* Generates one API class for each resource and each end point in the resource is translated as method.
* @param resources
* @param templateGroup
*/
private void generateAPIClasses(List<Resource> resources, StringTemplateGroup templateGroup) {
for(Resource resource : resources) {
try{
List<ResourceMethod> methods = new ArrayList<ResourceMethod>();
List<String> imports = new ArrayList<String>();
imports.addAll(this.config.getDefaultServiceImports());
methods = resource.generateMethods(resource, dataTypeMappingProvider, nameGenerator, languageConfig);
StringTemplate template = templateGroup.getInstanceOf(languageConfig.getTemplateLocation()+"/"+API_OBJECT_TEMPLATE);
String className = resource.generateClassName(nameGenerator);
if(className != null){
List<ResourceMethod> filteredMethods = new ArrayList<ResourceMethod>();
for(ResourceMethod method:methods){
if(method.getArguments() != null){
for(MethodArgument methodArg: method.getArguments()){
methodArg.setName(reservedWordMapper.translate(methodArg.getName()));
}
}
if(!this.getCodeGenRulesProvider().isMethodIgnored(className, method.getName())){
filteredMethods.add(method);
}
}
template.setAttribute("imports", imports);
template.setAttribute(PACKAGE_NAME, config.getApiPackageName());
template.setAttribute("annotationPackageName", languageConfig.getAnnotationPackageName());
template.setAttribute("modelPackageName", config.getModelPackageName());
template.setAttribute("exceptionPackageName", languageConfig.getExceptionPackageName());
template.setAttribute("resource", className);
template.setAttribute("methods", filteredMethods);
template.setAttribute("extends", config.getServiceBaseClass(className));
File aFile = new File(languageConfig.getResourceClassLocation()+ resource.generateClassName(nameGenerator) +languageConfig.getClassFileExtension());
writeFile(aFile, template.toString(), "API Classes");
}
}catch(RuntimeException t){
System.out.println("Failed generating api class for the resource : " + resource.getResourcePath());
throw t;
}
}
}
/**
* Creates a wrapper model class that contains all model classes as list of objects.
* This class is used for storing test data
*/
private void generateWrapperClassForTestData(List<String> generatedClassNames, StringTemplateGroup templateGroup) {
Model model = new Model();
model.setName("TestData");
model.setDescription("Class used to store all the test data. This should not be used for any development");
List<ModelField> modelFields = new ArrayList<ModelField>();
model.setFields(modelFields);
for(String className : generatedClassNames){
ModelField aParam = new ModelField();
aParam.setName(this.getNameGenerator().applyMethodNamingPolicy(className)+"List");
aParam.setParamType(this.getDataTypeMappingProvider().getListReturnTypeSignature(className));
modelFields.add(aParam);
}
List<String> imports = new ArrayList<String>();
imports.addAll(this.config.getDefaultModelImports());
imports.addAll(this.getDataTypeMappingProvider().getListIncludes());
for(ModelField param : model.getFields()){
for(String importDef : param.getFieldDefinition(this.getDataTypeMappingProvider(), config, nameGenerator, reservedWordMapper).getImportDefinitions()){
if(!imports.contains(importDef)){
imports.add(importDef);
}
}
}
StringTemplate template = templateGroup.getInstanceOf(languageConfig.getTemplateLocation()+"/"+MODEL_OBJECT_TEMPLATE);
template.setAttribute("fields", model.getFields());
template.setAttribute("imports", imports);
template.setAttribute("annotationPackageName", languageConfig.getAnnotationPackageName());
template.setAttribute("extends", config.getDefaultModelBaseClass());
template.setAttribute(PACKAGE_NAME, config.getModelPackageName());
template.setAttribute("className", model.getGenratedClassName());
File aFile = new File(languageConfig.getModelClassLocation()+model.getGenratedClassName()+languageConfig.getClassFileExtension());
writeFile(aFile, template.toString(), "Wrapper class for test data file");
}
/**
* Override this method in the derived classes to generate language specific classes
* @param resources
* @param aTemplateGroup
*/
protected void generateMiscClasses(List<Resource> resources, StringTemplateGroup aTemplateGroup) {
//nothing here in the base class
}
protected void writeFile(File aFile, String content, String classType){
try{
System.out.println("Writing to the file " + aFile.getAbsolutePath());
FileWriter aWriter = new FileWriter(aFile);
BufferedWriter bufWriter = new BufferedWriter(aWriter);
bufWriter.write(content);
bufWriter.close();
}catch(IOException ioe){
throw new CodeGenerationException("Error generating " + classType + " : " + ioe.getMessage());
}
}
public ApiConfiguration getConfig() {
return config;
}
public void setApiConfig(ApiConfiguration config) {
this.config = config;
}
public LanguageConfiguration getLanguageConfig() {
return languageConfig;
}
public void setLanguageConfig(LanguageConfiguration config) {
this.languageConfig = config;
}
public void setDataTypeMappingProvider(DataTypeMappingProvider dataTypeMappingProvider) {
this.dataTypeMappingProvider = dataTypeMappingProvider;
}
public void setCodeGenRulesProvider(RulesProvider codeGenRulesProvider) {
this.codeGenRulesProvider = codeGenRulesProvider;
}
public void setNameGenerator(NamingPolicyProvider nameGenerator) {
this.nameGenerator = nameGenerator;
}
public DataTypeMappingProvider getDataTypeMappingProvider() {
return dataTypeMappingProvider;
}
public RulesProvider getCodeGenRulesProvider() {
return codeGenRulesProvider;
}
public NamingPolicyProvider getNameGenerator() {
return nameGenerator;
}
/**
* In java enum names can't start with number so if the enums are numbers then we prefix them with ENUM_
* @return
*/
protected boolean canEnumNameStartsWithNumber() {
return true;
}
protected CodeGenRulesProvider readRulesProviderConfig(String rulesProviderLocation, ObjectMapper mapper, File configFile) {
CodeGenRulesProvider codeGenRules = null;
try {
codeGenRules = mapper.readValue(configFile, CodeGenRulesProvider.class);
} catch (IOException e) {
throw new CodeGenerationException("Java codegen rules configuration could not be read from the location : " + rulesProviderLocation);
}
return codeGenRules;
}
protected ApiConfiguration readApiConfiguration(String apiConfigLocation, ObjectMapper mapper, File configFile) {
ApiConfiguration configuration = null;
try {
configuration = mapper.readValue(configFile, ApiConfiguration.class);
} catch (IOException e) {
throw new CodeGenerationException("Api configuration could not be read from the location : " + apiConfigLocation);
}
return configuration;
}
protected LanguageConfiguration readLanguageConfiguration(String langConfigLocation, ObjectMapper mapper, File configFile) {
LanguageConfiguration langConfig = null;
try {
langConfig = mapper.readValue(configFile, LanguageConfiguration.class);
} catch (IOException e) {
throw new CodeGenerationException("Language configuration value could not be read from the location : " + langConfigLocation);
}
return langConfig;
}
protected LanguageConfiguration initializeLangConfig(LanguageConfiguration configuration) {
return configuration;
}
}

View File

@ -1,97 +0,0 @@
/**
* 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.codegen;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
public class MethodArgument {
public static String ARGUMENT_STRING = "String";
public static String ARGUMENT_INTEGER = "int";
public static String ARGUMENT_OBJECT = "Object";
private String name;
private String description;
private String dataType;
private String allowedValues;
private String inputModelClassArgument;
private String methodNameFromModelClass;
private String defaultValue;
private boolean required;
public String getDefaultValue(){
return defaultValue;
}
public void setDefaultValue(String defaultValue){
this.defaultValue = defaultValue;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required){
this.required = required;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getAllowedValues() {
return allowedValues;
}
public void setAllowedValues(String allowedValues) {
this.allowedValues = allowedValues;
}
public String getInputModelClassArgument() {
return inputModelClassArgument;
}
public void setInputModelClassArgument(String inputModelClass, NamingPolicyProvider nameGenerator) {
this.inputModelClassArgument = nameGenerator.applyMethodNamingPolicy(inputModelClass);
if(name != null) {
methodNameFromModelClass = nameGenerator.createGetterMethodName(inputModelClassArgument, name);
}
}
public String getMethodNameFromModelClass() {
return methodNameFromModelClass;
}
}

View File

@ -1,224 +0,0 @@
/**
* 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.codegen;
import com.wordnik.swagger.codegen.resource.Model;
import java.util.List;
public class ResourceMethod {
private String title;
private String description;
private List<MethodArgument> arguments;
private List<MethodArgument> queryParameters;
private List<MethodArgument> pathParameters;
private List<MethodArgument> headerParameters;
//set the original response name, this is used in identifying if the response is single valued or multi valued
private String returnValueFromOperationJson;
private String returnValue;
private String returnClassName;
private String exceptionDescription;
private List<String> argumentDefinitions;
private List<String> argumentNames;
private String name;
private boolean authToken;
private String resourcePath;
private String methodType;
private boolean postObject;
private Model inputModel;
private Model listWrapperModel;
private boolean hasResponseValue;
public boolean isHasResponseValue(){
return hasResponseValue;
}
public void setHasResponseValue(boolean hasResponseValue){
this.hasResponseValue = hasResponseValue;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<MethodArgument> getArguments() {
return arguments;
}
public void setArguments(List<MethodArgument> arguments) {
this.arguments = arguments;
}
public List<MethodArgument> getQueryParameters() {
return queryParameters;
}
public void setQueryParameters(List<MethodArgument> queryParameters) {
this.queryParameters = queryParameters;
}
public List<MethodArgument> getPathParameters() {
return pathParameters;
}
public void setPathParameters(List<MethodArgument> pathParameters) {
this.pathParameters = pathParameters;
}
public List<MethodArgument> getHeaderParameters() {
return headerParameters;
}
public void setHeaderParameters(List<MethodArgument> headerParameters) {
this.headerParameters = headerParameters;
}
public String getReturnValue() {
return returnValue;
}
public void setReturnValue(String returnValue) {
this.returnValue = returnValue;
}
public String getReturnValueFromOperationJson() {
return returnValueFromOperationJson;
}
public void setReturnValueFromOperationJson(String returnValue) {
this.returnValueFromOperationJson = returnValue;
}
public String getReturnClassName() {
return returnClassName;
}
public void setReturnClassName(String returnClassName) {
this.returnClassName = returnClassName;
}
public String getExceptionDescription() {
return exceptionDescription;
}
public void setExceptionDescription(String exceptionDescription) {
this.exceptionDescription = exceptionDescription;
}
public List<String> getArgumentDefinitions() {
return argumentDefinitions;
}
public void setArgumentDefinitions(List<String> argumentDefinitions) {
this.argumentDefinitions = argumentDefinitions;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isAuthToken() {
return authToken;
}
public void setAuthToken(boolean authToken) {
this.authToken = authToken;
}
public String getResourcePath() {
return resourcePath;
}
public void setResourcePath(String resourcePath) {
this.resourcePath = resourcePath;
}
public String getMethodType() {
return methodType;
}
public void setMethodType(String methodType) {
this.methodType = methodType;
}
public boolean isPostObject() {
return postObject;
}
public void setPostObject(boolean postObject) {
this.postObject = postObject;
}
public boolean isResponseVoid() {
return (this.getReturnClassName().equalsIgnoreCase("void"));
}
public Model getInputModel() {
return inputModel;
}
public void setInputModel(Model inputModel) {
this.inputModel = inputModel;
}
public List<String> getArgumentNames() {
return argumentNames;
}
public void setArgumentNames(List<String> argumentNames) {
this.argumentNames = argumentNames;
}
public boolean getHasArguments() {
if(this.getArgumentNames() != null && this.getArgumentNames().size() > 0){
return true;
}
return false;
}
public boolean isReturnValueList() {
if(this.getReturnValueFromOperationJson().startsWith("List")){
return true;
}
return false;
}
public void setListWrapperModel(Model listWrapperModel) {
this.listWrapperModel = listWrapperModel;
}
public Model getListWrapperModel() {
return listWrapperModel;
}
}

View File

@ -1,31 +0,0 @@
package com.wordnik.swagger.codegen;
import org.antlr.stringtemplate.AttributeRenderer;
class StringRenderer implements AttributeRenderer {
@Override
public String toString(Object o) {
if (o == null) {
return "";
}
return o.toString();
}
@Override
public String toString(Object o, String formatName) {
if (o == null) {
return "";
}
String result = o.toString();
if (formatName != null && "xml-safe".equals(formatName)) {
result = result.replace("<", "%lt;").replace(">", "&gt;");
}
return result;
}
}

View File

@ -1,182 +0,0 @@
/**
* 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.codegen.api;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.wordnik.swagger.codegen.config.DataTypeMappingProvider;
import com.wordnik.swagger.codegen.exception.CodeGenerationException;
import com.wordnik.swagger.codegen.resource.Endpoint;
import com.wordnik.swagger.codegen.resource.Resource;
import com.wordnik.swagger.codegen.config.ApiConfiguration;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* User: deepakmichael
* Date: 27/07/11
* Time: 9:32 PM
*/
public class SwaggerResourceDocReader {
private static String HEADER_NAME_API_VERSION = "Wordnik-Api-Version";
private String baseUrl;
private String apiKey;
private String apiListResource;
private ApiConfiguration apiConfiguration;
private final DataTypeMappingProvider dataTypeMappingProvider;
private final NamingPolicyProvider nameGenerator;
public SwaggerResourceDocReader(ApiConfiguration apiConfiguration, DataTypeMappingProvider dataTypeMappingProvider, NamingPolicyProvider nameGenerator) {
this.apiConfiguration = apiConfiguration;
this.dataTypeMappingProvider = dataTypeMappingProvider;
this.nameGenerator = nameGenerator;
readApiConfig();
}
public void readApiConfig() {
baseUrl = apiConfiguration.getApiUrl();
apiKey = apiConfiguration.getApiKey();
apiListResource = apiConfiguration.getApiListResource();
}
/**
* Reads the documentation of the resources and constructs the resource object that can be used
* for generating the driver related classes. The resource list string should be "," separated
*/
public List<Resource> readResourceDocumentation() {
List<Resource> resourceDocs = new ArrayList<Resource>();
Client apiClient = Client.create();
String resourceList = retrieveResourceList(apiClient);
//valid for input
if (baseUrl == null || resourceList == null ||
baseUrl.trim().length() == 0 ||
resourceList.trim().length() == 0) {
throw new CodeGenerationException("Base URL or Resource list input is null");
}
//create list of resource URL
String[] resources = resourceList.split(",");
List<String> resourceURLs = new ArrayList<String>();
for (String resource : resources) {
resource = trimResourceName(resource);
if (!resource.equals(trimResourceName( apiListResource ))) {
if(resource.endsWith(".{format}")){
resource = resource.replace(".{format}", ".json");
}
resourceURLs.add(baseUrl + resource);
}
}
//make connection to resource and get the documentation
for (String resourceURL : resourceURLs) {
ClientResponse clientResponse = buildClientResponse(apiClient, resourceURL);
String response = clientResponse.getEntity(String.class);
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Resource aResourceDoc = deserializeResource(response, mapper);
resourceDocs.add(aResourceDoc);
} catch (IOException ioe) {
ioe.printStackTrace();
throw new CodeGenerationException("Error in coverting resource json documentation to java object");
}
}
return resourceDocs;
}
private ClientResponse buildClientResponse(Client apiClient, String url) {
if(null != apiKey && apiKey.length() > 0){
url = url + "?api_key="+ apiKey;
}
WebResource aResource = apiClient.resource(url);
ClientResponse clientResponse = null;
if(null != apiKey && apiKey.length() > 0){
aResource.header("api_key", apiKey);
clientResponse = aResource.header("api_key", apiKey).get(ClientResponse.class);
}else{
clientResponse = aResource.get(ClientResponse.class);
}
return clientResponse;
}
private String trimResourceName(String resource) {
if(resource.startsWith("/")){
resource = resource.substring(1,resource.length());
}
return resource;
}
private String retrieveResourceList(Client apiClient) {
String resourceCsv = "";
Resource resourceApi;
String apiResourceUrl = null;
apiListResource = baseUrl + "resources.json";
if(!apiListResource.endsWith(".json")){
apiResourceUrl = trimResourceName( apiListResource.concat(".json") );
}else{
apiResourceUrl = trimResourceName( apiListResource);
}
ClientResponse clientResponse = buildClientResponse(apiClient, apiResourceUrl);
String response = clientResponse.getEntity(String.class);
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
resourceApi = deserializeResource(response, mapper);
for(Endpoint api: resourceApi.getEndPoints()){
resourceCsv += (api.getPath() + ",");
}
}
catch (IOException ex) {
ex.printStackTrace();
throw new CodeGenerationException("Error in coverting resource listing json documentation to java object");
}
return resourceCsv;
}
/**
* Deserializes the response and returns a Response object
* @param response
* @param mapper
* @return
* @throws IOException
*/
private Resource deserializeResource(String response, ObjectMapper mapper) throws IOException {
Resource resource = mapper.readValue(response, Resource.class);
resource.generateModelsFromWrapper(nameGenerator);
return resource;
}
}

View File

@ -1,162 +0,0 @@
/**
* 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.codegen.config;
import com.wordnik.swagger.codegen.exception.CodeGenerationException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User: ramesh
* Date: 5/31/11
* Time: 7:04 AM
*/
public class ApiConfiguration {
private Map<String, String> serviceBaseClasses = new HashMap<String, String>();
private String defaultServiceBaseClass = "Object";
private String defaultModelBaseClass = "Object";
/**
* Default model imports that we need to include in all service classes. This is needed because some times,
* we may need to write custom classes and those classes will not be known to code generation. To import those
* classes in service classes we use this property
*/
private List<String> defaultModelImports = new ArrayList<String>();
/**
* Default service imports that we need to include in all service classes. This is needed because some times,
* we may need to write custom classes ans those classes will not be known to code generation. To import those
* classes in service classes we use this property
*/
private List<String> defaultServiceImports = new ArrayList<String>();
private String modelPackageName;
private String apiPackageName;
private String apiUrl;
private String apiKey;
private String apiListResource;
public ApiConfiguration() {
}
public Map<String, String> getServiceBaseClasses() {
return serviceBaseClasses;
}
public void setServiceBaseClasses(Map<String, String> serviceBaseClasses) {
this.serviceBaseClasses = serviceBaseClasses;
}
public void setDefaultServiceBaseClass(String defaultServiceBaseClass) {
this.defaultServiceBaseClass = defaultServiceBaseClass;
}
public String getDefaultServiceBaseClass() {
return this.defaultServiceBaseClass;
}
public void setServiceBaseClass(String serviceName, String className) {
if(serviceName == null || serviceName.length() == 0){
throw new CodeGenerationException("Error setting base class for service: service name was not provided");
}
if(className == null || className.length() == 0) {
throw new CodeGenerationException("Error settting base class for service: class name was not provided");
}
serviceBaseClasses.put(serviceName, className);
}
public String getServiceBaseClass(String serviceName) {
if(serviceBaseClasses.containsKey(serviceName)){
return serviceBaseClasses.get(serviceName);
}
return defaultServiceBaseClass;
}
public String getDefaultModelBaseClass() {
return defaultModelBaseClass;
}
public void setDefaultModelBaseClass(String defaultModelBaseClass) {
this.defaultModelBaseClass = defaultModelBaseClass;
}
public List<String> getDefaultModelImports() {
return defaultModelImports;
}
public void setDefaultModelImports(List<String> defaultModelImports) {
this.defaultModelImports = defaultModelImports;
}
public List<String> getDefaultServiceImports() {
return defaultServiceImports;
}
public void setDefaultServiceImports(List<String> defaultServiceImports) {
this.defaultServiceImports = defaultServiceImports;
}
public String getModelPackageName() {
return modelPackageName;
}
public void setModelPackageName(String modelPackageName) {
this.modelPackageName = modelPackageName;
}
public String getApiPackageName() {
return apiPackageName;
}
public void setApiPackageName(String apiPackageName) {
this.apiPackageName = apiPackageName;
}
public String getApiUrl() {
return apiUrl;
}
public void setApiUrl(String apiUrl) {
this.apiUrl = apiUrl;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiListResource() {
return apiListResource;
}
public void setApiListResource(String apiListResource) {
this.apiListResource = apiListResource;
}
}

View File

@ -1,62 +0,0 @@
/**
* 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.codegen.config;
import com.wordnik.swagger.codegen.config.RulesProvider;
import java.util.ArrayList;
import java.util.List;
/**
* User: ramesh
* Date: 5/31/11
* Time: 7:04 AM
*/
public class CodeGenRulesProvider implements RulesProvider {
private List<String> ignoreMethods = new ArrayList<String>();
private List<String> ignoreModels = new ArrayList<String>();
public CodeGenRulesProvider() {
}
public boolean isMethodIgnored(String serviceName, String methodName){
return (ignoreMethods.contains(serviceName+"."+methodName));
}
public boolean isModelIgnored(String modelName) {
return ignoreModels.contains(modelName);
}
public List<String> getIgnoreMethods() {
return ignoreMethods;
}
public void setIgnoreMethods(List<String> ignoreMethods) {
this.ignoreMethods = ignoreMethods;
}
public List<String> getIgnoreModels() {
return ignoreModels;
}
public void setIgnoreModels(List<String> ignoreModels) {
this.ignoreModels = ignoreModels;
}
}

View File

@ -1,234 +0,0 @@
/**
* 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.codegen.config;
import java.util.List;
/**
* Implementations of this class is responsible for generating mapping between resource documentation data types and language
* specific data type
*
* User: ramesh
* Date: 5/27/11
* Time: 7:39 AM
*/
public interface DataTypeMappingProvider {
/**
* Checks nature of data type.
*
* This is needed in generating return values, input and model class generations.
*
* Example: in java <Code>String</Code>, <Code>Integer</Code>, <Code>Boolean</Code> are considered as primitive
* types
* @param type
* @return
*/
public boolean isPrimitiveType(String type);
/**
* Signature that should be used when returning list of given object type.
*
* Example: in java this output will look as <Code> List<User> </Code> for methods that returns a list of user objects
* @param typeClass of class that list object contains.
* @return
*/
public String getListReturnTypeSignature(String typeClass);
/**
* Signature that should be used when returning map of given object type.
*
* Example: in java this output will look as <Code> Map<User> </Code> for methods that returns maps
* @param typeClass of class that list object contains.
* @return
*/
public String getMapReturnTypeSignature(String typeClass);
/**
* Signature that should be used when returning set of given object type.
*
* Example: in java this output will look as <Code> Set<User> </Code> for methods that returns a set of user objects
* @param typeClass of class that the set object contains.
* @return
*/
public String getSetReturnTypeSignature(String typeClass);
/**
* Signature that should be used when returning array of given object type.
*
* Example: in java this output will look as <Code> Array<User> </Code> for methods that returns a set of user objects
* @param typeClass of class that the set object contains.
* @return
*/
public String getArrayReturnTypeSignature(String typeClass);
/**
* Initialization need for list objects. Example. If it is java list the initialization will look as
*
* <Code>
* new ArrayList<ClassName>()
* </Code>
*
* @param typeClass
* @return
*/
public String generateListInitialization(String typeClass);
/**
* Initialization need for map objects. Example. If it is java map the initialization will look as
*
* <Code>
* new HashMap<ClassName>()
* </Code>
*
* @param typeClass
* @return
*/
public String generateMapInitialization(String typeClass);
/**
* Initialization need for set objects. Example. If it is java set the initialization will look as
*
* <Code>
* new HashSet<ClassName>()
* </Code>
*
* @param typeClass
* @return
*/
public String generateSetInitialization(String typeClass);
/**
* Initialization need for Array objects. Example. If it is Java Array initialization will look as
*
* <Code>
* new ObjectName[]()
* </Code>
*
* @param typeClass
* @return
*/
public String generateArrayInitialization(String typeClass);
/**
* Sets variable initialization.
*
* Example: In scala initializing a variable with an unknown value will be:
* <Code>
* var age:String = _
* </Code>
* @return
*/
public String generateVariableInitialization(String typeClass);
/**
* Gets list of items that needs to be included when referring list objects in model or resource classes.
*
* Example: In java this information is used as java imports. In java while using lists we use an interface of
* <Code>List</Code> and implementation of <Code>ArrayList</Code>. So the the implementation of this method in java
* language will be:
* <Code>
* List<String> imports = new ArrayList<String>();
imports.add("java.util.List");
imports.add("java.util.ArrayList");
* </Code>
* @return
*/
public List<String> getListIncludes();
/**
* Gets list of items that needs to be included when referring map objects in model or resource classes.
*
* Example: In java this information is used as java imports. In java while using map we use an interface of
* <Code>Map</Code> and implementation of <Code>HashMap</Code>. So the the implementation of this method in java
* language will be:
* <Code>
* List<String> imports = new ArrayList<String>();
imports.add("java.util.Map");
imports.add("java.util.HashMap");
* </Code>
* @return
*/
public List<String> getMapIncludes();
/**
* Gets list of to needs to be included when referring set objects in model or resource classes.
*
* Example: in java while using sets we use an interface of <Code>Array</Code> and implementation of
* <Code>Arry</Code>. So the the implementation of this method in java
* language will be:
* <Code>
* List<String> imports = new ArrayList<String>();
imports.add("java.lang.Array");
* </Code>
* @return
*/
public List<String> getSetIncludes();
/**
* Gets list of items that needs to be included when referring date objects in model or resource classes.
*
* Example: in java while using Data we use <Code> java.util.Date</Code>. So the output will as follows:
* <Code>
* List<String> imports = new ArrayList<String>();
imports.add("java.util.Date");
* </Code>
* @return
*/
public List<String> getDateIncludes();
/**
* Class type definition for a given input.
*
* Example: In java language: For inputs Integer and primitive true, the class type will be int, if primitiveObject is false
* the class type will be Integer. For inputs user the class type will be User as the input object is not primitive.
* for input List[user] the class type will be <Code> List<User> </Code> . For input Map[int, String] the equivalent java
* translation will be <Code> Map<Integer, String> </Code>
*
* @param type
* @param primitiveObject This argument used to indicate, if the given input type is primitive,
* should we return primitive types or primitive classes.
* @return
*/
public String getClassType(String type, boolean primitiveObject);
/**
* If the class contains generics then this will return type of generics object else returns same object
*
* Example: If the resource documentation says return type as List[User] the equivalent generic type for java will be
*
* <Code> User </Code>
*
* If the input is Map[int] the equivalent java translation will be <Code> Int </Code>
* @param type
* @return
*/
public String getGenericType(String type);
/**
* Returns the syntax for defintion of an object of type and name
*
* @param argumentType
* @param argumentName
* @return
*/
public String getArgumentDefinition(String argumentType, String argumentName);
}

View File

@ -1,38 +0,0 @@
/**
* 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.codegen.config;
/**
* class to translate reserved words to safe variable names
*
* @author tony
*
*/
public class DefaultReservedWordMapper implements ReservedWordMapper {
@Override
public String translate(String input) {
// does nothing
return input;
}
@Override
public String retranslate(String input) {
// does nothing
return input;
}
}

View File

@ -1,159 +0,0 @@
/**
* 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.codegen.config;
import com.wordnik.swagger.codegen.exception.CodeGenerationException;
/**
* User: deepakmichael
* Date: 23/07/11
* Time: 8:01 AM
*/
public class LanguageConfiguration {
private String classFileExtension;
private String templateLocation;
private String structureLocation;
private String libraryHome;
private String modelClassLocation;
private String resourceClassLocation;
private String exceptionPackageName;
private String annotationPackageName;
private boolean isModelEnumRequired = true;
private boolean isOutputWrapperRequired = false;
private boolean isMethodOverloadingSupported = true;
public String getClassFileExtension() {
return classFileExtension;
}
public void setClassFileExtension(String classFileExtension) {
this.classFileExtension = classFileExtension;
}
public String getTemplateLocation() {
return templateLocation;
}
public void setTemplateLocation(String templateLocation) {
this.templateLocation = templateLocation;
}
public void setOutputDirectory(String outputDirectory) {
if(outputDirectory == null || outputDirectory.length() == 0){
throw new CodeGenerationException("Error creating output path : Output path was null ");
}
outputDirectory = outputDirectory.endsWith("/") ? outputDirectory.substring(0, outputDirectory.lastIndexOf("/")) : outputDirectory;
this.modelClassLocation = outputDirectory + "/model/";
this.resourceClassLocation = outputDirectory + "/api/";
}
public void setOutputDirectory(String outputDirectory, String modelDirectory, String resourceDirectory){
if(outputDirectory == null || outputDirectory.length() == 0){
throw new CodeGenerationException("Error creating output path : Output path was null ");
}
outputDirectory = outputDirectory.endsWith("/") ? outputDirectory.substring(0, outputDirectory.lastIndexOf("/")) : outputDirectory;
// add leading + trailing slashes
if(!modelDirectory.startsWith("/")) modelDirectory = "/" + modelDirectory;
if(!modelDirectory.endsWith("/")) modelDirectory = modelDirectory + "/";
if(!resourceDirectory.startsWith("/")) resourceDirectory = "/" + resourceDirectory;
if(!resourceDirectory.endsWith("/")) resourceDirectory = resourceDirectory + "/";
this.modelClassLocation = outputDirectory + modelDirectory;
this.resourceClassLocation = outputDirectory + resourceDirectory;
}
public String getModelClassLocation() {
return modelClassLocation;
}
public String getResourceClassLocation() {
return resourceClassLocation;
}
public String getExceptionPackageName() {
return exceptionPackageName;
}
public void setExceptionPackageName(String exceptionPackageName) {
this.exceptionPackageName = exceptionPackageName;
}
public String getAnnotationPackageName() {
return annotationPackageName;
}
public void setAnnotationPackageName(String annotationPackageName) {
this.annotationPackageName = annotationPackageName;
}
public String getStructureLocation() {
return structureLocation;
}
public void setStructureLocation(String structureLocation) {
this.structureLocation = structureLocation;
}
public String getLibraryHome() {
return libraryHome;
}
public void setLibraryHome(String libraryHome) {
this.libraryHome = libraryHome;
}
public void setModelEnumRequired(boolean modelEnumRequired) {
this.isModelEnumRequired = modelEnumRequired;
}
public boolean isModelEnumRequired() {
return isModelEnumRequired;
}
public void setOutputWrapperRequired(boolean outputWrapperRequired) {
this.isOutputWrapperRequired = outputWrapperRequired;
}
public boolean isOutputWrapperRequired() {
return isOutputWrapperRequired;
}
@Override
public String toString() {
return "LanguageConfiguration [classFileExtension="
+ classFileExtension + ", templateLocation=" + templateLocation
+ ", structureLocation=" + structureLocation + ", libraryHome="
+ libraryHome + ", modelClassLocation=" + modelClassLocation
+ ", resourceClassLocation=" + resourceClassLocation
+ ", exceptionPackageName=" + exceptionPackageName
+ ", annotationPackageName=" + annotationPackageName
+ ", isModelEnumRequired=" + isModelEnumRequired
+ ", isOutputWrapperRequired=" + isOutputWrapperRequired + "]";
}
public boolean isMethodOverloadingSupported() {
return isMethodOverloadingSupported;
}
public void setMethodOverloadingSupported(boolean methodOverloadingSupported) {
isMethodOverloadingSupported = methodOverloadingSupported;
}
}

View File

@ -1,133 +0,0 @@
/**
* 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.codegen.config;
/**
* Implementation of this class is responsible for generating the names for service classes and methods in
* each of those service classes
*
* User: ramesh
* Date: 5/27/11
* Time: 7:36 AM
*/
public interface NamingPolicyProvider {
/**
* Gets name of the version checker class. We need not provide extension for the class as that will be read
* through a class extention configuration value.
*
* Example: In java this is VersionChecker.
*
* @return
*/
public String getVersionCheckerClassName();
/**
* Convert input string into class name format.
*
* Example: in java this will be init caps.
*
* @param input
* @return
*/
public String applyClassNamingPolicy(String input);
/**
* Transform the input string into method naming convention format.
*
* Example: In java, the will be Camel case
*
* @param input
* @return
*/
public String applyMethodNamingPolicy(String input);
/**
* Generates the name of service based on resource path.
*
* Example: for a resource path of http://beta.wordnik.com/v4/word.json the service name can be WordAPI
*
* @param resourcePath
* @return
*/
public String getServiceName(String resourcePath);
/**
* Generates the name of service methods.
*
* Resource documentation provides suggested names. Individual language can choose to use suggested name or
* generate the name based on end point path. Example: IN java we use suggested name
*
* @param endPoint
* @param suggestedName
* @return
*/
public String getMethodName(String endPoint, String suggestedName);
/**
* Generate of the input object using the resource path name.
*
* When the number of arguments for a method increases beyond certain limit, we want to capture all the arguments
* as a single input objects so that it is easy for client to understand the API.
*
* Example: get examples API on words resource takes inputs as : word, limit, include duplicates, content provider,
* use canonical, skip, limit. Instead of having all these as individual arguments create an input object with name
* WordsExampleInput and have above arguments as properties fo the object.
*
* @param serviceName
* @param resourcePath
* @return
*/
public String getInputObjectName(String serviceName, String resourcePath);
/**
* Generate the name of the wrapper class used as a wrapper for a list of items returned by a service
*
* Example: get definitions API returns a list of definition objects as the result. This will be wrapped by an
* object. The object's name will be determined by invoking this service.
* eg. DefinitionList for a wrapper of 'definition's
*
* @param wrapperItemName
* @return
*/
public String getListWrapperName(String wrapperItemName);
/**
* Generates a name for an enum for the param or field name.
*
* Example: for a param source the return could be SourceEnum
*
* @param input
* @return
*/
public String getEnumName(String input);
/**
* Gets the signature of the method that gets value for give attribute name.
*
* Example: If class name is user and attribute name is email the out in java language will be
* <code>user.getEmail()</code>
*
* @param className
* @param attributeName
* @return
*/
public String createGetterMethodName(String className, String attributeName);
}

View File

@ -1,24 +0,0 @@
/**
* 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.codegen.config;
public interface ReservedWordMapper {
public String translate(String input);
public String retranslate(String input);
}

View File

@ -1,54 +0,0 @@
/**
* 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.codegen.config;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Maintains the overriding rules that we should use while generating the code.
*
* Example; If we need to ignore any REST methods or if we need special service extention classes they can be
* supplied through this configuration
*
* User: ramesh
* Date: 4/26/11
* Time: 8:01 AM
*/
public interface RulesProvider {
/**
* Checks if the method needs to be ignored when generating libraries.
*
* This is used if clients want to override the implementation of the method and not use methods generated by the code gen.
*
* @param serviceName
* @param methodName
* @return
*/
public boolean isMethodIgnored(String serviceName, String methodName);
/**
* Checks if model needs to be ignored in code generation.
*
* @param modelName
* @return
*/
public boolean isModelIgnored(String modelName);
}

View File

@ -1,208 +0,0 @@
package com.wordnik.swagger.codegen.config.as3;
import com.wordnik.swagger.codegen.config.DataTypeMappingProvider;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User: ramesh
* Date: 5/31/11
* Time: 7:03 AM
*/
public class As3DataTypeMappingProvider implements DataTypeMappingProvider {
public static Map<String, String> primitiveValueMap = new HashMap<String, String>();
static{
primitiveValueMap.put("string", "String");
primitiveValueMap.put("String", "String");
primitiveValueMap.put("int", "Number");
primitiveValueMap.put("integer", "int");
primitiveValueMap.put("Integer", "int");
primitiveValueMap.put("boolean", "Boolean");
primitiveValueMap.put("Boolean", "Boolean");
primitiveValueMap.put("long", "Number");
primitiveValueMap.put("Long", "Number");
primitiveValueMap.put("double", "Number");
primitiveValueMap.put("Double", "Number");
primitiveValueMap.put("float", "Number");
primitiveValueMap.put("Float", "Number");
primitiveValueMap.put("Date", "Date");
primitiveValueMap.put("date", "Date");
primitiveValueMap.put("byte", "byte");
primitiveValueMap.put("Byte", "byte");
}
public static Map<String, String> primitiveObjectMap = new HashMap<String, String>();
static{
primitiveObjectMap.put("string", "String");
primitiveObjectMap.put("String", "String");
primitiveObjectMap.put("int", "int");
primitiveObjectMap.put("integer", "int");
primitiveObjectMap.put("Integer", "int");
primitiveObjectMap.put("boolean", "Boolean");
primitiveObjectMap.put("Boolean", "Boolean");
primitiveObjectMap.put("long", "Number");
primitiveObjectMap.put("Long", "Number");
primitiveObjectMap.put("double", "Number");
primitiveObjectMap.put("Double", "Number");
primitiveObjectMap.put("float", "Number");
primitiveObjectMap.put("Float", "Number");
primitiveObjectMap.put("Date", "Date");
primitiveObjectMap.put("date", "Date");
primitiveObjectMap.put("byte", "byte");
}
private NamingPolicyProvider nameGenerator = new CamelCaseNamingPolicyProvider();
public boolean isPrimitiveType(String type) {
if(type.equalsIgnoreCase("String") || type.equalsIgnoreCase("int") || type.equalsIgnoreCase("integer") || type.equalsIgnoreCase("double") ||
type.equalsIgnoreCase("boolean") || type.equalsIgnoreCase("float")|| type.equalsIgnoreCase("long") || type.equalsIgnoreCase("Number") ){
return true;
}
return false;
}
/**
* If the data type is primitive and it is expecting object structure then return primitive objects
* else return primitive types
* @param type
* @param primitiveObject -- indicates if the object is primitive or not
* @return
*/
public String getObjectType(String type, boolean primitiveObject) {
if(isPrimitiveType(type)){
if(primitiveObject){
return primitiveObjectMap.get(type);
}else{
return primitiveValueMap.get(type);
}
}else{
return nameGenerator.applyClassNamingPolicy(type);
}
}
public String getListReturnTypeSignature(String typeClass) {
return "Array";
}
public String getReturnTypeForVoidMethods() {
return "void";
}
public String getMapReturnTypeSignature(String typeClass) {
return "Object";
}
public String getSetReturnTypeSignature(String typeClass) {
return "Array";
}
public String getArrayReturnTypeSignature(String typeClass) {
return "Array";
}
public String generateListInitialization(String typeClass) {
return " new Array()";
}
public String generateMapInitialization(String typeClass) {
return " new Object()";
}
public String generateSetInitialization(String typeClass) {
return " new Array()";
}
public String generateArrayInitialization(String typeClass) {
return " new Array()";
}
public List<String> getListIncludes() {
List<String> imports = new ArrayList<String>();
return imports;
}
public List<String> getMapIncludes() {
List<String> imports = new ArrayList<String>();
imports.add("flash.utils.Dictionary");
return imports;
}
public List<String> getSetIncludes() {
List<String> imports = new ArrayList<String>();
return imports; }
public List<String> getDateIncludes() {
List<String> imports = new ArrayList<String>();
return imports;
}
/**
* Gets the short name of the class the class.
* Input can be MAP, LIST or regular string. In case of map or list the class name will be class name
* that map or list is returning.
* @param type
* @return
*/
public String getClassType(String type, boolean primitiveObject) {
String classShortName = "";
if(type.startsWith("List[")){
classShortName = type.substring(5, type.length()-1);
classShortName = getObjectType(classShortName, true);
}else if (type.startsWith("Map[")) {
classShortName = type.substring(4, type.length()-1);
classShortName = getObjectType(classShortName, true);
}else if (type.startsWith("Set[")) {
classShortName = type.substring(4, type.length()-1);
classShortName = getObjectType(classShortName, true);
}else if (type.startsWith("Array[")) {
classShortName = type.substring(6, type.length()-1);
classShortName = getObjectType(classShortName, true);
}else if (type.equals("ok")) {
classShortName = "void";
}else{
classShortName = getObjectType(type, true);
}
return classShortName;
}
public String getArgumentDefinition(String argumentType, String argumentName) {
return argumentName + ": " + argumentType;
}
/**
* Gets the class of the expected return value for a type string. Examples of type Strings are int, User, List[User]
* If the type string is a collection type like a map or list the string value returned would be the class
* that map or list is returning.
*
* @param type
* @return
*/
public String getGenericType(String type) {
if(type.equalsIgnoreCase("void")|| type.equalsIgnoreCase("ok")){
return "void";
}
String classShortName = "";
if(type.startsWith("List[") || type.startsWith("Map[") || type.startsWith("Set[") || type.startsWith("Array[") ){
classShortName = "Array";
}else{
classShortName = getObjectType(type, true);
}
return classShortName;
}
@Override
public String generateVariableInitialization(String typeClass) {
return "";
}
}

View File

@ -1,144 +0,0 @@
package com.wordnik.swagger.codegen.config.as3;
import com.wordnik.swagger.codegen.LibraryCodeGenerator;
import com.wordnik.swagger.codegen.config.LanguageConfiguration;
import com.wordnik.swagger.codegen.exception.CodeGenerationException;
import com.wordnik.swagger.codegen.resource.Model;
import com.wordnik.swagger.codegen.resource.ModelField;
import com.wordnik.swagger.codegen.resource.Resource;
import com.wordnik.swagger.codegen.util.FileUtil;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* User: deepakmichael
* Date: 17/08/11
* Time: 5:02 PM
*/
public class As3LibCodeGen extends LibraryCodeGenerator{
protected static final String MANIFEST_OBJECT_TEMPLATE = "ReferencesObject";
private static final String DEFAULT_SERVICE_BASE_CLASS = "SwaggerApi";
public static void main(String[] args) {
if(args.length < 1){
throw new CodeGenerationException("Invalid number of arguments passed: No command line argument was passed to the program for config json");
}
if(args.length == 1) {
String configPath = args[0];
As3LibCodeGen codeGenerator = new As3LibCodeGen(configPath);
codeGenerator.generateCode();
}
if(args.length == 4) {
String apiServerURL = args[0];
if(!apiServerURL.endsWith("/")){
apiServerURL = apiServerURL + "/";
}
String apiKey = args[1];
String packageName = args[2];
String libraryHome = args[3];
if(libraryHome.endsWith("/")){
libraryHome = libraryHome.substring(0, libraryHome.length()-1);
}
String modelPackageName = packageName+".model";
String apiPackageName = packageName+".api";
String classOutputDir = libraryHome + "/src/main/as3/" + packageName.replace(".","/");
As3LibCodeGen codeGenerator = new As3LibCodeGen(apiServerURL, apiKey, modelPackageName,
apiPackageName, classOutputDir, libraryHome);
codeGenerator.getConfig().setDefaultServiceBaseClass(DEFAULT_SERVICE_BASE_CLASS);
codeGenerator.generateCode();
}
}
public As3LibCodeGen(String apiServerURL, String apiKey, String modelPackageName, String apiPackageName,
String classOutputDir, String libraryHome){
super(apiServerURL, apiKey, modelPackageName, apiPackageName, classOutputDir, libraryHome);
this.setDataTypeMappingProvider(new As3DataTypeMappingProvider());
this.setNameGenerator(new As3NamingPolicyProvider());
}
public As3LibCodeGen(String configPath){
super(configPath);
this.setDataTypeMappingProvider(new As3DataTypeMappingProvider());
this.setNameGenerator(new As3NamingPolicyProvider());
}
@Override
protected LanguageConfiguration initializeLangConfig(LanguageConfiguration as3Configuration) {
as3Configuration.setClassFileExtension(".as");
as3Configuration.setTemplateLocation("conf/as3/templates");
as3Configuration.setStructureLocation("conf/as3/structure");
as3Configuration.setExceptionPackageName("com.wordnik.swagger.exception");
as3Configuration.setAnnotationPackageName("com.wordnik.swagger.annotations");
//create ouput directories
FileUtil.createOutputDirectories(as3Configuration.getModelClassLocation(), as3Configuration.getClassFileExtension());
FileUtil.createOutputDirectories(as3Configuration.getResourceClassLocation(), as3Configuration.getClassFileExtension());
//delete previously generated files
FileUtil.clearFolder(as3Configuration.getModelClassLocation());
FileUtil.clearFolder(as3Configuration.getResourceClassLocation());
FileUtil.clearFolder(as3Configuration.getLibraryHome() + "/src/main/as3/com/wordnik/swagger/common");
FileUtil.clearFolder(as3Configuration.getLibraryHome() + "/src/main/as3/com/wordnik/swagger/exception");
FileUtil.clearFolder(as3Configuration.getLibraryHome() + "/src/main/as3/com/wordnik/swagger/event");
FileUtil.copyDirectoryFromUrl(this.getClass().getClassLoader().getResource(as3Configuration.getStructureLocation()), new File(as3Configuration.getLibraryHome()));
as3Configuration.setModelEnumRequired(false);
as3Configuration.setOutputWrapperRequired(true);
as3Configuration.setMethodOverloadingSupported(false);
return as3Configuration;
}
protected void generateMiscClasses(List<Resource> resources, StringTemplateGroup aTemplateGroup) {
generateReferencesObject(resources, aTemplateGroup);
}
private void generateReferencesObject(List<Resource> resources, StringTemplateGroup templateGroup) {
StringTemplate template = templateGroup.getInstanceOf(MANIFEST_OBJECT_TEMPLATE);
if(template == null){
System.out.println("WrapperObject template not found to generate output wrappers");
return;
}
Model referencesModel = new Model();
List<ModelField> refFields = new ArrayList<ModelField>();
ModelField refModelField;
for(Resource resource: resources) {
for(Model model : resource.getModels()){
for(ModelField modelField : model.getFields()){
if (modelField.getFieldDefinition() != null) {
final String collectionItemType = modelField.getFieldDefinition().getCollectionItemType();
if(collectionItemType != null){
refModelField = new ModelField();
refModelField.setName(modelField.getName() + model.getName());
refModelField.setParamType(collectionItemType);
refFields.add(refModelField);
}
}
}
}
refModelField = new ModelField();
refModelField.setName( nameGenerator.applyMethodNamingPolicy( resource.generateClassName(nameGenerator) ) );
refModelField.setParamType( resource.generateClassName(nameGenerator) );
refFields.add(refModelField);
}
List<String> imports = new ArrayList<String>();
imports.addAll(this.config.getDefaultModelImports());
referencesModel.setFields(refFields);
referencesModel.setName("LibraryReferences");
template = templateGroup.getInstanceOf(MANIFEST_OBJECT_TEMPLATE);
template.setAttribute("model", referencesModel);
template.setAttribute("fields", referencesModel.getFields());
template.setAttribute("imports", imports);
template.setAttribute("annotationPackageName", languageConfig.getAnnotationPackageName());
template.setAttribute("extends", config.getDefaultModelBaseClass());
template.setAttribute("className", referencesModel.getGenratedClassName());
template.setAttribute(PACKAGE_NAME, config.getModelPackageName());
File aFile = new File(languageConfig.getModelClassLocation()+referencesModel.getGenratedClassName()+languageConfig.getClassFileExtension());
writeFile(aFile, template.toString(), "Model class");
}
}

View File

@ -1,25 +0,0 @@
package com.wordnik.swagger.codegen.config.as3;
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider;
/**
* User: deepakmichael
* Date: 16/08/11
* Time: 11:01 AM
*/
public class As3NamingPolicyProvider extends CamelCaseNamingPolicyProvider {
/**
* Gets the signature of the method that gets value for give attribute name.
*
* Example: If class name is user and attibute name is email the out in java language will be
* <code>user.getEmail()</code>
*
* @param className
* @param attributeName
* @return
*/
public String createGetterMethodName(String className, String attributeName) {
return className+"."+ attributeName;
}
}

View File

@ -1,190 +0,0 @@
/**
* 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.codegen.config.common;
import com.wordnik.swagger.codegen.exception.CodeGenerationException;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
/**
* User: ramesh
* Date: 5/31/11
* Time: 7:03 AM
*/
public class CamelCaseNamingPolicyProvider implements NamingPolicyProvider {
public static String INPUT_OBJECT_SUFFIX = "Input";
/**
* gets the name of class that is responsible for tracking current library version
* @return
*/
public String getVersionCheckerClassName() {
return "VersionChecker";
}
/**
* Converts the first character of the input into upper case .
* Example: If the input is word, the return value will be Word
* @param input
* @return
*/
public String applyClassNamingPolicy(String input) {
if(input != null && input.length() > 0) {
String output = input.substring(0,1).toUpperCase() + input.substring(1);
//class name can't have . so if dot exists remove the same
output = output.replace(".","");
return output;
}else{
throw new CodeGenerationException("Error converting input to first letter caps becuase of null or empty input");
}
}
/**
* Converts the first character of the input into lower case.
* Example: If the input is GetWord, the return value will be getWord
* @param input
* @return
*/
public String applyMethodNamingPolicy(String input) {
if(input != null && input.length() > 0) {
return input.substring(0,1).toLowerCase() + input.substring(1);
}else{
throw new CodeGenerationException("Error converting input to first letter to lower because of null or empty input");
}
}
/**
* Generate name of the service from resource path.
*
* Example: if input is /user.json the generated name for this path will be UserAPI
* If the input is /user.json/{userId}, the service name will still be generated as UserAPI
*
* @param resourcePath
* @return
*/
public String getServiceName(String resourcePath) {
String className = null;
int index = resourcePath.indexOf(".");
if(index >= 0) {
String resourceName = resourcePath.substring(1,index);
className = applyClassNamingPolicy(resourceName);
}else{
String[] paths = resourcePath.split("/");
for(String path : paths) {
if(path != null && path.length() > 0) {
className = applyClassNamingPolicy(path);
break;
}
}
}
return className+ "API";
}
/**
* Generates the name of service methods.
*
* Resource documentation provides suggested names. Individual language can choose to use suggested name or
* generate the name based on end point path. Example: IN java we use suggested name
*
* @param endPoint
* @param suggestedName
* @return
*/
public String getMethodName(String endPoint, String suggestedName) {
return suggestedName;
}
/**
* For input UserAPI and resource path /findUserById the suggested input object name will be: UserFindUserByIdInput
*
* If the input path is /{userId}/delete the suggested name will be UserDeleteInput. The path parameters are ignored
* in generating the input object name
*
* Note: Input objects are only created when the number of input arguments in a method exceeds certain number so <br/> that the method signatures are clean
*
*
* @param serviceName
* @param resourcePath
* @return
*/
public String getInputObjectName(String serviceName, String resourcePath) {
//Since service name has API at the end remove that format he name
String inputobjectName = serviceName.substring(0, serviceName.length() - 3);
String[] pathElements = resourcePath.split("/");
StringBuilder urlPath = new StringBuilder("");
if(pathElements != null){
for(int i=0; i < pathElements.length; i++){
String pathElement = pathElements[i];
if(pathElement != null && pathElement.length() > 0) {
int position = pathElement.indexOf("{");
if(position < 0) {
inputobjectName = inputobjectName + applyClassNamingPolicy(pathElement) + INPUT_OBJECT_SUFFIX;
}
}
}
}
return inputobjectName;
}
/**
* Generate the name of the wrapper class used as a wrapper for a list of items returned by a service
* <p/>
* Example: get definitions API returns a list of definition objects as the result. This will be wrapped by an
* object. The object's name will be determined by invoking this service.
* eg. DefinitionList for a wrapper of 'definition's
*
* @param wrapperItemName
* @return
*/
public String getListWrapperName(String wrapperItemName) {
return applyClassNamingPolicy(wrapperItemName) + "List";
}
/**
* Generates a name for an enum for the param or field name.
* <p/>
* Example: for a param source the return could be SourceEnum
*
* @param input
* @return
*/
public String getEnumName(String input) {
if (input != null && input.length() > 0) {
return this.applyClassNamingPolicy(input).concat("Values");
} else {
throw new CodeGenerationException("Error getting Enum name becuase of null input");
}
}
/**
* Gets the signature of the method that gets value for give attribute name.
*
* Example: If class name is user and attibute name is email the out in java language will be
* <code>user.getEmail()</code>
*
* @param className
* @param attributeName
* @return
*/
public String createGetterMethodName(String className, String attributeName) {
return className+".get"+ applyClassNamingPolicy(attributeName)+"()";
}
}

View File

@ -1,198 +0,0 @@
/**
* 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.codegen.config.common;
import com.wordnik.swagger.codegen.exception.CodeGenerationException;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
/**
* User: ramesh
* Date: 5/31/11
* Time: 7:03 AM
*/
public class UnderscoreNamingPolicyProvider implements NamingPolicyProvider {
public static String INPUT_OBJECT_SUFFIX = "Input";
String convertToUnderscoreName(String input){
if(null==input) return null;
return input.replaceAll(
String.format("%s|%s|%s",
"(?<=[A-Z])(?=[A-Z][a-z])",
"(?<=[^A-Z])(?=[A-Z])",
"(?<=[A-Za-z])(?=[^A-Za-z])"),
"_").toLowerCase();
}
/**
* gets the name of class that is responsible for tracking current library version
* @return
*/
public String getVersionCheckerClassName() {
return "version_checker";
}
/**
* Converts the first character of the input into upper case .
* Example: If the input is word, the return value will be Word
* @param input
* @return
*/
public String applyClassNamingPolicy(String input) {
if(input != null && input.length() > 0) {
return convertToUnderscoreName(input);
}else{
throw new CodeGenerationException("Error converting input to first letter caps becuase of null or empty input");
}
}
/**
* Converts the first character of the input into lower case.
* Example: If the input is GetWord, the return value will be getWord
* @param input
* @return
*/
public String applyMethodNamingPolicy(String input) {
if(input != null && input.length() > 0) {
return convertToUnderscoreName(input);
}else{
throw new CodeGenerationException("Error converting input to first letter to lower because of null or empty input");
}
}
/**
* Generate name of the service from resource path.
*
* Example: if input is /user.json the generated name for this path will be UserAPI
* If the input is /user.json/{userId}, the service name will still be generated as UserAPI
*
* @param resourcePath
* @return
*/
public String getServiceName(String resourcePath) {
String className = null;
int index = resourcePath.indexOf(".");
if(index >= 0) {
String resourceName = resourcePath.substring(1,index);
className = applyClassNamingPolicy(resourceName);
}else{
String[] paths = resourcePath.split("/");
for(String path : paths) {
if(path != null && path.length() > 0) {
className = applyClassNamingPolicy(path);
break;
}
}
}
return className + "_api";
}
/**
* Generates the name of service methods.
*
* Resource documentation provides suggested names. Individual language can choose to use suggested name or
* generate the name based on end point path. Example: IN java we use suggested name
*
* @param endPoint
* @param suggestedName
* @return
*/
public String getMethodName(String endPoint, String suggestedName) {
return convertToUnderscoreName(suggestedName);
}
/**
* For input UserAPI and resource path /findUserById the suggested input object name will be: UserFindUserByIdInput
*
* If the input path is /{userId}/delete the suggested name will be UserDeleteInput. The path parameters are ignored
* in generating the input object name
*
* Note: Input objects are only created when the number of input arguments in a method exceeds certain number so <br/> that the method signatures are clean
*
*
* @param serviceName
* @param resourcePath
* @return
*/
public String getInputObjectName(String serviceName, String resourcePath) {
//Since service name has API at the end remove that format he name
String inputobjectName = serviceName.substring(0, serviceName.length() - 3);
String[] pathElements = resourcePath.split("/");
StringBuilder urlPath = new StringBuilder("");
if(pathElements != null){
for(int i=0; i < pathElements.length; i++){
String pathElement = pathElements[i];
if(pathElement != null && pathElement.length() > 0) {
int position = pathElement.indexOf("{");
if(position < 0) {
inputobjectName = inputobjectName + applyClassNamingPolicy(pathElement) + INPUT_OBJECT_SUFFIX;
}
}
}
}
return inputobjectName;
}
/**
* Generate the name of the wrapper class used as a wrapper for a list of items returned by a service
* <p/>
* Example: get definitions API returns a list of definition objects as the result. This will be wrapped by an
* object. The object's name will be determined by invoking this service.
* eg. DefinitionList for a wrapper of 'definition's
*
* @param wrapperItemName
* @return
*/
public String getListWrapperName(String wrapperItemName) {
return applyClassNamingPolicy(wrapperItemName) + "_list";
}
/**
* Generates a name for an enum for the param or field name.
* <p/>
* Example: for a param source the return could be SourceEnum
*
* @param input
* @return
*/
public String getEnumName(String input) {
if (input != null && input.length() > 0) {
return this.applyClassNamingPolicy(input).concat("_values");
} else {
throw new CodeGenerationException("Error getting Enum name becuase of null input");
}
}
/**
* Gets the signature of the method that gets value for give attribute name.
*
* Example: If class name is user and attibute name is email the out in java language will be
* <code>user.getEmail()</code>
*
* @param className
* @param attributeName
* @return
*/
public String createGetterMethodName(String className, String attributeName) {
return className+".get_"+ applyClassNamingPolicy(attributeName)+"()";
}
}

View File

@ -1,274 +0,0 @@
/**
* 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.codegen.config.csharp;
import com.wordnik.swagger.codegen.config.DataTypeMappingProvider;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User: marek-stoj
* Date: 5/11/12
* Time: 5:56 PM
*/
public class CSharpDataTypeMappingProvider implements DataTypeMappingProvider {
private static final Map<String, String> _primitiveValueMap;
private static final Map<String, String> _primitiveObjectMap;
private NamingPolicyProvider _nameGenerator = new CSharpNamingPolicyProvider();
static {
_primitiveValueMap = new HashMap<String, String>();
_primitiveValueMap.put("string", "string");
_primitiveValueMap.put("String", "string");
_primitiveValueMap.put("int", "int");
_primitiveValueMap.put("integer", "int");
_primitiveValueMap.put("Integer", "int");
_primitiveValueMap.put("boolean", "bool");
_primitiveValueMap.put("Boolean", "bool");
_primitiveValueMap.put("long", "long");
_primitiveValueMap.put("Long", "long");
_primitiveValueMap.put("float", "float");
_primitiveValueMap.put("Float", "float");
_primitiveValueMap.put("Date", "DateTime");
_primitiveValueMap.put("date", "DateTime");
_primitiveValueMap.put("Byte", "byte");
_primitiveObjectMap = new HashMap<String, String>();
_primitiveObjectMap.put("string", "string");
_primitiveObjectMap.put("String", "string");
_primitiveObjectMap.put("java.lang.String", "string");
_primitiveObjectMap.put("int", "int");
_primitiveObjectMap.put("integer", "int");
_primitiveObjectMap.put("Integer", "int");
_primitiveObjectMap.put("java.lang.Integer", "int");
_primitiveObjectMap.put("boolean", "bool");
_primitiveObjectMap.put("Boolean", "bool");
_primitiveObjectMap.put("java.lang.Boolean", "bool");
_primitiveObjectMap.put("long", "long");
_primitiveObjectMap.put("Long", "long");
_primitiveObjectMap.put("java.lang.Long", "long");
_primitiveObjectMap.put("float", "float");
_primitiveObjectMap.put("Float", "float");
_primitiveObjectMap.put("java.lang.Float", "float");
_primitiveObjectMap.put("Date", "DateTime");
_primitiveObjectMap.put("date", "DateTime");
_primitiveObjectMap.put("java.util.Date", "DateTime");
_primitiveObjectMap.put("byte", "byte");
}
@Override
public boolean isPrimitiveType(String type) {
if (_primitiveObjectMap.containsKey(type)) {
return true;
}
return false;
}
@Override
public String getListReturnTypeSignature(String typeClass) {
return "List<" + _nameGenerator.applyClassNamingPolicy(typeClass) + ">";
}
@Override
public String getMapReturnTypeSignature(String typeClass) {
return "Dictionary<" + _nameGenerator.applyClassNamingPolicy(typeClass) + ">";
}
@Override
public String getSetReturnTypeSignature(String typeClass) {
return "HashSet<" + _nameGenerator.applyClassNamingPolicy(typeClass) + ">";
}
@Override
public String getArrayReturnTypeSignature(String typeClass) {
return _nameGenerator.applyClassNamingPolicy(typeClass) + "[]";
}
@Override
public String generateListInitialization(String typeClass) {
return " new List<" + _nameGenerator.applyClassNamingPolicy(typeClass) + ">()";
}
@Override
public String generateMapInitialization(String typeClass) {
return " new Dictionary<" + _nameGenerator.applyClassNamingPolicy(typeClass) + ">()";
}
@Override
public String generateSetInitialization(String typeClass) {
return " new HashSet<" + _nameGenerator.applyClassNamingPolicy(typeClass) + ">()";
}
@Override
public String generateArrayInitialization(String typeClass) {
return " null";
}
@Override
public List<String> getListIncludes() {
List<String> imports = new ArrayList<String>();
imports.add("System.Collections.Generic");
return imports;
}
@Override
public List<String> getMapIncludes() {
List<String> imports = new ArrayList<String>();
imports.add("System.Collections.Generic");
return imports;
}
@Override
public List<String> getSetIncludes() {
List<String> imports = new ArrayList<String>();
imports.add("System.Collections.Generic");
return imports;
}
@Override
public List<String> getDateIncludes() {
return new ArrayList<String>();
}
/**
* Gets the short name of the class the class.
* Input can be MAP, LIST or regular string. In case of map or list the class name will be class name
* that map or list is returning.
* @param type
* @return
*/
@Override
public String getGenericType(String type) {
String classShortName = "";
if (type.startsWith("List[")) {
classShortName = type.substring(5, type.length() - 1);
classShortName = getClassType(classShortName, true);
}
else if (type.startsWith("Map[")) {
classShortName = type.substring(4, type.length() - 1);
classShortName = getClassType(classShortName, true);
}
else if (type.startsWith("Set[")) {
classShortName = type.substring(4, type.length() - 1);
classShortName = getClassType(classShortName, true);
}
else if (type.startsWith("Array[")) {
classShortName = type.substring(6, type.length() - 1);
classShortName = getClassType(classShortName, true);
}
else if (type.equalsIgnoreCase("ok")) {
classShortName = "void";
}
else {
classShortName = getClassType(type, true);
}
return classShortName;
}
/**
* Returns the syntax for defintion of an object of type and name
*
* @param argumentType
* @param argumentName
* @return
*/
@Override
public String getArgumentDefinition(String argumentType, String argumentName) {
return argumentType + " " + argumentName;
}
/**
* Gets the class of the expected return value for a type string. Examples of type Strings are int, User, List[User]
* If the type string is a collection type like a map or list the string value returned would be the class
* that map or list is returning.
*
* @param type
* @return
*/
@Override
public String getClassType(String type, boolean primitiveObject) {
if (type.equalsIgnoreCase("void") || type.equalsIgnoreCase("ok")) {
return "void";
}
String classShortName = "";
if (type.startsWith("List[")) {
classShortName = type.substring(5, type.length() - 1);
classShortName = "List<" + getClassType(classShortName, true) + ">";
}
else if (type.startsWith("Map[")) {
classShortName = type.substring(4, type.length() - 1);
String[] mapTypes = classShortName.split(",");
classShortName = "Map<" + getClassType(mapTypes[0], true) + "," + getClassType(mapTypes[1], true) + ">";
}
else if (type.startsWith("Set[")) {
classShortName = type.substring(4, type.length() - 1);
classShortName = "Set<" + getClassType(classShortName, true) + ">";
}
else if (type.startsWith("Array[")) {
classShortName = type.substring(6, type.length() - 1);
classShortName = getClassName(classShortName, true) + "[]";
}
else {
classShortName = getClassName(type, true);
}
return classShortName;
}
/**
* If the data type is primitive and it is expecting object structure then return primitive objects
* else return primitive types
* @param type
* @param primitiveObject -- indicates if the object is primitive or not
* @return
*/
private String getClassName(String type, boolean primitiveObject) {
if (isPrimitiveType(type)) {
if (primitiveObject) {
return _primitiveObjectMap.get(type);
}
else {
return _primitiveValueMap.get(type);
}
}
else {
return _nameGenerator.applyClassNamingPolicy(type);
}
}
@Override
public String generateVariableInitialization(String typeClass) {
return "";
}
}

View File

@ -1,122 +0,0 @@
/**
* 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.codegen.config.csharp;
import com.wordnik.swagger.codegen.LibraryCodeGenerator;
import com.wordnik.swagger.codegen.config.ApiConfiguration;
import com.wordnik.swagger.codegen.config.LanguageConfiguration;
import com.wordnik.swagger.codegen.exception.CodeGenerationException;
import com.wordnik.swagger.codegen.util.FileUtil;
import java.io.File;
/**
* User: marek-stoj
* Date: 5/11/12
* Time: 5:56 PM
*/
public class CSharpLibCodeGen extends LibraryCodeGenerator {
public static void main(String[] args) {
if (args.length < 1) {
throw new CodeGenerationException("Invalid number of arguments passed: No command line argument was passed to the program for config json");
}
if (args.length == 1) {
String configPath = args[0];
CSharpLibCodeGen codeGenerator = new CSharpLibCodeGen(configPath);
codeGenerator.generateCode();
}
if (args.length == 4) {
String apiServerURL = args[0];
if (!apiServerURL.endsWith("/")) {
apiServerURL = apiServerURL + "/";
}
String apiKey = args[1];
String packageName = args[2];
String libraryHome = args[3];
if (libraryHome.endsWith("/")) {
libraryHome = libraryHome.substring(0, libraryHome.length() - 1);
}
String modelPackageName = packageName + ".Model";
String apiPackageName = packageName + ".Api";
String classOutputDir = libraryHome + "/" + packageName.replace(".", "/");
CSharpLibCodeGen codeGenerator =
new CSharpLibCodeGen(
apiServerURL,
apiKey,
modelPackageName,
apiPackageName,
classOutputDir,
libraryHome);
ApiConfiguration config = codeGenerator.getConfig();
config.setDefaultServiceBaseClass("ApiBase");
codeGenerator.generateCode();
}
}
public CSharpLibCodeGen(String apiServerURL, String apiKey, String modelPackageName, String apiPackageName, String classOutputDir, String libraryHome) {
super(apiServerURL, apiKey, modelPackageName, apiPackageName, classOutputDir, "Model", "Api", libraryHome);
this.setDataTypeMappingProvider(new CSharpDataTypeMappingProvider());
this.setNameGenerator(new CSharpNamingPolicyProvider());
}
public CSharpLibCodeGen(String configPath) {
super(configPath);
this.setDataTypeMappingProvider(new CSharpDataTypeMappingProvider());
this.setNameGenerator(new CSharpNamingPolicyProvider());
}
@Override
protected LanguageConfiguration initializeLangConfig(LanguageConfiguration cSharpConfiguration) {
cSharpConfiguration.setClassFileExtension(".cs");
cSharpConfiguration.setTemplateLocation("conf/csharp/templates");
cSharpConfiguration.setStructureLocation("conf/csharp/structure");
cSharpConfiguration.setExceptionPackageName("Swagger.Exceptions");
cSharpConfiguration.setAnnotationPackageName("Swagger.Attributes");
cSharpConfiguration.setMethodOverloadingSupported(true);
FileUtil.createOutputDirectories(cSharpConfiguration.getModelClassLocation(), cSharpConfiguration.getClassFileExtension());
FileUtil.createOutputDirectories(cSharpConfiguration.getResourceClassLocation(), cSharpConfiguration.getClassFileExtension());
FileUtil.clearFolder(cSharpConfiguration.getModelClassLocation());
FileUtil.clearFolder(cSharpConfiguration.getResourceClassLocation());
FileUtil.copyDirectoryFromUrl(
this.getClass().getClassLoader().getResource(cSharpConfiguration.getStructureLocation()),
new File(cSharpConfiguration.getResourceClassLocation()).getParentFile().getParentFile());
return cSharpConfiguration;
}
@Override
protected boolean canEnumNameStartsWithNumber() {
return false;
}
}

View File

@ -1,211 +0,0 @@
/**
* 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.codegen.config.csharp;
import com.wordnik.swagger.codegen.exception.CodeGenerationException;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
/**
* User: marek-stoj
* Date: 5/11/12
* Time: 5:56 PM
*/
public class CSharpNamingPolicyProvider implements NamingPolicyProvider {
public static String INPUT_OBJECT_SUFFIX = "Input";
/**
* gets the name of class that is responsible for tracking current library version
* @return
*/
@Override
public String getVersionCheckerClassName() {
return "VersionChecker";
}
/**
* Converts the first character of the input into upper case .
* Example: If the input is word, the return value will be Word
* @param input
* @return
*/
@Override
public String applyClassNamingPolicy(String input) {
if (input != null && input.length() > 0) {
if ("string".equalsIgnoreCase(input)) {
return "string";
}
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
// class name can't have . so if dot exists remove the same
output = output.replace(".", "");
return output;
}
else {
throw new CodeGenerationException("Error converting input to first letter caps becuase of null or empty input");
}
}
/**
* Converts the first character of the input into upper case.
* Example: If the input is getWord, the return value will be GetWord
* @param input
* @return
*/
@Override
public String applyMethodNamingPolicy(String input) {
if (input != null && input.length() > 0) {
return input.substring(0, 1).toUpperCase() + input.substring(1);
}
else {
throw new CodeGenerationException("Error converting input to first letter to upper because of null or empty input");
}
}
/**
* Generate name of the service from resource path.
*
* Example: if input is /user.json the generated name for this path will be UserAPI
* If the input is /user.json/{userId}, the service name will still be generated as UserAPI
*
* @param resourcePath
* @return
*/
@Override
public String getServiceName(String resourcePath) {
String className = null;
int index = resourcePath.indexOf(".");
if (index >= 0) {
String resourceName = resourcePath.substring(1, index);
className = applyClassNamingPolicy(resourceName);
}
else {
String[] paths = resourcePath.split("/");
for (String path : paths) {
if (path != null && path.length() > 0) {
className = applyClassNamingPolicy(path);
break;
}
}
}
return className + "Api";
}
/**
* Generates the name of service methods.
*
* Resource documentation provides suggested names. Individual language can choose to use suggested name or
* generate the name based on end point path. Example: IN java we use suggested name
*
* @param endPoint
* @param suggestedName
* @return
*/
@Override
public String getMethodName(String endPoint, String suggestedName) {
return suggestedName;
}
/**
* For input UserAPI and resource path /findUserById the suggested input object name will be: UserFindUserByIdInput
*
* If the input path is /{userId}/delete the suggested name will be UserDeleteInput. The path parameters are ignored
* in generating the input object name
*
* Note: Input objects are only created when the number of input arguments in a method exceeds certain number so <br/> that the method signatures are clean
*
*
* @param serviceName
* @param resourcePath
* @return
*/
@Override
public String getInputObjectName(String serviceName, String resourcePath) {
// Since service name has Api at the end remove that format he name
String inputobjectName = serviceName.substring(0, serviceName.length() - 3);
String[] pathElements = resourcePath.split("/");
StringBuilder urlPath = new StringBuilder("");
if (pathElements != null) {
for (int i = 0; i < pathElements.length; i++) {
String pathElement = pathElements[i];
if (pathElement != null && pathElement.length() > 0) {
int position = pathElement.indexOf("{");
if (position < 0) {
inputobjectName = inputobjectName + applyClassNamingPolicy(pathElement) + INPUT_OBJECT_SUFFIX;
}
}
}
}
return inputobjectName;
}
/**
* Generate the name of the wrapper class used as a wrapper for a list of items returned by a service
* <p/>
* Example: get definitions API returns a list of definition objects as the result. This will be wrapped by an
* object. The object's name will be determined by invoking this service.
* eg. DefinitionList for a wrapper of 'definition's
*
* @param wrapperItemName
* @return
*/
@Override
public String getListWrapperName(String wrapperItemName) {
return applyClassNamingPolicy(wrapperItemName) + "List";
}
/**
* Generates a name for an enum for the param or field name.
* <p/>
* Example: for a param source the return could be SourceEnum
*
* @param input
* @return
*/
@Override
public String getEnumName(String input) {
if (input != null && input.length() > 0) {
return this.applyClassNamingPolicy(input).concat("Values");
}
else {
throw new CodeGenerationException("Error getting Enum name becuase of null input");
}
}
/**
* Gets the signature of the method that gets value for give attribute name.
*
* Example: If class name is user and attibute name is email the out in java language will be
* <code>user.getEmail()</code>
*
* @param className
* @param attributeName
* @return
*/
@Override
public String createGetterMethodName(String className, String attributeName) {
return className + "." + applyClassNamingPolicy(attributeName);
}
}

View File

@ -1,244 +0,0 @@
/**
* 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.codegen.config.java;
import com.wordnik.swagger.codegen.config.DataTypeMappingProvider;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User: ramesh
* Date: 5/31/11
* Time: 7:03 AM
*/
public class JavaDataTypeMappingProvider implements DataTypeMappingProvider {
public static Map<String, String> primitiveValueMap = new HashMap<String, String>();
static{
primitiveValueMap.put("string", "String");
primitiveValueMap.put("String", "String");
primitiveValueMap.put("int", "int");
primitiveValueMap.put("integer", "int");
primitiveValueMap.put("Integer", "int");
primitiveValueMap.put("boolean", "boolean");
primitiveValueMap.put("Boolean", "boolean");
primitiveValueMap.put("long", "long");
primitiveValueMap.put("Long", "long");
primitiveValueMap.put("float", "float");
primitiveValueMap.put("Float", "float");
primitiveValueMap.put("Date", "Date");
primitiveValueMap.put("date", "Date");
primitiveValueMap.put("Byte", "byte");
}
public static Map<String, String> primitiveObjectMap = new HashMap<String, String>();
static{
primitiveObjectMap.put("string", "String");
primitiveObjectMap.put("String", "String");
primitiveObjectMap.put("java.lang.String", "String");
primitiveObjectMap.put("int", "Integer");
primitiveObjectMap.put("integer", "Integer");
primitiveObjectMap.put("Integer", "Integer");
primitiveObjectMap.put("java.lang.Integer", "Integer");
primitiveObjectMap.put("boolean", "Boolean");
primitiveObjectMap.put("Boolean", "Boolean");
primitiveObjectMap.put("java.lang.Boolean", "Boolean");
primitiveObjectMap.put("long", "Long");
primitiveObjectMap.put("Long", "Long");
primitiveObjectMap.put("java.lang.Long", "Long");
primitiveObjectMap.put("float", "Float");
primitiveObjectMap.put("Float", "Float");
primitiveObjectMap.put("java.lang.Float", "Float");
primitiveObjectMap.put("Date", "Date");
primitiveObjectMap.put("date", "Date");
primitiveObjectMap.put("java.util.Date", "Date");
primitiveObjectMap.put("byte", "byte");
}
private NamingPolicyProvider nameGenerator = new CamelCaseNamingPolicyProvider();
public boolean isPrimitiveType(String type) {
if(primitiveObjectMap.containsKey(type)){
return true;
}
return false;
}
public String getListReturnTypeSignature(String typeClass) {
return "List<"+nameGenerator.applyClassNamingPolicy(typeClass)+">";
}
public String getMapReturnTypeSignature(String typeClass) {
return "Map<"+nameGenerator.applyClassNamingPolicy(typeClass)+">";
}
public String getSetReturnTypeSignature(String typeClass) {
return "Set<"+nameGenerator.applyClassNamingPolicy(typeClass)+">";
}
public String getArrayReturnTypeSignature(String typeClass) {
return nameGenerator.applyClassNamingPolicy(typeClass)+"[]";
}
public String generateListInitialization(String typeClass) {
return " new ArrayList<"+nameGenerator.applyClassNamingPolicy(typeClass)+">()";
}
public String generateMapInitialization(String typeClass) {
return " new HashMap<"+nameGenerator.applyClassNamingPolicy(typeClass)+">()";
}
public String generateSetInitialization(String typeClass) {
return " new HashSet<"+nameGenerator.applyClassNamingPolicy(typeClass)+">()";
}
public String generateArrayInitialization(String typeClass) {
return " null";
}
public List<String> getListIncludes() {
List<String> imports = new ArrayList<String>();
imports.add("java.util.List");
imports.add("java.util.ArrayList");
return imports;
}
public List<String> getMapIncludes() {
List<String> imports = new ArrayList<String>();
imports.add("java.util.Map");
imports.add("java.util.HashMap");
return imports;
}
public List<String> getSetIncludes() {
List<String> imports = new ArrayList<String>();
imports.add("java.util.Set");
imports.add("java.util.HashSet");
return imports; }
public List<String> getDateIncludes() {
List<String> imports = new ArrayList<String>();
imports.add("java.util.Date");
return imports;
}
/**
* Gets the short name of the class the class.
* Input can be MAP, LIST or regular string. In case of map or list the class name will be class name
* that map or list is returning.
* @param type
* @return
*/
public String getGenericType(String type) {
String classShortName = "";
if(type.startsWith("List[")){
classShortName = type.substring(5, type.length()-1);
classShortName = getClassType(classShortName, true);
}else if (type.startsWith("Map[")) {
classShortName = type.substring(4, type.length()-1);
classShortName = getClassType(classShortName, true);
}else if (type.startsWith("Set[")) {
classShortName = type.substring(4, type.length()-1);
classShortName = getClassType(classShortName, true);
}else if (type.startsWith("Array[")) {
classShortName = type.substring(6, type.length()-1);
classShortName = getClassType(classShortName, true);
}else if (type.equalsIgnoreCase("ok")) {
classShortName = "void";
}else{
classShortName = getClassType(type, true);
}
return classShortName;
}
/**
* Returns the syntax for defintion of an object of type and name
*
* @param argumentType
* @param argumentName
* @return
*/
public String getArgumentDefinition(String argumentType, String argumentName) {
return argumentType + " " + argumentName;
}
/**
* Gets the class of the expected return value for a type string. Examples of type Strings are int, User, List[User]
* If the type string is a collection type like a map or list the string value returned would be the class
* that map or list is returning.
*
* @param type
* @return
*/
public String getClassType(String type, boolean primitiveObject) {
if(type.equalsIgnoreCase("void")|| type.equalsIgnoreCase("ok")){
return "void";
}
String classShortName = "";
if(type.startsWith("List[")){
classShortName = type.substring(5, type.length()-1);
classShortName = "List<"+ getClassType(classShortName, true)+">";
}else if (type.startsWith("Map[")) {
classShortName = type.substring(4, type.length()-1);
String[] mapTypes = classShortName.split(",");
classShortName = "Map<"+ getClassType(mapTypes[0], true) + "," + getClassType(mapTypes[1], true) +">";
}else if (type.startsWith("Set[")) {
classShortName = type.substring(4, type.length()-1);
classShortName = "Set<"+ getClassType(classShortName, true) +">";
}else if (type.startsWith("Array[")) {
classShortName = type.substring(6, type.length()-1);
classShortName = getClassName(classShortName, true) +"[]";
}else{
classShortName = getClassName(type, true);
}
return classShortName;
}
/**
* If the data type is primitive and it is expecting object structure then return primitive objects
* else return primitive types
* @param type
* @param primitiveObject -- indicates if the object is primitive or not
* @return
*/
private String getClassName(String type, boolean primitiveObject) {
if(isPrimitiveType(type)){
if(primitiveObject){
return primitiveObjectMap.get(type);
}else{
return primitiveValueMap.get(type);
}
}else{
return nameGenerator.applyClassNamingPolicy(type);
}
}
@Override
public String generateVariableInitialization(String typeClass) {
return "";
}
}

View File

@ -1,107 +0,0 @@
/**
* 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.codegen.config.java;
import com.wordnik.swagger.codegen.LibraryCodeGenerator;
import com.wordnik.swagger.codegen.config.LanguageConfiguration;
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider;
import com.wordnik.swagger.codegen.exception.CodeGenerationException;
import com.wordnik.swagger.codegen.util.FileUtil;
import java.io.File;
/**
* User: ramesh
* Date: 6/16/11
* Time: 1:31 PM
*/
public class JavaLibCodeGen extends LibraryCodeGenerator {
public static void main(String[] args) {
if(args.length < 1){
throw new CodeGenerationException("Invalid number of arguments passed: No command line argument was passed to the program for config json");
}
if(args.length == 1) {
String configPath = args[0];
JavaLibCodeGen codeGenerator = new JavaLibCodeGen(configPath);
codeGenerator.generateCode();
}
if(args.length == 4) {
String apiServerURL = args[0];
if(!apiServerURL.endsWith("/")){
apiServerURL = apiServerURL + "/";
}
String apiKey = args[1];
String packageName = args[2];
String libraryHome = args[3];
if(libraryHome.endsWith("/")){
libraryHome = libraryHome.substring(0, libraryHome.length()-1);
}
String modelPackageName = packageName+".model";
String apiPackageName = packageName+".api";
String classOutputDir = libraryHome + "/src/main/java/" + packageName.replace(".","/");
JavaLibCodeGen codeGenerator = new JavaLibCodeGen(apiServerURL, apiKey, modelPackageName,
apiPackageName, classOutputDir, libraryHome);
codeGenerator.generateCode();
}
}
public JavaLibCodeGen(String apiServerURL, String apiKey, String modelPackageName, String apiPackageName,
String classOutputDir, String libraryHome){
super(apiServerURL, apiKey, modelPackageName, apiPackageName, classOutputDir, libraryHome);
this.setDataTypeMappingProvider(new JavaDataTypeMappingProvider());
this.setNameGenerator(new CamelCaseNamingPolicyProvider());
}
public JavaLibCodeGen(String configPath){
super(configPath);
this.setDataTypeMappingProvider(new JavaDataTypeMappingProvider());
this.setNameGenerator(new CamelCaseNamingPolicyProvider());
}
@Override
protected LanguageConfiguration initializeLangConfig(LanguageConfiguration javaConfiguration) {
javaConfiguration.setClassFileExtension(".java");
javaConfiguration.setTemplateLocation("conf/java/templates");
javaConfiguration.setStructureLocation("conf/java/structure");
javaConfiguration.setExceptionPackageName("com.wordnik.swagger.exception");
javaConfiguration.setAnnotationPackageName("com.wordnik.swagger.annotations");
//create ouput directories
FileUtil.createOutputDirectories(javaConfiguration.getModelClassLocation(), javaConfiguration.getClassFileExtension());
FileUtil.createOutputDirectories(javaConfiguration.getResourceClassLocation(), javaConfiguration.getClassFileExtension());
FileUtil.clearFolder(javaConfiguration.getModelClassLocation());
FileUtil.clearFolder(javaConfiguration.getResourceClassLocation());
FileUtil.clearFolder(javaConfiguration.getLibraryHome() + "/src/main/java/com/wordnik/swagger/runtime");
FileUtil.createOutputDirectories(javaConfiguration.getLibraryHome() + "/src/main/java/com/wordnik/swagger/runtime", "java");
try{
FileUtil.copyDirectoryFromUrl(this.getClass().getClassLoader().getResource("conf/java/structure/src/main/java"), new File(javaConfiguration.getLibraryHome() + "/src/main/java"));
}catch(Exception e){
e.printStackTrace();
}
return javaConfiguration;
}
@Override
protected boolean canEnumNameStartsWithNumber() {
return false;
}
}

View File

@ -1,204 +0,0 @@
package com.wordnik.swagger.codegen.config.js;
import com.wordnik.swagger.codegen.config.DataTypeMappingProvider;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User: ramesh
* Date: 5/31/11
* Time: 7:03 AM
*/
public class JSDataTypeMappingProvider implements DataTypeMappingProvider {
public static Map<String, String> primitiveValueMap = new HashMap<String, String>();
static{
primitiveValueMap.put("string", "String");
primitiveValueMap.put("String", "String");
primitiveValueMap.put("int", "Number");
primitiveValueMap.put("integer", "Number");
primitiveValueMap.put("Integer", "Number");
primitiveValueMap.put("boolean", "Boolean");
primitiveValueMap.put("Boolean", "Boolean");
primitiveValueMap.put("long", "Number");
primitiveValueMap.put("Long", "Number");
primitiveValueMap.put("double", "Number");
primitiveValueMap.put("Double", "Number");
primitiveValueMap.put("float", "Number");
primitiveValueMap.put("Float", "Number");
primitiveValueMap.put("Date", "Date");
primitiveValueMap.put("date", "Date");
primitiveValueMap.put("byte", "byte");
}
public static Map<String, String> primitiveObjectMap = new HashMap<String, String>();
static{
primitiveObjectMap.put("string", "String");
primitiveObjectMap.put("String", "String");
primitiveObjectMap.put("int", "Number");
primitiveObjectMap.put("integer", "Number");
primitiveObjectMap.put("Integer", "Number");
primitiveObjectMap.put("boolean", "Boolean");
primitiveObjectMap.put("Boolean", "Boolean");
primitiveObjectMap.put("long", "Number");
primitiveObjectMap.put("Long", "Number");
primitiveObjectMap.put("double", "Number");
primitiveObjectMap.put("Double", "Number");
primitiveObjectMap.put("float", "Number");
primitiveObjectMap.put("Float", "Number");
primitiveObjectMap.put("Date", "Date");
primitiveObjectMap.put("date", "Date");
primitiveObjectMap.put("byte", "Byte");
}
private NamingPolicyProvider nameGenerator = new CamelCaseNamingPolicyProvider();
public boolean isPrimitiveType(String type) {
if(type.equalsIgnoreCase("String") || type.equalsIgnoreCase("int") || type.equalsIgnoreCase("integer") || type.equalsIgnoreCase("double") ||
type.equalsIgnoreCase("boolean") || type.equalsIgnoreCase("float")|| type.equalsIgnoreCase("long") || type.equalsIgnoreCase("Number") ){
return true;
}
return false;
}
/**
* If the data type is primitive and it is expecting object structure then return primitive objects
* else return primitive types
* @param type
* @param primitiveObject -- indicates if the object is primitive or not
* @return
*/
public String getObjectType(String type, boolean primitiveObject) {
if(isPrimitiveType(type)){
if(primitiveObject){
return primitiveObjectMap.get(type);
}else{
return primitiveValueMap.get(type);
}
}else{
return nameGenerator.applyClassNamingPolicy(type);
}
}
public String getListReturnTypeSignature(String typeClass) {
return "Array";
}
public String getReturnTypeForVoidMethods() {
return "void";
}
public String getMapReturnTypeSignature(String typeClass) {
return "Object";
}
public String getSetReturnTypeSignature(String typeClass) {
return "Array";
}
public String getArrayReturnTypeSignature(String typeClass) {
return "Array";
}
public String generateListInitialization(String typeClass) {
return " new Array()";
}
public String generateMapInitialization(String typeClass) {
return " new Object()";
}
public String generateSetInitialization(String typeClass) {
return " new Array()";
}
public String generateArrayInitialization(String typeClass) {
return " new Array()";
}
public List<String> getListIncludes() {
List<String> imports = new ArrayList<String>();
return imports;
}
public List<String> getMapIncludes() {
List<String> imports = new ArrayList<String>();
return imports;
}
public List<String> getSetIncludes() {
List<String> imports = new ArrayList<String>();
return imports; }
public List<String> getDateIncludes() {
List<String> imports = new ArrayList<String>();
return imports;
}
/**
* Gets the short name of the class the class.
* Input can be MAP, LIST or regular string. In case of map or list the class name will be class name
* that map or list is returning.
* @param type
* @return
*/
public String getClassType(String type, boolean primitiveObject) {
String classShortName = "";
if(type.startsWith("List[")){
classShortName = type.substring(5, type.length()-1);
classShortName = getObjectType(classShortName, true);
}else if (type.startsWith("Map[")) {
classShortName = type.substring(4, type.length()-1);
classShortName = getObjectType(classShortName, true);
}else if (type.startsWith("Set[")) {
classShortName = type.substring(4, type.length()-1);
classShortName = getObjectType(classShortName, true);
}else if (type.startsWith("Array[")) {
classShortName = type.substring(6, type.length()-1);
classShortName = getObjectType(classShortName, true);
}else if (type.equals("ok")) {
classShortName = "void";
}else{
classShortName = getObjectType(type, true);
}
return classShortName;
}
public String getArgumentDefinition(String argumentType, String argumentName) {
return argumentName + ": " + argumentType;
}
/**
* Gets the class of the expected return value for a type string. Examples of type Strings are int, User, List[User]
* If the type string is a collection type like a map or list the string value returned would be the class
* that map or list is returning.
*
* @param type
* @return
*/
public String getGenericType(String type) {
if(type.equalsIgnoreCase("void")|| type.equalsIgnoreCase("ok")){
return "void";
}
String classShortName = "";
if(type.startsWith("List[") || type.startsWith("Map[") || type.startsWith("Set[") || type.startsWith("Array[")){
classShortName = "Array";
}else{
classShortName = getObjectType(type, true);
}
return classShortName;
}
public String generateVariableInitialization(String typeClass) {
return "";
}
}

View File

@ -1,132 +0,0 @@
package com.wordnik.swagger.codegen.config.js;
import com.wordnik.swagger.codegen.LibraryCodeGenerator;
import com.wordnik.swagger.codegen.config.LanguageConfiguration;
import com.wordnik.swagger.codegen.exception.CodeGenerationException;
import com.wordnik.swagger.codegen.util.FileUtil;
import java.io.*;
/**
* @author ayush
* @since 10/24/11 7:47 PM
*/
public class JSLibCodeGen extends LibraryCodeGenerator {
private static final String DEFAULT_SERVICE_BASE_CLASS = "SwaggerApi";
public static void main(String[] args) {
if (args.length < 1) {
throw new CodeGenerationException("Invalid number of arguments passed: No command line argument was passed to the program for config json");
}
String libraryHome = null;
if (args.length == 1) {
String configPath = args[0];
JSLibCodeGen codeGenerator = new JSLibCodeGen(configPath);
codeGenerator.generateCode();
libraryHome = codeGenerator.getLanguageConfig().getLibraryHome();
}
if (args.length == 3) {
String apiServerURL = args[0];
if (!apiServerURL.endsWith("/")) {
apiServerURL = apiServerURL + "/";
}
String apiKey = args[1];
String packageName = args[2];
libraryHome = args[2];
if (libraryHome.endsWith("/")) {
libraryHome = libraryHome.substring(0, libraryHome.length() - 1);
}
String modelPackageName = "";
String apiPackageName = "";
String classOutputDir = libraryHome + "/src/main/js/";
JSLibCodeGen codeGenerator = new JSLibCodeGen(apiServerURL, apiKey, modelPackageName,
apiPackageName, classOutputDir, libraryHome);
codeGenerator.getConfig().setDefaultServiceBaseClass(DEFAULT_SERVICE_BASE_CLASS);
codeGenerator.generateCode();
}
try {
if (libraryHome != null) {
concatinateFiles(libraryHome + "/api-lib.js", libraryHome + "/src/main/js/");
}
} catch (IOException e) {
System.out.println("Unable to combine files");
e.printStackTrace();
}
}
private static void concatinateFiles(String outFile, String sourcePath) throws IOException {
final PrintWriter pw = new PrintWriter(new FileOutputStream(outFile));
final File file = new File(sourcePath);
System.out.println("Scanning " + file);
appendFiles(pw, file.listFiles());
final File modelSource = new File(file, "model");
System.out.println("Scanning " + modelSource.getAbsolutePath());
appendFiles(pw, modelSource.listFiles());
final File apiSource = new File(file, "api");
System.out.println("Scanning " + apiSource.getAbsolutePath());
appendFiles(pw, apiSource.listFiles());
pw.close();
System.out.println("Concatenated to " + outFile);
}
private static void appendFiles(PrintWriter pw, File[] files) throws IOException {
for (int i = 0; i < files.length; i++) {
System.out.println("Processing " + files[i].getPath() + "...");
if(!files[i].isDirectory()) {
BufferedReader br = new BufferedReader(new FileReader(files[i]
.getPath()));
String line = br.readLine();
while (line != null) {
pw.println(line);
line = br.readLine();
}
br.close();
}
}
}
public JSLibCodeGen(String apiServerURL, String apiKey, String modelPackageName, String apiPackageName,
String classOutputDir, String libraryHome) {
super(apiServerURL, apiKey, modelPackageName, apiPackageName, classOutputDir, libraryHome);
this.setDataTypeMappingProvider(new JSDataTypeMappingProvider());
this.setNameGenerator(new JSNamingPolicyProvider());
}
public JSLibCodeGen(String configPath) {
super(configPath);
this.setDataTypeMappingProvider(new JSDataTypeMappingProvider());
this.setNameGenerator(new JSNamingPolicyProvider());
}
@Override
protected LanguageConfiguration initializeLangConfig(LanguageConfiguration jsConfiguration) {
jsConfiguration.setClassFileExtension(".js");
jsConfiguration.setTemplateLocation("conf/js/templates");
jsConfiguration.setStructureLocation("conf/js/structure");
jsConfiguration.setExceptionPackageName("com.wordnik.swagger.exception");
jsConfiguration.setAnnotationPackageName("com.wordnik.swagger.annotations");
//create ouput directories
FileUtil.createOutputDirectories(jsConfiguration.getModelClassLocation(), jsConfiguration.getClassFileExtension());
FileUtil.createOutputDirectories(jsConfiguration.getResourceClassLocation(), jsConfiguration.getClassFileExtension());
//delete previously generated files
FileUtil.clearFolder(jsConfiguration.getModelClassLocation());
FileUtil.clearFolder(jsConfiguration.getResourceClassLocation());
FileUtil.clearFolder(jsConfiguration.getLibraryHome() + "/src/main/js/com/wordnik/swagger/common");
FileUtil.clearFolder(jsConfiguration.getLibraryHome() + "/src/main/js/com/wordnik/swagger/exception");
FileUtil.clearFolder(jsConfiguration.getLibraryHome() + "/src/main/js/com/wordnik/swagger/event");
FileUtil.copyDirectoryFromUrl(this.getClass().getClassLoader().getResource(jsConfiguration.getStructureLocation()), new File(jsConfiguration.getLibraryHome()));
jsConfiguration.setModelEnumRequired(false);
jsConfiguration.setOutputWrapperRequired(true);
return jsConfiguration;
}
}

View File

@ -1,24 +0,0 @@
package com.wordnik.swagger.codegen.config.js;
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider;
/**
* @author ayush
* @since oct 24 2011
*/
public class JSNamingPolicyProvider extends CamelCaseNamingPolicyProvider {
/**
* Gets the signature of the method that gets value for give attribute name.
*
* Example: If class name is user and attibute name is email the out in java language will be
* <code>user.getEmail()</code>
*
* @param className
* @param attributeName
* @return
*/
public String createGetterMethodName(String className, String attributeName) {
return className+"."+ attributeName;
}
}

View File

@ -1,241 +0,0 @@
/**
* 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.codegen.config.php;
import com.wordnik.swagger.codegen.config.DataTypeMappingProvider;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User: ramesh
* Date: 5/31/11
* Time: 7:03 AM
*/
public class PHPDataTypeMappingProvider implements DataTypeMappingProvider {
public static Map<String, String> primitiveValueMap = new HashMap<String, String>();
static{
primitiveValueMap.put("string", "string");
primitiveValueMap.put("String", "string");
primitiveValueMap.put("int", "int");
primitiveValueMap.put("integer", "int");
primitiveValueMap.put("Integer", "int");
primitiveValueMap.put("boolean", "bool");
primitiveValueMap.put("Boolean", "bool");
primitiveValueMap.put("long", "int");
primitiveValueMap.put("Long", "int");
primitiveValueMap.put("float", "float");
primitiveValueMap.put("Float", "float");
primitiveValueMap.put("Date", "string");
primitiveValueMap.put("date", "string");
primitiveValueMap.put("Double", "float");
primitiveValueMap.put("double", "float");
primitiveValueMap.put("byte", "byte");
primitiveValueMap.put("Byte", "byte");
}
public static Map<String, String> primitiveObjectMap = new HashMap<String, String>();
static{
primitiveObjectMap.put("string", "string");
primitiveObjectMap.put("String", "string");
primitiveObjectMap.put("java.lang.String", "string");
primitiveObjectMap.put("int", "int");
primitiveObjectMap.put("integer", "int");
primitiveObjectMap.put("Integer", "int");
primitiveObjectMap.put("java.lang.Integer", "int");
primitiveObjectMap.put("bool", "bool");
primitiveObjectMap.put("boolean", "bool");
primitiveObjectMap.put("Boolean", "bool");
primitiveObjectMap.put("java.lang.Boolean", "bool");
primitiveObjectMap.put("long", "int");
primitiveObjectMap.put("Long", "int");
primitiveObjectMap.put("java.lang.Long", "int");
primitiveObjectMap.put("float", "float");
primitiveObjectMap.put("Float", "float");
primitiveObjectMap.put("double", "float");
primitiveObjectMap.put("Double", "float");
primitiveObjectMap.put("java.lang.Float", "float");
primitiveObjectMap.put("Date", "string");
primitiveObjectMap.put("date", "string");
primitiveObjectMap.put("java.util.Date", "string");
primitiveObjectMap.put("Byte", "byte");
}
private NamingPolicyProvider nameGenerator = new CamelCaseNamingPolicyProvider();
public boolean isPrimitiveType(String type) {
if(primitiveObjectMap.containsKey(type)){
return true;
}
return false;
}
public String getListReturnTypeSignature(String typeClass) {
if (isPrimitiveType(typeClass)) {
return "array<"+typeClass+">";
} else {
return "array<"+nameGenerator.applyClassNamingPolicy(typeClass)+">";
}
}
public String getMapReturnTypeSignature(String typeClass) {
return "array<"+nameGenerator.applyClassNamingPolicy(typeClass)+">";
}
public String getSetReturnTypeSignature(String typeClass) {
return "array<"+nameGenerator.applyClassNamingPolicy(typeClass)+">";
}
public String getArrayReturnTypeSignature(String typeClass) {
return "array<"+nameGenerator.applyClassNamingPolicy(typeClass)+">";
}
public String generateListInitialization(String typeClass) {
return " array()";
}
public String generateMapInitialization(String typeClass) {
return " array()";
}
public String generateSetInitialization(String typeClass) {
return " array()";
}
public String generateArrayInitialization(String typeClass) {
return " array()";
}
public List<String> getListIncludes() {
List<String> imports = new ArrayList<String>();
return imports;
}
public List<String> getMapIncludes() {
List<String> imports = new ArrayList<String>();
return imports;
}
public List<String> getSetIncludes() {
List<String> imports = new ArrayList<String>();
return imports; }
public List<String> getDateIncludes() {
List<String> imports = new ArrayList<String>();
return imports;
}
/**
* Gets the short name of the class the class.
* Input can be MAP, LIST or regular string. In case of map or list the class name will be class name
* that map or list is returning.
* @param type
* @return
*/
public String getGenericType(String type) {
String classShortName = "";
if(type.startsWith("List[")){
classShortName = type.substring(5, type.length()-1);
classShortName = getClassType(classShortName, true);
}else if (type.startsWith("Map[")) {
classShortName = type.substring(4, type.length()-1);
classShortName = getClassType(classShortName, true);
}else if (type.startsWith("Set[")) {
classShortName = type.substring(4, type.length()-1);
classShortName = getClassType(classShortName, true);
}else if (type.equalsIgnoreCase("ok")) {
classShortName = "void";
}else{
classShortName = getClassType(type, true);
}
return classShortName;
}
/**
* Returns the syntax for defintion of an object of type and name
*
* @param argumentType
* @param argumentName
* @return
*/
public String getArgumentDefinition(String argumentType, String argumentName) {
return argumentType + " " + argumentName;
}
/**
* Gets the class of the expected return value for a type string. Examples of type Strings are int, User, List[User]
* If the type string is a collection type like a map or list the string value returned would be the class
* that map or list is returning.
*
* @param type
* @return
*/
public String getClassType(String type, boolean primitiveObject) {
if(type.equalsIgnoreCase("void")|| type.equalsIgnoreCase("ok")){
return "void";
}
String classShortName = "";
if(type.startsWith("List[")){
classShortName = type.substring(5, type.length()-1);
classShortName = "Array<"+ getClassName(classShortName, true)+">";
}else if (type.startsWith("Map[")) {
classShortName = type.substring(4, type.length()-1);
classShortName = "Array<"+ getClassName(classShortName, true) +">";
}else if (type.startsWith("Set[")) {
classShortName = type.substring(4, type.length()-1);
classShortName = "Array<"+ getClassName(classShortName, true) +">";
}else{
classShortName = getClassName(type, true);
}
return classShortName;
}
/**
* If the data type is primitive and it is expecting object structure then return primitive objects
* else return primitive types
* @param type
* @param primitiveObject -- indicates if the object is primitive or not
* @return
*/
private String getClassName(String type, boolean primitiveObject) {
if(isPrimitiveType(type)){
if(primitiveObject){
return primitiveObjectMap.get(type);
}else{
return primitiveValueMap.get(type);
}
}else{
return nameGenerator.applyClassNamingPolicy(type);
}
}
@Override
public String generateVariableInitialization(String typeClass) {
return "";
}
}

View File

@ -1,95 +0,0 @@
/**
* 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.codegen.config.php;
import com.wordnik.swagger.codegen.LibraryCodeGenerator;
import com.wordnik.swagger.codegen.config.LanguageConfiguration;
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider;
import com.wordnik.swagger.codegen.exception.CodeGenerationException;
import com.wordnik.swagger.codegen.util.FileUtil;
import java.io.File;
/**
* User: russ
* Date: 9/1/11
* Time: 11:00 PM
*/
public class PHPLibCodeGen extends LibraryCodeGenerator {
public static void main(String[] args) {
if(args.length < 1){
throw new CodeGenerationException("Invalid number of arguments passed: No command line argument was passed to the program for config json");
}
if(args.length == 1) {
String configPath = args[0];
PHPLibCodeGen codeGenerator = new PHPLibCodeGen(configPath);
codeGenerator.generateCode();
}
if(args.length == 4) {
String apiServerURL = args[0];
if(!apiServerURL.endsWith("/")){
apiServerURL = apiServerURL + "/";
}
String apiKey = args[1];
String packageName = args[2];
String libraryHome = args[3];
if(libraryHome.endsWith("/")){
libraryHome = libraryHome.substring(0, libraryHome.length()-1);
}
String modelPackageName = packageName+".model";
String apiPackageName = packageName+".api";
String classOutputDir = libraryHome + '/' + packageName.replace(".","/");
PHPLibCodeGen codeGenerator = new PHPLibCodeGen(apiServerURL, apiKey, modelPackageName,
apiPackageName, classOutputDir, libraryHome);
codeGenerator.generateCode();
}
}
public PHPLibCodeGen(String apiServerURL, String apiKey, String modelPackageName, String apiPackageName,
String classOutputDir, String libraryHome){
super(apiServerURL, apiKey, modelPackageName, apiPackageName, classOutputDir, libraryHome);
this.setDataTypeMappingProvider(new PHPDataTypeMappingProvider());
this.setNameGenerator(new CamelCaseNamingPolicyProvider());
}
public PHPLibCodeGen(String configPath){
super(configPath);
this.setDataTypeMappingProvider(new PHPDataTypeMappingProvider());
this.setNameGenerator(new CamelCaseNamingPolicyProvider());
}
@Override
protected LanguageConfiguration initializeLangConfig(LanguageConfiguration PHPConfiguration) {
PHPConfiguration.setClassFileExtension(".php");
PHPConfiguration.setTemplateLocation("conf/php/templates");
PHPConfiguration.setStructureLocation("conf/php/structure");
PHPConfiguration.setExceptionPackageName("com.wordnik.swagger.exception");
PHPConfiguration.setAnnotationPackageName("com.wordnik.swagger.annotations");
//create ouput directories
FileUtil.createOutputDirectories(PHPConfiguration.getModelClassLocation(), PHPConfiguration.getClassFileExtension());
FileUtil.createOutputDirectories(PHPConfiguration.getResourceClassLocation(), PHPConfiguration.getClassFileExtension());
FileUtil.clearFolder(PHPConfiguration.getModelClassLocation());
FileUtil.clearFolder(PHPConfiguration.getResourceClassLocation());
FileUtil.copyDirectoryFromUrl(this.getClass().getClassLoader().getResource(PHPConfiguration.getStructureLocation()), new File(PHPConfiguration.getResourceClassLocation()));
return PHPConfiguration;
}
}

View File

@ -1,247 +0,0 @@
/**
* 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.codegen.config.python;
import com.wordnik.swagger.codegen.config.DataTypeMappingProvider;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User: ramesh
* Date: 5/31/11
* Time: 7:03 AM
*/
public class PythonDataTypeMappingProvider implements DataTypeMappingProvider {
public static Map<String, String> primitiveValueMap = new HashMap<String, String>();
static{
primitiveValueMap.put("string", "str");
primitiveValueMap.put("String", "str");
primitiveValueMap.put("int", "int");
primitiveValueMap.put("integer", "int");
primitiveValueMap.put("Integer", "int");
primitiveValueMap.put("boolean", "bool");
primitiveValueMap.put("Boolean", "bool");
primitiveValueMap.put("long", "int");
primitiveValueMap.put("Long", "int");
primitiveValueMap.put("float", "float");
primitiveValueMap.put("Float", "float");
primitiveValueMap.put("Date", "str");
primitiveValueMap.put("date", "str");
primitiveValueMap.put("Double", "float");
primitiveValueMap.put("double", "float");
primitiveValueMap.put("Byte", "byte");
primitiveValueMap.put("byte", "byte");
}
public static Map<String, String> primitiveObjectMap = new HashMap<String, String>();
static{
primitiveObjectMap.put("string", "str");
primitiveObjectMap.put("String", "str");
primitiveObjectMap.put("java.lang.String", "str");
primitiveObjectMap.put("int", "int");
primitiveObjectMap.put("integer", "int");
primitiveObjectMap.put("Integer", "int");
primitiveObjectMap.put("java.lang.Integer", "int");
primitiveObjectMap.put("bool", "bool");
primitiveObjectMap.put("boolean", "bool");
primitiveObjectMap.put("Boolean", "bool");
primitiveObjectMap.put("java.lang.Boolean", "bool");
primitiveObjectMap.put("long", "int");
primitiveObjectMap.put("Long", "int");
primitiveObjectMap.put("java.lang.Long", "int");
primitiveObjectMap.put("float", "float");
primitiveObjectMap.put("Float", "float");
primitiveObjectMap.put("double", "float");
primitiveObjectMap.put("Double", "float");
primitiveObjectMap.put("java.lang.Float", "float");
primitiveObjectMap.put("Date", "str");
primitiveObjectMap.put("date", "str");
primitiveObjectMap.put("java.util.Date", "str");
primitiveObjectMap.put("byte", "Byte");
}
private NamingPolicyProvider nameGenerator = new CamelCaseNamingPolicyProvider();
public boolean isPrimitiveType(String type) {
if(primitiveObjectMap.containsKey(type)){
return true;
}
return false;
}
public String getListReturnTypeSignature(String typeClass) {
if (isPrimitiveType(typeClass)) {
return "list<"+typeClass+">";
} else {
return "list<"+nameGenerator.applyClassNamingPolicy(typeClass)+">";
}
}
public String getMapReturnTypeSignature(String typeClass) {
return "dict<"+nameGenerator.applyClassNamingPolicy(typeClass)+">";
}
public String getSetReturnTypeSignature(String typeClass) {
return "set<"+nameGenerator.applyClassNamingPolicy(typeClass)+">";
}
public String getArrayReturnTypeSignature(String typeClass) {
return getListReturnTypeSignature(typeClass);
}
public String generateListInitialization(String typeClass) {
return " list()";
}
public String generateMapInitialization(String typeClass) {
return " dict()";
}
public String generateArrayInitialization(String typeClass) {
return " list()";
}
public String generateSetInitialization(String typeClass) {
return " set()";
}
public List<String> getListIncludes() {
List<String> imports = new ArrayList<String>();
return imports;
}
public List<String> getMapIncludes() {
List<String> imports = new ArrayList<String>();
return imports;
}
public List<String> getSetIncludes() {
List<String> imports = new ArrayList<String>();
return imports; }
public List<String> getDateIncludes() {
List<String> imports = new ArrayList<String>();
return imports;
}
/**
* Gets the short name of the class the class.
* Input can be MAP, LIST or regular string. In case of map or list the class name will be class name
* that map or list is returning.
* @param type
* @return
*/
public String getGenericType(String type) {
String classShortName = "";
if(type.startsWith("List[")){
classShortName = type.substring(5, type.length()-1);
classShortName = getClassType(classShortName, true);
}else if (type.startsWith("Map[")) {
classShortName = type.substring(4, type.length()-1);
classShortName = getClassType(classShortName, true);
}else if (type.startsWith("Set[")) {
classShortName = type.substring(4, type.length()-1);
classShortName = getClassType(classShortName, true);
}else if (type.startsWith("Array[")) {
classShortName = type.substring(6, type.length()-1);
classShortName = getClassType(classShortName, true);
}else if (type.equalsIgnoreCase("ok")) {
classShortName = "void";
}else{
classShortName = getClassType(type, true);
}
return classShortName;
}
/**
* Returns the syntax for defintion of an object of type and name
*
* @param argumentType
* @param argumentName
* @return
*/
public String getArgumentDefinition(String argumentType, String argumentName) {
return argumentType + " " + argumentName;
}
/**
* Gets the class of the expected return value for a type string. Examples of type Strings are int, User, List[User]
* If the type string is a collection type like a map or list the string value returned would be the class
* that map or list is returning.
*
* @param type
* @return
*/
public String getClassType(String type, boolean primitiveObject) {
if(type.equalsIgnoreCase("void")|| type.equalsIgnoreCase("ok")){
return "void";
}
String classShortName = "";
if(type.startsWith("List[")){
classShortName = type.substring(5, type.length()-1);
classShortName = "list<"+ getClassName(classShortName, true)+">";
}else if (type.startsWith("Map[")) {
classShortName = type.substring(4, type.length()-1);
classShortName = "dict<"+ getClassName(classShortName, true) +">";
}else if (type.startsWith("Set[")) {
classShortName = type.substring(4, type.length()-1);
classShortName = "set<"+ getClassName(classShortName, true) +">";
}else if (type.startsWith("Array[")) {
classShortName = type.substring(6, type.length()-1);
classShortName = "list<"+ getClassName(classShortName, true) +">";
}else{
classShortName = getClassName(type, true);
}
return classShortName;
}
/**
* If the data type is primitive and it is expecting object structure then return primitive objects
* else return primitive types
* @param type
* @param primitiveObject -- indicates if the object is primitive or not
* @return
*/
private String getClassName(String type, boolean primitiveObject) {
if(isPrimitiveType(type)){
if(primitiveObject){
return primitiveObjectMap.get(type);
}else{
return primitiveValueMap.get(type);
}
}else{
return nameGenerator.applyClassNamingPolicy(type);
}
}
@Override
public String generateVariableInitialization(String typeClass) {
return "";
}
}

View File

@ -1,104 +0,0 @@
/**
* 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.codegen.config.python;
import com.wordnik.swagger.codegen.LibraryCodeGenerator;
import com.wordnik.swagger.codegen.config.LanguageConfiguration;
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider;
import com.wordnik.swagger.codegen.exception.CodeGenerationException;
import com.wordnik.swagger.codegen.util.FileUtil;
import java.io.File;
/**
* User: russ
* Date: 9/1/11
* Time: 11:00 PM
*/
public class PythonLibCodeGen extends LibraryCodeGenerator {
public static void main(String[] args) {
if(args.length < 1){
throw new CodeGenerationException("Invalid number of arguments passed: No command line argument was passed to the program for config json");
}
if(args.length == 1) {
String configPath = args[0];
PythonLibCodeGen codeGenerator = new PythonLibCodeGen(configPath);
codeGenerator.generateCode();
}
if(args.length == 4) {
String apiServerURL = args[0];
if(!apiServerURL.endsWith("/")){
apiServerURL = apiServerURL + "/";
}
String apiKey = args[1];
String packageName = args[2];
String libraryHome = args[3];
if(libraryHome.endsWith("/")){
libraryHome = libraryHome.substring(0, libraryHome.length()-1);
}
String modelPackageName = packageName+".model";
String apiPackageName = packageName+".api";
String classOutputDir = libraryHome + '/' + packageName.replace(".","/");
PythonLibCodeGen codeGenerator = new PythonLibCodeGen(apiServerURL, apiKey, modelPackageName,
apiPackageName, classOutputDir, libraryHome);
codeGenerator.generateCode();
}
}
public PythonLibCodeGen(String apiServerURL, String apiKey, String modelPackageName, String apiPackageName,
String classOutputDir, String libraryHome){
super(apiServerURL, apiKey, modelPackageName, apiPackageName, classOutputDir, libraryHome);
this.setDataTypeMappingProvider(new PythonDataTypeMappingProvider());
this.setNameGenerator(new CamelCaseNamingPolicyProvider());
}
public PythonLibCodeGen(String configPath){
super(configPath);
this.setDataTypeMappingProvider(new PythonDataTypeMappingProvider());
this.setNameGenerator(new CamelCaseNamingPolicyProvider());
}
@Override
protected LanguageConfiguration initializeLangConfig(LanguageConfiguration PythonConfiguration) {
PythonConfiguration.setClassFileExtension(".py");
PythonConfiguration.setTemplateLocation("conf/python/templates");
PythonConfiguration.setStructureLocation("conf/python/structure");
PythonConfiguration.setExceptionPackageName("com.wordnik.swagger.exception");
PythonConfiguration.setAnnotationPackageName("com.wordnik.swagger.annotations");
//create ouput directories
FileUtil.createOutputDirectories(PythonConfiguration.getModelClassLocation(), PythonConfiguration.getClassFileExtension());
FileUtil.createOutputDirectories(PythonConfiguration.getResourceClassLocation(), PythonConfiguration.getClassFileExtension());
FileUtil.clearFolder(PythonConfiguration.getModelClassLocation());
FileUtil.clearFolder(PythonConfiguration.getResourceClassLocation());
FileUtil.copyDirectoryFromUrl(this.getClass().getClassLoader().getResource(PythonConfiguration.getStructureLocation()), new File(PythonConfiguration.getResourceClassLocation()));
File initFile = new File(PythonConfiguration.getResourceClassLocation() + "__init__.py");
File newInitFile = new File(PythonConfiguration.getModelClassLocation() + "__init__.py");
initFile.renameTo(newInitFile);
// try {
// initFile.createNewFile();
// } catch (java.io.IOException e) {
// e.printStackTrace();
// throw new CodeGenerationException("Creating model/__init__.py failed");
// }
return PythonConfiguration;
}
}

View File

@ -1,216 +0,0 @@
/**
* 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.codegen.config.ruby
import com.wordnik.swagger.codegen.config.DataTypeMappingProvider
import com.wordnik.swagger.codegen.config.NamingPolicyProvider
import com.wordnik.swagger.codegen.config.common.UnderscoreNamingPolicyProvider
import scala.collection.mutable._
import scala.collection.JavaConversions._
object RubyDataTypeMappingProvider {
val primitiveValueMap = Map("string" -> "String",
"String" -> "String",
"int" -> "int",
"integer" -> "int",
"Integer" -> "int",
"boolean" -> "boolean",
"Boolean" -> "boolean",
"long" -> "long",
"Long" -> "long",
"float" -> "float",
"Float" -> "float",
"Date" -> "Date",
"date" -> "Date")
val primitiveObjectMap = Map("string" -> "String",
"String" -> "String",
"java.lang.String" -> "String",
"int" -> "Integer",
"integer" -> "Integer",
"Integer" -> "Integer",
"java.lang.Integer" -> "Integer",
"boolean" -> "Boolean",
"Boolean" -> "Boolean",
"java.lang.Boolean" -> "Boolean",
"long" -> "Long",
"Long" -> "Long",
"java.lang.Long" -> "Long",
"float" -> "Float",
"Float" -> "Float",
"java.lang.Float" -> "Float",
"Date" -> "Date",
"date" -> "Date",
"byte" -> "Byte",
"java.util.Date" -> "Date")
}
class RubyDataTypeMappingProvider extends DataTypeMappingProvider {
val nameGenerator = new UnderscoreNamingPolicyProvider()
def isPrimitiveType(input: String): Boolean = {
RubyDataTypeMappingProvider.primitiveObjectMap.contains(input) match {
case true => true
case _ => false
}
}
def getListReturnTypeSignature(typeClass: String): String = {
return "List[" + nameGenerator.applyClassNamingPolicy(typeClass) + "]";
}
def getArrayReturnTypeSignature(typeClass: String): String = {
return "List[" + nameGenerator.applyClassNamingPolicy(typeClass) + "]";
}
def getMapReturnTypeSignature(typeClass: String): String = {
return "Map[" + nameGenerator.applyClassNamingPolicy(typeClass) + "]";
}
def getSetReturnTypeSignature(typeClass: String): String = {
return "Set[" + nameGenerator.applyClassNamingPolicy(typeClass) + "]";
}
def generateVariableInitialization(typeClass:String):String = "=_"
def generateListInitialization(typeClass: String): String = {
return " new ListBuffer[" + nameGenerator.applyClassNamingPolicy(typeClass) + "]";
}
def generateMapInitialization(typeClass: String): String = {
return " new HashMap[" + nameGenerator.applyClassNamingPolicy(typeClass) + "]";
}
def generateSetInitialization(typeClass: String): String = {
return " new HashSet[" + nameGenerator.applyClassNamingPolicy(typeClass) + "]";
}
def generateArrayInitialization(typeClass: String): String = {
return generateListInitialization(typeClass)
}
def getListIncludes(): java.util.List[String] = {
List("scala.collection.mutable.ListBuffer")
}
def getMapIncludes(): java.util.List[String] = {
List("java.util.Map", "java.util.HashMap")
}
def getSetIncludes: java.util.List[String] = {
List("java.util.Set", "java.util.HashSet")
}
def getDateIncludes: java.util.List[String] = {
List("java.util.Date")
}
/**
* Gets the short name of the class the class.
* Input can be MAP, LIST or regular string. In case of map or list the class name will be class name
* that map or list is returning.
* @param type
* @return
*/
def getGenericType(inputType: String): String = {
var classShortName = ""
if (inputType.startsWith("List[")) {
classShortName = inputType.substring(5, inputType.length() - 1);
classShortName = getClassType(classShortName, true);
} else if (inputType.startsWith("Map[")) {
classShortName = inputType.substring(4, inputType.length() - 1)
classShortName = getClassType(classShortName, true)
} else if (inputType.startsWith("Set[")) {
classShortName = inputType.substring(4, inputType.length() - 1)
classShortName = getClassType(classShortName, true)
} else if (inputType.startsWith("Array[")) {
classShortName = inputType.substring(6, inputType.length() - 1)
classShortName = getClassType(classShortName, true)
} else if (inputType.equalsIgnoreCase("ok")) {
classShortName = ""
} else {
classShortName = getClassType(inputType, true)
}
classShortName
}
/**
* Returns the syntax for defintion of an object of type and name
*
* @param argumentType
* @param argumentName
* @return
*/
def getArgumentDefinition(argumentType: String, argumentName: String): String = {
argumentName + ":" + argumentType
}
/**
* Gets the class of the expected return value for a type string. Examples of type Strings are int, User, List[User]
* If the type string is a collection type like a map or list the string value returned would be the class
* that map or list is returning.
*
* @param type
* @return
*/
def getClassType(input: String, primitiveObject: Boolean): String = {
if (input.equalsIgnoreCase("void") || input.equalsIgnoreCase("ok")) {
""
} else {
var classShortName = ""
if (input.startsWith("List[")) {
classShortName = input.substring(5, input.length() - 1);
classShortName = "List[" + getClassName(classShortName, true) + "]";
} else if (input.startsWith("Map[")) {
classShortName = input.substring(4, input.length() - 1);
classShortName = "Map[" + getClassName(classShortName, true) + "]";
} else if (input.startsWith("Set[")) {
classShortName = input.substring(4, input.length() - 1);
classShortName = "Set[" + getClassName(classShortName, true) + "]";
}else if (input.startsWith("Array[")) {
classShortName = input.substring(6, input.length() - 1);
classShortName = "List[" + getClassName(classShortName, true) + "]";
}
else {
classShortName = getClassName(input, true);
}
classShortName
}
}
/**
* If the data type is primitive and it is expecting object structure then return primitive objects
* else return primitive types
* @param type
* @param primitiveObject -- indicates if the object is primitive or not
* @return
*/
def getClassName(input: String, primitiveObject: Boolean): String = {
isPrimitiveType(input) match {
case true => {
if (primitiveObject) {
RubyDataTypeMappingProvider.primitiveObjectMap(input)
} else {
RubyDataTypeMappingProvider.primitiveValueMap(input)
}
}
case _ => nameGenerator.applyClassNamingPolicy(input)
}
}
}

View File

@ -1,98 +0,0 @@
/**
* 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.codegen.config.ruby
import com.wordnik.swagger.codegen.LibraryCodeGenerator
import com.wordnik.swagger.codegen.config.LanguageConfiguration
import com.wordnik.swagger.codegen.config.common.UnderscoreNamingPolicyProvider
import com.wordnik.swagger.codegen.exception.CodeGenerationException
import com.wordnik.swagger.codegen.util.FileUtil
import java.io.File
import com.wordnik.swagger.codegen.resource.EndpointOperation
object RubyLibCodeGen {
def main(args: Array[String]) = {
val codeGenerator = args.length match {
case 1 => new RubyLibCodeGen(args(0))
case 4 => {
var apiServerURL = args(0)
if (!apiServerURL.endsWith("/")) {
apiServerURL = apiServerURL + "/"
}
val apiKey = args(1);
val packageName = args(2)
var libraryHome = args(3)
if (libraryHome.endsWith("/")) {
libraryHome = libraryHome.substring(0, libraryHome.length() - 1)
}
val modelPackageName = packageName + ".models"
val apiPackageName = packageName + ".resources"
val classOutputDir = libraryHome + "/src/main/ruby/lib/" + packageName.replace(".", "/")
new RubyLibCodeGen(apiServerURL, apiKey, modelPackageName, apiPackageName, classOutputDir, libraryHome)
}
case _ => throw new CodeGenerationException("Invalid number of arguments passed: No command line argument was passed to the program for config json")
}
codeGenerator.generateCode()
}
}
class RubyLibCodeGen (
apiServerURL: String,
apiKey: String,
modelPackageName: String,
apiPackageName: String,
classOutputDir: String,
libraryHome: String,
configPath: String) extends LibraryCodeGenerator {
// don't want to generate input models
EndpointOperation.setArgCountForInputModel(10000)
if (null != configPath) {
initializeWithConfigPath(configPath)
this.setDataTypeMappingProvider(new RubyDataTypeMappingProvider())
this.setNameGenerator(new UnderscoreNamingPolicyProvider())
}
else{
initialize(apiServerURL, apiKey, modelPackageName, apiPackageName, classOutputDir, libraryHome)
setDataTypeMappingProvider(new RubyDataTypeMappingProvider())
setNameGenerator(new UnderscoreNamingPolicyProvider())
}
def this(apiServerURL: String, apiKey: String, modelPackageName: String, apiPackageName: String, classOutputDir: String, libraryHome: String) = this(apiServerURL, apiKey, modelPackageName, apiPackageName, classOutputDir, libraryHome, null)
def this(configPath: String) = this(null, null, null, null, null, null, configPath)
override def initializeLangConfig(config: LanguageConfiguration): LanguageConfiguration = {
config.setClassFileExtension(".rb");
config.setTemplateLocation("conf/ruby/templates");
config.setStructureLocation("conf/ruby/structure");
config.setExceptionPackageName("com.wordnik.swagger.exception");
config.setAnnotationPackageName("com.wordnik.swagger.annotations");
config.setOutputDirectory(classOutputDir, "models", "resources");
//create ouput directories
FileUtil.createOutputDirectories(config.getModelClassLocation(), config.getClassFileExtension());
FileUtil.createOutputDirectories(config.getResourceClassLocation(), config.getClassFileExtension());
FileUtil.clearFolder(config.getModelClassLocation());
FileUtil.clearFolder(config.getResourceClassLocation());
FileUtil.clearFolder(config.getLibraryHome() + "/src/main/ruby/com/wordnik/swagger/runtime");
FileUtil.createOutputDirectories(config.getLibraryHome() + "/src/main/ruby/lib", "ruby");
FileUtil.copyDirectoryFromUrl(this.getClass.getClassLoader.getResource(config.getStructureLocation()), new File(classOutputDir));
config
}
}

View File

@ -1,221 +0,0 @@
/**
* 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.codegen.config.scala
import com.wordnik.swagger.codegen.config.DataTypeMappingProvider
import com.wordnik.swagger.codegen.config.NamingPolicyProvider
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider
import scala.collection.mutable._
import scala.collection.JavaConversions._
object ScalaDataTypeMappingProvider {
val primitiveValueMap = Map("string" -> "String",
"String" -> "String",
"int" -> "int",
"integer" -> "int",
"Integer" -> "int",
"boolean" -> "boolean",
"Boolean" -> "boolean",
"long" -> "long",
"Long" -> "long",
"float" -> "float",
"Float" -> "float",
"Date" -> "Date",
"date" -> "Date",
"byte" -> "Byte",
"Byte" -> "Byte")
val primitiveObjectMap = Map("string" -> "String",
"String" -> "String",
"java.lang.String" -> "String",
"int" -> "Integer",
"integer" -> "Integer",
"Integer" -> "Integer",
"java.lang.Integer" -> "Integer",
"boolean" -> "Boolean",
"Boolean" -> "Boolean",
"java.lang.Boolean" -> "Boolean",
"long" -> "Long",
"Long" -> "Long",
"java.lang.Long" -> "Long",
"float" -> "Float",
"Float" -> "Float",
"java.lang.Float" -> "Float",
"Date" -> "Date",
"date" -> "Date",
"byte" -> "Byte",
"java.util.Date" -> "Date")
val reservedWordMapper = new ScalaReservedWordMapper
}
class ScalaDataTypeMappingProvider extends DataTypeMappingProvider {
import ScalaDataTypeMappingProvider._
val nameGenerator = new CamelCaseNamingPolicyProvider()
def isPrimitiveType(input: String): Boolean = {
ScalaDataTypeMappingProvider.primitiveObjectMap.contains(input) match {
case true => true
case _ => false
}
}
def getListReturnTypeSignature(typeClass: String): String = {
return "List[" + nameGenerator.applyClassNamingPolicy(typeClass) + "]";
}
def getMapReturnTypeSignature(typeClass: String): String = {
return "Map[" + nameGenerator.applyClassNamingPolicy(typeClass) + "]";
}
def getSetReturnTypeSignature(typeClass: String): String = {
return "Set[" + nameGenerator.applyClassNamingPolicy(typeClass) + "]";
}
def getArrayReturnTypeSignature(typeClass: String): String = {
return "Array["+nameGenerator.applyClassNamingPolicy(typeClass) + "]";
}
def generateVariableInitialization(typeClass:String):String = "=_"
def generateListInitialization(typeClass: String): String = {
return " new ListBuffer[" + nameGenerator.applyClassNamingPolicy(typeClass) + "]";
}
def generateMapInitialization(typeClass: String): String = {
return " new HashMap[" + nameGenerator.applyClassNamingPolicy(typeClass) + "]";
}
def generateSetInitialization(typeClass: String): String = {
return " new HashSet[" + nameGenerator.applyClassNamingPolicy(typeClass) + "]";
}
def generateArrayInitialization(typeClass: String): String = {
return " null ";
}
def getListIncludes(): java.util.List[String] = {
List("scala.collection.mutable.ListBuffer")
}
def getMapIncludes(): java.util.List[String] = {
List("java.util.Map", "java.util.HashMap")
}
def getSetIncludes: java.util.List[String] = {
List("java.util.Set", "java.util.HashSet")
}
def getDateIncludes: java.util.List[String] = {
List("java.util.Date")
}
/**
* Gets the short name of the class the class.
* Input can be MAP, LIST or regular string. In case of map or list the class name will be class name
* that map or list is returning.
* @param type
* @return
*/
def getGenericType(inputType: String): String = {
var classShortName = ""
if (inputType.startsWith("List[")) {
classShortName = inputType.substring(5, inputType.length() - 1);
classShortName = getClassType(classShortName, true);
} else if (inputType.startsWith("Map[")) {
classShortName = inputType.substring(4, inputType.length() - 1)
classShortName = getClassType(classShortName, true)
} else if (inputType.startsWith("Set[")) {
classShortName = inputType.substring(4, inputType.length() - 1)
classShortName = getClassType(classShortName, true)
}else if (inputType.startsWith("Array[")) {
classShortName = inputType.substring(6, inputType.length() - 1)
classShortName = getClassType(classShortName, true)
}else if (inputType.equalsIgnoreCase("ok")) {
classShortName = ""
} else {
classShortName = getClassType(inputType, true)
}
classShortName
}
/**
* Returns the syntax for defintion of an object of type and name
*
* @param argumentType
* @param argumentName
* @return
*/
def getArgumentDefinition(argumentType: String, argumentName: String): String = {
reservedWordMapper.translate(argumentName) + ":" + argumentType
}
/**
* Gets the class of the expected return value for a type string. Examples of type Strings are int, User, List[User]
* If the type string is a collection type like a map or list the string value returned would be the class
* that map or list is returning.
*
* @param type
* @return
*/
def getClassType(input: String, primitiveObject: Boolean): String = {
if (input.equalsIgnoreCase("void") || input.equalsIgnoreCase("ok")) {
""
} else {
var classShortName = ""
if (input.startsWith("List[")) {
classShortName = input.substring(5, input.length() - 1);
classShortName = "List[" + getClassType(classShortName, true) + "]";
} else if (input.startsWith("Map[")) {
classShortName = input.substring(4, input.length() - 1);
val mapTypes:Array[String] = classShortName.split(",");
classShortName = "Map[" + getClassType(mapTypes(0), true) + "," + getClassType(mapTypes(1), true) + "]";
} else if (input.startsWith("Set[")) {
classShortName = input.substring(4, input.length() - 1);
classShortName = "Set[" + getClassType(classShortName, true) + "]";
} else if (input.startsWith("Array[")) {
classShortName = input.substring(6, input.length() - 1);
classShortName = "Array["+getClassName(classShortName, true) + "]";
} else {
classShortName = getClassName(input, true);
}
classShortName
}
}
/**
* If the data type is primitive and it is expecting object structure then return primitive objects
* else return primitive types
* @param type
* @param primitiveObject -- indicates if the object is primitive or not
* @return
*/
def getClassName(input: String, primitiveObject: Boolean): String = {
isPrimitiveType(input) match {
case true => {
if (primitiveObject) {
ScalaDataTypeMappingProvider.primitiveObjectMap(input)
} else {
ScalaDataTypeMappingProvider.primitiveValueMap(input)
}
}
case _ => nameGenerator.applyClassNamingPolicy(input)
}
}
}

View File

@ -1,94 +0,0 @@
/**
* 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.codegen.config.scala
import com.wordnik.swagger.codegen.LibraryCodeGenerator
import com.wordnik.swagger.codegen.config.LanguageConfiguration
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider
import com.wordnik.swagger.codegen.exception.CodeGenerationException
import com.wordnik.swagger.codegen.util.FileUtil
import java.io.File
object ScalaLibCodeGen {
def main(args: Array[String]) = {
val codeGenerator = args.length match {
case 1 => new ScalaLibCodeGen(args(0))
case 4 => {
var apiServerURL = args(0)
if (!apiServerURL.endsWith("/")) {
apiServerURL = apiServerURL + "/"
}
val apiKey = args(1);
val packageName = args(2)
var libraryHome = args(3)
if (libraryHome.endsWith("/")) {
libraryHome = libraryHome.substring(0, libraryHome.length() - 1)
}
val modelPackageName = packageName + ".model"
val apiPackageName = packageName + ".api"
val classOutputDir = libraryHome + "/src/main/scala/" + packageName.replace(".", "/")
new ScalaLibCodeGen(apiServerURL, apiKey, modelPackageName, apiPackageName, classOutputDir, libraryHome)
}
case _ => throw new CodeGenerationException("Invalid number of arguments passed: No command line argument was passed to the program for config json")
}
codeGenerator.generateCode()
}
}
class ScalaLibCodeGen(
apiServerURL: String,
apiKey: String,
modelPackageName: String,
apiPackageName: String,
classOutputDir: String,
libraryHome: String,
configPath: String) extends LibraryCodeGenerator {
this.reservedWordMapper = new ScalaReservedWordMapper
if (null != configPath) {
initializeWithConfigPath(configPath)
this.setDataTypeMappingProvider(new ScalaDataTypeMappingProvider())
this.setNameGenerator(new ScalaNamingPolicyProvider())
} else {
initialize(apiServerURL, apiKey, modelPackageName, apiPackageName, classOutputDir, libraryHome)
setDataTypeMappingProvider(new ScalaDataTypeMappingProvider())
setNameGenerator(new ScalaNamingPolicyProvider())
}
def this(apiServerURL: String, apiKey: String, modelPackageName: String, apiPackageName: String, classOutputDir: String, libraryHome: String) = this(apiServerURL, apiKey, modelPackageName, apiPackageName, classOutputDir, libraryHome, null)
def this(configPath: String) = this(null, null, null, null, null, null, configPath)
override def initializeLangConfig(config: LanguageConfiguration): LanguageConfiguration = {
config.setClassFileExtension(".scala");
config.setTemplateLocation("conf/scala/templates");
config.setStructureLocation("conf/scala/structure");
config.setExceptionPackageName("com.wordnik.swagger.exception");
config.setAnnotationPackageName("com.wordnik.swagger.annotations");
//create ouput directories
FileUtil.createOutputDirectories(config.getModelClassLocation(), config.getClassFileExtension());
FileUtil.createOutputDirectories(config.getResourceClassLocation(), config.getClassFileExtension());
FileUtil.clearFolder(config.getModelClassLocation());
FileUtil.clearFolder(config.getResourceClassLocation());
FileUtil.clearFolder(config.getLibraryHome() + "/src/main/java/com/wordnik/swagger/runtime");
FileUtil.createOutputDirectories(config.getLibraryHome() + "/src/main/java/com/wordnik/swagger/runtime", "java");
FileUtil.copyDirectoryFromUrl(this.getClass.getClassLoader.getResource("conf/scala/structure/src/main/java"), new File(config.getLibraryHome() + "/src/main/java"));
config
}
}

View File

@ -1,26 +0,0 @@
package com.wordnik.swagger.codegen.config.scala
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider
/**
* User: ramesh
* Date: 3/29/12
* Time: 3:49 PM
*/
class ScalaNamingPolicyProvider extends CamelCaseNamingPolicyProvider {
/**
* Gets the signature of the method that gets value for give attribute name.
*
* Example: If class name is user and attibute name is email the out in java language will be
* <code>user.getEmail</code>
*
* @param className
* @param attributeName
* @return
*/
override def createGetterMethodName(className: String, attributeName: String): String = {
return className + ".get" + applyClassNamingPolicy(attributeName)
}
}

View File

@ -1,40 +0,0 @@
/**
* 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.codegen.config.scala
import com.wordnik.swagger.codegen.config.ReservedWordMapper
object ScalaKeywordMapper {
val reservedWords = Array("type", "case", "object","match")
}
class ScalaReservedWordMapper extends ReservedWordMapper {
override def translate(input: String): String = {
ScalaKeywordMapper.reservedWords.contains(input) match {
case true => "`" + input + "`"
case false => input
}
}
override def retranslate(input: String): String = {
(input.startsWith("`") && input.endsWith("`")) match {
case true => input.substring(1, input.length()-1)
case false => input
}
}
}

View File

@ -1,41 +0,0 @@
/**
* 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.codegen.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;
}
}

View File

@ -1,59 +0,0 @@
/**
* 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.codegen.resource;
import java.util.List;
/**
* User: ramesh
* Date: 10/18/11
* Time: 11:34 PM
*/
public class AllowableListValues extends AllowableValues {
private String valueType = "LIST";
private List<String> values;
public String getValueType() {
return valueType;
}
public void setValueType(String valueType) {
this.valueType = valueType;
}
public List<String> getValues() {
return values;
}
public void setValues(List<String> values) {
this.values = values;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
if(this.getValues() != null){
for(String value : values ){
buffer.append(value);
buffer.append(",");
}
}
return buffer.toString().substring(0, buffer.toString().length()-1);
}
}

View File

@ -1,61 +0,0 @@
/**
* 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.codegen.resource;
/**
* User: ramesh
* Date: 10/18/11
* Time: 11:35 PM
*/
public class AllowableRangeValues extends AllowableValues {
private String valueType = "RANGE";
private float min;
private float max;
public String getValueType() {
return valueType;
}
public void setValueType(String valueType) {
this.valueType = valueType;
}
public float getMin() {
return min;
}
public void setMin(float minValue) {
this.min = minValue;
}
public float getMax() {
return max;
}
public void setMax(float maxValue) {
this.max = maxValue;
}
@Override
public String toString() {
return "range[" + min + "," + max + "]";
}
}

View File

@ -1,67 +0,0 @@
/**
* 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.codegen.resource;
import org.codehaus.jackson.annotate.JsonSubTypes;
import org.codehaus.jackson.annotate.JsonTypeInfo;
import java.util.ArrayList;
import java.util.List;
/**
* Common interface between range and list allowable values
* User: ramesh
* Date: 10/18/11
* Time: 11:34 PM
*/
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "valueType")
@JsonSubTypes({
@JsonSubTypes.Type(value = AllowableListValues.class, name = "LIST"),
@JsonSubTypes.Type(value = AllowableRangeValues.class, name = "RANGE")
})
public abstract class AllowableValues {
public abstract String getValueType();
public static AllowableValues ConvertAllowableValuesStringToObject(String data) {
if(data != null){
if(data.toLowerCase().startsWith("range[")){
AllowableRangeValues av = new AllowableRangeValues();
String[] values = null;
values = data.substring(6, data.length()-1).split(",");
av.setMin(new Float(values[0]));
av.setMin(new Float(values[1]));
return av;
}else{
List<String> allowedValues = new ArrayList<String>();
if (data != null) {
String[] tokens = data.split(",");
for(String token: tokens){
allowedValues.add(token);
}
}
AllowableListValues av = new AllowableListValues();
av.setValues(allowedValues);
return av;
}
}
return null;
}
}

View File

@ -1,69 +0,0 @@
/**
* 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.codegen.resource;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
import org.codehaus.jackson.annotate.JsonProperty;
/**
* User: deepakmichael
* Date: 19/07/11
* Time: 1:21 AM
*/
public class ApiModelDefn {
@JsonProperty("id")
private String id;
@JsonProperty("properties")
private ApiPropertyListWrapper properties;
@JsonProperty("description")
private String description;
@JsonProperty("id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@JsonProperty("properties")
public ApiPropertyListWrapper getProperties() {
return properties;
}
public void setProperties(ApiPropertyListWrapper properties) {
this.properties = properties;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Model toModel(String modelName, NamingPolicyProvider nameGenerator) {
Model model = new Model();
model.setName(modelName);
model.setDescription(this.getDescription());
model.setFields( this.getProperties().toFieldList( nameGenerator ) );
return model;
}
}

View File

@ -1,43 +0,0 @@
/**
* 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.codegen.resource;
import org.codehaus.jackson.annotate.JsonAnyGetter;
import org.codehaus.jackson.annotate.JsonAnySetter;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ApiModelListWrapper implements Serializable
{
private Map<String, ApiModelDefn> modelList = new HashMap<String, ApiModelDefn>();
@JsonAnyGetter
public Map<String, ApiModelDefn> getModelList() {
return this.modelList;
}
@JsonAnySetter
public void setModelList(String modelName, ApiModelDefn modelDefn) {
this.modelList.put(modelName, modelDefn);
}
}

View File

@ -1,191 +0,0 @@
/**
* 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.codegen.resource;
import org.codehaus.jackson.annotate.JsonAnyGetter;
import org.codehaus.jackson.annotate.JsonAnySetter;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonPropertyOrder({
"id",
"default",
"items",
"description",
"name",
"allowableValues",
"properties",
"required",
"notes",
"access",
"type"
})
public class ApiPropertyDefn implements Serializable {
@JsonProperty("id")
private String id;
@JsonProperty("default")
private String defaultValue;
@JsonProperty("items")
private ApiPropertyDefn items;
@JsonProperty("description")
private String description;
@JsonProperty("name")
private String name;
@JsonProperty("allowableValues")
private AllowableValues allowableValues = null;
@JsonProperty("properties")
private ApiPropertyListWrapper properties;
@JsonProperty("required")
private boolean required;
@JsonProperty("notes")
private String notes;
@JsonProperty("access")
private String access;
@JsonProperty("type")
private String type;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("id")
public String getId() {
return id;
}
@JsonProperty("id")
public void setId(String id) {
this.id = id;
}
@JsonProperty("default")
public String getDefaultValue() {
return defaultValue;
}
@JsonProperty("default")
public void setDefault(String defaultvalue) {
this.defaultValue = defaultValue;
}
@JsonProperty("items")
public ApiPropertyDefn getItems() {
return items;
}
@JsonProperty("items")
public void setItems(ApiPropertyDefn items) {
this.items = items;
}
@JsonProperty("description")
public String getDescription() {
return description;
}
@JsonProperty("description")
public void setDescription(String description) {
this.description = description;
}
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
@JsonProperty("allowableValues")
public AllowableValues getAllowableValues() {
return allowableValues;
}
@JsonProperty("allowableValues")
public void setAllowableValues(AllowableValues possibleValues) {
this.allowableValues = possibleValues;
}
@JsonProperty("properties")
public ApiPropertyListWrapper getProperties() {
return properties;
}
@JsonProperty("properties")
public void setProperties(ApiPropertyListWrapper properties) {
this.properties = properties;
}
@JsonProperty("required")
public boolean isRequired() {
return required;
}
@JsonProperty("required")
public void setRequired(boolean required) {
this.required = required;
}
@JsonProperty("notes")
public String getNotes() {
return notes;
}
@JsonProperty("notes")
public void setNotes(String notes) {
this.notes = notes;
}
@JsonProperty("access")
public String getAccess() {
return access;
}
@JsonProperty("access")
public void setAccess(String access) {
this.access = access;
}
@JsonProperty("type")
public String getType() {
return type;
}
@JsonProperty("type")
public void setType(String type) {
this.type = type;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperties(String name, Object value) {
this.additionalProperties.put(name, value);
}
}

View File

@ -1,83 +0,0 @@
/**
* 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.codegen.resource;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
import org.codehaus.jackson.annotate.JsonAnyGetter;
import org.codehaus.jackson.annotate.JsonAnySetter;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ApiPropertyListWrapper implements Serializable
{
private Map<String, ApiPropertyDefn> propertyList = new HashMap<String, ApiPropertyDefn>();
@JsonAnyGetter
public Map<String, ApiPropertyDefn> getPropertyList() {
return this.propertyList;
}
@JsonAnySetter
public void setPropertyList(String name, ApiPropertyDefn value) {
this.propertyList.put(name, value);
}
public List<ModelField> toFieldList(NamingPolicyProvider nameGenerator) {
List<ModelField> fields = new ArrayList<ModelField>();
ModelField field;
String propertyName;
ApiPropertyDefn propertyDefn;
for(Map.Entry<String, ApiPropertyDefn> propertyDefnEntry : this.getPropertyList().entrySet()) {
propertyName = propertyDefnEntry.getKey();
propertyDefn = propertyDefnEntry.getValue();
field = new ModelField();
field.setName(propertyName);
//TODO - need to handle this via the nameGenerator which will do this in case the propertyName is a key word in the language
if(propertyName.equals("enum") || propertyName.equals("default")){
field.setName(propertyName+"Value");
}
field.setDescription(propertyDefn.getDescription());
//field.setAllowableValues(propertyDefn.getPossibleValues()); //TODO
//field.setDataType(propertyDefn.getType()); //TODO - verify if this is needed for a model field - paramType is set
field.setParamType(propertyDefn.getType());
if(propertyDefn.getType().equals("array")){
String arrayItemType = propertyDefn.getItems().getType();
if(propertyDefn.getItems().getAdditionalProperties().get("$ref") != null) {
arrayItemType = (String) propertyDefn.getItems().getAdditionalProperties().get("$ref");
}
field.setParamType("List[" + nameGenerator.applyClassNamingPolicy(arrayItemType) + "]");
}
field.setDefaultValue(propertyDefn.getDefaultValue());
field.setInternalDescription(propertyDefn.getNotes());
field.setParamAccess(propertyDefn.getAccess());
field.setRequired(propertyDefn.isRequired());
//field.setWrapperName(propertyDefn);
fields.add(field);
}
return fields;
}
}

View File

@ -1,150 +0,0 @@
/**
* 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.codegen.resource;
import com.wordnik.swagger.codegen.ResourceMethod;
import com.wordnik.swagger.codegen.config.DataTypeMappingProvider;
import com.wordnik.swagger.codegen.config.LanguageConfiguration;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
import java.util.ArrayList;
import java.util.List;
/**
* User: ramesh
* Date: 3/30/11
* Time: 7:01 PM
*/
public class Endpoint {
private String path;
private String description;
private List<String> pathParameters;
private List<EndpointOperation> operations;
private List<ResourceMethod> methods;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<String> getPathParameters() {
return pathParameters;
}
public void setPathParameters(List<String> pathParameters) {
this.pathParameters = pathParameters;
}
public List<EndpointOperation> getOperations() {
return operations;
}
public void setOperations(List<EndpointOperation> operations) {
this.operations = operations;
}
public List<ResourceMethod> generateMethods(Resource resource, DataTypeMappingProvider dataTypeMapper,
NamingPolicyProvider nameGenerator, LanguageConfiguration languageConfig) {
if(methods == null){
methods = new ArrayList<ResourceMethod>();
ResourceMethod newMethod;
List<String> endPointMethodNames = new ArrayList<String>();
if(getOperations() != null) {
for(EndpointOperation operation: getOperations()) {
//Note: Currently we are generating methods for depricated APIs also, We should provide this deprecation info on generated APIs also.
if(areModelsAvailable(operation.getParameters(), resource, dataTypeMapper)) {
newMethod = operation.generateMethod(this, resource, dataTypeMapper, nameGenerator);
if (!endPointMethodNames.contains(newMethod.getName())) {
methods.add(newMethod);
}
else{
//handleOverloadingSupport
if(!languageConfig.isMethodOverloadingSupported()){
handleOverloadedMethod(newMethod, endPointMethodNames);
}
}
endPointMethodNames.add(newMethod.getName());
}else{
System.out.println("Method not generated for resource " + resource.getResourcePath() + " and method " +
operation.getNickname() + " because of un-available model objects specified in the post " );
}
}
}
}
return methods;
}
void handleOverloadedMethod(ResourceMethod method, List<String> methods) {
//handleOverloadingSupport
int counter = 1;
String newMethodName;
boolean generatedNewName = false;
do{
newMethodName = method.getName() + counter;
if (!methods.contains(newMethodName)){
method.setName(newMethodName);
generatedNewName = true;
}
System.out.println("Handling overloaded method for " + method.getName());
counter++;
}while (!generatedNewName);
System.out.println("Handling overloaded method : New method name - " + method.getName());
}
private boolean areModelsAvailable(List<ModelField> modelFields, Resource resource, DataTypeMappingProvider dataTypeMapper) {
Boolean isParamSetAvailable = true;
if(modelFields == null) return true;
for(ModelField modelField : modelFields){
if (modelField.getParamType().equalsIgnoreCase(EndpointOperation.PARAM_TYPE_BODY) ){
isParamSetAvailable = false;
for(Model model : resource.getModels()){
if(dataTypeMapper.isPrimitiveType(modelField.getGenericType())){
isParamSetAvailable = true;
break;
}
if(model.getName().equalsIgnoreCase(modelField.getGenericType())){
isParamSetAvailable = true;
break;
}
}
if(!isParamSetAvailable){
return false;
}
}
}
return isParamSetAvailable;
}
}

View File

@ -1,390 +0,0 @@
/**
* 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.codegen.resource;
import com.wordnik.swagger.codegen.MethodArgument;
import com.wordnik.swagger.codegen.ResourceMethod;
import com.wordnik.swagger.codegen.config.DataTypeMappingProvider;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User: ramesh
* Date: 3/31/11
* Time: 7:54 AM
*/
public class EndpointOperation {
public static String PARAM_TYPE_QUERY = "query";
public static String PARAM_TYPE_PATH = "path";
public static String PARAM_TYPE_BODY = "body";
public static String PARAM_TYPE_HEADER = "header";
public static String POST_PARAM_NAME = "postData";
private static String AUTH_TOKEN_PARAM_NAME = "auth_token";
private static String API_KEY_PARAM_NAME = "api_key";
private static String FORMAT_PARAM_NAME = "format";
private static String AUTH_TOKEN_ARGUMENT_NAME = "auth_token";
private static Map<String, String> alreadyGeneratedModels = new HashMap<String, String>();
private static int ARG_COUNT_FOR_INPUT_MODEL = 4;
private String httpMethod;
private String summary = "";
private String notes = "";
private boolean open;
private String responseClass;
private List<ModelField> parameters;
private boolean deprecated;
private ResourceMethod method;
private List<String> tags;
private String nickname;
private List<ErrorResponse> errorResponses;
public static int getArgCountForInputModel(){
return ARG_COUNT_FOR_INPUT_MODEL;
}
public static void setArgCountForInputModel(int argCount){
ARG_COUNT_FOR_INPUT_MODEL = argCount;
}
public List<ErrorResponse> getErrorResponses() {
return errorResponses;
}
public void setErrorResponses(List<ErrorResponse> errorResponses) {
this.errorResponses = errorResponses;
}
public String getHttpMethod() {
return httpMethod;
}
public void setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public boolean isOpen() {
return open;
}
public void setOpen(boolean open) {
this.open = open;
}
public String getResponseClass() {
return responseClass;
}
public void setResponseClass(String responseClass) {
this.responseClass = responseClass;
}
public List<ModelField> getParameters() {
return parameters;
}
public void setParameters(List<ModelField> parameters) {
this.parameters = parameters;
}
public boolean isDeprecated() {
return deprecated;
}
public void setDeprecated(boolean deprecated) {
this.deprecated = deprecated;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getNickname() {
return nickname;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public ResourceMethod generateMethod(Endpoint endPoint, Resource resource, DataTypeMappingProvider dataTypeMapper, NamingPolicyProvider nameGenerator) {
if(method == null){
method = new ResourceMethod();
//add method description
method.setTitle(this.getSummary() );
method.setDescription(this.getNotes());
//add method name
//get resource path for making web service call
/**
* Logic for method names
* 1. remove all path parameters
* 2. Remove format path parameter
* 3. For POST add save
* 4. For PUT add update
* 5. For DELETE add delete
* 6. For GET add get
* 7. Concatenate rest of the path with init caps
* 8.
*/
String inputobjectName = nameGenerator.getInputObjectName(resource.generateClassName(nameGenerator), endPoint.getPath());
String[] pathElements = endPoint.getPath().split("/");
StringBuilder urlPath = new StringBuilder("");
if(pathElements != null){
for(int i=0; i < pathElements.length; i++){
String pathElement = pathElements[i];
if(pathElement != null && pathElement.length() > 0) {
int position = pathElement.indexOf("{");
if(urlPath.length() > 0) {
urlPath.append("+");
}
if(position < 0) {
urlPath.append("\"/"+pathElement+"\"");
}else if (position == 0) {
urlPath.append("\"/\"+"+pathElement.substring(1, pathElement.length()-1));
}else{
urlPath.append("\"/"+pathElement.replace("{format}", "json")+"\"");
}
}
}
}
method.setResourcePath(endPoint.getPath());
method.setName(nameGenerator.getMethodName(endPoint.getPath(), this.getNickname()));
//create method argument
/**
* 1. API token need not be included as that is always added to the calls as HTTP headers
* 2. We need to handle auth token specially, hence need to differentiate that
* 3. Query parameters needs to be added as query string hence need to separate them out
* 4. Post parameters are usually WordnikObjects, hence we need to handle them separately
*/
List<String> argNames = new ArrayList<String>();
if(this.getParameters() != null) {
List<MethodArgument> arguments = new ArrayList<MethodArgument>();
List<MethodArgument> queryParams= new ArrayList<MethodArgument>();
List<MethodArgument> pathParams= new ArrayList<MethodArgument>();
List<MethodArgument> headerParams= new ArrayList<MethodArgument>();
method.setArguments(arguments);
method.setQueryParameters(queryParams);
method.setPathParameters(pathParams);
method.setHeaderParameters(headerParams);
for(ModelField modelField : this.getParameters()){
if(!argNames.contains(modelField.getName())) {
argNames.add(modelField.getName());
MethodArgument anArgument = new MethodArgument();
anArgument.setAllowedValues(modelField.getAllowedValuesString());
//check if arguments has auth token
if(modelField.getParamType().equalsIgnoreCase(PARAM_TYPE_HEADER) &&
modelField.getName().equals(AUTH_TOKEN_PARAM_NAME)){
method.setAuthToken(true);
anArgument.setName(AUTH_TOKEN_ARGUMENT_NAME);
anArgument.setDataType(dataTypeMapper.getClassType(MethodArgument.ARGUMENT_STRING, true));
anArgument.setDescription(modelField.getDescription());
anArgument.setRequired(modelField.isRequired());
anArgument.setDefaultValue(modelField.getDefaultValue());
arguments.add(anArgument);
headerParams.add(anArgument);
}else if(modelField.getParamType().equalsIgnoreCase(PARAM_TYPE_HEADER) &&
modelField.getName().equals(API_KEY_PARAM_NAME)){
anArgument.setName(API_KEY_PARAM_NAME);
anArgument.setDataType(dataTypeMapper.getClassType(MethodArgument.ARGUMENT_STRING, true));
anArgument.setRequired(true);
arguments.add(anArgument);
headerParams.add(anArgument);
}else if (modelField.getParamType().equalsIgnoreCase(PARAM_TYPE_PATH) &&
!modelField.getName().equalsIgnoreCase(FORMAT_PARAM_NAME)) {
anArgument.setName(modelField.getName());
anArgument.setDataType(dataTypeMapper.getClassType(MethodArgument.ARGUMENT_STRING, true));
anArgument.setDescription(modelField.getDescription());
anArgument.setRequired(true); // always true
anArgument.setDefaultValue(modelField.getDefaultValue());
arguments.add(anArgument);
pathParams.add(anArgument);
}else if (modelField.getParamType().equalsIgnoreCase(PARAM_TYPE_QUERY)) {
anArgument.setName(modelField.getName());
anArgument.setDataType(dataTypeMapper.getClassType(MethodArgument.ARGUMENT_STRING, true));
anArgument.setDescription(modelField.getDescription());
anArgument.setRequired(modelField.isRequired());
anArgument.setDefaultValue(modelField.getDefaultValue());
queryParams.add(anArgument);
arguments.add(anArgument);
}else if (modelField.getParamType().equalsIgnoreCase(PARAM_TYPE_BODY)) {
if(modelField.getName() == null) {
modelField.setName(POST_PARAM_NAME);
}
anArgument.setName(modelField.getName());
anArgument.setDataType(dataTypeMapper.getClassType(modelField.getDataType(), false));
anArgument.setDescription(modelField.getDescription());
anArgument.setRequired(modelField.isRequired());
anArgument.setDefaultValue(modelField.getDefaultValue());
arguments.add(anArgument);
method.setPostObject(true);
}
if(modelField.isAllowMultiple() && dataTypeMapper.isPrimitiveType(modelField.getDataType())){
anArgument.setDataType(dataTypeMapper.getListReturnTypeSignature(
dataTypeMapper.getClassType(modelField.getDataType(), false)));
}
anArgument.setInputModelClassArgument(inputobjectName, nameGenerator);
}
}
}
//check if input model with the given name is already generated for some other path
boolean inputModelAlreadyGenerated = false;
if(alreadyGeneratedModels.containsKey(inputobjectName)){
if(!alreadyGeneratedModels.get(inputobjectName).equals(endPoint.getPath())){
inputModelAlreadyGenerated = true;
}
}
//check for number of arguments, if we have more than 4 then send the arguments as input object
if(method.getArguments() != null && method.getArguments().size() > ARG_COUNT_FOR_INPUT_MODEL &&
!inputModelAlreadyGenerated){
List<MethodArgument> arguments = new ArrayList<MethodArgument>();
Model modelforMethodInput = new Model();
modelforMethodInput.setName(inputobjectName);
List<ModelField> fields = new ArrayList<ModelField>();
for(MethodArgument argument: method.getArguments()){
if(!argument.getName().equals(POST_PARAM_NAME)){
ModelField aModelField = new ModelField();
aModelField.setAllowedValues(argument.getAllowedValues());
aModelField.setDescription(argument.getDescription());
aModelField.setName(argument.getName());
aModelField.setParamType(argument.getDataType());
fields.add(aModelField);
}else{
arguments.add(argument);
}
}
modelforMethodInput.setFields(fields);
MethodArgument anArgument = new MethodArgument();
anArgument.setDataType(inputobjectName);
anArgument.setName(nameGenerator.applyMethodNamingPolicy(inputobjectName));
arguments.add(anArgument);
method.setArguments(arguments);
method.setInputModel(modelforMethodInput);
alreadyGeneratedModels.put(inputobjectName, endPoint.getPath());
}
List<String> argumentDefinitions = new ArrayList<String>();
List<String> argumentNames = new ArrayList<String>();
if (method.getArguments() != null && method.getArguments().size() > 0) {
for(MethodArgument arg: method.getArguments()) {
if(!arg.getName().equalsIgnoreCase(FORMAT_PARAM_NAME)){
argumentDefinitions.add( dataTypeMapper.getArgumentDefinition(arg.getDataType(), arg.getName()) );
argumentNames.add(arg.getName());
}
}
method.setArgumentDefinitions(argumentDefinitions);
method.setArgumentNames(argumentNames);
}
//get method type
method.setMethodType(this.getHttpMethod());
//get return value
String returnType = dataTypeMapper.getClassType(responseClass, false);
if("".equals(returnType)){
method.setHasResponseValue(false);
}
else{
method.setHasResponseValue(true);
}
//set the original response name, this is used in identifying if the respone is single valued or multi valued
method.setReturnValueFromOperationJson(responseClass);
method.setReturnValue(dataTypeMapper.getClassType(responseClass, false));
method.setReturnClassName(dataTypeMapper.getGenericType(responseClass));
//if this is a list return type
if(method.getReturnClassName().equals(dataTypeMapper.getListReturnTypeSignature(responseClass))){
String returnValueTypeName = method.getReturnValue();
Model listWrapperModel = new Model();
listWrapperModel.setName(nameGenerator.getListWrapperName(returnValueTypeName));
List<ModelField> fields = new ArrayList<ModelField>();
ModelField aModelField = new ModelField();
aModelField.setName(nameGenerator.applyMethodNamingPolicy(returnValueTypeName));
aModelField.setParamType(responseClass);
fields.add(aModelField);
listWrapperModel.setFields(fields);
method.setListWrapperModel(listWrapperModel);
}
//get description string for exception
method.setExceptionDescription(calculateExceptionMessage());
}
return method;
}
/**
* Each operation can have one or many error responses Concatenate all the error responses and create on string
* @return
*/
private String calculateExceptionMessage() {
StringBuilder errorMessage = new StringBuilder();
if(this.getErrorResponses() != null) {
for(ErrorResponse errorResponse : this.getErrorResponses()){
errorMessage.append(errorResponse.getCode() + " - " + errorResponse.getReason() +" ");
}
}
return errorMessage.toString();
}
}

View File

@ -1,47 +0,0 @@
/**
* 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.codegen.resource;
/**
* User: ramesh
* Date: 3/31/11
* Time: 8:24 AM
*/
public class ErrorResponse {
private int code;
private String reason;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
}

View File

@ -1,58 +0,0 @@
/**
* 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.codegen.resource;
import java.util.List;
/**
* User: ramesh
* Date: 3/31/11
* Time: 8:31 AM
*/
public class Model {
private String name;
private String description;
private List<ModelField> fields;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ModelField> getFields() {
return fields;
}
public void setFields(List<ModelField> fields) {
this.fields = fields;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getGenratedClassName() {
return name.substring(0,1).toUpperCase() + name.substring(1);
}
}

View File

@ -1,277 +0,0 @@
/**
* 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.codegen.resource;
import com.wordnik.swagger.codegen.FieldDefinition;
import com.wordnik.swagger.codegen.config.ApiConfiguration;
import com.wordnik.swagger.codegen.config.DataTypeMappingProvider;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
import com.wordnik.swagger.codegen.config.ReservedWordMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* User: ramesh
* Date: 3/31/11
* Time: 7:57 AM
*/
public class ModelField {
private String name;
private String wrapperName;
private String description = "";
private String defaultValue;
private boolean required = false;
private boolean allowMultiple = false;
private AllowableValues allowableValues = null;
private String paramType;
private String dataType;
private String internalDescription;
private String paramAccess;
private String valueTypeInternal;
private String genericType;
private FieldDefinition fieldDefinition;
Logger logger = LoggerFactory.getLogger(ModelField.class);
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWrapperName() {
return wrapperName;
}
public void setWrapperName(String wrapperName) {
this.wrapperName = wrapperName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public AllowableValues getAllowableValues() {
return allowableValues;
}
public boolean isAllowMultiple() {
return allowMultiple;
}
public void setAllowMultiple(boolean allowMultiple) {
this.allowMultiple = allowMultiple;
}
public void setAllowableValues(AllowableValues allowableValues) {
this.allowableValues = allowableValues;
}
public String getAllowedValuesString() {
if(this.allowableValues != null){
return this.allowableValues.toString();
}else{
return null;
}
}
public void setAllowedValues(String csvAlowedValue) {
this.setAllowableValues(AllowableValues.ConvertAllowableValuesStringToObject(csvAlowedValue));
}
public String getParamType() {
return paramType;
}
public void setParamType(String paramType) {
this.paramType = paramType;
}
public String getInternalDescription() {
return internalDescription;
}
public void setInternalDescription(String internalDescription) {
this.internalDescription = internalDescription;
}
public String getParamAccess() {
return paramAccess;
}
public void setParamAccess(String paramAccess) {
this.paramAccess = paramAccess;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getValueTypeInternal() {
return valueTypeInternal;
}
public void setValueTypeInternal(String valueTypeInternal) {
this.valueTypeInternal = valueTypeInternal;
}
public String getGenericType() {
if(genericType == null){
if(dataType.startsWith("List[")){
genericType = dataType.substring(5, dataType.length()-1);
} else if(dataType.startsWith("Set[")){
genericType = dataType.substring(4, dataType.length()-1);
} else if(dataType.startsWith("Array[")){
genericType = dataType.substring(6, dataType.length()-1);
} else if(dataType.startsWith("Map[")){
genericType = dataType.substring(4, dataType.length()-1);
} else {
genericType = dataType;
}
}
return genericType;
}
public FieldDefinition getFieldDefinition(){
return fieldDefinition;
}
public FieldDefinition getFieldDefinition(DataTypeMappingProvider dataTypeMapper, ApiConfiguration config, NamingPolicyProvider nameGenerator, ReservedWordMapper reservedWordMapper) {
try{
if(fieldDefinition == null) {
fieldDefinition = new FieldDefinition();
String type = paramType.trim();
if(type.contains("date")||type.contains("Date") ){
fieldDefinition.getImportDefinitions().addAll(dataTypeMapper.getDateIncludes());
fieldDefinition.setHasDateResponse(true);
}
if(type.startsWith("List[")){
fieldDefinition.getImportDefinitions().addAll(dataTypeMapper.getListIncludes());
String entryType = type.substring(5, type.length()-1);
if (dataTypeMapper.isPrimitiveType(entryType)) {
fieldDefinition.setCollectionItemType(entryType);
fieldDefinition.setCollectionItemName(entryType);
} else {
final String collectionItemType = config.getModelPackageName().length() == 0 ? nameGenerator.applyClassNamingPolicy(entryType) : config.getModelPackageName() + "." + nameGenerator.applyClassNamingPolicy(entryType);
fieldDefinition.setCollectionItemType(collectionItemType);
fieldDefinition.setCollectionItemName(nameGenerator.applyMethodNamingPolicy(entryType));
}
entryType = dataTypeMapper.getClassType(entryType, true);
fieldDefinition.setHasPrimitiveType(dataTypeMapper.isPrimitiveType(entryType));
fieldDefinition.setHasListResponse(true);
String returnType = dataTypeMapper.getListReturnTypeSignature(entryType);
fieldDefinition.setReturnType(returnType);
fieldDefinition.setInitialization(" = " + dataTypeMapper.generateListInitialization(entryType));
if(this.getWrapperName() != null){
fieldDefinition.setName(this.getWrapperName());
}else{
fieldDefinition.setName(this.getName());
}
}else if(type.startsWith("Set[")){
fieldDefinition.getImportDefinitions().addAll(dataTypeMapper.getSetIncludes());
String entryType = type.substring(4, type.length()-1);
entryType = dataTypeMapper.getClassType(entryType, true);
fieldDefinition.setHasPrimitiveType(dataTypeMapper.isPrimitiveType(entryType));
fieldDefinition.setHasSetResponse(true);
String returnType = dataTypeMapper.getSetReturnTypeSignature(entryType);
fieldDefinition.setReturnType(returnType);
fieldDefinition.setInitialization(" = " + dataTypeMapper.generateSetInitialization(entryType));
if(this.getWrapperName() != null){
fieldDefinition.setName(this.getWrapperName());
}else{
fieldDefinition.setName(this.getName());
}
}else if(type.startsWith("Array[")){
fieldDefinition.getImportDefinitions().addAll(dataTypeMapper.getSetIncludes());
String entryType = type.substring(6, type.length()-1);
entryType = dataTypeMapper.getClassType(entryType, true);
fieldDefinition.setHasPrimitiveType(dataTypeMapper.isPrimitiveType(entryType));
fieldDefinition.setHasArrayResponse(true);
String returnType = dataTypeMapper.getArrayReturnTypeSignature(entryType);
fieldDefinition.setReturnType(returnType);
fieldDefinition.setInitialization(" = " + dataTypeMapper.generateArrayInitialization(entryType));
if(this.getWrapperName() != null){
fieldDefinition.setName(this.getWrapperName());
}else{
fieldDefinition.setName(this.getName());
}
}else if (type.startsWith("Map[")) {
fieldDefinition.getImportDefinitions().addAll(dataTypeMapper.getMapIncludes());
String keyClass, entryClass = "";
String entryType = type.substring(4, type.length()-1);
keyClass = entryType.substring(0, entryType.indexOf(",") );
entryClass = entryType.substring(entryType.indexOf(",") + 1, entryType.length());
fieldDefinition.setHasPrimitiveType(dataTypeMapper.isPrimitiveType(entryClass));
fieldDefinition.setHasMapResponse(true);
//entryType = dataTypeMapper.getClassType(entryType, true);
entryType = dataTypeMapper.getClassType(keyClass, true) + "," + dataTypeMapper.getClassType(entryClass, true);
String returnType = dataTypeMapper.getMapReturnTypeSignature(entryType);
fieldDefinition.setReturnType(returnType);
fieldDefinition.setInitialization("= " + dataTypeMapper.generateMapInitialization(entryType));
if(this.getWrapperName() != null){
fieldDefinition.setName(this.getWrapperName());
}else{
fieldDefinition.setName(this.getName());
}
}else{
fieldDefinition.setInitialization(dataTypeMapper.generateVariableInitialization(type));
fieldDefinition.setReturnType(dataTypeMapper.getClassType(type, false));
fieldDefinition.setName(this.getName());
fieldDefinition.setHasPrimitiveType(dataTypeMapper.isPrimitiveType(fieldDefinition.getReturnType()));
}
}
fieldDefinition.setOriginalName(reservedWordMapper.retranslate(fieldDefinition.getName()));
return fieldDefinition;
}catch(RuntimeException t){
logger.error("Error generating field definition for object " + this.getName() + " data type " + this.getDataType());
throw t;
}
}
}

View File

@ -1,159 +0,0 @@
/**
* 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.codegen.resource;
import com.wordnik.swagger.codegen.ResourceMethod;
import com.wordnik.swagger.codegen.config.DataTypeMappingProvider;
import com.wordnik.swagger.codegen.config.LanguageConfiguration;
import com.wordnik.swagger.codegen.config.NamingPolicyProvider;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* User: ramesh
* Date: 3/30/11
* Time: 7:01 PM
*/
public class Resource {
private String apiVersion;
@JsonProperty("swaggerVersion")
private String swaggerVersion;
@JsonProperty("resourcePath")
private String resourcePath;
@JsonProperty("apis")
private List<Endpoint> endPoints = new ArrayList<Endpoint>();
@JsonProperty("models")
private ApiModelListWrapper modelListWrapper;
private List<Model> models = new ArrayList<Model>();
private String generatedClassName;
private List<ResourceMethod> methods;
@JsonCreator
public Resource() {
}
public String getApiVersion() {
return apiVersion;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
@JsonProperty("swaggerVersion")
public String getSwaggerVersion() {
return swaggerVersion;
}
@JsonProperty("swaggerVersion")
public void setSwaggerVersion(String swaggerVersion) {
this.swaggerVersion = swaggerVersion;
}
@JsonProperty("resourcePath")
public String getResourcePath() {
return resourcePath;
}
@JsonProperty("resourcePath")
public void setResourcePath(String resourcePath) {
this.resourcePath = resourcePath;
}
@JsonProperty("apis")
public List<Endpoint> getEndPoints() {
return endPoints;
}
@JsonProperty("apis")
public void setEndPoints(List<Endpoint> endPoints) {
this.endPoints = endPoints;
}
@JsonProperty("models")
public ApiModelListWrapper getModelListWrapper() {
return modelListWrapper;
}
@JsonProperty("models")
public void setModelListWrapper(ApiModelListWrapper modelListWrapper) {
this.modelListWrapper = modelListWrapper;
}
public List<Model> getModels() {
return models;
}
/*public void setModels(List<Model> models) {
this.models = models;
}*/
public String generateClassName(NamingPolicyProvider nameGenerator) {
if (generatedClassName == null && endPoints.size() > 0) {
String endPointPath = endPoints.get(0).getPath();
generatedClassName = nameGenerator.getServiceName(endPointPath);
}
return generatedClassName;
}
public List<ResourceMethod> generateMethods(Resource resource, DataTypeMappingProvider dataTypeMapper,
NamingPolicyProvider nameGenerator, LanguageConfiguration languageConfig) {
if(methods == null){
methods = new ArrayList<ResourceMethod>();
List<ResourceMethod> newMethods = new ArrayList<ResourceMethod>();
List<String> endPointMethodNames = new ArrayList<String>();
if(getEndPoints() != null) {
for(Endpoint endpoint: getEndPoints()){
newMethods = endpoint.generateMethods(resource, dataTypeMapper, nameGenerator, languageConfig);
if (!languageConfig.isMethodOverloadingSupported()) {
for(ResourceMethod newMethod: newMethods){
if(endPointMethodNames.contains( newMethod.getName() )) {
endpoint.handleOverloadedMethod(newMethod, endPointMethodNames);
}
endPointMethodNames.add(newMethod.getName());
}
}
methods.addAll(newMethods);
}
}
}
return methods;
}
public void generateModelsFromWrapper(NamingPolicyProvider nameGenerator) {
String modelName;
ApiModelDefn modelDefn;
if (modelListWrapper != null) {
for (Map.Entry<String, ApiModelDefn> entry : modelListWrapper.getModelList().entrySet()) {
modelName = entry.getKey();
modelDefn = entry.getValue();
models.add (modelDefn.toModel(modelName, nameGenerator) );
}
}
}
}

View File

@ -1,204 +0,0 @@
/**
* 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.codegen.util;
import com.wordnik.swagger.codegen.exception.CodeGenerationException;
import java.io.*;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.commons.lang.StringUtils;
/**
* User: deepakmichael
* Date: 03/08/11
* Time: 12:02 AM
*/
public class FileUtil {
/**
* Creates directory if doesn't exists and also cleans the files of given type if directory already contains some
* files.
*
* @param classLocation
* @param fileExtension
*/
public static void createOutputDirectories(String classLocation, String fileExtension) {
File outputLocation = new File(classLocation);
outputLocation.mkdirs(); //make folder if necessary
//clear contents
clearFolder(classLocation, fileExtension);
}
/**
* Deletes a fingle file and returns false fi file doesn't exists
* @param sFilePath
* @return
*/
public static boolean deleteFile(String sFilePath) {
File oFile = new File(sFilePath);
if (!oFile.exists()) {
return false;
}
return oFile.delete();
}
/**
* Deleet all the files from the specified location
* @param directoryLocation
*/
public static void clearFolder(String directoryLocation) {
File fDir = new File(directoryLocation);
File[] files = fDir.listFiles();
if(files != null) {
for(File aFile : files) {
aFile.delete();
}
}
}
// Clears the folder of the files with extension
public static void clearFolder(String strFolder, final String strExt) {
File fLogDir = new File(strFolder);
File[] fLogs = fLogDir.listFiles(new FilenameFilter() {
public boolean accept(File fDir, String strName) {
return (strName.endsWith(strExt));
}
});
if (fLogs != null) {
for (int i = 0; i < fLogs.length; i++) {
deleteFile(fLogs[i].getAbsolutePath());
}
}
}
public static void copyDirectory(File srcPath, File dstPath) {
if (srcPath.isDirectory()) {
if (!dstPath.exists()) {
dstPath.mkdir();
}
String files[] = srcPath.list();
for (int i = 0; i < files.length; i++) {
copyDirectory(new File(srcPath, files[i]), new File(dstPath, files[i]));
}
} else {
if (!srcPath.exists()) {
throw new CodeGenerationException("Source folder does not exist");
} else {
try {
InputStream in = new FileInputStream(srcPath);
OutputStream out = new FileOutputStream(dstPath);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
throw new CodeGenerationException("Copy directory operation failed");
}
}
}
}
public static void copyDirectoryFromUrl(final URL originUrl, final File destination) {
try {
final URLConnection urlConnection = originUrl.openConnection();
if (urlConnection instanceof JarURLConnection) {
FileUtil.copyJarResourcesRecursively(destination,
(JarURLConnection) urlConnection);
} else {
FileUtil.copyDirectory(new File(originUrl.getPath()),
destination);
}
} catch (final IOException e) {
e.printStackTrace();
}
}
public static boolean copyJarResourcesRecursively(final File destDir,
final JarURLConnection jarConnection) throws IOException {
final JarFile jarFile = jarConnection.getJarFile();
for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
final JarEntry entry = e.nextElement();
if (entry.getName().startsWith(jarConnection.getEntryName())) {
final String filename = StringUtils.removeStart(entry.getName(), //
jarConnection.getEntryName());
final File f = new File(destDir, filename);
if (!entry.isDirectory()) {
final InputStream entryInputStream = jarFile.getInputStream(entry);
if(!FileUtil.copyStream(entryInputStream, f)){
return false;
}
entryInputStream.close();
} else {
if (!FileUtil.ensureDirectoryExists(f)) {
throw new IOException("Could not create directory: "
+ f.getAbsolutePath());
}
}
}
}
return true;
}
private static boolean copyStream(final InputStream is, final File f) {
try {
return FileUtil.copyStream(is, new FileOutputStream(f));
} catch (final FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
private static boolean copyStream(final InputStream is, final OutputStream os) {
try {
final byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) > 0) {
os.write(buf, 0, len);
}
is.close();
os.close();
return true;
} catch (final IOException e) {
e.printStackTrace();
}
return false;
}
private static boolean ensureDirectoryExists(final File f) {
return f.exists() || f.mkdir();
}
}

View File

@ -1,35 +0,0 @@
/**
* 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.runtime.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

@ -1,29 +0,0 @@
/**
* 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.runtime.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

@ -1,33 +0,0 @@
/**
* 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.runtime.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

@ -1,322 +0,0 @@
/**
* 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.runtime.common;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.String;
import java.net.URLEncoder;
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.runtime.exception.APIException;
import com.wordnik.swagger.runtime.exception.APIExceptionCodes;
import org.codehaus.jackson.map.DeserializationConfig;
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 String apiServer = "http://api.wordnik.com/v4";
private SecurityHandler securityHandler = null;
private static boolean loggingEnabled;
private static Logger logger = null;
private static APIInvoker apiInvoker = null;
private static Client apiClient = 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.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(SerializationConfig.Feature.WRITE_NULL_PROPERTIES, false);
mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
apiClient = Client.create();
}
/**
* 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 APIInvoker initialize(SecurityHandler securityHandler, String apiServer, boolean enableLogging) {
APIInvoker invoker = new APIInvoker();
invoker.setSecurityHandler(securityHandler);
if(apiServer != null && apiServer.length() > 0) {
if(apiServer.substring(apiServer.length()-1).equals("/")){
apiServer = apiServer.substring(0, apiServer.length()-1);
}
invoker.setApiServer(apiServer);
}
invoker.setLoggingEnable(enableLogging);
//initialize the logger if needed
if(loggingEnabled && apiInvoker == null) {
if(logger == null) {
apiClient.addFilter(new LoggingFilter());
}else{
apiClient.addFilter(new LoggingFilter(logger));
}
}
apiInvoker = invoker;
return invoker;
}
/**
* Returns lst initialized API invoker
* @return
*/
public static APIInvoker getApiInvoker(){
return apiInvoker;
}
/**
* Set the logger instance used for Jersey logging.
* @param aLogger
*/
public void setLogger(Logger aLogger) {
logger = aLogger;
}
/**
* Gets the API key used for server communication.
* This value is set using initialize method.
* @return
*/
public SecurityHandler setSecurityHandler() {
return securityHandler;
}
private 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 String getApiServer() {
return apiServer;
}
public 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 postData - 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.runtime.exception.APIException if the call to API server fails.
*/
public String invokeAPI(String resourceURL, String method, Map<String,
String> queryParams, Object postData, Map<String, String> headerParams) throws APIException {
//check for app server values
if(getApiServer() == null || getApiServer().length() == 0) {
String[] args = {getApiServer()};
throw new APIException(APIExceptionCodes.API_SERVER_NOT_VALID, args);
}
//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));
}
if(headerParams != null){
for(String key : headerParams.keySet()){
builder.header(key, headerParams.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 {
if(inputClassName.isAssignableFrom(String.class)){
return response;
} else if (inputClassName.isAssignableFrom(Integer.class)){
return new Integer(response);
} else if (inputClassName.isAssignableFrom(Boolean.class)){
return new Boolean(response);
} else if (inputClassName.isAssignableFrom(Long.class)){
return new Long(response);
} else if (inputClassName.isAssignableFrom(Double.class)){
return new Double(response);
} else{
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) {
if (input instanceof String) {
return (String)input;
} else {
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) {
value = (value == null) ? "" : value;
return encode(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();
String output = "";
for(Object o: objects){
out.append(o.toString());
out.append(",");
}
if(out.indexOf(",") != -1) {
output = out.substring(0, out.lastIndexOf(",") );
}
return encode(output);
}
private static String encode(String value){
try{
return URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20");
}catch(UnsupportedEncodingException uee){
throw new RuntimeException(uee.getMessage());
}
}
public boolean isLoggingEnable() {
return loggingEnabled;
}
public void setLoggingEnable(boolean enabled) {
loggingEnabled = enabled;
}
}

View File

@ -1,67 +0,0 @@
/**
* 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.runtime.common;
import java.util.Map;
/**
* User: ramesh
* Date: 8/4/11
* Time: 6:39 PM
*/
public class ApiKeyAuthTokenBasedSecurityHandler implements SecurityHandler {
private String apiKey = "";
private String authToken = "";
public ApiKeyAuthTokenBasedSecurityHandler(String apiKey, String authToken) {
this.apiKey = apiKey;
this.authToken = authToken;
}
public String getAuthToken() {
return authToken;
}
public void setAuthToken(String authToken) {
this.authToken = authToken;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
/**
* Populate the security infomration in http headers map and/or reqsource URL.
*
* Value spopulated in the http headers map will be set as http headers while making the server communication.
*
* Depending on the usecase requried information can be added to either of them or both.
*
* @param resourceURL
* @param headers
*/
public void populateSecurityInfo(String resourceURL, Map<String, String> httpHeaders) {
resourceURL = resourceURL + "api_key="+apiKey;
httpHeaders.put("api_key", apiKey);
httpHeaders.put("auth_token", authToken);
}
}

View File

@ -1,47 +0,0 @@
/**
* 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.runtime.common;
import java.util.Map;
/**
* Provide methods that are responsible for handling security aspect while communicating with the backend server.
*
* Example: For some cases API key may need to be passed in the headers for all server communication and some times
* user authentication token may need to be passed along with api key.
*
* Implementers of this class are responsible for handling storing information related to secutiry and sending it
* along with all API calls
*
* User: ramesh
* Date: 4/12/11
* Time: 5:46 PM
*/
public interface SecurityHandler {
/**
* Populate the security infomration in http headers map and/or reqsource URL.
*
* Value spopulated in the http headers map will be set as http headers while making the server communication.
*
* Depending on the usecase requried information can be added to either of them or both.
*
* @param resourceURL
* @param headers
*/
public void populateSecurityInfo(String resourceURL, Map<String, String> httpHeaders);
}

View File

@ -1,100 +0,0 @@
/**
* 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.runtime.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

@ -1,54 +0,0 @@
/**
* 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.runtime.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

@ -1,581 +0,0 @@
/**
* 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.testframework;
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider;
import com.wordnik.swagger.runtime.common.APIInvoker;
import com.wordnik.swagger.runtime.common.ApiKeyAuthTokenBasedSecurityHandler;
import com.wordnik.swagger.runtime.common.SecurityHandler;
import com.wordnik.swagger.runtime.exception.APIException;
import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.type.TypeFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Instance of this class is used to run the tests and assert the results based on
* JSON based test script.
* Created by IntelliJ IDEA.
* User: ramesh
* Date: 3/30/11
* Time: 6:27 PM
*/
public class APITestRunner {
private static String INPUT_DATA_EXPRESSION_PREFIX = "${input.";
private static String OUTPUT_DATA_EXPRESSION_PREFIX = "${output";
public static String POST_PARAM_NAME = "postData";
private static String CONDITION_EQUAL = "==";
private static String CONDITION_NOT_EQUAL = "!=";
private static String CONDITION_GREATER = ">";
private static String CONDITION_LESSER = "<";
private static String CONDITION_GREATER_EQUAL = ">=";
private static String CONDITION_LESSER_EQUAL = "<=";
private TestOutput testCaseOutput = new TestOutput();
private TestStatus testStatus = new TestStatus();
private Object testData = null;
private TestPackage aPackage = null;
private static String JAVA = "JAVA";
private static String SCALA = "SCALA";
private static String PYTHON = "PYTHON";
private static String RUBY = "RUBY";
private static String ANDROID = "ANDROID";
private static String OBJECTIVE_C = "OBJECTIVE_C";
private static String AS3 = "AS3";
private static String NET = "NET";
private static String PHP = "PHP";
private static String HASKEL = "HASKEL";
private static String CLOJURE = "CLOJURE";
private static ObjectMapper mapper = new ObjectMapper();
static{
mapper.getDeserializationConfig().set(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(SerializationConfig.Feature.WRITE_NULL_PROPERTIES, false);
mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
}
private CamelCaseNamingPolicyProvider namingPolicyProvider = new CamelCaseNamingPolicyProvider();
/**
* Follow the following argument pattern
*
* Arg[0] --> api server URL
* Arg[1] --> api key
* Arg[2] --> test script file path
* Arg[3] --> test data file path
* Arg[4] --> test data class name (class to which test data file will be deserialized)
* Arg[5] --> package where API classes are available
* Arg[6] --> Language to execute test cases
* Arg[7] --> Library location
* Arg[8] --> Optional test cases id. provide this if you need to execute only one test case
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String apiServer = args[0];
if(!apiServer.endsWith("/")){
apiServer = apiServer + "/";
}
String apiKey = args[1];
String testScriptLocation = args[2];
String testDataLocation = args[3];
String testDataClass = args[4].trim();
System.out.println("class"+testDataClass+"test");
String apiPackageName = args[5];
String libraryLocation = args[6];
String language = args[7];
String suiteId = "0";
if(args.length > 8){
suiteId = args[8];
}
ApiKeyAuthTokenBasedSecurityHandler securityHandler = new ApiKeyAuthTokenBasedSecurityHandler(apiKey, "");
APIInvoker aAPIInvoker = APIInvoker.initialize(securityHandler, apiServer, true);
APITestRunner runner = new APITestRunner();
runner.initialize(testScriptLocation, testDataLocation, testDataClass);
runner.runTests(apiServer, apiPackageName, runner.getTestPackage(), language, new Integer(suiteId), apiPackageName, securityHandler, libraryLocation);
}
public void initialize(String testScriptLocation, String testDataLocation, String testDataClass) throws Exception {
//load test script
File aFile = new File(testScriptLocation);
BufferedReader reader = new BufferedReader(new FileReader(aFile));
StringBuilder builder = new StringBuilder();
while(true){
String line = reader.readLine();
if(line == null){
break;
}else{
builder.append(line);
}
}
mapper.getDeserializationConfig().set(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
aPackage = (TestPackage) mapper.readValue(builder.toString(), TestPackage.class);
//load test data
aFile = new File(testDataLocation);
reader = new BufferedReader(new FileReader(aFile));
builder = new StringBuilder();
while(true){
String line = reader.readLine();
if(line == null){
break;
}else{
builder.append(line);
}
}
testData = mapper.readValue(builder.toString(), Class.forName(testDataClass));
reader.close();
}
/**
* Gets the package that is initialized for testing
* @return
*/
public TestPackage getTestPackage() {
return aPackage;
}
/***
* Runs individual test cases in all test suites and stored the result in output object
* @param testPackage
*/
private void runTests(String apiServer, String apiPackageName, TestPackage testPackage, String language, int suiteId,
String libraryPackageName, ApiKeyAuthTokenBasedSecurityHandler securityHandler,
String libraryLocation) throws Exception {
/**
* Logic:
*
* 1. Get each test case
*
* 2. based on the patch arrive at the method that needs to be executed
*
* 3. From the method get list of input parameters
*
* 4. Read input parameters based on input structure
*
* 5 Execute method by calling system command
*
* 6. Get the output
*
* 7. Store output in output object
*
* 8. execute assertions
*
* 9. Continue with next test case
*/
Map<Integer, TestResource> resourceMap = new HashMap<Integer, TestResource>();
for(TestResource resource: testPackage.getResources()){
resourceMap.put(resource.getId(), resource);
}
for(TestSuite suite : testPackage.getTestSuites()) {
if(suiteId != 0 && suiteId != suite.getId()){
continue;
}
int testSuiteId = suite.getId();
//1
for(TestCase testCase : suite.getTestCases()){
String testCasePath = testCasePath(testSuiteId , testCase.getId());
//2
TestResource resource = resourceMap.get(testCase.getResourceId());
String path = resource.getPath();
String className = namingPolicyProvider.getServiceName(path);
String methodName = resource.getSuggestedMethodName();
//3
Class apiClass = Class.forName(libraryPackageName +"." + className);
Method[] methods = apiClass.getMethods();
Method methodToExecute = null;
for(Method method : methods){
if(method.getName().equals(methodName)){
methodToExecute = method;
break;
}
}
try {
if(methodToExecute != null) {
//4
Map<String, Object> arguments = getArgumentsForMethodCall(methodToExecute, testCase);
String authToken = "\"\"";
String postData = "\"\"";
StringBuilder queryPathParameters = new StringBuilder();
for(String argName : arguments.keySet()){
Object value = arguments.get(argName);
if(argName.equals("authToken")){
authToken = value.toString();
}else if (argName.equals(POST_PARAM_NAME)){
postData = convertObjectToJSONString(value);
}else{
if(queryPathParameters.toString().length()> 0){
queryPathParameters.append("~");
}
queryPathParameters.append(argName+"="+value.toString());
}
}
//get eternal command
String[] externalCommand = constructExternalCommand(apiServer, apiPackageName,
securityHandler.getApiKey(), authToken,
resource.getPath(), resource.getHttpMethod(), resource.getSuggestedMethodName(),
queryPathParameters.toString(), postData, language, libraryLocation);
//print the command
System.out.println("Test Case :" + testCasePath);
for(String arg : externalCommand){
System.out.print(arg + " ");
}
System.out.println("");
//execute and get data
String outputString = executeExternalTestCaseAndGetResult(externalCommand);
Object output = null;
if(outputString != null && outputString.length() > 0) {
output = convertJSONStringToObject(outputString, methodToExecute.getReturnType());
}
//6
Class returnType = methodToExecute.getReturnType();
if(!returnType.getName().equalsIgnoreCase("void")){
//7
testCaseOutput.getData().put(testCasePath, output);
}
//8
//log it as passed, if there is any failures in assertions, assertions will update the status
//to failed
testStatus.logStatus(testCase, testCasePath, true);
executeAssertions(testCasePath, testCase);
}
}catch(Exception e){
boolean asserted = false;
if(testCase.getAssertions() != null) {
for(Assertion assertion : testCase.getAssertions()){
if(assertion.getCondition().equals("==") && assertion.getExpectedOutput().equalsIgnoreCase("Exception")){
testStatus.logStatus(testCase, testCasePath, true);
asserted = true;
}
}
}
if(!asserted){
testStatus.logStatus(testCase, testCasePath, false, e.getMessage(), e);
}
}
}
}
System.out.println(testStatus.printTestStatus());
}
/**
* Populate necessayr argument values tat needs ot be populated before calling the method
* @return
*/
protected Map<String, Object> getArgumentsForMethodCall(Method methodToExecute, TestCase testCase) throws Exception {
Map<String, Object> queryPathParameters = new HashMap<String, Object>();
if(testCase.getInput() != null) {
for(String inputParamName: testCase.getInput().keySet()){
Object value = getParamValue(testCase.getInput().get(inputParamName));
queryPathParameters.put(inputParamName, value);
}
}
return queryPathParameters;
}
/**
* Execute all assertions in the test case. If there are nay failures test case will be amrked as failed
* and logged into test status object.
* @param testCase
*/
private void executeAssertions(String testCasePath, TestCase testCase) {
List<Assertion> assertions = testCase.getAssertions();
if(assertions != null) {
for(Assertion assertion: assertions){
try{
Object actualOutPut = getParamValue(assertion.getActualOutput());
Object expectedValue = getParamValue(assertion.getExpectedOutput());
boolean failed = false;
if(assertion.getCondition().equals(CONDITION_EQUAL)){
if(expectedValue.toString().equalsIgnoreCase("NULL") && actualOutPut == null){
failed = false;
}else{
if(expectedValue.getClass().isAssignableFrom(String.class)){
actualOutPut = actualOutPut.toString();
}
if(!actualOutPut.equals(expectedValue)){
failed = true;
}
}
}else if(assertion.getCondition().equals(CONDITION_NOT_EQUAL)){
if(expectedValue.toString().equalsIgnoreCase("EXCEPTION")){
//this means user is not expecting any exception, output can be null, if we have reached
// here means there are no exceptions hence we can call the assertion is passed.
failed = false;
}
else if(actualOutPut == null || actualOutPut.equals(expectedValue)){
failed = true;
}
}else{
float actual = new Float(actualOutPut.toString());
float expected = new Float(expectedValue.toString());
if(assertion.getCondition().equals(CONDITION_GREATER)){
if(!(actual > expected)){
failed = true;
}
}else if(assertion.getCondition().equals(CONDITION_LESSER)){
if(!(actual < expected)){
failed = true;
}
}else if(assertion.getCondition().equals(CONDITION_LESSER_EQUAL)){
if(!(actual <= expected)){
failed = true;
}
}else if(assertion.getCondition().equals(CONDITION_GREATER_EQUAL)){
if(!(actual >= expected)){
failed = true;
}
}
}
if(failed) {
if(actualOutPut == null) {
testStatus.logAssertionStatus(testCasePath, false, expectedValue.toString(), null, assertion.getCondition());
}else{
testStatus.logAssertionStatus(testCasePath, false, expectedValue.toString(), actualOutPut.toString(), assertion.getCondition());
}
} else{
if(actualOutPut == null) {
testStatus.logAssertionStatus(testCasePath, true, expectedValue.toString(), "null", assertion.getCondition());
}else{
testStatus.logAssertionStatus(testCasePath, true, expectedValue.toString(), actualOutPut.toString(), assertion.getCondition());
}
}
}catch(Exception e){
e.printStackTrace();
testStatus.logAssertionStatus(testCasePath, false, assertion.getExpectedOutput(), assertion.getActualOutput(), assertion.getCondition(), e);
}
}
}
}
/**
* creates the test case unique path
* @param suiteId
* @param caseId
* @return
*/
private String testCasePath(int suiteId, int caseId) {
return suiteId + "." + caseId;
}
/**
* Read the values based on expression.
* The expression can refer the value in input data structure or outputs generated from executing the current or previous
* test cases or direct input. The Test script follow the syntax of ${output if it is referring output data,
* ${input if it is referring input data.
* @param name
* @return
* @throws Exception
*/
private Object getParamValue(String name) throws Exception {
//this means we should use the input form previous steps or data file.
if(name.startsWith("$")){
//sample:"${input.userList[0].username}"
if(name.startsWith(INPUT_DATA_EXPRESSION_PREFIX)){
String expression = name.substring(INPUT_DATA_EXPRESSION_PREFIX.length(), name.length()-1);
boolean hasSize = false;
if(expression.endsWith("size")){
expression = expression.substring(0, expression.length()-5);
hasSize = true;
}
Object value = PropertyUtils.getProperty(testData, expression);
if(hasSize){
return MethodUtils.invokeMethod(value, "size", null);
}
return value;
}else if(name.startsWith(OUTPUT_DATA_EXPRESSION_PREFIX)) {
//sample: ${output(1.1.1).token}
String expression = name.substring(OUTPUT_DATA_EXPRESSION_PREFIX.length(), name.length()-1);
expression = "data"+expression;
boolean hasSize = false;
if(expression.endsWith("size")){
expression = expression.substring(0, expression.length()-5);
hasSize = true;
}
Object value = PropertyUtils.getProperty(testCaseOutput, expression);
if(hasSize){
return MethodUtils.invokeMethod(value, "size", null);
}
return value;
}else{
throw new RuntimeException("Input expression for parameter " + name + "is not as per valid syntax ");
}
}else{
return name;
}
}
/**
* Converts JSON string to object.
*/
public static Object convertJSONStringToObject(String inputJSON, Class objectType) throws Exception {
boolean isArray = false;
boolean isList = false;
Class className = objectType;
String ObjectTypeName = objectType.getName();
//identify if the input is a array
if(ObjectTypeName.startsWith("[")){
isArray = true;
className = objectType.getComponentType();
}
//identify if the input is a list
if(List.class.isAssignableFrom(objectType)){
isList = true;
}
if(isArray || isList){
Object responseObject = mapper.readValue(inputJSON, TypeFactory.type(objectType));
return responseObject;
}else{
return APIInvoker.deserialize(inputJSON, className);
}
}
/**
* Converts JSON string to object.
*/
public static String convertObjectToJSONString(Object input) throws Exception {
return APIInvoker.serialize(input);
}
/**
* Reads the test case results from standard out, converts that into java object and stores the value
* in test case output data so that the same can be used in subsequent test case execution
*
* First line fo response should be a status line with possible values as SUCCESS, ERROR
*/
private String executeExternalTestCaseAndGetResult(String[] command) throws Exception {
Process p = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
StringBuilder output = new StringBuilder();
String s = null;
boolean isStatusLine = true;
String status = "";
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
if(isStatusLine){
status = s;
if(status.equalsIgnoreCase("SUCCESS")||status.equalsIgnoreCase("OK") ) {
isStatusLine = false;
}
}else{
output.append(s);
}
}
if(status.equalsIgnoreCase("SUCCESS")||status.equalsIgnoreCase("OK") ) {
return output.toString();
}else{
APIException exception = (APIException)convertJSONStringToObject(output.toString(),
APIException.class);
throw exception;
}
}
/**
* Get the java command line that needs to be executed for runnign a test case
*/
private String[] constructExternalCommand(String apiServer, String apiPackageName, String apiKey, String authToken,
String resource, String httpMethod, String suggestedMethodName, String queryAndPathParams,
String postData, String language, String libraryLocation) {
List<String> command = new ArrayList<String>();
if(language.equals(JAVA)){
command.add("./bin/runjavaTestCase.sh");
command.add("com.wordnik.swagger.testframework.JavaTestCaseExecutor");
command.add( libraryLocation );
}else if (language.equals(PYTHON)){
command.add("../python/runtest.py ");
}else if (language.equals(ANDROID)){
command.add("../android/driver-test/bin/runandroid.sh");
command.add("com.wordnik.swagger.testframework.JavaTestCaseExecutor");
}else if (language.equals(AS3)){
command.add("./bin/runas3TestCase.sh");
command.add("com.wordnik.swagger.testframework.AS3TestCaseExecutor");
if(postData == null){
postData = "\"\"";
}
else{
postData = "\"" + postData + "\"";
}
}
command.addAll(getCommandInputs(apiServer, apiPackageName, apiKey, authToken, resource, httpMethod,
suggestedMethodName, queryAndPathParams, postData,
language));
String[] commandArray = new String[command.size()];
command.toArray(commandArray);
return commandArray;
}
private List<String> getCommandInputs(String apiServer, String apiPackageName, String apiKey, String authToken, String resource, String httpMethod,
String suggestedMethodName, String queryAndPathParams, String postData,
String language) {
List<String> inputs = new ArrayList<String>();
inputs.add(apiServer);
inputs.add(apiPackageName);
inputs.add(apiKey);
inputs.add(authToken);
inputs.add(resource);
inputs.add(httpMethod);
inputs.add(suggestedMethodName);
inputs.add(queryAndPathParams);
if(postData.equals("\"\"")){
inputs.add(postData);
}else{
inputs.add(postData);
}
return inputs;
}
}

View File

@ -1,167 +0,0 @@
package com.wordnik.swagger.testframework;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User: deepakmichael
* Date: 08/09/11
* Time: 10:34 AM
*/
public class AS3TestCaseExecutor {
/**
* Follow the following argument pattern
* Arguments in calling this method:
* ApiServerURL
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
AS3TestCaseExecutor runner = new AS3TestCaseExecutor();
String apiServer = args[0];
String servicePackageName = args[1];
String apiKey = args[2];
String authToken = args[3];
String resource = args[4];
String httpMethod = args[5];
String suggestedMethodName = args[6];
Map<String, String> queryAndPathParameters = new HashMap<String, String>();
String postData = null;
if(args.length > 7 && args[7].length() > 0){
String[] qpTuple = args[7].split("~");
for(String tuple: qpTuple){
String[] nameValue = tuple.split("=");
if (nameValue.length == 2 ) {
queryAndPathParameters.put(nameValue[0], nameValue[1]);
}
}
}
if(args.length > 8 ){
postData = args[8];
}
queryAndPathParameters.put("authToken", authToken);
servicePackageName = args[9];
String testAppConfigPath = args[10];
String flexHome = args[11];
runner.writeJSONTestData(apiServer, apiKey, authToken, httpMethod, resource, servicePackageName,
suggestedMethodName, queryAndPathParameters, postData, testAppConfigPath);
runner.executeTestCase(testAppConfigPath, flexHome);
}
private void executeTestCase(String testAppConfigPath, String flexHome) throws Exception {
String[] externalCommand = constructExternalCommand(testAppConfigPath, flexHome);
executeExternalTestCaseAndGetResult(externalCommand);
}
private void writeJSONTestData(String apiServer, String apiKey, String authToken, String httpMethod, String resource,
String servicePackageName, String suggestedMethodName, Map<String,
String> queryAndPathParameters, String postData, String testAppConfigPath) throws IOException {
//write JSON file
HashMap<String, Object> testInfo = new HashMap<String, Object>();
testInfo.put("apiUrl",apiServer);
testInfo.put("apiPackageName", servicePackageName);
testInfo.put("apiKey", apiKey);
testInfo.put("authToken", authToken);
testInfo.put("resource", resource);
testInfo.put("httpMethod", httpMethod);
testInfo.put("methodName", suggestedMethodName);
testInfo.put("queryAndPathParams",queryAndPathParameters);
testInfo.put("postData", postData);
testInfo.put("language","AS3");
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
File aFileInOutputPath = new File(testAppConfigPath);
String parentDirectory = aFileInOutputPath.getParent();
mapper.writeValue(new File(parentDirectory+"/testData.json"), testInfo);
}
private void executeExternalTestCaseAndGetResult(String[] command) throws Exception {
Process p = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
StringBuilder output = new StringBuilder();
String s = null;
boolean isStatusLine = true;
String status = "";
while ((s = stdInput.readLine()) != null) {
//System.out.println(s);
if(isStatusLine){
status = s;
if(status.equalsIgnoreCase("SUCCESS")||status.equalsIgnoreCase("OK") ) {
isStatusLine = false;
}
}else{
output.append(s);
}
//System.out.println(s);
}
String userDirectory = System.getProperty("user.home")+ File.separator+"Documents";
String outputFile = userDirectory + File.separator+"testOutput.json";
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
File from = new File(outputFile);
TypeReference<HashMap<String,Object>> typeRef
= new TypeReference<
HashMap<String,Object>
>() {};
HashMap<String,Object> o
= mapper.readValue(from, typeRef);
Boolean isSuccess = false;
if(o.containsKey("isSuccess")){
isSuccess = (Boolean) o.get("isSuccess");
}
System.out.println(isSuccess ? "SUCCESS" : "FAILURE");
if(isSuccess){
if ( o.get("payload") != null ) {
mapper.writeValue(System.out, o.get("payload"));
}
}
else{
mapper.writeValue(System.out, o.get("errorMessage"));
}
from.delete();
}
/**
* Get the java command line that needs to be executed for runnign a test case
* @param testAppConfigPath
* @param flexHome
*/
private String[] constructExternalCommand(String testAppConfigPath, String flexHome) {
List<String> command = new ArrayList<String>();
command.add(flexHome + "/bin/adl");
command.add(testAppConfigPath);
String[] commandArray = new String[command.size()];
command.toArray(commandArray);
return commandArray;
}
}

View File

@ -1,60 +0,0 @@
/**
* 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.testframework;
public class Assertion {
private String expectedOutput;
private String actualOutputWithOutputWrapper;
private String condition;
private String actualOutput;
public String getExpectedOutput() {
return expectedOutput;
}
public void setExpectedOutput(String expression) {
this.expectedOutput = expression;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getActualOutput() {
return actualOutput;
}
public void setActualOutput(String value) {
this.actualOutput = value;
}
public String getActualOutputWithOutputWrapper() {
return actualOutputWithOutputWrapper;
}
public void setActualOutputWithOutputWrapper(String actualOutputWithOutputWrapper) {
this.actualOutputWithOutputWrapper = actualOutputWithOutputWrapper;
}
}

View File

@ -1,227 +0,0 @@
/**
* 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.testframework;
import com.wordnik.swagger.codegen.config.java.JavaDataTypeMappingProvider;
import com.wordnik.swagger.runtime.annotations.MethodArgumentNames;
import com.wordnik.swagger.codegen.config.common.CamelCaseNamingPolicyProvider;
import com.wordnik.swagger.runtime.common.APIInvoker;
import com.wordnik.swagger.runtime.common.ApiKeyAuthTokenBasedSecurityHandler;
import com.wordnik.swagger.runtime.exception.APIException;
import com.wordnik.swagger.runtime.exception.APIExceptionCodes;
import org.apache.commons.beanutils.BeanUtils;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Instance of this class runs single test case
* User: ramesh
* Date: 4/22/11
* Time: 7:32 AM
*/
public class JavaTestCaseExecutor {
private CamelCaseNamingPolicyProvider namingPolicyProvider = new CamelCaseNamingPolicyProvider();
private JavaDataTypeMappingProvider datatypeMppingProvider = new JavaDataTypeMappingProvider();
/**
* Follow the following argument pattern
* Arguments in calling this method:
* ApiServerURL
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
JavaTestCaseExecutor runner = new JavaTestCaseExecutor();
String apiServer = args[1];
String servicePackageName = args[2];
String apiKey = args[3];
String authToken = args[4];
String resource = args[5];
String httpMethod = args[6];
String suggestedMethodName = args[7];
Map<String, String> queryAndPathParameters = new HashMap<String, String>();
String postData = null;
if(args.length > 8 && args[8].length() > 0){
String[] qpTuple = args[8].split("~");
for(String tuple: qpTuple){
String[] nameValue = tuple.split("=");
queryAndPathParameters.put(nameValue[0], nameValue[1]);
}
}
if(args.length > 9 ){
postData = args[9];
}
queryAndPathParameters.put("authToken", authToken);
ApiKeyAuthTokenBasedSecurityHandler securityHandler = new ApiKeyAuthTokenBasedSecurityHandler(apiKey, authToken);
APIInvoker aAPIInvoker = APIInvoker.initialize(securityHandler, apiServer, true);
runner.executeTestCase(resource, servicePackageName, suggestedMethodName, queryAndPathParameters, postData);
}
private void executeTestCase(String resourceName, String servicePackageName, String suggestedName,
Map<String, String> queryAndPathParameters, String postData) {
String className = namingPolicyProvider.getServiceName(resourceName);
String methodName = suggestedName;
//3
try {
Class apiClass = Class.forName(servicePackageName + "." + className);
Method[] methods = apiClass.getMethods();
Method methodToExecute = null;
for(Method method : methods){
if(method.getName().equals(methodName)){
methodToExecute = method;
break;
}
}
if(methodToExecute != null) {
//4
Object[] arguments = populateArgumentsForTestCaseExecution(methodToExecute, queryAndPathParameters,
postData, className, resourceName);
Object output = null;
if(arguments != null && arguments.length > 0){
//5
output = methodToExecute.invoke(null, arguments);
}else{
//5
output = methodToExecute.invoke(null);
}
//6
System.out.println("SUCCESS");
System.out.println(APITestRunner.convertObjectToJSONString(output));
}
}catch(APIException e){
StringWriter sWriter = new StringWriter();
PrintWriter writer = new PrintWriter(sWriter);
e.printStackTrace(writer);
System.out.println(sWriter.getBuffer().toString());
System.out.println(e.getMessage());
System.out.println("ERROR");
try{
System.out.println(APITestRunner.convertObjectToJSONString(e));
}catch(Exception ex){
ex.printStackTrace();
}
} catch(Exception e){
StringWriter sWriter = new StringWriter();
PrintWriter writer = new PrintWriter(sWriter);
e.printStackTrace(writer);
System.out.println(sWriter.getBuffer().toString());
e.printStackTrace();
System.out.println("ERROR");
try{
APIException apiException = new APIException(APIExceptionCodes.SYSTEM_EXCEPTION,
e.getMessage());
System.out.println(APITestRunner.convertObjectToJSONString(apiException));
}catch(Exception ex){
ex.printStackTrace();
}
}
}
/**
* Gets the list of input query and path parameters and post data vlues and covenrt them to arguments that
* can be used for calling the method. This logic will be different in each driver language depends on how method
* input arguments are created.
*/
private Object[] populateArgumentsForTestCaseExecution(Method methodToExecute, Map<String, String> queryAndPathParameters,
String postData, String serviceName, String resourcePath) throws Exception {
MethodArgumentNames argNames = methodToExecute.getAnnotation(MethodArgumentNames.class);
String[] argNamesArray = null;
if(argNames != null && argNames.value().length() > 0) {
argNamesArray = argNames.value().split(",");
}
Class[] argTypesArray = methodToExecute.getParameterTypes();
Object output = null;
String inputClassName = namingPolicyProvider.getInputObjectName(serviceName, resourcePath);
if(argNamesArray != null && argNamesArray.length > 0){
Object[] arguments = new Object[argNamesArray.length];
for(int i=0; i < argNamesArray.length; i++){
Object argument = null;
//if the method takes input model instead of individual arguments, convert individual arguments into input model object
if(argTypesArray[i].getName().equalsIgnoreCase(inputClassName)){
argument = populateInputModelObject(argTypesArray[i], queryAndPathParameters);
}else if(datatypeMppingProvider.isPrimitiveType(argTypesArray[i].getName())){
argument = queryAndPathParameters.get(argNamesArray[i].trim());
}else if (argNamesArray[i].trim().equals(APITestRunner.POST_PARAM_NAME)){
String input = postData;
if(postData.startsWith("\"") && postData.endsWith("\"")){input = postData.substring(1, postData.length()-1);}
input = input.replaceAll("\\\\\"","\"");
argument = APITestRunner.convertJSONStringToObject(input, argTypesArray[i]);
}else{
//some times input can be list of primitives for supporting multivalued values. however test case sends the input as comma separated values
//so we need to convert comma separated string into JSON list format
if(List.class.isAssignableFrom(argTypesArray[i]) && !queryAndPathParameters.get(argNamesArray[i].trim()).startsWith("[")){
String listInput= "[";
int x = 0;
String[] values = queryAndPathParameters.get(argNamesArray[i].trim()).split(",");
for(String value : values){
if(x > 0){listInput = listInput + ",";}
listInput = listInput + "\""+ value + "\"";
x++;
}
listInput = listInput + "]";
argument = APITestRunner.convertJSONStringToObject(listInput, argTypesArray[i]);
}else{
argument = APITestRunner.convertJSONStringToObject(queryAndPathParameters.get(argNamesArray[i].trim()), argTypesArray[i]);
}
}
arguments[i] = argument;
}
return arguments;
}
return null;
}
/**
* Populates the swagger input model object.
*
* Input model is created when number of inputs to a method exceed certain limit.
* @param inputDefinitions
* @return
*/
private Object populateInputModelObject(Class swaggerInputClass, Map<String, String> inputDefinitions) throws Exception {
Object object = swaggerInputClass.getConstructor().newInstance();
Method[] methods = swaggerInputClass.getMethods();
for(Method method : methods){
if(method.getName().startsWith("get")){
String methodName = method.getName();
String fieldName = methodName.substring(3);
fieldName = namingPolicyProvider.applyMethodNamingPolicy(fieldName);
Object value = inputDefinitions.get(fieldName);
BeanUtils.setProperty(object, fieldName, value);
}
}
return object;
}
}

View File

@ -1,91 +0,0 @@
/**
* 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.testframework;
import java.util.List;
import java.util.Map;
/**
* Test case executes individual test case. A given test suite has one or many test cases.
* @author ramesh
*
*/
public class TestCase {
private String name;
private int id;
private int resourceId;
private Map<String, String> input;
private String referenceInput;
private List<Assertion> assertions;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getResourceId() {
return resourceId;
}
public void setResourceId(int resourceId) {
this.resourceId = resourceId;
}
public Map<String, String> getInput() {
return input;
}
public void setInput(Map<String, String> input) {
this.input = input;
}
public String getReferenceInput() {
return referenceInput;
}
public void setReferenceInput(String referenceInput) {
this.referenceInput = referenceInput;
}
public List<Assertion> getAssertions() {
return assertions;
}
public void setAssertions(List<Assertion> assertions) {
this.assertions = assertions;
}
}

View File

@ -1,34 +0,0 @@
/**
* 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.testframework;
import java.util.HashMap;
import java.util.Map;
public class TestOutput {
Map<String, Object> data = new HashMap<String, Object>();
public Map<String, Object> getData() {
return data;
}
public void setData(Map<String, Object> data) {
this.data = data;
}
}

View File

@ -1,65 +0,0 @@
/**
* 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.testframework;
import java.util.List;
public class TestPackage {
private List<TestResource> resources;
private List<TestSuite> testSuites;
public List<TestResource> getResources() {
return resources;
}
public void setResources(List<TestResource> resources) {
this.resources = resources;
}
public List<TestSuite> getTestSuites() {
return testSuites;
}
public void setTestSuites(List<TestSuite> testSuites) {
this.testSuites = testSuites;
}
public TestCase getTestCaseById(int suiteId, int caseId) {
TestSuite aSuite = null;
TestCase aTestCase = null;
if(this.getTestSuites() != null){
for(TestSuite suite : getTestSuites()){
if(suite.getId() == suiteId){
aSuite = suite;
break;
}
}
}
if(aSuite != null){
for(TestCase testCase : aSuite.getTestCases()){
if(testCase.getId() == caseId){
aTestCase = testCase;
break;
}
}
}
return aTestCase;
}
}

View File

@ -1,71 +0,0 @@
/**
* 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.testframework;
public class TestResource {
private int id;
private String name;
private String httpMethod;
private String path;
private String suggestedMethodName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHttpMethod() {
return httpMethod;
}
public void setHttpMethod(String method) {
this.httpMethod = method;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getSuggestedMethodName() {
return suggestedMethodName;
}
public void setSuggestedMethodName(String suggestedMethodName) {
this.suggestedMethodName = suggestedMethodName;
}
}

View File

@ -1,181 +0,0 @@
/**
* 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.testframework;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Stores the status of the tests executed.
* @author ramesh
*
*/
public class TestStatus {
private int totalTestCaseCount;
private int failedTestCaseCount;
private List<TestCaseStatus> testCaseStatuses = new ArrayList<TestCaseStatus>();
private Map<String, TestCaseStatus> testCaseStatusMap = new HashMap<String, TestCaseStatus>();
public void logStatus(TestCase testCase, String testCasePath, boolean passed){
logStatus(testCase, testCasePath, passed, null, null);
}
public void logStatus(TestCase testCase, String testCasePath, boolean passed, String failureDescription){
logStatus(testCase, testCasePath, passed, failureDescription, null);
}
public void logStatus(TestCase testCase, String testCasePath, boolean passed, String failureDescription, Throwable exception){
TestCaseStatus status = new TestCaseStatus(testCase, testCasePath, passed, failureDescription, exception);
testCaseStatuses.add(status);
testCaseStatusMap.put(testCasePath, status);
totalTestCaseCount++;
if(!passed){
failedTestCaseCount++;
}
}
public void logAssertionStatus(String path, boolean passed, String expectedValue, String actualValue, String condition) {
logAssertionStatus(path, passed, expectedValue, actualValue, condition, null);
}
public void logAssertionStatus(String path, boolean passed, String expectedValue, String actualValue, String condition, Throwable stack) {
TestCaseStatus status = testCaseStatusMap.get(path);
if(!passed && status.passed) {
status.passed = false;
failedTestCaseCount++;
}
status.addAssertionStatus(passed, expectedValue, actualValue, condition, stack);
}
public String printTestStatus() {
StringBuilder output = new StringBuilder();
output.append("Summary --> Total Test Cases: " + totalTestCaseCount + " Failed Test Cases: " + failedTestCaseCount);
output.append("\nDetails: \n");
for(TestCaseStatus status : testCaseStatuses) {
output.append(status.getStatusDescription() + "\n");
}
return output.toString();
}
/**
* Indicates if there are any failured in executing the test cases.
* @return
*/
public boolean hasFailures() {
return (failedTestCaseCount > 0);
}
/**
* Inner class Stores the details on individual test cases.
* @author ramesh
*
*/
private class TestCaseStatus {
String testCasePath;
boolean passed;
String failureDescription;
Throwable exceptionStack;
TestCase testCase;
List<AssertionStatus> assertionStatuses = new ArrayList<AssertionStatus>();
public TestCaseStatus(TestCase testCase, String testCasePath, boolean passed, String failureDescription,
Throwable exceptionStack) {
this.exceptionStack = exceptionStack;
this.testCase = testCase;
this.passed = passed;
this.failureDescription = failureDescription;
this.testCasePath = testCasePath;
}
public void addAssertionStatus(boolean passed, String expectedValue, String actualValue, String condition, Throwable stack) {
String assertionDesc = expectedValue + " " + condition + " " + actualValue;
AssertionStatus status = new AssertionStatus(assertionDesc, passed, stack);
assertionStatuses.add(status);
if(!passed){
this.passed = false;
}
}
public String getStatusDescription(){
StringBuilder output = new StringBuilder();
if(passed){
output.append(testCasePath);
output.append(" : ");
output.append(testCase.getName());
output.append(" : ");
output.append(" passed ");
output.append(" \n ");
}else{
output.append(testCasePath);
output.append(" : ");
output.append(testCase.getName());
output.append(" : ");
output.append(" failed ");
output.append(" \n ");
if ( failureDescription != null) {
output.append(" failure message : ");
output.append(failureDescription + "\n");
}
if(exceptionStack != null){
StringWriter out = new StringWriter();
PrintWriter writer = new PrintWriter(out);
exceptionStack.printStackTrace(writer);
output.append(out.toString());
}
for(AssertionStatus status:assertionStatuses){
if(!status.passed) {
output.append(status.getAssertionDescription()+"\n");
}
}
}
return output.toString();
}
}
private class AssertionStatus {
String assertionDescription;
boolean passed;
Throwable exceptionStack;
public AssertionStatus(String description, boolean passed, Throwable stack){
this.assertionDescription = description;
this.passed = passed;
this.exceptionStack = stack;
}
public String getAssertionDescription() {
return assertionDescription + " : " + (passed ? "Passed " : " Failed ") + ((exceptionStack !=null) ? exceptionStack.getMessage() : "" );
}
}
}

View File

@ -1,61 +0,0 @@
/**
* 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.testframework;
import java.util.List;
/**
* Test suite contains collection of test cases.
*
* As a best practice write one test suite for each resource
* @author ramesh
*
*/
public class TestSuite {
private String name ;
private int id;
private List<TestCase> testCases;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<TestCase> getTestCases() {
return testCases;
}
public void setTestCases(List<TestCase> testCases) {
this.testCases = testCases;
}
}