コード例 #1
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);
  }
コード例 #2
0
  private void addHashCode(JDefinedClass jclass) {
    Map<String, JFieldVar> fields = jclass.fields();
    if (fields.isEmpty()) {
      return;
    }

    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().name().equals("Object")) {
      hashCodeBuilderInvocation =
          hashCodeBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("hashCode"));
    }

    for (JFieldVar fieldVar : fields.values()) {
      hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("append").arg(fieldVar);
    }

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

    hashCode.annotate(Override.class);
  }
コード例 #3
0
 private void addResultTypeMethod(JCodeModel model, JDefinedClass cls, JClass transformedType) {
   JClass classCls = model.ref(Class.class);
   JMethod method =
       cls.method(JMod.PROTECTED | JMod.FINAL, classCls.narrow(transformedType), "resultsType");
   method.body()._return(JExpr.dotclass(transformedType));
   method.annotate(Override.class);
 }
コード例 #4
0
 private void addParamAnnotation(
     final String resourceInterfacePath, final Action action, final JMethod method) {
   final String path =
       StringUtils.substringAfter(action.getResource().getUri(), resourceInterfacePath + "/");
   if (isNotBlank(path)) {
     method.annotate(Path.class).param(DEFAULT_ANNOTATION_PARAMETER, path);
   }
 }
コード例 #5
0
  private void addResourcePath(JDefinedClass cls, Feed feed) {
    JFieldVar field = cls.field(privateStaticFinal, String.class, "RESOURCE_PATH");
    field.init(JExpr.lit(feed.getHref()));

    JMethod method = cls.method(JMod.PROTECTED | JMod.FINAL, String.class, "resourcePath");
    method.annotate(Override.class);
    method.body()._return(field);
  }
コード例 #6
0
ファイル: BeanGenerator.java プロジェクト: tduehr/ldaptive
 /**
  * Creates the equals method on the supplied class. Leverages {@link
  * org.ldaptive.LdapUtils#areEqual(Object, Object)}.
  *
  * @param clazz to put equals method on
  */
 private void createEquals(final JDefinedClass clazz) {
   final JClass ldapUtilsClass = codeModel.ref(org.ldaptive.LdapUtils.class);
   final JInvocation areEqual = ldapUtilsClass.staticInvoke("areEqual");
   final JMethod equals = clazz.method(JMod.PUBLIC, boolean.class, "equals");
   equals.annotate(java.lang.Override.class);
   areEqual.arg(JExpr._this());
   areEqual.arg(equals.param(Object.class, "o"));
   equals.body()._return(areEqual);
 }
コード例 #7
0
  public JMethod createOnCreate() {
    JMethod onCreate = activity.method(JMod.PROTECTED, void.class, "onCreate");
    onCreate.annotate(Override.class);

    JVar sis = onCreate.param(factory.ref(Const.BUNDLE), "savedInstanceState");
    onCreate.body().invoke(JExpr._super(), "onCreate").arg(sis);

    return onCreate;
  }
コード例 #8
0
ファイル: HoldrGenerator.java プロジェクト: h87kg/holdr
  private void genListeners(
      Refs r,
      Map<Ref, JFieldVar> fieldVarMap,
      JFieldVar holdrListener,
      Collection<Ref> refs,
      JBlock body,
      Map<Listener.Type, ListenerType> listenerTypeMap) {
    if (holdrListener == null) return;

    for (Ref ref : refs) {
      if (ref instanceof View) {
        JFieldVar fieldVar = fieldVarMap.get(ref);
        View view = (View) ref;

        if (view.isNullable) {
          body = body._if(fieldVar.ne(_null()))._then();
        }

        for (Listener listener : view.listeners) {
          ListenerType listenerType = listenerTypeMap.get(listener.type);

          JDefinedClass listenerClass = r.m.anonymousClass(listenerType.classType);

          JMethod method =
              listenerClass.method(PUBLIC, listenerType.methodReturn, listenerType.methodName);

          List<JVar> params = new ArrayList<JVar>();
          for (Pair<JType, String> arg : listenerType.methodParams) {
            JVar param = method.param(arg.first, arg.second);
            params.add(arg.second.equals("view") ? fieldVar : param);
          }

          method.annotate(r.overrideAnnotation);
          JBlock innerBody = method.body();
          JBlock innerIf = innerBody._if(holdrListener.ne(_null()))._then();

          JInvocation invokeHoldrListener;
          if (listenerType.defaultReturn == null) {
            invokeHoldrListener = innerIf.invoke(holdrListener, listener.name);
          } else {
            invokeHoldrListener = holdrListener.invoke(listener.name);
            innerIf._return(invokeHoldrListener);
            innerBody._return(listenerType.defaultReturn);
          }

          for (JVar param : params) {
            invokeHoldrListener.arg(param);
          }

          body.invoke(fieldVar, listenerType.setter).arg(_new(listenerClass));
        }
      }
    }
  }
コード例 #9
0
ファイル: BeanGenerator.java プロジェクト: tduehr/ldaptive
 /**
  * Creates the hashCode method on the supplied class. Leverages {@link
  * org.ldaptive.LdapUtils#computeHashCode(int, Object...)}.
  *
  * @param clazz to put hashCode method on
  */
 private void createHashCode(final JDefinedClass clazz) {
   final JClass ldapUtilsClass = codeModel.ref(org.ldaptive.LdapUtils.class);
   final JInvocation computeHashCode = ldapUtilsClass.staticInvoke("computeHashCode");
   final JMethod hashCode = clazz.method(JMod.PUBLIC, int.class, "hashCode");
   hashCode.annotate(java.lang.Override.class);
   // CheckStyle:MagicNumber OFF
   computeHashCode.arg(JExpr.lit(7919));
   // CheckStyle:MagicNumber ON
   for (Map.Entry<String, JFieldVar> entry : clazz.fields().entrySet()) {
     computeHashCode.arg(JExpr._this().ref(entry.getValue()));
   }
   hashCode.body()._return(computeHashCode);
 }
コード例 #10
0
  protected void setOnFinishInflate() {
    onFinishInflate = generatedClass.method(PUBLIC, codeModel().VOID, "onFinishInflate");
    onFinishInflate.annotate(Override.class);
    onFinishInflate.javadoc().append(ALREADY_INFLATED_COMMENT);

    JBlock ifNotInflated = onFinishInflate.body()._if(getAlreadyInflated().not())._then();
    ifNotInflated.assign(getAlreadyInflated(), JExpr.TRUE);

    getInit();
    viewNotifierHelper.invokeViewChanged(ifNotInflated);

    onFinishInflate.body().invoke(JExpr._super(), "onFinishInflate");
  }
コード例 #11
0
  private void addProducesAnnotation(
      final Collection<MimeType> uniqueResponseMimeTypes, final JMethod method) {
    if (uniqueResponseMimeTypes.isEmpty()) {
      return;
    }

    final JAnnotationArrayMember paramArray =
        method.annotate(Produces.class).paramArray(DEFAULT_ANNOTATION_PARAMETER);

    for (final MimeType responseMimeType : uniqueResponseMimeTypes) {
      paramArray.param(responseMimeType.getType());
    }
  }
コード例 #12
0
  private void addActionInOnHandleIntent(
      EIntentServiceHolder holder,
      ExecutableElement executableElement,
      String methodName,
      JFieldVar actionKeyField) {
    // If action match, call the method
    JInvocation actionCondition =
        actionKeyField.invoke("equals").arg(holder.getOnHandleIntentIntentAction());
    JBlock callActionBlock = holder.getOnHandleIntentBody()._if(actionCondition)._then();
    JInvocation callActionInvocation = JExpr._super().invoke(methodName);

    // For each method params, we get back value from extras and put it
    // in super calls
    List<? extends VariableElement> methodParameters = executableElement.getParameters();
    if (methodParameters.size() > 0) {
      // Extras
      JVar extras = callActionBlock.decl(classes().BUNDLE, "extras");
      extras.init(holder.getOnHandleIntentIntent().invoke("getExtras"));
      JBlock extrasNotNullBlock = callActionBlock._if(extras.ne(_null()))._then();

      // Extras params
      for (VariableElement param : methodParameters) {
        String paramName = param.getSimpleName().toString();
        String extraParamName = paramName + "Extra";
        JFieldVar paramVar = getStaticExtraField(holder, paramName);
        JClass extraParamClass = codeModelHelper.typeMirrorToJClass(param.asType(), holder);
        BundleHelper bundleHelper = new BundleHelper(annotationHelper, param);

        JExpression getExtraExpression =
            JExpr.invoke(extras, bundleHelper.getMethodNameToRestore()).arg(paramVar);
        if (bundleHelper.restoreCallNeedCastStatement()) {
          getExtraExpression = JExpr.cast(extraParamClass, getExtraExpression);

          if (bundleHelper.restoreCallNeedsSuppressWarning()) {
            JMethod onHandleIntentMethod = holder.getOnHandleIntentMethod();
            if (onHandleIntentMethod.annotations().size() == 0) {
              onHandleIntentMethod.annotate(SuppressWarnings.class).param("value", "unchecked");
            }
          }
        }

        JVar extraField =
            extrasNotNullBlock.decl(extraParamClass, extraParamName, getExtraExpression);
        callActionInvocation.arg(extraField);
      }
      extrasNotNullBlock.add(callActionInvocation);
    } else {
      callActionBlock.add(callActionInvocation);
    }
    callActionBlock._return();
  }
コード例 #13
0
  private static void processPacket(
      PacketType packet, JPackage dirPackage, JCodeModel codeModel, boolean fromClient)
      throws JClassAlreadyExistsException {
    // get the packet info
    String packetName =
        (packet.getInfo() == null || packet.getInfo().getName() == null)
            ? "Unknown"
            : packet.getInfo().getName();
    String packetNamePrefixed = "P" + String.format("%03d", packet.getHeader()) + "_" + packetName;
    String packetDescription =
        (packet.getInfo() == null
                || packet.getInfo().getDescription() == null
                || packet.getInfo().getDescription().isEmpty())
            ? ""
            : "\n" + WordUtils.wrap(packet.getInfo().getDescription(), /* maximumLength */ 50);

    JDefinedClass packetClass =
        dirPackage._class(JMod.FINAL | JMod.PUBLIC, packetNamePrefixed)._extends(GWMessage.class);

    LOGGER.info("+-Processing packet: {}", packetNamePrefixed);
    LOGGER.debug("|+-Packet description: {}", packetDescription);

    StringBuilder packetJavadoc =
        new StringBuilder("Auto-generated by PacketCodeGen.").append(packetDescription);

    JDocComment jDocComment = packetClass.javadoc();
    jDocComment.add(packetJavadoc.toString());

    AtomicInteger numberOfUnknowns = new AtomicInteger(); // unknown field number

    // get all fields in this packet
    for (FieldType field : packet.getField()) {
      processField(field, packetClass, codeModel, numberOfUnknowns, fromClient);
    }

    // generate the header method
    JMethod headerMeth = packetClass.method(JMod.PUBLIC, short.class, "getHeader");
    headerMeth.annotate(Override.class);
    headerMeth.body()._return(JExpr.lit(packet.getHeader().intValue()));

    // generate getters, setters
    for (JFieldVar fieldVar : packetClass.fields().values()) {
      processAccessors(fieldVar, packetClass, fromClient);
    }

    // generate the toString method
    processToString(packetClass, codeModel);
  }
コード例 #14
0
  private void addToString(JDefinedClass jclass) {
    JMethod toString = jclass.method(JMod.PUBLIC, String.class, "toString");

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

    JBlock body = toString.body();
    JInvocation reflectionToString =
        jclass.owner().ref(toStringBuilder).staticInvoke("reflectionToString");
    reflectionToString.arg(JExpr._this());
    body._return(reflectionToString);

    toString.annotate(Override.class);
  }
コード例 #15
0
  private JDefinedClass getMixinEnum(Feed feed) throws JClassAlreadyExistsException {
    String enumName = camel(feed.getName(), true) + "Mixin";
    if (pkg.isDefined(enumName)) {
      return pkg._getClass(enumName);
    }
    JDefinedClass valueEnum = pkg._enum(enumName);

    JFieldVar valField = valueEnum.field(JMod.PRIVATE | JMod.FINAL, String.class, "value");
    JMethod ctor = valueEnum.constructor(JMod.PRIVATE);
    JVar param = ctor.param(String.class, "val");
    ctor.body().assign(valField, param);

    JMethod toString = valueEnum.method(JMod.PUBLIC, String.class, "toString");
    toString.annotate(Override.class);
    toString.body()._return(valField);
    return valueEnum;
  }
コード例 #16
0
  private void addEquals(JDefinedClass jclass) {
    Map<String, JFieldVar> fields = jclass.fields();
    if (fields.isEmpty()) {
      return;
    }

    JMethod equals = jclass.method(JMod.PUBLIC, boolean.class, "equals");
    JVar otherObject = equals.param(Object.class, "other");

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

    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));
    JClass equalsBuilderClass = jclass.owner().ref(equalsBuilder);
    JInvocation equalsBuilderInvocation = JExpr._new(equalsBuilderClass);

    if (!jclass._extends().name().equals("Object")) {
      equalsBuilderInvocation =
          equalsBuilderInvocation
              .invoke("appendSuper")
              .arg(JExpr._super().invoke("equals").arg(otherObject));
    }

    for (JFieldVar fieldVar : fields.values()) {
      equalsBuilderInvocation =
          equalsBuilderInvocation.invoke("append").arg(fieldVar).arg(rhsVar.ref(fieldVar.name()));
    }

    JInvocation reflectionEquals =
        jclass.owner().ref(equalsBuilder).staticInvoke("reflectionEquals");
    reflectionEquals.arg(JExpr._this());
    reflectionEquals.arg(otherObject);

    body._return(equalsBuilderInvocation.invoke("isEquals"));

    equals.annotate(Override.class);
  }
コード例 #17
0
  private static void processToString(JDefinedClass packetClass, JCodeModel codeModel) {
    JClass string = codeModel.ref(String.class);
    JClass stringBuilder = codeModel.ref(StringBuilder.class);
    JClass arrays = codeModel.ref(Arrays.class);

    JMethod toStringMeth = packetClass.method(JMod.PUBLIC, String.class, "toString");
    toStringMeth.annotate(Override.class);
    JBlock body = toStringMeth.body();

    JVar stringBuilderVar = body.decl(stringBuilder, "sb");
    stringBuilderVar =
        stringBuilderVar.init(JExpr._new(stringBuilder).arg(packetClass.name() + "["));

    JInvocation appendChain = null;

    for (JFieldVar fieldVar : packetClass.fields().values()) {
      if (appendChain != null) {
        // a comma is needed
        appendChain = appendChain.invoke("append").arg("," + fieldVar.name() + "=");
      } else {
        appendChain = stringBuilderVar.invoke("append").arg(fieldVar.name() + "=");
      }

      // now add the field to the toString output
      JExpression expression =
          fieldVar.type().isArray()
              ? arrays.staticInvoke("toString").arg(JExpr._this().ref(fieldVar.name()))
              : fieldVar.type().isReference()
                  ? JExpr._this().ref(fieldVar.name()).invoke("toString")
                  : JExpr._this().ref(fieldVar.name());

      appendChain = appendChain.invoke("append").arg(expression);
    }

    if (appendChain != null) {
      appendChain = appendChain.invoke("append").arg("]");
    } else {
      appendChain = stringBuilderVar.invoke("append").arg("]");
    }

    body.add(appendChain);
    body._return(stringBuilderVar.invoke("toString"));
  }
コード例 #18
0
ファイル: BeanGenerator.java プロジェクト: tduehr/ldaptive
  /**
   * Creates the toString method on the supplied class. Creates a string that contains every
   * property on the generated bean.
   *
   * @param clazz to put toString method on
   */
  private void createToString(final JDefinedClass clazz) {
    final JClass stringClass = codeModel.ref(java.lang.String.class);
    final JInvocation format = stringClass.staticInvoke("format");
    final JMethod toString = clazz.method(JMod.PUBLIC, String.class, "toString");
    toString.annotate(java.lang.Override.class);

    final StringBuilder sb = new StringBuilder("[%s@%d::");
    for (Map.Entry<String, JFieldVar> entry : clazz.fields().entrySet()) {
      sb.append(entry.getKey()).append("=%s, ");
    }
    sb.setLength(sb.length() - 2);
    sb.append("]");
    format.arg(sb.toString());
    format.arg(JExpr._this().invoke("getClass").invoke("getName"));
    format.arg(JExpr._this().invoke("hashCode"));
    for (Map.Entry<String, JFieldVar> entry : clazz.fields().entrySet()) {
      format.arg(JExpr._this().ref(entry.getValue()));
    }
    toString.body()._return(format);
  }
コード例 #19
0
  @Override
  public void process(Element element, HasInstanceState holder) {
    String fieldName = element.getSimpleName().toString();

    JBlock saveStateBody = holder.getSaveStateMethodBody();
    JVar saveStateBundleParam = holder.getSaveStateBundleParam();
    JMethod restoreStateMethod = holder.getRestoreStateMethod();
    JBlock restoreStateBody = restoreStateMethod.body();
    JVar restoreStateBundleParam = holder.getRestoreStateBundleParam();

    AnnotationHelper annotationHelper = new AnnotationHelper(processingEnv);
    BundleHelper bundleHelper = new BundleHelper(annotationHelper, element);
    APTCodeModelHelper codeModelHelper = new APTCodeModelHelper();

    JFieldRef ref = ref(fieldName);
    saveStateBody
        .invoke(saveStateBundleParam, bundleHelper.getMethodNameToSave())
        .arg(fieldName)
        .arg(ref);

    JInvocation restoreMethodCall =
        JExpr.invoke(restoreStateBundleParam, bundleHelper.getMethodNameToRestore()).arg(fieldName);
    if (bundleHelper.restoreCallNeedCastStatement()) {

      JClass jclass = codeModelHelper.typeMirrorToJClass(element.asType(), holder);
      JExpression castStatement = JExpr.cast(jclass, restoreMethodCall);
      restoreStateBody.assign(ref, castStatement);

      if (bundleHelper.restoreCallNeedsSuppressWarning()) {
        if (restoreStateMethod.annotations().size() == 0) {
          restoreStateMethod.annotate(SuppressWarnings.class).param("value", "unchecked");
        }
      }

    } else {
      restoreStateBody.assign(ref, restoreMethodCall);
    }
  }
コード例 #20
0
  private JClass getParamTypeEnum(Filter filter) throws JClassAlreadyExistsException {
    String enumName = camel(filter.getName(), true) + "Option";
    if (pkg.isDefined(enumName)) {
      return pkg._getClass(enumName);
    }
    List<Option> options = filter.getOption();
    if (options.size() == 1) {
      /*turn into '*Only' method?*/
    }
    if (options.size() == 2) {
      if (ImmutableSet.of("true", "false")
          .equals(
              ImmutableSet.of(
                  options.get(0).getValue().toLowerCase(),
                  options.get(1).getValue().toLowerCase()))) {
        return model.ref(Boolean.class);
      }
    }

    JDefinedClass valueEnum = pkg._enum(enumName);

    JFieldVar valField = valueEnum.field(JMod.PRIVATE | JMod.FINAL, String.class, "value");
    JMethod ctor = valueEnum.constructor(JMod.PRIVATE);
    JVar param = ctor.param(String.class, "val");
    ctor.body().assign(valField, param);

    JMethod toString = valueEnum.method(JMod.PUBLIC, String.class, "toString");
    toString.annotate(Override.class);
    toString.body()._return(valField);

    for (Option option : options) {
      String optionName = option.getValue().toUpperCase().replace(' ', '_');
      JEnumConstant optionCst = valueEnum.enumConstant(optionName);
      optionCst.arg(JExpr.lit(option.getValue().replace(' ', '+')));
    }
    return valueEnum;
  }
コード例 #21
0
 @Override
 public void enumValueMethod(JMethod valueMethod) {
   valueMethod.annotate(JsonValue.class);
 }
コード例 #22
0
 @Override
 public void anyGetter(JMethod getter) {
   getter.annotate(JsonAnyGetter.class);
 }
コード例 #23
0
 @Override
 public void anySetter(JMethod setter) {
   setter.annotate(JsonAnySetter.class);
 }
コード例 #24
0
 @Override
 public void enumCreatorMethod(JMethod creatorMethod) {
   creatorMethod.annotate(JsonCreator.class);
 }
コード例 #25
0
 @Override
 public void propertySetter(JMethod setter, String propertyName) {
   setter.annotate(JsonProperty.class).param("value", propertyName);
 }
コード例 #26
0
 private void addConsumesAnnotation(final MimeType bodyMimeType, final JMethod method) {
   if (bodyMimeType != null) {
     method.annotate(Consumes.class).param(DEFAULT_ANNOTATION_PARAMETER, bodyMimeType.getType());
   }
 }