Пример #1
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);
  }
Пример #2
0
  private void createConstructorAndBuilder() {
    List<ExecutableElement> constructors = new ArrayList<ExecutableElement>();
    for (Element e : annotatedElement.getEnclosedElements()) {
      if (e.getKind() == CONSTRUCTOR) {
        constructors.add((ExecutableElement) e);
      }
    }

    for (ExecutableElement userConstructor : constructors) {
      JMethod copyConstructor = generatedClass.constructor(PUBLIC);
      JMethod staticHelper =
          generatedClass.method(PUBLIC | STATIC, generatedClass._extends(), "build");

      codeModelHelper.generifyStaticHelper(this, staticHelper, getAnnotatedElement());

      JBlock body = copyConstructor.body();
      JInvocation superCall = body.invoke("super");
      JInvocation newInvocation = JExpr._new(generatedClass);
      for (VariableElement param : userConstructor.getParameters()) {
        String paramName = param.getSimpleName().toString();
        JClass paramType = codeModelHelper.typeMirrorToJClass(param.asType(), this);
        copyConstructor.param(paramType, paramName);
        staticHelper.param(paramType, paramName);
        superCall.arg(JExpr.ref(paramName));
        newInvocation.arg(JExpr.ref(paramName));
      }

      JVar newCall = staticHelper.body().decl(generatedClass, "instance", newInvocation);
      staticHelper.body().invoke(newCall, getOnFinishInflate());
      staticHelper.body()._return(newCall);
      body.invoke(getInit());
    }
  }
  public void build() {
    declareMethod();

    ExceptionWrapper mainTryBlock = new ExceptionWrapper(codeModel, method.body(), context);
    for (Integer arity : primitive.getArity()) {
      JInvocation invocation = invoke("doApply").arg(context).arg(environment);

      for (int i = 0; i < arity; ++i) {
        invocation.arg(args.component(lit(i)));
      }
      mainTryBlock
          .body()
          ._if(JExpr.direct("args.length").eq(JExpr.lit(arity)))
          ._then()
          ._return(invocation);
    }

    mainTryBlock.catchEvalExceptions();
    mainTryBlock.catchRuntimeExceptions();
    mainTryBlock.catchExceptions();

    method
        .body()
        ._throw(
            JExpr._new(codeModel.ref(EvalException.class))
                .arg(lit(primitive.getName() + ": max arity is " + primitive.getMaxArity())));
  }
Пример #4
0
  private static JInvocation generateInvocation(Method method) {
    JInvocation generatedInvocation = JExpr.invoke(JExpr.invoke("getWrapped"), method.getName());

    for (Parameter parameter : method.getParameters()) {
      generatedInvocation.arg(JExpr.ref(parameter.getName()));
    }

    return generatedInvocation;
  }
Пример #5
0
 /**
  * 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);
 }
Пример #6
0
  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));
        }
      }
    }
  }
Пример #7
0
 /**
  * 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);
 }
  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();
  }
Пример #9
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);
  }
  @Override
  public void process(Element element, JCodeModel codeModel, EBeansHolder activitiesHolder) {

    EBeanHolder holder = activitiesHolder.getEnclosingEBeanHolder(element);

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

    ExecutableElement executableElement = (ExecutableElement) element;
    List<? extends VariableElement> parameters = executableElement.getParameters();
    boolean hasBundleParameter = parameters.size() == 1;

    JInvocation methodCall = holder.init.body().invoke(methodName);

    if (hasBundleParameter) {
      methodCall.arg(holder.beforeCreateSavedInstanceStateParam);
    }
  }
Пример #11
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"));
  }
Пример #12
0
 private void addWither(
     Filter filter, JDefinedClass bldrCls, JVar paramBuilder, JFieldVar field, JClass paramType)
     throws JClassAlreadyExistsException {
   JMethod method = createWitherMethod(filter, bldrCls);
   if (filter.getTitle() != null) {
     method.javadoc().add(String.format("<p>%s</p>", filter.getTitle()));
   }
   JVar param = addParam(filter, method, paramType);
   JBlock mthdBody = method.body();
   boolean needsNullCheck = true;
   if (filter.getMinValue() != null) {
     mthdBody.add(precs.staticInvoke("checkNotNull").arg(param));
     needsNullCheck = false;
     int min = filter.getMinValue().intValue();
     mthdBody.add(
         precs
             .staticInvoke("checkArgument")
             .arg(JExpr.lit(min).lte(param))
             .arg(JExpr.lit(param.name() + ": %s < " + min))
             .arg(param));
   }
   if (filter.getMaxValue() != null) {
     if (needsNullCheck) {
       mthdBody.add(precs.staticInvoke("checkNotNull").arg(param));
       needsNullCheck = false;
     }
     int max = filter.getMaxValue().intValue();
     mthdBody.add(
         precs
             .staticInvoke("checkArgument")
             .arg(JExpr.lit(max).gte(param))
             .arg(JExpr.lit(param.name() + ": %s > " + max))
             .arg(param));
   }
   JInvocation putIntoMap = paramBuilder.invoke("put").arg(field);
   if (needsNullCheck) {
     putIntoMap.arg(precs.staticInvoke("checkNotNull").arg(param));
   } else {
     putIntoMap.arg(param);
   }
   mthdBody.add(putIntoMap);
   mthdBody._return(JExpr._this());
 }
Пример #13
0
  /**
   * 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);
  }
  public void buildVarArgs() {
    declareMethod();

    ExceptionWrapper mainTryBlock = new ExceptionWrapper(codeModel, method.body(), context);

    JvmMethod overload = primitive.getOverloads().get(0);
    VarArgParser parser = new VarArgParser(this, mainTryBlock.body(), overload);

    // convert the positional arguments
    convertArguments(parser.getArgumentProcessingBlock(), parser);

    // finally invoke the underlying function
    JInvocation invocation =
        classRef(overload.getDeclaringClass()).staticInvoke(overload.getName());
    for (JExpression argument : parser.getArguments()) {
      invocation.arg(argument);
    }

    CodeModelUtils.returnSexp(codeModel, mainTryBlock.body(), overload, invocation);

    mainTryBlock.catchEvalExceptions();
    mainTryBlock.catchRuntimeExceptions();
    mainTryBlock.catchExceptions();
  }
Пример #15
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);
  }
Пример #16
0
  private InjectionNode innerGenerateProxyCode(InjectionNode injectionNode) {
    AOPProxyAspect aopProxyAspect = injectionNode.getAspect(AOPProxyAspect.class);
    JDefinedClass definedClass;
    String proxyClassName = injectionNode.getClassName() + "_AOPProxy";
    ASTInjectionAspect injectionAspect = injectionNode.getAspect(ASTInjectionAspect.class);
    ConstructorInjectionPoint constructorInjectionPoint =
        injectionAspect.getConstructorInjectionPoint();
    ConstructorInjectionPoint proxyConstructorInjectionPoint =
        new ConstructorInjectionPoint(ASTAccessModifier.PUBLIC);

    try {

      definedClass = codeModel._class(JMod.PUBLIC, proxyClassName, ClassType.CLASS);

      annotateGeneratedClass(definedClass);

      // extending injectionNode
      definedClass._extends(codeModel.ref(injectionNode.getClassName()));

      // copy constructor elements and add aop interceptors
      JMethod constructor = definedClass.constructor(JMod.PUBLIC);

      // converting exceptions into runtime exceptions
      proxyConstructorInjectionPoint.addThrows(constructorInjectionPoint.getThrowsTypes());
      for (ASTType throwType : constructorInjectionPoint.getThrowsTypes()) {
        constructor._throws(codeModel.ref(throwType.getName()));
      }

      JBlock constructorBody = constructor.body();

      List<JVar> superArguments = new ArrayList<JVar>();
      for (InjectionNode node : constructorInjectionPoint.getInjectionNodes()) {
        String paramName = namer.generateName(node);
        JVar param = constructor.param(codeModel.ref(node.getClassName()), paramName);
        superArguments.add(param);
        proxyConstructorInjectionPoint.addInjectionNode(node);
      }

      // super construction
      JInvocation constructorInvocation = constructorBody.invoke(SUPER_REF);
      for (JVar paramArgument : superArguments) {
        constructorInvocation.arg(paramArgument);
      }

      // method interceptors
      Map<ASTMethod, Map<InjectionNode, JFieldVar>> interceptorFields =
          new HashMap<ASTMethod, Map<InjectionNode, JFieldVar>>();
      for (Map.Entry<ASTMethod, Set<InjectionNode>> methodInterceptorEntry :
          aopProxyAspect.getMethodInterceptors().entrySet()) {

        buildMethodInterceptor(
            definedClass,
            proxyConstructorInjectionPoint,
            constructor,
            constructorBody,
            interceptorFields,
            methodInterceptorEntry);
      }

    } catch (JClassAlreadyExistsException e) {
      logger.error("JClassAlreadyExistsException while building AOP Proxy", e);
    } catch (ClassNotFoundException e) {
      logger.error("ClassNotFoundException while building AOP Proxy", e);
    }

    return buildProxyInjectionNode(
        injectionNode, proxyClassName, injectionAspect, proxyConstructorInjectionPoint);
  }
Пример #17
0
  private JExpression buildInterceptorChain(
      JDefinedClass definedClass,
      ASTMethod method,
      Map<ASTParameter, JVar> parameterMap,
      Set<InjectionNode> interceptors,
      Map<InjectionNode, JFieldVar> interceptorNameMap) {

    try {
      JDefinedClass methodExecutionClass =
          definedClass._class(
              JMod.PRIVATE | JMod.FINAL,
              namer.generateClassName(MethodInterceptorChain.MethodExecution.class));
      methodExecutionClass._implements(MethodInterceptorChain.MethodExecution.class);

      // setup constructor with needed parameters
      JMethod constructor = methodExecutionClass.constructor(JMod.PUBLIC);
      JBlock constructorbody = constructor.body();
      List<JExpression> methodParameters = new ArrayList<JExpression>();
      for (ASTParameter parameter : method.getParameters()) {
        JType parameterType = parameterMap.get(parameter).type();
        JVar param = constructor.param(parameterType, namer.generateName(parameterType));
        JFieldVar field =
            methodExecutionClass.field(
                JMod.PRIVATE, parameterType, namer.generateName(parameterType));
        constructorbody.assign(field, param);
        methodParameters.add(field);
      }

      // getMethod()
      JMethod getMethod =
          methodExecutionClass.method(
              JMod.PUBLIC, Method.class, MethodInterceptorChain.MethodExecution.GET_METHOD);

      JInvocation getMethodInvocation =
          definedClass.dotclass().invoke(CLASS_GET_METHOD).arg(method.getName());
      getMethod.body()._return(getMethodInvocation);
      getMethod._throws(NoSuchMethodException.class);

      for (ASTParameter astParameter : method.getParameters()) {
        getMethodInvocation.arg(codeModel.ref(astParameter.getASTType().getName()).dotclass());
      }

      // invoke()
      JMethod invokeMethod =
          methodExecutionClass.method(
              JMod.PUBLIC, Object.class, MethodInterceptorChain.MethodExecution.INVOKE);

      // add all throws of contained method
      for (ASTType throwable : method.getThrowsTypes()) {
        invokeMethod._throws(codeModel.ref(throwable.getName()));
      }

      JInvocation superCall = definedClass.staticRef(SUPER_REF).invoke(method.getName());

      for (JExpression methodParam : methodParameters) {
        superCall.arg(methodParam);
      }

      if (method.getReturnType().equals(ASTVoidType.VOID)) {
        invokeMethod.body().add(superCall);
        invokeMethod.body()._return(JExpr._null());
      } else {
        invokeMethod.body()._return(superCall);
      }

      JInvocation methodExecutionInvocation = JExpr._new(methodExecutionClass);

      for (ASTParameter astParameter : method.getParameters()) {
        methodExecutionInvocation.arg(parameterMap.get(astParameter));
      }

      JInvocation newInterceptorInvocation =
          JExpr._new(codeModel.ref(MethodInterceptorChain.class))
              .arg(methodExecutionInvocation)
              .arg(JExpr._this());

      for (InjectionNode interceptor : interceptors) {
        newInterceptorInvocation.arg(interceptorNameMap.get(interceptor));
      }

      return newInterceptorInvocation;
    } catch (JClassAlreadyExistsException e) {
      throw new TransfuseAnalysisException("Class already defined while generating inner class", e);
    }
  }
Пример #18
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));
    }
  }
Пример #19
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")));
  }