Search in sources :

Example 46 with JFieldVar

use of com.sun.codemodel.JFieldVar in project jsonschema2pojo by joelittlejohn.

the class EnumRule method addFactoryMethod.

protected void addFactoryMethod(EnumDefinition enumDefinition, JDefinedClass _enum) {
    JType backingType = enumDefinition.getBackingType();
    JFieldVar quickLookupMap = addQuickLookupMap(enumDefinition, _enum);
    JMethod fromValue = _enum.method(JMod.PUBLIC | JMod.STATIC, _enum, "fromValue");
    JVar valueParam = fromValue.param(backingType, "value");
    JBlock body = fromValue.body();
    JVar constant = body.decl(_enum, "constant");
    constant.init(quickLookupMap.invoke("get").arg(valueParam));
    JConditional _if = body._if(constant.eq(JExpr._null()));
    JInvocation illegalArgumentException = JExpr._new(_enum.owner().ref(IllegalArgumentException.class));
    JExpression expr = valueParam;
    // if string no need to add ""
    if (!isString(backingType)) {
        expr = expr.plus(JExpr.lit(""));
    }
    illegalArgumentException.arg(expr);
    _if._then()._throw(illegalArgumentException);
    _if._else()._return(constant);
    ruleFactory.getAnnotator().enumCreatorMethod(_enum, fromValue);
}
Also used : JFieldVar(com.sun.codemodel.JFieldVar) JBlock(com.sun.codemodel.JBlock) JConditional(com.sun.codemodel.JConditional) JInvocation(com.sun.codemodel.JInvocation) JExpression(com.sun.codemodel.JExpression) JMethod(com.sun.codemodel.JMethod) JType(com.sun.codemodel.JType) JVar(com.sun.codemodel.JVar)

Example 47 with JFieldVar

use of com.sun.codemodel.JFieldVar in project jsonschema2pojo by joelittlejohn.

the class EnumRule method apply.

/**
 * Applies this schema rule to take the required code generation steps.
 * <p>
 * A Java {@link Enum} is created, with constants for each of the enum
 * values present in the schema. The enum name is derived from the nodeName,
 * and the enum type itself is created as an inner class of the owning type.
 * In the rare case that no owning type exists (the enum is the root of the
 * schema), then the enum becomes a public class in its own right.
 * <p>
 * The actual JSON value for each enum constant is held in a property called
 * "value" in the generated type. A static factory method
 * <code>fromValue(String)</code> is added to the generated enum, and the
 * methods are annotated to allow Jackson to marshal/unmarshal values
 * correctly.
 *
 * @param nodeName
 *            the name of the property which is an "enum"
 * @param node
 *            the enum node
 * @param parent
 *            the parent node
 * @param container
 *            the class container (class or package) to which this enum
 *            should be added
 * @return the newly generated Java type that was created to represent the
 *         given enum
 */
@Override
public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer container, Schema schema) {
    if (node.has("existingJavaType")) {
        JType type = ruleFactory.getTypeRule().apply(nodeName, node, parent, container.getPackage(), schema);
        schema.setJavaTypeIfEmpty(type);
        return type;
    }
    JDefinedClass _enum;
    try {
        _enum = createEnum(node, nodeName, container);
    } catch (ClassAlreadyExistsException e) {
        ruleFactory.getLogger().error("Could not create enum.", e);
        return e.getExistingClass();
    }
    schema.setJavaTypeIfEmpty(_enum);
    // Add JavaDocs
    if (node.has("title")) {
        ruleFactory.getTitleRule().apply(nodeName, node.get("title"), node, _enum, schema);
    }
    if (node.has("description")) {
        ruleFactory.getDescriptionRule().apply(nodeName, node.get("description"), node, _enum, schema);
    }
    if (node.has("$comment")) {
        ruleFactory.getCommentRule().apply(nodeName, node.get("$comment"), node, _enum, schema);
    }
    if (node.has("javaInterfaces")) {
        addInterfaces(_enum, node.get("javaInterfaces"));
    }
    // copy our node; remove the javaType as it will throw off the TypeRule for our case
    ObjectNode typeNode = (ObjectNode) node.deepCopy();
    typeNode.remove("javaType");
    // If type is specified on the enum, get a type rule for it.  Otherwise, we're a string.
    // (This is different from the default of Object, which is why we don't do this for every case.)
    JType backingType = node.has("type") ? ruleFactory.getTypeRule().apply(nodeName, typeNode, parent, container, schema) : container.owner().ref(String.class);
    EnumDefinition enumDefinition = buildEnumDefinition(nodeName, node, backingType);
    if (ruleFactory.getGenerationConfig() != null && ruleFactory.getGenerationConfig().isIncludeGeneratedAnnotation()) {
        AnnotationHelper.addGeneratedAnnotation(_enum);
    }
    JFieldVar valueField = addConstructorAndFields(enumDefinition, _enum);
    // override toString only if we have a sensible string to return
    if (isString(backingType)) {
        addToString(_enum, valueField);
    }
    addFieldAccessors(_enum, valueField);
    addEnumConstants(enumDefinition, _enum, schema);
    addFactoryMethod(enumDefinition, _enum);
    applyCustomizations(enumDefinition, _enum);
    return _enum;
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JDefinedClass(com.sun.codemodel.JDefinedClass) JFieldVar(com.sun.codemodel.JFieldVar) EnumDefinition(org.jsonschema2pojo.model.EnumDefinition) JType(com.sun.codemodel.JType) JClassAlreadyExistsException(com.sun.codemodel.JClassAlreadyExistsException) ClassAlreadyExistsException(org.jsonschema2pojo.exception.ClassAlreadyExistsException)

Example 48 with JFieldVar

use of com.sun.codemodel.JFieldVar in project jsonschema2pojo by joelittlejohn.

the class DigitsRuleTest method testNotUsed.

@Test
public void testNotUsed() {
    when(config.isIncludeJsr303Annotations()).thenReturn(true);
    when(node.has("integerDigits")).thenReturn(false);
    when(node.has("fractionalDigits")).thenReturn(false);
    when(fieldVar.type().boxify().fullName()).thenReturn(fieldClass.getTypeName());
    JFieldVar result = rule.apply("node", node, null, fieldVar, null);
    assertSame(fieldVar, result);
    verify(fieldVar, never()).annotate(sizeClass);
    verify(annotation, never()).param(anyString(), anyInt());
}
Also used : JFieldVar(com.sun.codemodel.JFieldVar) Test(org.junit.Test)

Example 49 with JFieldVar

use of com.sun.codemodel.JFieldVar in project jsonschema2pojo by joelittlejohn.

the class DigitsRuleTest method jsrDisable.

@Test
public void jsrDisable() {
    when(config.isIncludeJsr303Annotations()).thenReturn(false);
    JFieldVar result = rule.apply("node", node, null, fieldVar, null);
    assertSame(fieldVar, result);
    verify(fieldVar, never()).annotate(decimalMinClass);
    verify(annotation, never()).param(anyString(), anyInt());
}
Also used : JFieldVar(com.sun.codemodel.JFieldVar) Test(org.junit.Test)

Example 50 with JFieldVar

use of com.sun.codemodel.JFieldVar in project jsonschema2pojo by joelittlejohn.

the class MinItemsMaxItemsRuleTest method testMaxAndMinLengthGenericsOnType.

@Test
public void testMaxAndMinLengthGenericsOnType() {
    when(config.isIncludeJsr303Annotations()).thenReturn(true);
    final int minValue = new Random().nextInt();
    final int maxValue = new Random().nextInt();
    JsonNode maxSubNode = Mockito.mock(JsonNode.class);
    when(subNode.asInt()).thenReturn(minValue);
    when(maxSubNode.asInt()).thenReturn(maxValue);
    when(node.get("minItems")).thenReturn(subNode);
    when(node.get("maxItems")).thenReturn(maxSubNode);
    when(fieldVar.annotate(sizeClass)).thenReturn(annotation);
    when(node.has("minItems")).thenReturn(true);
    when(node.has("maxItems")).thenReturn(true);
    when(fieldVar.type().boxify().fullName()).thenReturn(fieldClass.getTypeName() + "<String>");
    JFieldVar result = rule.apply("node", node, null, fieldVar, null);
    assertSame(fieldVar, result);
    verify(fieldVar, times(isApplicable ? 1 : 0)).annotate(sizeClass);
    verify(annotation, times(isApplicable ? 1 : 0)).param("min", minValue);
    verify(annotation, times(isApplicable ? 1 : 0)).param("max", maxValue);
}
Also used : Random(java.util.Random) JFieldVar(com.sun.codemodel.JFieldVar) JsonNode(com.fasterxml.jackson.databind.JsonNode) Test(org.junit.Test)

Aggregations

JFieldVar (com.sun.codemodel.JFieldVar)74 JMethod (com.sun.codemodel.JMethod)33 JVar (com.sun.codemodel.JVar)28 JClass (com.sun.codemodel.JClass)24 Test (org.junit.Test)24 JBlock (com.sun.codemodel.JBlock)21 JInvocation (com.sun.codemodel.JInvocation)19 JDefinedClass (com.sun.codemodel.JDefinedClass)16 Random (java.util.Random)12 ByteString (com.linkedin.data.ByteString)10 HashMap (java.util.HashMap)10 JsonNode (com.fasterxml.jackson.databind.JsonNode)9 JExpression (com.sun.codemodel.JExpression)9 JConditional (com.sun.codemodel.JConditional)8 JType (com.sun.codemodel.JType)8 ArrayList (java.util.ArrayList)7 Map (java.util.Map)6 JFieldRef (com.sun.codemodel.JFieldRef)5 JCodeModel (com.sun.codemodel.JCodeModel)3 JPackage (com.sun.codemodel.JPackage)3