コード例 #1
0
 @Test
 public void testRecursivlyCreateAllTypesAny() throws ClassNotFoundException {
   schema.setType(TYPE.ANY);
   JCodeModel codeModel = new JCodeModel();
   JType type = driver.createOrGetType(codeModel, schema);
   assertNotNull(type);
   assertEquals(Object.class.getName(), type.fullName());
 }
コード例 #2
0
  @Override
  public JType visit(ReferenceType type, JCodeModel codeModel) {
    final JType referencedType = type.getType().accept(this, codeModel);

    JType referencedTypeArray = referencedType;
    for (int index = 0; index < type.getArrayCount(); index++) {
      referencedTypeArray = referencedTypeArray.array();
    }
    return referencedTypeArray;
  }
コード例 #3
0
 @Test
 public void testRecursivlyCreateAllTypesArrayNull() throws ClassNotFoundException {
   schema.setType(TYPE.ARRAY);
   ObjectSchema arrayType = new ObjectSchema();
   arrayType.setType(TYPE.NULL);
   schema.setItems(arrayType);
   JCodeModel codeModel = new JCodeModel();
   JType type = driver.createOrGetType(codeModel, schema);
   assertNotNull(type);
   assertEquals(List.class.getName() + "<" + Object.class.getName() + ">", type.fullName());
 }
コード例 #4
0
 @Test
 public void testRecursivlyCreateAllTypesNumber() throws ClassNotFoundException {
   ObjectSchema schema = new ObjectSchema();
   schema.setType(TYPE.NUMBER);
   JCodeModel codeModel = new JCodeModel();
   schema.setId("org.sample.SampleClass");
   JPackage _package = codeModel._package("org.sample");
   JType type = driver.createOrGetType(codeModel, schema);
   assertNotNull(type);
   assertEquals(Double.class.getName(), type.fullName());
 }
コード例 #5
0
 @Test
 public void testRecursivlyCreateAllTypesArrayAnySet() throws ClassNotFoundException {
   schema.setType(TYPE.ARRAY);
   // set it to be unique to get a set
   schema.setUniqueItems(true);
   ObjectSchema arrayType = new ObjectSchema();
   arrayType.setType(TYPE.ANY);
   schema.setItems(arrayType);
   JCodeModel codeModel = new JCodeModel();
   JType type = driver.createOrGetType(codeModel, schema);
   assertNotNull(type);
   assertEquals(Set.class.getName() + "<" + Object.class.getName() + ">", type.fullName());
 }
コード例 #6
0
  public JType getTypeClass() {
    CAdapter a = typeUse.getAdapterUse();
    NType nt;
    if (a != null) nt = a.customType;
    else nt = typeUse.getInfo().getType();

    JType jt = nt.toType(outline, EXPOSED);

    JPrimitiveType prim = jt.boxify().getPrimitiveType();
    if (!typeUse.isCollection() && prim != null) jt = prim;

    if (typeUse.isCollection()) jt = jt.array();

    return jt;
  }
コード例 #7
0
ファイル: HashCodeGenerator.java プロジェクト: Gyropyro/Gean
  @Override
  public void generate(JDefinedClass cls, GenerationContext context) {
    if (classSpec.getFields().isEmpty()) {
      return; // No equals needed.
    }

    // Import the objects class, for hash coding.
    JClass objects = context.getTypeManager().getClassDirect("java.util.Objects");

    // Create the equals method.
    JMethod hashMethod = cls.method(JMod.PUBLIC, int.class, "hashCode");
    hashMethod.annotate(Override.class);
    JBlock body = hashMethod.body();

    // Check if the object is null.
    JVar hash = body.decl(JType.parse(context.getCodeModel(), "int"), "hash", JExpr.lit(3));

    // Do check for each field.
    for (DataFieldSpecification fieldSpec : classSpec.getFields()) {
      List<String> parts = NameFormat.namesToList(fieldSpec.getFieldName());
      String camelCaseFieldName = NameFormat.camelCase(parts, false);
      // Get the field value.
      JExpression thisField = JExpr.refthis(camelCaseFieldName);
      // Accumulate the hash code.
      JExpression fieldHashCode = objects.staticInvoke("hashCode").arg(thisField);

      body.assign(hash, JExpr.lit(79).mul(hash).plus(fieldHashCode));
    }

    // Return the processed hash value.
    body._return(hash);
  }
コード例 #8
0
 private boolean isFinal(JType superType) {
   try {
     Class<?> javaClass = Class.forName(superType.fullName());
     return Modifier.isFinal(javaClass.getModifiers());
   } catch (ClassNotFoundException e) {
     return false;
   }
 }
コード例 #9
0
  private String getGenericType(JType jType) {
    if (jType.erasure().name().equals("List")) {
      final String typeName = jType.fullName();
      int start = 0;
      int end = typeName.length();

      for (int i = 0; i < typeName.length(); ++i) {
        switch (typeName.charAt(i)) {
          case '<':
            start = i;
            break;
          case '>':
            end = i;
            break;
        }
      }
      // plus one for excluding '<'
      return typeName.substring(start + 1, end);
    }
    return jType.erasure().name();
  }
コード例 #10
0
  private void buildMethodInterceptor(
      JDefinedClass definedClass,
      ConstructorInjectionPoint proxyConstructorInjectionPoint,
      JMethod constructor,
      JBlock constructorBody,
      Map<ASTMethod, Map<InjectionNode, JFieldVar>> interceptorFields,
      Map.Entry<ASTMethod, Set<InjectionNode>> methodInterceptorEntry)
      throws ClassNotFoundException {
    ASTMethod method = methodInterceptorEntry.getKey();

    if (method.getAccessModifier().equals(ASTAccessModifier.PRIVATE)) {
      throw new TransfuseAnalysisException("Unable to provide AOP on private methods");
    }

    if (!interceptorFields.containsKey(methodInterceptorEntry.getKey())) {
      interceptorFields.put(
          methodInterceptorEntry.getKey(), new HashMap<InjectionNode, JFieldVar>());
    }
    Map<InjectionNode, JFieldVar> injectionNodeInstanceNameMap =
        interceptorFields.get(methodInterceptorEntry.getKey());

    // setup interceptor fields
    for (InjectionNode interceptorInjectionNode : methodInterceptorEntry.getValue()) {
      String interceptorInstanceName = namer.generateName(interceptorInjectionNode);

      JFieldVar interceptorField =
          definedClass.field(
              JMod.PRIVATE,
              codeModel.ref(interceptorInjectionNode.getClassName()),
              interceptorInstanceName);

      injectionNodeInstanceNameMap.put(interceptorInjectionNode, interceptorField);

      JVar interceptorParam =
          constructor.param(
              codeModel.ref(interceptorInjectionNode.getClassName()),
              namer.generateName(interceptorInjectionNode));

      constructorBody.assign(interceptorField, interceptorParam);

      proxyConstructorInjectionPoint.addInjectionNode(interceptorInjectionNode);
    }

    JType returnType = codeModel.parseType(method.getReturnType().getName());

    JMethod methodDeclaration =
        definedClass.method(
            method.getAccessModifier().getCodeModelJMod(), returnType, method.getName());
    JBlock body = methodDeclaration.body();

    // define method parameter
    Map<ASTParameter, JVar> parameterMap = new HashMap<ASTParameter, JVar>();
    for (ASTParameter parameter : method.getParameters()) {
      parameterMap.put(
          parameter,
          methodDeclaration.param(
              JMod.FINAL,
              codeModel.ref(parameter.getASTType().getName()),
              namer.generateName(parameter.getASTType())));
    }

    // aop interceptor
    Map<InjectionNode, JFieldVar> interceptorNameMap =
        interceptorFields.get(methodInterceptorEntry.getKey());

    JArray paramArray = JExpr.newArray(codeModel.ref(Object.class));

    for (ASTParameter astParameter : method.getParameters()) {
      paramArray.add(parameterMap.get(astParameter));
    }

    JInvocation interceptorInvocation =
        buildInterceptorChain(
                definedClass,
                method,
                parameterMap,
                methodInterceptorEntry.getValue(),
                interceptorNameMap)
            .invoke("invoke");
    interceptorInvocation.arg(paramArray);

    if (method.getReturnType().equals(ASTVoidType.VOID)) {
      body.add(interceptorInvocation);
    } else {
      body._return(JExpr.cast(returnType.boxify(), interceptorInvocation));
    }
  }
コード例 #11
0
 private void setAlreadyInflated() {
   alreadyInflated =
       generatedClass.field(
           PRIVATE, JType.parse(codeModel(), "boolean"), "alreadyInflated_", JExpr.FALSE);
 }
コード例 #12
0
  /**
   * Applies this schema rule to take the required code generation steps.
   *
   * <p>When this rule is applied for schemas of type object, the properties of the schema are used
   * to generate a new Java class and determine its characteristics. See other implementers of
   * {@link Rule} for details.
   *
   * <p>A new Java type will be created when this rule is applied, it is annotated as {@link
   * Generated}, it is given <code>equals</code>, <code>hashCode</code> and <code>toString</code>
   * methods and implements {@link Serializable}.
   */
  @Override
  public JType apply(String nodeName, JsonNode node, JPackage _package, Schema schema) {

    JType superType = getSuperType(nodeName, node, _package, schema);

    if (superType.isPrimitive() || isFinal(superType)) {
      return superType;
    }

    JDefinedClass jclass;
    try {

      String qualifiedClassName = deriveClassQualifiedName(_package, node, schema);
      if (qualifiedClassName != null) {
        int lastIndexOfDot = qualifiedClassName.lastIndexOf('.');
        String packageTemplate = qualifiedClassName.substring(0, lastIndexOfDot);
        JPackage currentPkg = _package.owner()._package(packageTemplate);
        String className = qualifiedClassName.substring(lastIndexOfDot + 1);
        jclass = createClass(className, node, currentPkg);
      } else {
        jclass = createClass(nodeName, node, _package);
      }
    } catch (ClassAlreadyExistsException e) {
      return e.getExistingClass();
    }

    jclass._extends((JClass) superType);

    schema.setJavaTypeIfEmpty(jclass);
    addGeneratedAnnotation(jclass);

    if (node.has("deserializationClassProperty")) {
      addJsonTypeInfoAnnotation(jclass, node);
    }

    if (node.has("title")) {
      ruleFactory.getTitleRule().apply(nodeName, node.get("title"), jclass, schema);
    }

    if (node.has("description")) {
      ruleFactory.getDescriptionRule().apply(nodeName, node.get("description"), jclass, schema);
    }

    if (node.has("properties")) {
      ruleFactory.getPropertiesRule().apply(nodeName, node.get("properties"), jclass, schema);
    }

    if (ruleFactory.getGenerationConfig().isIncludeToString()) {
      addToString(jclass);
    }

    if (node.has("javaInterfaces")) {
      addInterfaces(jclass, node.get("javaInterfaces"));
    }

    ruleFactory
        .getAdditionalPropertiesRule()
        .apply(nodeName, node.get("additionalProperties"), jclass, schema);

    if (node.has("required")) {
      ruleFactory.getRequiredArrayRule().apply(nodeName, node.get("required"), jclass, schema);
    }

    if (ruleFactory.getGenerationConfig().isIncludeHashcodeAndEquals()) {
      addHashCode(jclass);
      addEquals(jclass);
    }

    if (ruleFactory.getGenerationConfig().isParcelable()) {
      addParcelSupport(jclass);
    }

    if (ruleFactory.getGenerationConfig().isIncludeConstructors()) {
      addConstructors(
          jclass,
          getConstructorProperties(
              node, ruleFactory.getGenerationConfig().isConstructorsRequiredPropertiesOnly()));
    }

    if (node.has("id")) {
      ruleFactory.getSchemaRule().apply("id", node, jclass, schema);
    }

    return jclass;
  }