コード例 #1
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();
  }
コード例 #2
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);
  }
コード例 #3
0
  protected HoldingContainer generateEvalBody(
      ClassGenerator<?> g, HoldingContainer[] inputVariables, String body, JVar[] workspaceJVars) {

    // g.getBlock().directStatement(String.format("//---- start of eval portion of %s function.
    // ----//", functionName));

    JBlock sub = new JBlock(true, true);
    JBlock topSub = sub;
    HoldingContainer out = null;
    MajorType returnValueType = returnValue.type;

    // add outside null handling if it is defined.
    if (nullHandling == NullHandling.NULL_IF_NULL) {
      JExpression e = null;
      for (HoldingContainer v : inputVariables) {
        if (v.isOptional()) {
          if (e == null) {
            e = v.getIsSet();
          } else {
            e = e.mul(v.getIsSet());
          }
        }
      }

      if (e != null) {
        // if at least one expression must be checked, set up the conditional.
        returnValueType = returnValue.type.toBuilder().setMode(DataMode.OPTIONAL).build();
        out = g.declare(returnValueType);
        e = e.eq(JExpr.lit(0));
        JConditional jc = sub._if(e);
        jc._then().assign(out.getIsSet(), JExpr.lit(0));
        sub = jc._else();
      }
    }

    if (out == null) out = g.declare(returnValueType);

    // add the subblock after the out declaration.
    g.getEvalBlock().add(topSub);

    JVar internalOutput =
        sub.decl(
            JMod.FINAL,
            g.getHolderType(returnValueType),
            returnValue.name,
            JExpr._new(g.getHolderType(returnValueType)));
    addProtectedBlock(g, sub, body, inputVariables, workspaceJVars, false);
    if (sub != topSub)
      sub.assign(internalOutput.ref("isSet"), JExpr.lit(1)); // Assign null if NULL_IF_NULL mode
    sub.assign(out.getHolder(), internalOutput);
    if (sub != topSub)
      sub.assign(internalOutput.ref("isSet"), JExpr.lit(1)); // Assign null if NULL_IF_NULL mode
    return out;
  }
コード例 #4
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);
  }
コード例 #5
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"));
  }
コード例 #6
0
  @Override
  public void process(Element element, JCodeModel codeModel, EBeanHolder holder) {
    Classes classes = holder.classes();

    String fieldName = element.getSimpleName().toString();

    Res resInnerClass = androidValue.getRInnerClass();

    JFieldRef idRef =
        annotationHelper.extractOneAnnotationFieldRef(holder, element, resInnerClass, true);

    JBlock methodBody = holder.init.body();

    TypeMirror fieldTypeMirror = element.asType();
    String fieldType = fieldTypeMirror.toString();

    // Special case for loading animations
    if (CanonicalNameConstants.ANIMATION.equals(fieldType)) {
      methodBody.assign(
          ref(fieldName),
          classes.ANIMATION_UTILS.staticInvoke("loadAnimation").arg(holder.contextRef).arg(idRef));
    } else {
      if (holder.resources == null) {
        holder.resources =
            methodBody.decl(
                classes.RESOURCES, "resources_", holder.contextRef.invoke("getResources"));
      }

      String resourceMethodName = androidValue.getResourceMethodName();

      // Special case for @HtmlRes
      if (element.getAnnotation(HtmlRes.class) != null) {
        methodBody.assign(
            ref(fieldName),
            classes
                .HTML
                .staticInvoke("fromHtml")
                .arg(invoke(holder.resources, resourceMethodName).arg(idRef)));
      } else {
        methodBody.assign(ref(fieldName), invoke(holder.resources, resourceMethodName).arg(idRef));
      }
    }
  }
コード例 #7
0
  private void createResponseBuilderInResourceMethodReturnType(
      final JDefinedClass responseClass,
      final int statusCode,
      final Response response,
      final MimeType responseMimeType)
      throws Exception {
    final String responseBuilderMethodName =
        Names.buildResponseMethodName(statusCode, responseMimeType);

    final JMethod responseBuilderMethod =
        responseClass.method(PUBLIC + STATIC, responseClass, responseBuilderMethodName);

    final JDocComment javadoc = responseBuilderMethod.javadoc();

    if (isNotBlank(response.getDescription())) {
      javadoc.add(response.getDescription());
    }

    if ((responseMimeType != null) && (isNotBlank(responseMimeType.getExample()))) {
      javadoc.add(EXAMPLE_PREFIX + responseMimeType.getExample());
    }

    JInvocation builderArgument =
        types
            .getGeneratorClass(javax.ws.rs.core.Response.class)
            .staticInvoke("status")
            .arg(JExpr.lit(statusCode));

    if (responseMimeType != null) {
      builderArgument =
          builderArgument
              .invoke("header")
              .arg(HttpHeaders.CONTENT_TYPE)
              .arg(responseMimeType.getType());
    }

    final StringBuilder freeFormHeadersDescription = new StringBuilder();

    for (final Entry<String, Header> namedHeaderParameter : response.getHeaders().entrySet()) {
      final String headerName = namedHeaderParameter.getKey();
      final Header header = namedHeaderParameter.getValue();

      if (headerName.contains(RESPONSE_HEADER_WILDCARD_SYMBOL)) {
        appendParameterJavadocDescription(header, freeFormHeadersDescription);
        continue;
      }

      final String argumentName = Names.buildVariableName(headerName);

      builderArgument =
          builderArgument.invoke("header").arg(headerName).arg(JExpr.ref(argumentName));

      addParameterJavaDoc(header, argumentName, javadoc);

      responseBuilderMethod.param(types.buildParameterType(header, argumentName), argumentName);
    }

    final JBlock responseBuilderMethodBody = responseBuilderMethod.body();

    final JVar builderVariable =
        responseBuilderMethodBody.decl(
            types.getGeneratorType(ResponseBuilder.class), "responseBuilder", builderArgument);

    if (freeFormHeadersDescription.length() > 0) {
      // generate a Map<String, List<Object>> argument for {?} headers
      final JClass listOfObjectsClass = types.getGeneratorClass(List.class).narrow(Object.class);
      final JClass headersArgument =
          types
              .getGeneratorClass(Map.class)
              .narrow(types.getGeneratorClass(String.class), listOfObjectsClass);

      builderArgument =
          responseBuilderMethodBody
              .invoke("headers")
              .arg(JExpr.ref(MULTIPLE_RESPONSE_HEADERS_ARGUMENT_NAME))
              .arg(builderVariable);

      final JVar param =
          responseBuilderMethod.param(headersArgument, MULTIPLE_RESPONSE_HEADERS_ARGUMENT_NAME);

      javadoc.addParam(param).add(freeFormHeadersDescription.toString());
    }

    if (responseMimeType != null) {
      responseBuilderMethodBody
          .invoke(builderVariable, "entity")
          .arg(JExpr.ref(GENERIC_PAYLOAD_ARGUMENT_NAME));
      responseBuilderMethod.param(
          types.getResponseEntityClass(responseMimeType), GENERIC_PAYLOAD_ARGUMENT_NAME);
      javadoc
          .addParam(GENERIC_PAYLOAD_ARGUMENT_NAME)
          .add(defaultString(responseMimeType.getExample()));
    }

    responseBuilderMethodBody._return(
        JExpr._new(responseClass).arg(builderVariable.invoke("build")));
  }
コード例 #8
0
  public List<JVar> readIntent(
      List<? extends VariableElement> parameters,
      JBlock body,
      JVar intentParam,
      BaseAnnotationHandler handler)
      throws Exception {
    List<JVar> vars = new ArrayList<JVar>();

    for (VariableElement variableElement : parameters) {
      String type = variableElement.asType().toString();
      LOGGER.debug("var type:{} {}", variableElement.getSimpleName().toString(), type);
      JVar var = null;
      if (type.equals("java.lang.String")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getStringExtra")
                    .arg(variableElement.getSimpleName().toString()));
      } else if (type.equals("int")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getIntExtra")
                    .arg(variableElement.getSimpleName().toString())
                    .arg(JExpr.lit(0)));

      } else if (type.equals("float")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getFloatExtra")
                    .arg(variableElement.getSimpleName().toString())
                    .arg(JExpr.lit(0)));
      }
      if (type.equals("double")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getDoubleExtra")
                    .arg(variableElement.getSimpleName().toString())
                    .arg(JExpr.lit(0)));
      }
      if (type.equals("char")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getCharExtra")
                    .arg(variableElement.getSimpleName().toString())
                    .arg(JExpr.lit((char) 0)));
      } else if (type.equals("java.util.ArrayList<java.lang.Integer>")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getIntegerArrayListExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("java.util.ArrayList<java.lang.String>")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getStringArrayListExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("float[]")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getFloatArrayExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("double[]")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getDoubleArrayExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("char[]")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getCharArrayExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("java.lang.String[]")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getStringArrayExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("boolean[]")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getBooleanArrayExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("boolean")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getBooleanExtra")
                    .arg(variableElement.getSimpleName().toString())
                    .arg(JExpr.lit(false)));

      } else if (type.equals("int[]")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getIntArrayExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("long[]")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getLongArrayExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("long")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getLongExtra")
                    .arg(variableElement.getSimpleName().toString())
                    .arg(JExpr.lit(0)));

      } else if (type.equals("byte[]")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getByteArrayExtra")
                    .arg(variableElement.getSimpleName().toString()));

      } else if (type.equals("byte")) {
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                intentParam
                    .invoke("getByteExtra")
                    .arg(variableElement.getSimpleName().toString())
                    .arg(JExpr.lit(0)));

      } else if (type.endsWith("[]")) {
        if (EntityHandler.isInterface(
            type.substring(0, type.length() - 2), "android.os.Parcelable")) {
          var =
              body.decl(
                  handler.refClass(type),
                  variableElement.getSimpleName().toString(),
                  JExpr.cast(
                      handler.refClass(type),
                      intentParam
                          .invoke("getParcelableArrayExtra")
                          .arg(variableElement.getSimpleName().toString())));
        } else {
          var =
              body.decl(
                  handler.refClass(type),
                  variableElement.getSimpleName().toString(),
                  JExpr.cast(
                      handler.refClass(type),
                      intentParam
                          .invoke("getSerializableExtra")
                          .arg(variableElement.getSimpleName().toString())));
        }
        // JConditional
        // parcel=body._if(JExpr._new(handler.refClass(type.substring(0,type.length()-2)))._instanceof(handler.refClass("android.os.Parcelable")));
        // parcel._then().assign(var,JExpr.cast(handler.refClass(type),
        //
        // intentParam.invoke("getParcelableArrayExtra").arg(variableElement.getSimpleName().toString())));
        // JConditional serializable=
        // parcel._else()._if(JExpr._new(handler.refClass(type.substring(0,type.length()-2)))._instanceof(handler.refClass("java.io.Serializable")));
        // serializable._then().assign(var,
        // JExpr.cast(handler.refClass(variableElement.asType().toString()),
        //
        // intentParam.invoke("getSerializableExtra").arg(variableElement.getSimpleName().toString())));

      } else if (type.startsWith("java.util.ArrayList")) {

        String clz = type.substring(type.indexOf('<') + 1, type.lastIndexOf('>'));
        var =
            body.decl(
                handler.codeModel().parseType(variableElement.asType().toString()),
                variableElement.getSimpleName().toString(),
                JExpr.cast(
                    handler.refClass("java.util.ArrayList").narrow(handler.refClass(clz)),
                    intentParam
                        .invoke("getSerializableExtra")
                        .arg(variableElement.getSimpleName().toString())));
      }
      if (var == null) {
        if (EntityHandler.isInterface(type, "android.os.Parcelable")) {
          var =
              body.decl(
                  handler.refClass(type),
                  variableElement.getSimpleName().toString(),
                  JExpr.cast(
                      handler.refClass(type),
                      intentParam
                          .invoke("getParcelableExtra")
                          .arg(variableElement.getSimpleName().toString())));
        } else {
          var =
              body.decl(
                  handler.refClass(type),
                  variableElement.getSimpleName().toString(),
                  JExpr.cast(
                      handler.refClass(type),
                      intentParam
                          .invoke("getSerializableExtra")
                          .arg(variableElement.getSimpleName().toString())));
        }
        // var=body.decl(handler.refClass(type),variableElement.getSimpleName().toString(),JExpr._new(handler.refClass(type)));
        // JConditional parcel=body._if(var._instanceof(handler.refClass("android.os.Parcelable")));
        // parcel._then().assign(var,JExpr.cast(handler.refClass(variableElement.asType().toString()),
        //
        // intentParam.invoke("getParcelableExtra").arg(variableElement.getSimpleName().toString())));

        // JConditional serializable=
        // parcel._else()._if(var._instanceof(handler.refClass("java.io.Serializable")));
        // serializable._then().assign(var,
        // JExpr.cast(handler.refClass(variableElement.asType().toString()),
        //
        // intentParam.invoke("getSerializableExtra").arg(variableElement.getSimpleName().toString())));
      }
      vars.add(var);
    }
    return vars;
  }