Search in sources :

Example 61 with JFieldVar

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

the class SerializableHelper method addSerializableSupport.

public static void addSerializableSupport(JDefinedClass jclass) {
    jclass._implements(Serializable.class);
    try {
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        final DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
        processDefinedClassForSerializableSupport(jclass, dataOutputStream);
        dataOutputStream.flush();
        final MessageDigest digest = MessageDigest.getInstance("SHA");
        final byte[] digestBytes = digest.digest(byteArrayOutputStream.toByteArray());
        long serialVersionUID = 0L;
        for (int i = Math.min(digestBytes.length, 8) - 1; i >= 0; i--) {
            serialVersionUID = serialVersionUID << 8 | digestBytes[i] & 0xff;
        }
        JFieldVar serialUIDField = jclass.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, long.class, "serialVersionUID");
        serialUIDField.init(JExpr.lit(serialVersionUID));
    } catch (IOException exception) {
        throw new GenerationException("IOException while generating serialversionUID field while adding serializable support to class: " + jclass.fullName(), exception);
    } catch (NoSuchAlgorithmException exception) {
        throw new GenerationException("SHA algorithm not found when trying to generate serialversionUID field while adding serializable support to class: " + jclass.fullName(), exception);
    }
}
Also used : JFieldVar(com.sun.codemodel.JFieldVar) DataOutputStream(java.io.DataOutputStream) GenerationException(org.jsonschema2pojo.exception.GenerationException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest)

Example 62 with JFieldVar

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

the class ObjectRule method removeFieldsExcludedFromEqualsAndHashCode.

private Map<String, JFieldVar> removeFieldsExcludedFromEqualsAndHashCode(Map<String, JFieldVar> fields, JsonNode node) {
    Map<String, JFieldVar> filteredFields = new HashMap<>(fields);
    JsonNode properties = node.get("properties");
    if (properties != null) {
        if (node.has("excludedFromEqualsAndHashCode")) {
            JsonNode excludedArray = node.get("excludedFromEqualsAndHashCode");
            for (Iterator<JsonNode> iterator = excludedArray.elements(); iterator.hasNext(); ) {
                String excludedPropertyName = iterator.next().asText();
                JsonNode excludedPropertyNode = properties.get(excludedPropertyName);
                filteredFields.remove(ruleFactory.getNameHelper().getPropertyName(excludedPropertyName, excludedPropertyNode));
            }
        }
        for (Iterator<Map.Entry<String, JsonNode>> iterator = properties.fields(); iterator.hasNext(); ) {
            Map.Entry<String, JsonNode> entry = iterator.next();
            String propertyName = entry.getKey();
            JsonNode propertyNode = entry.getValue();
            if (propertyNode.has("excludedFromEqualsAndHashCode") && propertyNode.get("excludedFromEqualsAndHashCode").asBoolean()) {
                filteredFields.remove(ruleFactory.getNameHelper().getPropertyName(propertyName, propertyNode));
            }
        }
    }
    return filteredFields;
}
Also used : JFieldVar(com.sun.codemodel.JFieldVar) HashMap(java.util.HashMap) JsonNode(com.fasterxml.jackson.databind.JsonNode) HashMap(java.util.HashMap) Map(java.util.Map)

Example 63 with JFieldVar

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

the class ObjectRule method addEquals.

private void addEquals(JDefinedClass jclass, JsonNode node) {
    Map<String, JFieldVar> fields = removeFieldsExcludedFromEqualsAndHashCode(jclass.fields(), node);
    JMethod equals = jclass.method(JMod.PUBLIC, boolean.class, "equals");
    JVar otherObject = equals.param(Object.class, "other");
    JBlock body = equals.body();
    body._if(otherObject.eq(JExpr._this()))._then()._return(JExpr.TRUE);
    body._if(otherObject._instanceof(jclass).eq(JExpr.FALSE))._then()._return(JExpr.FALSE);
    JVar rhsVar = body.decl(jclass, "rhs").init(JExpr.cast(jclass, otherObject));
    JExpression result = JExpr.lit(true);
    // First, check super.equals(other)
    if (!jclass._extends().fullName().equals(Object.class.getName())) {
        result = result.cand(JExpr._super().invoke("equals").arg(rhsVar));
    }
    // Chain the results of checking all other fields
    for (JFieldVar fieldVar : fields.values()) {
        if ((fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC) {
            continue;
        }
        JFieldRef thisFieldRef = JExpr.refthis(fieldVar.name());
        JFieldRef otherFieldRef = JExpr.ref(rhsVar, fieldVar.name());
        JExpression fieldEquals;
        if (fieldVar.type().isPrimitive()) {
            if ("double".equals(fieldVar.type().name())) {
                JClass doubleClass = jclass.owner().ref(Double.class);
                fieldEquals = doubleClass.staticInvoke("doubleToLongBits").arg(thisFieldRef).eq(doubleClass.staticInvoke("doubleToLongBits").arg(otherFieldRef));
            } else if ("float".equals(fieldVar.type().name())) {
                JClass floatClass = jclass.owner().ref(Float.class);
                fieldEquals = floatClass.staticInvoke("floatToIntBits").arg(thisFieldRef).eq(floatClass.staticInvoke("floatToIntBits").arg(otherFieldRef));
            } else {
                fieldEquals = thisFieldRef.eq(otherFieldRef);
            }
        } else if (fieldVar.type().isArray()) {
            if (!fieldVar.type().elementType().isPrimitive()) {
                throw new UnsupportedOperationException("Only primitive arrays are supported");
            }
            fieldEquals = jclass.owner().ref(Arrays.class).staticInvoke("equals").arg(thisFieldRef).arg(otherFieldRef);
        } else {
            fieldEquals = thisFieldRef.eq(otherFieldRef).cor(thisFieldRef.ne(JExpr._null()).cand(thisFieldRef.invoke("equals").arg(otherFieldRef)));
        }
        // Chain the equality of this field with the previous comparisons
        result = result.cand(fieldEquals);
    }
    body._return(result);
    equals.annotate(Override.class);
}
Also used : JFieldRef(com.sun.codemodel.JFieldRef) JFieldVar(com.sun.codemodel.JFieldVar) JClass(com.sun.codemodel.JClass) JBlock(com.sun.codemodel.JBlock) JExpression(com.sun.codemodel.JExpression) JMethod(com.sun.codemodel.JMethod) Arrays(java.util.Arrays) JVar(com.sun.codemodel.JVar)

Example 64 with JFieldVar

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

the class ReflectionHelper method searchClassAndSuperClassesForField.

public JFieldVar searchClassAndSuperClassesForField(String property, JDefinedClass jclass) {
    Map<String, JFieldVar> fields = jclass.fields();
    JFieldVar field = fields.get(property);
    if (field == null) {
        return searchSuperClassesForField(property, jclass);
    }
    return field;
}
Also used : JFieldVar(com.sun.codemodel.JFieldVar)

Example 65 with JFieldVar

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

the class DefaultRuleTest method whenIsInitializeCollections_false_applyDoesNotInitializeField.

@Test
public void whenIsInitializeCollections_false_applyDoesNotInitializeField() throws JClassAlreadyExistsException {
    final String fieldName = "fieldName";
    when(config.isInitializeCollections()).thenReturn(false);
    JDefinedClass jclass = new JCodeModel()._class("org.jsonschema2pojo.rules.ExampleClass");
    JFieldVar field = jclass.field(JMod.NONE, jclass.owner().ref(fieldTypeClass).narrow(Object.class), fieldName);
    ArrayNode node = new ObjectMapper().createArrayNode();
    StringWriter sw = new StringWriter();
    rule.apply("fooBar", node, null, field, null).bind(new JFormatter(sw));
    assertThat(sw.toString(), is(String.format("%s<%s> %s", fieldTypeClass.getName(), Object.class.getName(), fieldName)));
}
Also used : StringWriter(java.io.StringWriter) JDefinedClass(com.sun.codemodel.JDefinedClass) JFieldVar(com.sun.codemodel.JFieldVar) JFormatter(com.sun.codemodel.JFormatter) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) JCodeModel(com.sun.codemodel.JCodeModel) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) 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