Java Code Examples for com.sun.codemodel.JDefinedClass

The following are top voted examples for showing how to use com.sun.codemodel.JDefinedClass. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: EnumRule.java   View source code 7 votes vote down vote up
private void addFactoryMethod(JDefinedClass _enum, JType backingType) {
    JFieldVar quickLookupMap = addQuickLookupMap(_enum, backingType);

    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(fromValue);
}
 
Example 2
Project: beanvalidation-benchmark   File: JavaBeanBasicField.java   View source code 6 votes vote down vote up
/**
 * Creates a random MetaField
 * 
 * @param owner
 *            The class that owns this field.
 * @param name
 *            The name of the meta field.
 */
public JavaBeanBasicField(MetaJavaBean owner, String name) {
    
    super(owner, name);
    
    this.basicType = BasicType.getRandom();

    // Generate the field declaration
    JDefinedClass ownerClass = owner.getGeneratedClass();
    this.generatedField = ownerClass.field(JMod.PRIVATE, basicType.getTypeClass(), name);
    
    // The getter
    getter = ownerClass.method(JMod.PUBLIC, basicType.getTypeClass(), "get" + name.substring(0, 1).toUpperCase() + name.substring(1));
    getter.body()._return(this.generatedField);
    
    // And the setter
    setter = ownerClass.method(JMod.PUBLIC, void.class, "set" + name.substring(0, 1).toUpperCase() + name.substring(1));
    JVar setterParam = setter.param(basicType.getTypeClass(), name);
    setter.body().assign(JExpr._this().ref(this.generatedField), setterParam);
}
 
Example 3
Project: GitHub   File: DynamicPropertiesRule.java   View source code 6 votes vote down vote up
private JMethod addPublicGetMethod(JDefinedClass jclass, JMethod internalGetMethod, JFieldRef notFoundValue) {
    JMethod method = jclass.method(PUBLIC, jclass.owner()._ref(Object.class), GETTER_NAME);
    JTypeVar returnType = method.generify("T");
    method.type(returnType);
    Models.suppressWarnings(method, "unchecked");
    JVar nameParam = method.param(String.class, "name");
    JBlock body = method.body();
    JVar valueVar = body.decl(jclass.owner()._ref(Object.class), "value",
            invoke(internalGetMethod).arg(nameParam).arg(notFoundValue));
    JConditional found = method.body()._if(notFoundValue.ne(valueVar));
    found._then()._return(cast(returnType, valueVar));
    JBlock notFound = found._else();

    JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {});
    if (getAdditionalProperties != null) {
        notFound._return(cast(returnType, invoke(getAdditionalProperties).invoke("get").arg(nameParam)));
    } else {
        notFound._throw(illegalArgumentInvocation(jclass, nameParam));
    }

    return method;
}
 
Example 4
Project: GitHub   File: DynamicPropertiesRule.java   View source code 6 votes vote down vote up
private JMethod addPublicSetMethod(JDefinedClass jclass, JMethod internalSetMethod) {
    JMethod method = jclass.method(PUBLIC, jclass.owner().VOID, SETTER_NAME);
    JVar nameParam = method.param(String.class, "name");
    JVar valueParam = method.param(Object.class, "value");
    JBlock body = method.body();
    JBlock notFound = body._if(JOp.not(invoke(internalSetMethod).arg(nameParam).arg(valueParam)))._then();

    // if we have additional properties, then put value.
    JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {});
    if (getAdditionalProperties != null) {
        JType additionalPropertiesType = ((JClass) (getAdditionalProperties.type())).getTypeParameters().get(1);
        notFound.add(invoke(getAdditionalProperties).invoke("put").arg(nameParam)
                .arg(cast(additionalPropertiesType, valueParam)));
    }
    // else throw exception.
    else {
        notFound._throw(illegalArgumentInvocation(jclass, nameParam));
    }

    return method;
}
 
Example 5
Project: GitHub   File: DynamicPropertiesRule.java   View source code 6 votes vote down vote up
private JMethod addPublicWithMethod(JDefinedClass jclass, JMethod internalSetMethod) {
    JMethod method = jclass.method(PUBLIC, jclass, BUILDER_NAME);
    JVar nameParam = method.param(String.class, "name");
    JVar valueParam = method.param(Object.class, "value");
    JBlock body = method.body();
    JBlock notFound = body._if(JOp.not(invoke(internalSetMethod).arg(nameParam).arg(valueParam)))._then();

    // if we have additional properties, then put value.
    JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {});
    if (getAdditionalProperties != null) {
        JType additionalPropertiesType = ((JClass) (getAdditionalProperties.type())).getTypeParameters().get(1);
        notFound.add(invoke(getAdditionalProperties).invoke("put").arg(nameParam)
                .arg(cast(additionalPropertiesType, valueParam)));
    }
    // else throw exception.
    else {
        notFound._throw(illegalArgumentInvocation(jclass, nameParam));
    }
    body._return(_this());

    return method;
}
 
Example 6
Project: beanvalidation-benchmark   File: JavaBeanRefField.java   View source code 6 votes vote down vote up
public JavaBeanRefField(MetaJavaBean owner, String name, MetaJavaBean refBean) {
    super(owner, name);
    
    this.refBean = refBean;
    
    // Generate the field declaration
    JDefinedClass ownerClass = owner.getGeneratedClass();
    this.generatedField = ownerClass.field(JMod.PRIVATE, refBean.getGeneratedClass(), name);
    
    // The getter
    getter = ownerClass.method(JMod.PUBLIC, refBean.getGeneratedClass(), "get"+name.substring(0, 1).toUpperCase()+name.substring(1));
    getter.body()._return(this.generatedField);
    
    // The setter
    setter = ownerClass.method(JMod.PUBLIC, void.class, "set"+name.substring(0, 1).toUpperCase()+name.substring(1));
    JVar setterParam = setter.param(refBean.getGeneratedClass(), name);
    setter.body().assign(JExpr._this().ref(this.generatedField), setterParam);
}
 
Example 7
Project: GitHub   File: EnumRule.java   View source code 6 votes vote down vote up
private void addEnumConstants(JsonNode node, JDefinedClass _enum, JsonNode customNames, JType type) {
    Collection<String> existingConstantNames = new ArrayList<String>();
    for (int i = 0; i < node.size(); i++) {
        JsonNode value = node.path(i);

        if (!value.isNull()) {
            String constantName = getConstantName(value.asText(), customNames.path(i).asText());
            constantName = makeUnique(constantName, existingConstantNames);
            existingConstantNames.add(constantName);

            JEnumConstant constant = _enum.enumConstant(constantName);
            constant.arg(DefaultRule.getDefaultValue(type, value));
            ruleFactory.getAnnotator().enumConstant(constant, value.asText());
        }
    }
}
 
Example 8
Project: QDrill   File: ClassGenerator.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
ClassGenerator(CodeGenerator<T> codeGenerator, MappingSet mappingSet, SignatureHolder signature, EvaluationVisitor eval, JDefinedClass clazz, JCodeModel model) throws JClassAlreadyExistsException {
  this.codeGenerator = codeGenerator;
  this.clazz = clazz;
  this.mappings = mappingSet;
  this.sig = signature;
  this.evaluationVisitor = eval;
  this.model = model;
  blocks = (LinkedList<JBlock>[]) new LinkedList[sig.size()];
  for (int i =0; i < sig.size(); i++) {
    blocks[i] = Lists.newLinkedList();
  }
  rotateBlock();

  for (SignatureHolder child : signature.getChildHolders()) {
    String innerClassName = child.getSignatureClass().getSimpleName();
    JDefinedClass innerClazz = clazz._class(Modifier.FINAL + Modifier.PRIVATE, innerClassName);
    innerClasses.put(innerClassName, new ClassGenerator<>(codeGenerator, mappingSet, child, eval, innerClazz, model));
  }
}
 
Example 9
Project: GitHub   File: PropertiesRule.java   View source code 6 votes vote down vote up
/**
 * Applies this schema rule to take the required code generation steps.
 * <p>
 * For each property present within the properties node, this rule will
 * invoke the 'property' rule provided by the given schema mapper.
 *
 * @param nodeName
 *            the name of the node for which properties are being added
 * @param node
 *            the properties node, containing property names and their
 *            definition
 * @param jclass
 *            the Java type which will have the given properties added
 * @return the given jclass
 */
@Override
public JDefinedClass apply(String nodeName, JsonNode node, JDefinedClass jclass, Schema schema) {
    if (node == null) {
        node = JsonNodeFactory.instance.objectNode();
    }

    for (Iterator<String> properties = node.fieldNames(); properties.hasNext(); ) {
        String property = properties.next();

        ruleFactory.getPropertyRule().apply(property, node.get(property), jclass, schema);
    }

    if (ruleFactory.getGenerationConfig().isGenerateBuilders() && !jclass._extends().name().equals("Object")) {
        addOverrideBuilders(jclass, jclass.owner()._getClass(jclass._extends().fullName()));
    }

    ruleFactory.getAnnotator().propertyOrder(jclass, node);

    return jclass;
}
 
Example 10
Project: GitHub   File: ObjectRule.java   View source code 6 votes vote down vote up
private void addToString(JDefinedClass jclass) {
    Map<String, JFieldVar> fields = jclass.fields();
    JMethod toString = jclass.method(JMod.PUBLIC, String.class, "toString");
    Set<String> excludes = new HashSet<String>(Arrays.asList(ruleFactory.getGenerationConfig().getToStringExcludes()));

    JBlock body = toString.body();
    Class<?> toStringBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.ToStringBuilder.class : org.apache.commons.lang.builder.ToStringBuilder.class;
    JClass toStringBuilderClass = jclass.owner().ref(toStringBuilder);
    JInvocation toStringBuilderInvocation = JExpr._new(toStringBuilderClass).arg(JExpr._this());

    if (!jclass._extends().fullName().equals(Object.class.getName())) {
        toStringBuilderInvocation = toStringBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("toString"));
    }

    for (JFieldVar fieldVar : fields.values()) {
        if (excludes.contains(fieldVar.name()) || (fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC) {
            continue;
        }
        toStringBuilderInvocation = toStringBuilderInvocation.invoke("append").arg(fieldVar.name()).arg(fieldVar);
    }

    body._return(toStringBuilderInvocation.invoke("toString"));

    toString.annotate(Override.class);
}
 
Example 11
Project: GitHub   File: ObjectRule.java   View source code 6 votes vote down vote up
private void addHashCode(JDefinedClass jclass, JsonNode node) {
    Map<String, JFieldVar> fields = removeFieldsExcludedFromEqualsAndHashCode(jclass.fields(), node);

    JMethod hashCode = jclass.method(JMod.PUBLIC, int.class, "hashCode");

    Class<?> hashCodeBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.HashCodeBuilder.class : org.apache.commons.lang.builder.HashCodeBuilder.class;

    JBlock body = hashCode.body();
    JClass hashCodeBuilderClass = jclass.owner().ref(hashCodeBuilder);
    JInvocation hashCodeBuilderInvocation = JExpr._new(hashCodeBuilderClass);

    if (!jclass._extends().fullName().equals(Object.class.getName())) {
        hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("hashCode"));
    }

    for (JFieldVar fieldVar : fields.values()) {
        if ((fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC) {
            continue;
        }
        hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("append").arg(fieldVar);
    }

    body._return(hashCodeBuilderInvocation.invoke("toHashCode"));

    hashCode.annotate(Override.class);
}
 
Example 12
Project: GitHub   File: Jackson2Annotator.java   View source code 6 votes vote down vote up
@Override
public void propertyField(JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) {
    field.annotate(JsonProperty.class).param("value", propertyName);
    if (field.type().erasure().equals(field.type().owner().ref(Set.class))) {
        field.annotate(JsonDeserialize.class).param("as", LinkedHashSet.class);
    }

    if (propertyNode.has("javaJsonView")) {
        field.annotate(JsonView.class).param(
                "value", field.type().owner().ref(propertyNode.get("javaJsonView").asText()));
    }

    if (propertyNode.has("description")) {
        field.annotate(JsonPropertyDescription.class).param("value", propertyNode.get("description").asText());
    }
}
 
Example 13
Project: QDrill   File: CodeGenerator.java   View source code 6 votes vote down vote up
CodeGenerator(MappingSet mappingSet, TemplateClassDefinition<T> definition,
    FunctionImplementationRegistry funcRegistry) {
  Preconditions.checkNotNull(definition.getSignature(),
      "The signature for defintion %s was incorrectly initialized.", definition);
  this.definition = definition;
  this.className = definition.getExternalInterface().getSimpleName() + "Gen" + definition.getNextClassNumber();
  this.fqcn = PACKAGE_NAME + "." + className;
  try {
    this.model = new JCodeModel();
    JDefinedClass clazz = model._package(PACKAGE_NAME)._class(className);
    rootGenerator = new ClassGenerator<>(this, mappingSet, definition.getSignature(), new EvaluationVisitor(
        funcRegistry), clazz, model);
  } catch (JClassAlreadyExistsException e) {
    throw new IllegalStateException(e);
  }
}
 
Example 14
Project: beanvalidation-benchmark   File: MetaJavaBean.java   View source code 6 votes vote down vote up
public MetaAnnotation buildGroupSequenceAnnot() {
    if ( this.groups.isEmpty() ) {
        return null; // No group sequence needed
    }
    else {
        // Build the array of groups
        JDefinedClass[] gs = new JDefinedClass[groups.size()+1];
        int i=0;
        for ( MetaGroup group : groups ) {
            gs[i++] = group.getGeneratedClass();
        }
        gs[i] = getGeneratedClass(); // Add the class itself (acts as Default)
        HashMap<String,Object> gsParams = Maps.newHashMap();
        gsParams.put("value", gs);
        MetaAnnotation gsAnnot = new MetaAnnotation(getGeneratedClass().owner(), GroupSequence.class, AnnotationType.OTHER, gsParams);
        return gsAnnot;
    }
}
 
Example 15
Project: beanvalidation-benchmark   File: Jsr303Annotator.java   View source code 6 votes vote down vote up
/**
 * @return A list of the class level annotations that the annotator will
 *         use.
 */
private List<MetaAnnotation> buildClassAnnotations() {

    List<MetaAnnotation> anns = Lists.newArrayList();
    HashMap<String, Object> annotParams;

    // AlwaysValid
    JDefinedClass alwaysValid = buildTemplateConstraint("AlwaysValid");
    JDefinedClass alwaysValidValidator = buildTemplateConstraintValidator("AlwaysValidValidator", alwaysValid, Object.class);
    JMethod isValid = getIsValidMethod(alwaysValidValidator);
    isValid.body()._return(JExpr.TRUE);
    alwaysValid.annotate(Constraint.class).param("validatedBy", alwaysValidValidator);
    
    annotParams = Maps.newHashMap();
    anns.add(new MetaAnnotation(alwaysValid, AnnotationType.JSR_303, annotParams));
    
    return anns;
}
 
Example 16
Project: dremio-oss   File: CodeGenerator.java   View source code 6 votes vote down vote up
CodeGenerator(CodeCompiler compiler, MappingSet mappingSet, TemplateClassDefinition<T> definition) {
  Preconditions.checkNotNull(definition.getSignature(),
      "The signature for defintion %s was incorrectly initialized.", definition);
  this.definition = definition;
  this.compiler = compiler;
  this.className = definition.getExternalInterface().getSimpleName() + "Gen" + definition.getNextClassNumber();
  this.fqcn = PACKAGE_NAME + "." + className;
  try {
    this.model = new JCodeModel();
    JDefinedClass clazz = model._package(PACKAGE_NAME)._class(className);
    clazz = clazz._extends(model.directClass(definition.getTemplateClassName()));
    clazz.constructor(JMod.PUBLIC).body().invoke(SignatureHolder.INIT_METHOD);
    rootGenerator = new ClassGenerator<>(this, mappingSet, definition.getSignature(), new EvaluationVisitor(), clazz, model);
  } catch (JClassAlreadyExistsException e) {
    throw new IllegalStateException(e);
  }
}
 
Example 17
Project: GitHub   File: Jackson1Annotator.java   View source code 5 votes vote down vote up
@Override
public void propertyOrder(JDefinedClass clazz, JsonNode propertiesNode) {
    JAnnotationArrayMember annotationValue = clazz.annotate(JsonPropertyOrder.class).paramArray("value");

    for (Iterator<String> properties = propertiesNode.fieldNames(); properties.hasNext();) {
        annotationValue.param(properties.next());
    }
}
 
Example 18
Project: GitHub   File: Jackson1Annotator.java   View source code 5 votes vote down vote up
@Override
public void propertyField(JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) {
    field.annotate(JsonProperty.class).param("value", propertyName);
    if (field.type().erasure().equals(field.type().owner().ref(Set.class))) {
        field.annotate(JsonDeserialize.class).param("as", LinkedHashSet.class);
    }

    if (propertyNode.has("javaJsonView")) {
        field.annotate(JsonView.class).param(
                "value", field.type().owner().ref(propertyNode.get("javaJsonView").asText()));
    }
}
 
Example 19
Project: GitHub   File: DynamicPropertiesRule.java   View source code 5 votes vote down vote up
private JMethod addInternalGetMethodJava7(JDefinedClass jclass, JsonNode propertiesNode) {
    JMethod method = jclass.method(PROTECTED, jclass.owner()._ref(Object.class), DEFINED_GETTER_NAME);
    JVar nameParam = method.param(String.class, "name");
    JVar notFoundParam = method.param(jclass.owner()._ref(Object.class), "notFoundValue");
    JBlock body = method.body();
    JSwitch propertySwitch = body._switch(nameParam);
    if (propertiesNode != null) {
        for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) {
            Map.Entry<String, JsonNode> property = properties.next();
            String propertyName = property.getKey();
            JsonNode node = property.getValue();
            String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node);
            JType propertyType = jclass.fields().get(fieldName).type();

            addGetPropertyCase(jclass, propertySwitch, propertyName, propertyType, node);
        }
    }
    JClass extendsType = jclass._extends();
    if (extendsType != null && extendsType instanceof JDefinedClass) {
        JDefinedClass parentClass = (JDefinedClass) extendsType;
        JMethod parentMethod = parentClass.getMethod(DEFINED_GETTER_NAME,
                new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) });
        propertySwitch._default().body()
        ._return(_super().invoke(parentMethod).arg(nameParam).arg(notFoundParam));
    } else {
        propertySwitch._default().body()
        ._return(notFoundParam);
    }

    return method;
}
 
Example 20
Project: GitHub   File: DynamicPropertiesRule.java   View source code 5 votes vote down vote up
private JMethod addInternalGetMethodJava6(JDefinedClass jclass, JsonNode propertiesNode) {
    JMethod method = jclass.method(PROTECTED, jclass.owner()._ref(Object.class), DEFINED_GETTER_NAME);
    JVar nameParam = method.param(String.class, "name");
    JVar notFoundParam = method.param(jclass.owner()._ref(Object.class), "notFoundValue");
    JBlock body = method.body();
    JConditional propertyConditional = null;

    if (propertiesNode != null) {
        for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) {
            Map.Entry<String, JsonNode> property = properties.next();
            String propertyName = property.getKey();
            JsonNode node = property.getValue();
            String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node);
            JType propertyType = jclass.fields().get(fieldName).type();

            JExpression condition = lit(propertyName).invoke("equals").arg(nameParam);
            if (propertyConditional == null) {
                propertyConditional = body._if(condition);
            } else {
                propertyConditional = propertyConditional._elseif(condition);
            }
            JMethod propertyGetter = jclass.getMethod(getGetterName(propertyName, propertyType, node), new JType[] {});
            propertyConditional._then()._return(invoke(propertyGetter));
        }
    }

    JClass extendsType = jclass._extends();
    JBlock lastBlock = propertyConditional == null ? body : propertyConditional._else();
    if (extendsType != null && extendsType instanceof JDefinedClass) {
        JDefinedClass parentClass = (JDefinedClass) extendsType;
        JMethod parentMethod = parentClass.getMethod(DEFINED_GETTER_NAME,
                new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) });
        lastBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(notFoundParam));
    } else {
        lastBlock._return(notFoundParam);
    }

    return method;
}
 
Example 21
Project: GitHub   File: DynamicPropertiesRule.java   View source code 5 votes vote down vote up
private JMethod addInternalSetMethodJava7(JDefinedClass jclass, JsonNode propertiesNode) {
    JMethod method = jclass.method(PROTECTED, jclass.owner().BOOLEAN, DEFINED_SETTER_NAME);
    JVar nameParam = method.param(String.class, "name");
    JVar valueParam = method.param(Object.class, "value");
    JBlock body = method.body();
    JSwitch propertySwitch = body._switch(nameParam);
    if (propertiesNode != null) {
        for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) {
            Map.Entry<String, JsonNode> property = properties.next();
            String propertyName = property.getKey();
            JsonNode node = property.getValue();
            String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node);
            JType propertyType = jclass.fields().get(fieldName).type();

            addSetPropertyCase(jclass, propertySwitch, propertyName, propertyType, valueParam, node);
        }
    }
    JBlock defaultBlock = propertySwitch._default().body();
    JClass extendsType = jclass._extends();
    if (extendsType != null && extendsType instanceof JDefinedClass) {
        JDefinedClass parentClass = (JDefinedClass) extendsType;
        JMethod parentMethod = parentClass.getMethod(DEFINED_SETTER_NAME,
                new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) });
        defaultBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(valueParam));
    } else {
        defaultBlock._return(FALSE);
    }
    return method;
}
 
Example 22
Project: GitHub   File: DynamicPropertiesRule.java   View source code 5 votes vote down vote up
private JMethod addInternalSetMethodJava6(JDefinedClass jclass, JsonNode propertiesNode) {
    JMethod method = jclass.method(PROTECTED, jclass.owner().BOOLEAN, DEFINED_SETTER_NAME);
    JVar nameParam = method.param(String.class, "name");
    JVar valueParam = method.param(Object.class, "value");
    JBlock body = method.body();
    JConditional propertyConditional = null;
    if (propertiesNode != null) {
        for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) {
            Map.Entry<String, JsonNode> property = properties.next();
            String propertyName = property.getKey();
            JsonNode node = property.getValue();
            String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node);
            JType propertyType = jclass.fields().get(fieldName).type();
            JExpression condition = lit(propertyName).invoke("equals").arg(nameParam);
            propertyConditional = propertyConditional == null ? propertyConditional = body._if(condition)
                    : propertyConditional._elseif(condition);

            JBlock callSite = propertyConditional._then();
            addSetProperty(jclass, callSite, propertyName, propertyType, valueParam, node);
            callSite._return(TRUE);
        }
    }
    JClass extendsType = jclass._extends();
    JBlock lastBlock = propertyConditional == null ? body : propertyConditional._else();

    if (extendsType != null && extendsType instanceof JDefinedClass) {
        JDefinedClass parentClass = (JDefinedClass) extendsType;
        JMethod parentMethod = parentClass.getMethod(DEFINED_SETTER_NAME,
                new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) });
        lastBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(valueParam));
    } else {
        lastBlock._return(FALSE);
    }
    return method;
}
 
Example 23
Project: GitHub   File: DynamicPropertiesRule.java   View source code 5 votes vote down vote up
private void addSetProperty(JDefinedClass jclass, JBlock callSite, String propertyName, JType propertyType, JVar valueVar, JsonNode node) {
    JMethod propertySetter = jclass.getMethod(getSetterName(propertyName, node), new JType[] { propertyType });
    JConditional isInstance = callSite._if(valueVar._instanceof(propertyType.boxify().erasure()));
    isInstance._then()
    .invoke(propertySetter).arg(cast(propertyType.boxify(), valueVar));
    isInstance._else()
    ._throw(illegalArgumentInvocation(jclass, propertyName, propertyType, valueVar));
}
 
Example 24
Project: GitHub   File: EnumRule.java   View source code 5 votes vote down vote up
private JFieldVar addQuickLookupMap(JDefinedClass _enum, JType backingType) {

        JClass lookupType = _enum.owner().ref(Map.class).narrow(backingType.boxify(), _enum);
        JFieldVar lookupMap = _enum.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, lookupType, "CONSTANTS");

        JClass lookupImplType = _enum.owner().ref(HashMap.class).narrow(backingType.boxify(), _enum);
        lookupMap.init(JExpr._new(lookupImplType));

        JForEach forEach = _enum.init().forEach(_enum, "c", JExpr.invoke("values"));
        JInvocation put = forEach.body().invoke(lookupMap, "put");
        put.arg(forEach.var().ref("value"));
        put.arg(forEach.var());

        return lookupMap;
    }
 
Example 25
Project: beanvalidation-benchmark   File: Generator.java   View source code 5 votes vote down vote up
/**
 * Generates a Holder class that will hold an {@link ArrayList} with all the
 * first level beans in the graph (contents of {@link #beans}) on it.
 */
private void generatePopulationCode() {
    try {
        // Generate the holder class
        JDefinedClass holderClass = cm._class(Config.CFG.getBasePackageName() + ".Holder");
        JClass alObject = (JClass) cm._ref(ArrayList.class);
        alObject = alObject.narrow(Object.class);
        JFieldVar beansField = holderClass.field(JMod.PUBLIC, alObject, "beans", JExpr._new(alObject));
        JMethod defConstructor = holderClass.constructor(JMod.PUBLIC);
        JBlock body = defConstructor.body();

        // Init the beans and add them to the array
        for (MetaJavaBean mjb : beans) {
            mjb.generateStaticInitCode();
            JVar beanDecl = generateBeanNonStaticInitCode(mjb, body, 0);
            body.add(beansField.invoke("add").arg(beanDecl));
        }

        // Init the base beans but don't add them to the array
        for (MetaJavaBean bmjb : baseBeans) {
            bmjb.generateStaticInitCode();
        }

    } catch (JClassAlreadyExistsException e) {
        throw new RuntimeException("Error generating the holder class.", e);
    }
}
 
Example 26
Project: GitHub   File: EnumRule.java   View source code 5 votes vote down vote up
private void addToString(JDefinedClass _enum, JFieldVar valueField) {
    JMethod toString = _enum.method(JMod.PUBLIC, String.class, "toString");
    JBlock body = toString.body();

    JExpression toReturn = JExpr._this().ref(valueField);
    if(!isString(valueField.type())){
        toReturn = toReturn.plus(JExpr.lit(""));
    }

    body._return(toReturn);

    toString.annotate(Override.class);
}
 
Example 27
Project: GitHub   File: EnumRule.java   View source code 5 votes vote down vote up
private void addValueMethod(JDefinedClass _enum, JFieldVar valueField) {
    JMethod fromValue = _enum.method(JMod.PUBLIC, valueField.type(), "value");

    JBlock body = fromValue.body();
    body._return(JExpr._this().ref(valueField));

    ruleFactory.getAnnotator().enumValueMethod(fromValue);
}
 
Example 28
Project: GitHub   File: EnumRule.java   View source code 5 votes vote down vote up
private String getEnumName(String nodeName, JsonNode node, JClassContainer container) {
    String fieldName = ruleFactory.getNameHelper().getFieldName(nodeName, node);
    String className = ruleFactory.getNameHelper().replaceIllegalCharacters(capitalize(fieldName));
    String normalizedName = ruleFactory.getNameHelper().normalizeName(className);

    Collection<String> existingClassNames = new ArrayList<String>();
    for (Iterator<JDefinedClass> classes = container.classes(); classes.hasNext();) {
        existingClassNames.add(classes.next().name());
    }
    return makeUnique(normalizedName, existingClassNames);
}
 
Example 29
Project: GitHub   File: DefaultRule.java   View source code 5 votes vote down vote up
/**
 * @see EnumRule
 */
private static JExpression getDefaultEnum(JType fieldType, JsonNode node) {

    JDefinedClass enumClass = (JDefinedClass) fieldType;
    JType backingType = enumClass.fields().get("value").type();
    JInvocation invokeFromValue = enumClass.staticInvoke("fromValue");
    invokeFromValue.arg(getDefaultValue(backingType, node));

    return invokeFromValue;

}
 
Example 30
Project: GitHub   File: PropertyRule.java   View source code 5 votes vote down vote up
private JMethod addGetter(JDefinedClass c, JFieldVar field, String jsonPropertyName, JsonNode node) {
    JMethod getter = c.method(JMod.PUBLIC, field.type(), getGetterName(jsonPropertyName, field.type(), node));

    JBlock body = getter.body();
    body._return(field);

    return getter;
}
 
Example 31
Project: GitHub   File: PropertyRule.java   View source code 5 votes vote down vote up
private JMethod addSetter(JDefinedClass c, JFieldVar field, String jsonPropertyName, JsonNode node) {
    JMethod setter = c.method(JMod.PUBLIC, void.class, getSetterName(jsonPropertyName, node));

    JVar param = setter.param(field.type(), field.name());
    JBlock body = setter.body();
    body.assign(JExpr._this().ref(field), param);

    return setter;
}
 
Example 32
Project: GitHub   File: PropertyRule.java   View source code 5 votes vote down vote up
private JMethod addBuilder(JDefinedClass c, JFieldVar field) {
    JMethod builder = c.method(JMod.PUBLIC, c, getBuilderName(field.name()));

    JVar param = builder.param(field.type(), field.name());
    JBlock body = builder.body();
    body.assign(JExpr._this().ref(field), param);
    body._return(JExpr._this());

    return builder;
}
 
Example 33
Project: GitHub   File: PropertiesRule.java   View source code 5 votes vote down vote up
private void addOverrideBuilders(JDefinedClass jclass, JDefinedClass parentJclass) {
    if (parentJclass == null) {
        return;
    }

    for (JMethod parentJMethod : parentJclass.methods()) {
        if (parentJMethod.name().startsWith("with") && parentJMethod.params().size() == 1) {
            addOverrideBuilder(jclass, parentJMethod, parentJMethod.params().get(0));
        }
    }
}
 
Example 34
Project: GitHub   File: PropertiesRule.java   View source code 5 votes vote down vote up
private void addOverrideBuilder(JDefinedClass thisJDefinedClass, JMethod parentBuilder, JVar parentParam) {

        if (thisJDefinedClass.getMethod(parentBuilder.name(), new JType[] {parentParam.type()}) == null) {

            JMethod builder = thisJDefinedClass.method(parentBuilder.mods().getValue(), thisJDefinedClass, parentBuilder.name());
            builder.annotate(Override.class);

            JVar param = builder.param(parentParam.type(), parentParam.name());
            JBlock body = builder.body();
            body.invoke(JExpr._super(), parentBuilder).arg(param);
            body._return(JExpr._this());

        }
    }
 
Example 35
Project: GitHub   File: AdditionalPropertiesRule.java   View source code 5 votes vote down vote up
private void addSetter(JDefinedClass jclass, JType propertyType, JFieldVar field) {
    JMethod setter = jclass.method(JMod.PUBLIC, void.class, "setAdditionalProperty");

    ruleFactory.getAnnotator().anySetter(setter);

    JVar nameParam = setter.param(String.class, "name");
    JVar valueParam = setter.param(propertyType, "value");

    JInvocation mapInvocation = setter.body().invoke(JExpr._this().ref(field), "put");
    mapInvocation.arg(nameParam);
    mapInvocation.arg(valueParam);
}
 
Example 36
Project: GitHub   File: AdditionalPropertiesRule.java   View source code 5 votes vote down vote up
private JMethod addGetter(JDefinedClass jclass, JFieldVar field) {
    JMethod getter = jclass.method(JMod.PUBLIC, field.type(), "getAdditionalProperties");

    ruleFactory.getAnnotator().anyGetter(getter);

    getter.body()._return(JExpr._this().ref(field));
    return getter;
}
 
Example 37
Project: GitHub   File: AdditionalPropertiesRule.java   View source code 5 votes vote down vote up
private void addBuilder(JDefinedClass jclass, JType propertyType, JFieldVar field) {
    JMethod builder = jclass.method(JMod.PUBLIC, jclass, "withAdditionalProperty");

    JVar nameParam = builder.param(String.class, "name");
    JVar valueParam = builder.param(propertyType, "value");

    JBlock body = builder.body();
    JInvocation mapInvocation = body.invoke(JExpr._this().ref(field), "put");
    mapInvocation.arg(nameParam);
    mapInvocation.arg(valueParam);
    body._return(JExpr._this());
}
 
Example 38
Project: GitHub   File: ObjectRule.java   View source code 5 votes vote down vote up
private void addParcelSupport(JDefinedClass jclass) {
    jclass._implements(Parcelable.class);

    parcelableHelper.addWriteToParcel(jclass);
    parcelableHelper.addDescribeContents(jclass);
    parcelableHelper.addCreator(jclass);
    parcelableHelper.addConstructorFromParcel(jclass);
    // #742 : includeConstructors will include the default constructor
    if (!ruleFactory.getGenerationConfig().isIncludeConstructors()) {
        // Add empty constructor
        jclass.constructor(JMod.PUBLIC);
    }
}
 
Example 39
Project: GitHub   File: ObjectRule.java   View source code 5 votes vote down vote up
private void addJsonTypeInfoAnnotation(JDefinedClass jclass, JsonNode node) {
    if (ruleFactory.getGenerationConfig().getAnnotationStyle() == AnnotationStyle.JACKSON2) {
        String annotationName = node.get("deserializationClassProperty").asText();
        JAnnotationUse jsonTypeInfo = jclass.annotate(JsonTypeInfo.class);
        jsonTypeInfo.param("use", JsonTypeInfo.Id.CLASS);
        jsonTypeInfo.param("include", JsonTypeInfo.As.PROPERTY);
        jsonTypeInfo.param("property", annotationName);
    }
}
 
Example 40
Project: GitHub   File: ObjectRule.java   View source code 5 votes vote down vote up
private static JDefinedClass definedClassOrNullFromType(JType type)
{
    if (type == null || type.isPrimitive())
    {
        return null;
    }
    JClass fieldClass = type.boxify();
    JPackage jPackage = fieldClass._package();
    return jPackage._getClass(fieldClass.name());
}