Skip to content

Commit

Permalink
Merge pull request #3 from fehguy/master
Browse files Browse the repository at this point in the history
added support for escaping reserved words in attribute names
  • Loading branch information
fehguy committed Sep 29, 2011
2 parents 2cc57fc + b5a826f commit 66214a3
Show file tree
Hide file tree
Showing 14 changed files with 351 additions and 105 deletions.
23 changes: 6 additions & 17 deletions conf/scala/sample/build.xml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@
<!-- this is the output module -->
<property name="module" value="${ant.project.name}" />

<target name="jar" description="creates jar file " depends="build.all">
<jar jarfile="build/${release.module}-${release.version}.${artifact.ext}">
<fileset dir="build/main/java" />
</jar>
</target>

<target name="build.all" depends="clean, resolve, fastcompile" description="builds the module (default target)" />

<target name="clean" description="cleans the project folder">
Expand All @@ -62,15 +68,6 @@
</delete>
</target>

<!-- copies ONLY the swagger-sample jar to dist-->
<target name="fastdist" depends="fastcompile">
<copy todir="dist/lib">
<fileset dir="build">
<include name="*.jar" />
</fileset>
</copy>
</target>

<!-- copies all dependencies into the lib folder -->
<target name="resolve" description="retreive dependencies with ivy">
<ivy:retrieve pattern="${basedir}/lib/[artifact]-[revision].[ext]" conf="build" />
Expand All @@ -94,7 +91,6 @@
</classpath>
</javac>


<scalac srcdir="src/main/java:src/main/scala" destdir="build/main/java">
<classpath>
<pathelement location="build/main/java" />
Expand All @@ -115,14 +111,7 @@
</jar>
</target>

<!-- cleans up the dist -->
<target name="dist.clean" description="cleans the distribution folder">
<delete quiet="true" dir="dist" />
<delete quiet="true" file="dist.zip" />
</target>

<target name="dependency.tree" description="builds a graphml dependency diagram for viewing with yEd">
<ivy:report conf="build" graph="true" todir="." outputpattern="[artifact]-[revision].[ext]" />
</target>

</project>
8 changes: 4 additions & 4 deletions conf/scala/templates/ResourceObject.st
Original file line number Diff line number Diff line change
Expand Up @@ -93,15 +93,15 @@ $endif$
//make the API Call
$if(method.hasResponseValue)$
$if(method.postObject)$
val response = APIInvoker.invokeAPI(resourcePath, method, queryParams, postData)
val response = APIInvoker.getApiInvoker.invokeAPI(resourcePath, method, queryParams, postData)
$else$
val response = APIInvoker.invokeAPI(resourcePath, method, queryParams, null)
val response = APIInvoker.getApiInvoker.invokeAPI(resourcePath, method, queryParams, null)
$endif$
$else$
$if(method.postObject)$
APIInvoker.invokeAPI(resourcePath, method, queryParams, postData)
APIInvoker.getApiInvoker.invokeAPI(resourcePath, method, queryParams, postData)
$else$
APIInvoker.invokeAPI(resourcePath, method, queryParams, null)
APIInvoker.getApiInvoker.invokeAPI(resourcePath, method, queryParams, null)
$endif$
$endif$
$if(!method.responseVoid)$
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,11 @@
import java.util.List;

public class FieldDefinition {

private String returnType;

private String name;

private String initialization;

private List<String> importDefinitions = new ArrayList<String>();

private String collectionItemType;

private String collectionItemName;

private boolean hasListResponse;
Expand Down Expand Up @@ -80,7 +74,7 @@ public void setReturnType(String returnType) {
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
Expand Down
59 changes: 39 additions & 20 deletions src/main/java/com/wordnik/swagger/codegen/LibraryCodeGenerator.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@

import com.wordnik.swagger.codegen.api.SwaggerResourceDocReader;
import com.wordnik.swagger.codegen.config.*;
import com.wordnik.swagger.codegen.config.ApiConfiguration;
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;
Expand All @@ -39,7 +39,6 @@
* 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";
Expand All @@ -49,6 +48,7 @@ public class LibraryCodeGenerator {
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;
Expand All @@ -64,7 +64,6 @@ public LibraryCodeGenerator(String 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));
Expand Down Expand Up @@ -102,6 +101,7 @@ 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("templates", languageConfig.getTemplateLocation());
if(resources.size() > 0) {
generateVersionHelper(resources.get(0).getApiVersion(), aTemplateGroup);
Expand All @@ -120,6 +120,21 @@ public void generateCode() {
}

/**
* 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
Expand Down Expand Up @@ -170,7 +185,7 @@ private void generateModelClasses(List<Resource> resources, StringTemplateGroup
}

/**
* Generates assembler classes if the API returns more than one objects.
* Generates assembler classes if the API returns more than one object.
* @param resources
* @param templateGroup
*/
Expand All @@ -189,6 +204,7 @@ private void generateModelClassesForInput(List<Resource> resources, StringTempla
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).getImportDefinitions()){
if(!imports.contains(importDef)){
imports.add(importDef);
Expand Down Expand Up @@ -340,23 +356,26 @@ private void generateAPIClasses(List<Resource> resources, StringTemplateGroup te
methods = resource.generateMethods(resource, dataTypeMappingProvider, nameGenerator);
StringTemplate template = templateGroup.getInstanceOf(API_OBJECT_TEMPLATE);
String className = resource.generateClassName(nameGenerator);
List<ResourceMethod> filteredMethods = new ArrayList<ResourceMethod>();
for(ResourceMethod method:methods){
if(!this.getCodeGenRulesProvider().isMethodIgnored(className, method.getName())){
filteredMethods.add(method);
}

if(className != null){
List<ResourceMethod> filteredMethods = new ArrayList<ResourceMethod>();
for(ResourceMethod method:methods){
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");
}
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;
Expand Down
21 changes: 1 addition & 20 deletions src/main/java/com/wordnik/swagger/codegen/ResourceMethod.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,44 +21,25 @@
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;

//set the original response name, this is used in identifying if the respone is single valued or multi valued
//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(){
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* 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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,25 +24,15 @@
* 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;

public String getClassFileExtension() {
Expand Down Expand Up @@ -129,4 +119,17 @@ public void setOutputWrapperRequired(boolean 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 + "]";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* 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);
}
Loading

0 comments on commit 66214a3

Please # to comment.