Skip to content

Commit

Permalink
Merge pull request #454 from ctrimble/feature_target-version
Browse files Browse the repository at this point in the history
Specify target JVM version
  • Loading branch information
joelittlejohn committed Nov 30, 2015
2 parents a552d36 + 233418e commit 005161a
Show file tree
Hide file tree
Showing 15 changed files with 256 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ public class Jsonschema2PojoTask extends Task implements GenerationConfig {
private boolean includeAdditionalProperties = true;

private boolean includeAccessors = true;

private String targetVersion = "1.6";

/**
* Execute this task (it's expected that all relevant setters will have been
Expand Down Expand Up @@ -546,6 +548,18 @@ public void setIncludeAccessors(boolean includeAccessors) {
this.includeAccessors = includeAccessors;
}

/**
* Sets the 'targetVersion' property of this class
*
* @param targetVersion
* The target version for generated source files.
* <p>
* Default: <code>1.6</code>.
*/
public void setTargetVersion(String targetVersion) {
this.targetVersion = targetVersion;
}

@Override
public boolean isGenerateBuilders() {
return generateBuilders;
Expand Down Expand Up @@ -727,4 +741,9 @@ public boolean isIncludeAdditionalProperties() {
public boolean isIncludeAccessors() {
return includeAccessors;
}

@Override
public String getTargetVersion() {
return targetVersion;
}
}
5 changes: 5 additions & 0 deletions jsonschema2pojo-ant/src/site/Jsonschema2PojoTask.html
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,11 @@ <h3>Parameters</h3>
<td valign="top">Whether to use primitives (<code>long</code>, <code>double</code>, <code>boolean</code>) instead of wrapper types where possible when generating bean properties (has the side-effect of making those.</td>
<td align="center" valign="top">No (default <code>false</code>)</td>
</tr>
<tr>
<td valign="top">targetVersion</td>
<td valign="top">The target version for generated source files.</td>
<td align="center" valign="top">No (default <code>1.6</code>)</td>
</tr>
</table>

<h3>Examples</h3>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,9 @@ public class Arguments implements GenerationConfig {

@Parameter(names = { "-da", "--disable-accessors" }, description = "Whether to omit getter/setter methods and create public fields instead.")
private boolean disableAccessors = false;

@Parameter(names = { "-tv", "--target-version" }, description = "The target version for generated source files.")
private String targetVersion = "1.6";

private static final int EXIT_OKAY = 0;
private static final int EXIT_ERROR = 1;
Expand Down Expand Up @@ -321,4 +324,9 @@ public boolean isIncludeAccessors() {
return !disableAccessors;
}

@Override
public String getTargetVersion() {
return targetVersion;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -255,4 +255,12 @@ public boolean isIncludeAdditionalProperties() {
public boolean isIncludeAccessors() {
return true;
}

/**
* @return <code>1.6</code>
*/
@Override
public String getTargetVersion() {
return "1.6";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -302,5 +302,12 @@ public interface GenerationConfig {
* methods and create public fields instead.
*/
boolean isIncludeAccessors();

/**
* Gets the 'targetVersion' configuration option
*
* @return The target version for generated source files.
*/
String getTargetVersion();

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Copyright © 2010-2014 Nokia
*
* 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 org.jsonschema2pojo.util;

import org.jsonschema2pojo.GenerationConfig;
import static java.util.Arrays.asList;

import java.util.Collection;

public class LanguageFeatures {

public static final Collection<String> LESS_THAN_8
= asList("1.1", "1.2", "1.3", "1.4", "1.5", "5", "1.6", "6", "1.7", "7");
public static final Collection<String> LESS_THAN_7
= asList("1.1", "1.2", "1.3", "1.4", "1.5", "5", "1.6", "6");
public static final Collection<String> LESS_THAN_6
= asList("1.1", "1.2", "1.3", "1.4", "1.5", "5");

public static boolean canUseJava7( GenerationConfig config ) {
return !LESS_THAN_7.contains(config.getTargetVersion());
}

public static boolean canUseJava8( GenerationConfig config ) {
return !LESS_THAN_8.contains(config.getTargetVersion());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* Copyright © 2010-2014 Nokia
*
* 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 org.jsonschema2pojo.util;

import com.sun.codemodel.JAnnotationArrayMember;
import com.sun.codemodel.JAnnotationUse;
import com.sun.codemodel.JMethod;

public class Models {

public static void suppressWarnings(JMethod method, String... values) {
JAnnotationUse annotation = method.annotate(SuppressWarnings.class);
JAnnotationArrayMember member = annotation.paramArray("value");
for( String value : values ) {
member.param(value);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.sun.codemodel.*;
import static org.jsonschema2pojo.util.Models.*;


public class ParcelableHelper {
Expand Down Expand Up @@ -63,6 +64,7 @@ private void addCreateFromParcel(JDefinedClass jclass, JDefinedClass creatorClas
JMethod createFromParcel = creatorClass.method(JMod.PUBLIC, jclass, "createFromParcel");
JVar in = createFromParcel.param(Parcel.class, "in");
JVar instance = createFromParcel.body().decl(jclass, "instance", JExpr._new(jclass));
suppressWarnings(createFromParcel, "unchecked");
for (JFieldVar f : jclass.fields().values()) {
if (f.type().erasure().name().equals("List")) {
createFromParcel.body()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/**
* Copyright © 2010-2014 Nokia
*
* 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 org.jsonschema2pojo.util;

import java.util.Arrays;
import java.util.Collection;

import org.jsonschema2pojo.GenerationConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import static org.jsonschema2pojo.util.LanguageFeaturesTest.VersionEnum.*;
import static org.mockito.Mockito.*;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.*;

@RunWith(Parameterized.class)
public class LanguageFeaturesTest {

public static enum VersionEnum {

BEFORE_6(false, false, false),
MAX_6(true, false, false),
MAX_7(true, true, false),
MAX_8(true, true, true),
AFTER_8(true, true, true);

public final boolean canUse6;
public final boolean canUse7;
public final boolean canUse8;

VersionEnum(boolean canUse6, boolean canUse7, boolean canUse8) {
this.canUse6 = canUse6;
this.canUse7 = canUse7;
this.canUse8 = canUse8;
}
}

@Parameters
public static Collection<Object[]> parameters() {
return Arrays.asList(new Object[][] {
{ "1.5", BEFORE_6 },
{ "5", BEFORE_6 },
{ "1.6", MAX_6 },
{ "6", MAX_6 },
{ "1.7", MAX_7 },
{ "7", MAX_7 },
{ "1.8", MAX_8 },
{ "8", MAX_8 },
{ "1.9", AFTER_8 },
{ "9", AFTER_8 }
});
}

private String version;
private VersionEnum versionSpec;

public LanguageFeaturesTest(String version, VersionEnum versionSpec) {
this.version = version;
this.versionSpec = versionSpec;
}

@Test
public void correctTestForJava7() {
assertThat(LanguageFeatures.canUseJava7(mockConfig(version)), equalTo(versionSpec.canUse7));
}

@Test
public void correctTestForJava8() {
assertThat(LanguageFeatures.canUseJava8(mockConfig(version)), equalTo(versionSpec.canUse8));
}

public static GenerationConfig mockConfig(String version) {
GenerationConfig config = mock(GenerationConfig.class);
when(config.getTargetVersion()).thenReturn(version);
return config;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public class JsonSchemaExtension implements GenerationConfig {
char[] propertyWordDelimiters
boolean removeOldOutput
SourceType sourceType
String targetVersion
boolean useCommonsLang3
boolean useDoubleNumbers
boolean useJodaDates
Expand Down Expand Up @@ -91,6 +92,7 @@ public class JsonSchemaExtension implements GenerationConfig {
classNameSuffix = ''
includeAdditionalProperties = true
includeAccessors = true
targetVersion = '1.6'
}

@Override
Expand Down Expand Up @@ -152,6 +154,7 @@ public class JsonSchemaExtension implements GenerationConfig {
|initializeCollections = ${initializeCollections}
|classNamePrefix = ${classNamePrefix}
|classNameSuffix = ${classNameSuffix}
|targetVersion = ${targetVersion}
""".stripMargin()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public void antTaskDocumentationIncludesAllProperties() throws IntrospectionExce
String documentation = FileUtils.readFileToString(new File("../jsonschema2pojo-ant/src/site/Jsonschema2PojoTask.html"));

for (Field f : Jsonschema2PojoTask.class.getDeclaredFields()) {
assertThat(documentation, containsString(f.getName()));
assertThat(documentation, containsString(">"+f.getName()+"<"));
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,17 +121,21 @@ private static MavenProject getMockProject() throws DependencyResolutionRequired
*/
public static ClassLoader compile(File sourceDirectory) {

return compile(sourceDirectory, new ArrayList<String>());
return compile(sourceDirectory, new ArrayList<String>(), new HashMap<String, Object>());

}

public static ClassLoader compile(File sourceDirectory, List<String> classpath ) {
return compile(sourceDirectory, classpath, new HashMap<String, Object>());
}

public static ClassLoader compile(File sourceDirectory, List<String> classpath) {
public static ClassLoader compile(File sourceDirectory, List<String> classpath, Map<String, Object> config) {

List<String> fullClasspath = new ArrayList<String>();
fullClasspath.addAll(classpath);
fullClasspath.add(System.getProperty("java.class.path"));

new Compiler().compile(sourceDirectory, join(fullClasspath, File.pathSeparatorChar));
new Compiler().compile(sourceDirectory, join(fullClasspath, File.pathSeparatorChar), (String)config.get("target"));

try {
return URLClassLoader.newInstance(new URL[] { sourceDirectory.toURI().toURL() }, Thread.currentThread().getContextClassLoader());
Expand All @@ -158,7 +162,7 @@ public static ClassLoader generateAndCompile(String schema, String targetPackage

File outputDirectory = generate(schema, targetPackage, configValues);

return compile(outputDirectory);
return compile(outputDirectory, new ArrayList<String>(), configValues);

}

Expand All @@ -174,7 +178,7 @@ public static ClassLoader generateAndCompile(URL schema, String targetPackage, M

File outputDirectory = generate(schema, targetPackage, configValues);

return compile(outputDirectory);
return compile(outputDirectory, new ArrayList<String>(), configValues);

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,29 @@
public class Compiler {

public void compile(File directory, String classpath) {
compile(directory, classpath, null);
}

public void compile(File directory, String classpath, String targetVersion) {

targetVersion = targetVersion == null ? "1.6" : targetVersion;

JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, null);

Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(findAllSourceFiles(directory));

ArrayList<String> options = new ArrayList<String>();
options.add("-source");
options.add(targetVersion);
options.add("-target");
options.add(targetVersion);
options.add("-classpath");
options.add(classpath);
options.add("-encoding");
options.add("UTF8");
options.add("-Xlint:-options");
options.add("-Xlint:unchecked");
if (compilationUnits.iterator().hasNext()) {
Boolean success = javaCompiler.getTask(null, fileManager, null, options, null, compilationUnits).call();
assertThat("Compilation was not successful, check stdout for errors", success, is(true));
Expand Down
Loading

0 comments on commit 005161a

Please sign in to comment.