Skip to content

Commit

Permalink
[issue joelittlejohn#110] Add support for Joda dates
Browse files Browse the repository at this point in the history
  • Loading branch information
joelittlejohn committed Jul 11, 2013
1 parent d15259a commit 7289cda
Show file tree
Hide file tree
Showing 12 changed files with 197 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ public class Jsonschema2PojoTask extends Task implements GenerationConfig {

private String outputEncoding = "UTF-8";

private boolean useJodaDates;

/**
* Execute this task (it's expected that all relevant setters will have been
* called by Ant to provide task configuration <em>before</em> this method
Expand Down Expand Up @@ -361,6 +363,18 @@ public void setOutputEncoding(String outputEncoding) {
this.outputEncoding = outputEncoding;
}

/**
* Sets the 'useJodaDates' property of this class
*
* @param useJodaDates
* Whether to use {@link org.joda.time.DateTime} instead of
* {@link java.util.Date} when adding date type fields to
* generated Java types.
*/
public void setUseJodaDates(boolean useJodaDates) {
this.useJodaDates = useJodaDates;
}

@Override
public boolean isGenerateBuilders() {
return generateBuilders;
Expand Down Expand Up @@ -468,4 +482,9 @@ public String getOutputEncoding() {
return outputEncoding;
}

@Override
public boolean isUseJodaDates() {
return useJodaDates;
}

}
5 changes: 5 additions & 0 deletions jsonschema2pojo-ant/src/site/Jsonschema2PojoTask.html
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,11 @@ <h3>Parameters</h3>
<td valign="top">The character encoding that should be used when writing the generated Java source files.</td>
<td align="center" valign="top">No (default <code>UTF-8</code>)</td>
</tr>
<tr>
<td valign="top">useJodaDates</td>
<td valign="top">Whether to use <code>org.joda.time.DateTime</code> instead of <code>java.util.Date</code> when adding date type fields to generated Java types.</td>
<td align="center" valign="top">No (default <code>false</code>)</td>
</tr>
</table>

<h3>Examples</h3>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ public class Arguments implements GenerationConfig {
@Parameter(names = { "-e", "--output-encoding" }, description = "The character encoding that should be used when writing the generated Java source files")
private String outputEncoding = "UTF-8";

@Parameter(names = { "-j", "--joda-dates" }, description = "Whether to use org.joda.time.DateTime instead of java.util.Date when adding date type fields to generated Java types.")
private boolean useJodaDates = false;

private static final int EXIT_OKAY = 0;
private static final int EXIT_ERROR = 1;

Expand Down Expand Up @@ -199,6 +202,11 @@ public String getOutputEncoding() {
return outputEncoding;
}

@Override
public boolean isUseJodaDates() {
return useJodaDates;
}

protected void exit(int status) {
System.exit(status);
}
Expand Down
4 changes: 4 additions & 0 deletions jsonschema2pojo-core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,12 @@ public String getOutputEncoding() {
public boolean isRemoveOldOutput() {
return false;
}

/**
* @return false
*/
@Override
public boolean isUseJodaDates() {
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -179,4 +179,13 @@ public interface GenerationConfig {
*/
String getOutputEncoding();

/**
* Gets the 'useJodaDates' configuration option.
*
* @return Whether to use {@link org.joda.time.DateTime} instead of
* {@link java.util.Date} when adding date type fields to generated
* Java types.
*/
boolean isUseJodaDates();

}
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@
import java.util.List;
import java.util.Set;

import org.joda.time.DateTime;
import org.jsonschema2pojo.Schema;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.util.StdDateFormat;
import org.jsonschema2pojo.Schema;
import com.sun.codemodel.ClassType;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JDefinedClass;
Expand All @@ -47,6 +49,12 @@
*/
public class DefaultRule implements Rule<JFieldVar, JFieldVar> {

private final RuleFactory ruleFactory;

public DefaultRule(RuleFactory ruleFactory) {
this.ruleFactory = ruleFactory;
}

/**
* Applies this schema rule to take the required code generation steps.
* <p>
Expand Down Expand Up @@ -108,10 +116,10 @@ private JExpression getDefaultValue(JType fieldType, JsonNode node) {
} else if (fieldType.fullName().equals(boolean.class.getName())) {
return JExpr.lit(Boolean.parseBoolean(node.asText()));

} else if (fieldType.fullName().equals(Date.class.getName())) {
} else if (fieldType.fullName().equals(getDateType().getName())) {
long millisecs = parseDateToMillisecs(node.asText());

JInvocation newDate = JExpr._new(fieldType.owner().ref(Date.class));
JInvocation newDate = JExpr._new(fieldType);
newDate.arg(JExpr.lit(millisecs));

return newDate;
Expand All @@ -130,6 +138,10 @@ private JExpression getDefaultValue(JType fieldType, JsonNode node) {

}

private Class<?> getDateType() {
return ruleFactory.getGenerationConfig().isUseJodaDates() ? DateTime.class : Date.class;
}

/**
* Creates a default value for a list property by:
* <ol>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@
import java.util.Date;
import java.util.regex.Pattern;

import com.fasterxml.jackson.databind.JsonNode;
import org.joda.time.DateTime;
import org.jsonschema2pojo.GenerationConfig;
import org.jsonschema2pojo.Schema;

import com.fasterxml.jackson.databind.JsonNode;
import com.sun.codemodel.JType;

/**
Expand Down Expand Up @@ -74,7 +76,7 @@ protected FormatRule(RuleFactory ruleFactory) {
public JType apply(String nodeName, JsonNode node, JType baseType, Schema schema) {

if (node.asText().equals("date-time")) {
return baseType.owner().ref(Date.class);
return baseType.owner().ref(getDateType());

} else if (node.asText().equals("date")) {
return baseType.owner().ref(String.class);
Expand Down Expand Up @@ -118,6 +120,10 @@ public JType apply(String nodeName, JsonNode node, JType baseType, Schema schema

}

private Class<?> getDateType() {
return ruleFactory.getGenerationConfig().isUseJodaDates() ? DateTime.class : Date.class;
}

private JType unboxIfNecessary(JType type, GenerationConfig config) {
if (config.isUsePrimitives()) {
return type.unboxify();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import org.jsonschema2pojo.GenerationConfig;
import org.jsonschema2pojo.Jackson2Annotator;
import org.jsonschema2pojo.SchemaStore;

import com.sun.codemodel.JClass;
import com.sun.codemodel.JClassContainer;
import com.sun.codemodel.JDefinedClass;
Expand Down Expand Up @@ -201,7 +202,7 @@ public Rule<JClassContainer, JType> getSchemaRule() {
* @return a schema rule that can handle the "default" declaration.
*/
public Rule<JFieldVar, JFieldVar> getDefaultRule() {
return new DefaultRule();
return new DefaultRule(this);
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* Copyright © 2010-2013 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.integration.config;

import static org.hamcrest.Matchers.*;
import static org.jsonschema2pojo.integration.util.CodeGenerationHelper.*;
import static org.junit.Assert.*;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.joda.time.DateTime;
import org.junit.Test;

public class JodaDatesIT {

@Test
public void defaultDateTypeIsJavaUtilDate() throws ClassNotFoundException, IntrospectionException {
ClassLoader classLoader = generateAndCompile("/schema/format/formattedProperties.json", "com.example");

Class<?> classWithDate = classLoader.loadClass("com.example.FormattedProperties");

Method getter = new PropertyDescriptor("stringAsDateTime", classWithDate).getReadMethod();

assertThat(getter.getReturnType().getName(), is("java.util.Date"));
}

@Test
public void useJodaDatesCausesJodaDateTimeDates() throws IntrospectionException, ClassNotFoundException {
ClassLoader classLoader = generateAndCompile("/schema/format/formattedProperties.json", "com.example", config("useJodaDates", true));

Class<?> classWithDate = classLoader.loadClass("com.example.FormattedProperties");

Method getter = new PropertyDescriptor("stringAsDateTime", classWithDate).getReadMethod();

assertThat(getter.getReturnType().getName(), is("org.joda.time.DateTime"));
}

@Test
public void disablingJodaDatesCausesJavaUtilDates() throws ClassNotFoundException, IntrospectionException {
ClassLoader classLoader = generateAndCompile("/schema/format/formattedProperties.json", "com.example", config("useJodaDates", false));

Class<?> classWithDate = classLoader.loadClass("com.example.FormattedProperties");

Method getter = new PropertyDescriptor("stringAsDateTime", classWithDate).getReadMethod();

assertThat(getter.getReturnType().getName(), is("java.util.Date"));
}

@Test
public void useJodaDatesCausesDateTimeDefaultValues() throws ClassNotFoundException, IntrospectionException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, InvocationTargetException {
ClassLoader classLoader = generateAndCompile("/schema/default/default.json", "com.example", config("useJodaDates", true));

Class<?> classWithDefaults = classLoader.loadClass("com.example.Default");

Object instance = classWithDefaults.newInstance();

Method getter = classWithDefaults.getMethod("getDateWithDefault");

assertThat((DateTime) getter.invoke(instance), is(equalTo(new DateTime(123456789))));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,16 @@ public class Jsonschema2PojoMojo extends AbstractMojo implements GenerationConfi
*/
private String outputEncoding = "UTF-8";

/**
* Whether to use {@link org.joda.time.DateTime} instead of
* {@link java.util.Date} when adding date type fields to generated Java
* types.
*
* @parameter expression="${jsonschema2pojo.useJodaDates}" default="false"
* @since 0.4.0
*/
private boolean useJodaDates = false;

/**
* The project being built.
*
Expand Down Expand Up @@ -433,4 +443,9 @@ public String getOutputEncoding() {
return outputEncoding;
}

@Override
public boolean isUseJodaDates() {
return useJodaDates;
}

}
45 changes: 25 additions & 20 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -179,21 +179,6 @@
<artifactId>jcommander</artifactId>
<version>1.30</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.8.4</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-project</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
Expand All @@ -220,22 +205,42 @@
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.11</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.8.4</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-project</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.11</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
Expand Down

0 comments on commit 7289cda

Please sign in to comment.