private void declareMethod() {
   method = invoker.method(JMod.PUBLIC | JMod.STATIC, SEXP.class, "doApply");
   context = method.param(Context.class, "context");
   environment = method.param(Environment.class, "environment");
   call = method.param(FunctionCall.class, "call");
   argNames = method.param(String[].class, "argNames");
   args = method.param(SEXP[].class, "args");
 }
Ejemplo n.º 2
0
 private void genSetListener(
     Refs r, JDefinedClass clazz, JClass listenerInterface, JFieldVar holdrListener) {
   if (listenerInterface == null) return;
   JMethod method = clazz.method(PUBLIC, r.m.VOID, "setListener");
   JVar listener = method.param(listenerInterface, "listener");
   method.body().assign(holdrListener, listener);
 }
  private void addActionToIntentBuilder(
      EIntentServiceHolder holder,
      ExecutableElement executableElement,
      String methodName,
      JFieldVar actionKeyField) {
    JMethod method =
        holder.getIntentBuilderClass().method(PUBLIC, holder.getIntentBuilderClass(), methodName);
    JBlock body = method.body();

    // setAction
    body.invoke("action").arg(actionKeyField);

    // For each method params, we get put value into extras
    List<? extends VariableElement> methodParameters = executableElement.getParameters();
    if (methodParameters.size() > 0) {

      // Extras params
      for (VariableElement param : methodParameters) {
        String paramName = param.getSimpleName().toString();
        JClass parameterClass = codeModelHelper.typeMirrorToJClass(param.asType(), holder);

        JFieldVar paramVar = getStaticExtraField(holder, paramName);
        JVar methodParam = method.param(parameterClass, paramName);

        JMethod putExtraMethod =
            holder.getIntentBuilder().getPutExtraMethod(param.asType(), paramName, paramVar);
        body.invoke(putExtraMethod).arg(methodParam);
      }
    }
    body._return(JExpr._this());
  }
Ejemplo n.º 4
0
  private void genConstructor(
      Refs r,
      JDefinedClass clazz,
      Collection<Ref> refs,
      Map<Ref, JFieldVar> fieldVarMap,
      JFieldVar holderListener,
      Map<Listener.Type, ListenerType> listenerTypeMap) {
    // private MyLayoutViewModel(View view) {
    JMethod constructor = clazz.constructor(PUBLIC);
    JVar viewVar = constructor.param(r.viewClass, "view");
    JBlock body = constructor.body();

    // super(view);
    body.invoke("super").arg(viewVar);

    // myLinearLayout = (LinearLayout) view.findViewById(R.id.my_linear_layout);
    // myTextView = (TextView) myLinearLayout.findViewById(R.id.my_text_view);
    genInitFields(r, fieldVarMap, viewVar, refs, body);

    // myButton.setOnClickListener((view) -> { if (_holderListener != null)
    // _holderListener.onMyButtonClick(myButton); });
    genListeners(r, fieldVarMap, holderListener, refs, body, listenerTypeMap);

    JDocComment doc = constructor.javadoc();
    doc.append(
        "Constructs a new {@link me.tatarka.holdr.Holdr} for {@link "
            + r.packageName
            + ".R.layout#"
            + r.layoutName
            + "}.");
    doc.addParam(viewVar).append("The root view to search for the holdr's views.");
  }
 private void addCreateFromParcel(JDefinedClass jclass, JDefinedClass creatorClass) {
   JMethod createFromParcel = creatorClass.method(JMod.PUBLIC, jclass, "createFromParcel");
   JVar in = createFromParcel.param(Parcel.class, "in");
   JVar instance = createFromParcel.body().decl(jclass, "instance", JExpr._new(jclass));
   suppressWarnings(createFromParcel, "unchecked");
   for (JFieldVar f : jclass.fields().values()) {
     if ((f.mods().getValue() & JMod.STATIC) == JMod.STATIC) {
       continue;
     }
     if (f.type().erasure().name().equals("List")) {
       createFromParcel
           .body()
           .invoke(in, "readList")
           .arg(instance.ref(f))
           .arg(JExpr.direct(getGenericType(f.type()) + ".class.getClassLoader()"));
     } else {
       createFromParcel
           .body()
           .assign(
               instance.ref(f),
               JExpr.cast(
                   f.type(),
                   in.invoke("readValue")
                       .arg(JExpr.direct(f.type().erasure().name() + ".class.getClassLoader()"))));
     }
   }
   createFromParcel.body()._return(instance);
 }
  public void addWriteToParcel(JDefinedClass jclass) {
    JMethod method = jclass.method(JMod.PUBLIC, void.class, "writeToParcel");
    JVar dest = method.param(Parcel.class, "dest");
    method.param(int.class, "flags");

    for (JFieldVar f : jclass.fields().values()) {
      if ((f.mods().getValue() & JMod.STATIC) == JMod.STATIC) {
        continue;
      }
      if (f.type().erasure().name().equals("List")) {
        method.body().invoke(dest, "writeList").arg(f);
      } else {
        method.body().invoke(dest, "writeValue").arg(f);
      }
    }
  }
Ejemplo n.º 7
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));
        }
      }
    }
  }
 public void run(Set<ClassOutline> sorted, JDefinedClass transformer) {
   for (ClassOutline classOutline : sorted) {
     // skip over abstract classes
     if (!classOutline.target.isAbstract()) {
       // add the accept method to the bean
       JDefinedClass beanImpl = classOutline.implClass;
       JMethod acceptMethod = beanImpl.method(JMod.PUBLIC, Object.class, "accept");
       JTypeVar genericType = acceptMethod.generify("T");
       acceptMethod.type(genericType);
       JVar vizParam = acceptMethod.param(transformer.narrow(genericType), "aTransformer");
       JBlock block = acceptMethod.body();
       block._return(vizParam.invoke("transform").arg(JExpr._this()));
     }
   }
 }
Ejemplo n.º 9
0
  private static void processAccessors(
      JFieldVar fieldVar, JDefinedClass packetClass, boolean fromClient) {
    String name = WordUtils.capitalize(fieldVar.name());

    if (fromClient) {
      String methodName = "get" + name;
      JMethod getter = packetClass.method(JMod.PUBLIC, fieldVar.type(), methodName);
      getter.body()._return(fieldVar);
    } else {
      String methodName = "set" + name;
      JMethod setter = packetClass.method(JMod.PUBLIC, Void.TYPE, methodName);
      setter.param(fieldVar.type(), fieldVar.name());
      setter.body().assign(JExpr._this().ref(fieldVar.name()), JExpr.ref(fieldVar.name()));
    }
  }
Ejemplo n.º 10
0
  private JClass genListenerInterface(
      Refs r,
      JDefinedClass clazz,
      Collection<Ref> refs,
      Map<Listener.Type, ListenerType> listenerTypeMap)
      throws JClassAlreadyExistsException {
    JDefinedClass listenerInterface = null;

    for (Ref ref : refs) {
      if (ref instanceof View) {
        View view = (View) ref;
        if (!view.listeners.isEmpty()) {
          if (listenerInterface == null) {
            listenerInterface = clazz._interface(PUBLIC, "Listener");
          }

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

            JMethod method =
                listenerInterface.method(PUBLIC, listenerType.methodReturn, listener.name);
            for (Pair<JType, String> param : listenerType.methodParams) {
              if (param.second.equals("view")) {
                // Replace view with reference to the field.
                method.param(r.ref(view.type), ref.fieldName);
              } else {
                method.param(param.first, param.second);
              }
            }
          }
        }
      }
    }

    return listenerInterface;
  }
  public XjcGuavaPluginTest() throws Exception {
    aPackage = aModel._package("test");
    aClass = aPackage._class("AClass");

    aSetter = aClass.method(JMod.PUBLIC, aModel.VOID, "setField");

    aField = aClass.field(JMod.PRIVATE, aModel.INT, "field");
    anotherField = aClass.field(JMod.PRIVATE, aModel.BOOLEAN, "anotherField");
    aStaticField = aClass.field(JMod.STATIC | JMod.PUBLIC, aModel.SHORT, "staticField");
    aGetter = aClass.method(JMod.PUBLIC, aModel.INT, "getField");
    aGetter.body()._return(aField);
    final JVar setterParam = aSetter.param(aModel.INT, "field");
    aSetter.body().assign(aField, setterParam);

    aSuperClass = aPackage._class("ASuperClass");
    aClass._extends(aSuperClass);
    aSuperClassField = aSuperClass.field(JMod.PRIVATE, aModel.DOUBLE, "superClassField");
  }
Ejemplo n.º 12
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);
  }
Ejemplo n.º 13
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);
    }
  }
Ejemplo n.º 14
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));
    }
  }
Ejemplo n.º 15
0
  public GeneratedClass createEnum(
      String namespace, String name, List<String> values, EnumBinding enumBinding)
      throws JClassAlreadyExistsException, NoSuchMethodException, IllegalAccessException,
          InvocationTargetException, InstantiationException {

    String className = NameConverter.smart.toClassName(name);
    if (enumBinding != null && !Utils.isEmpty(enumBinding.getClassName())) {
      className = enumBinding.getClassName();
    }

    String qualifiedClassName = targetPackage + "." + className;
    GeneratedClass generatedClass = generatedClasses.get(qualifiedClassName);
    if (generatedClass != null) {
      return generatedClass;
    }

    JDefinedClass enumClass = codeModel._class(JMod.PUBLIC, qualifiedClassName, ClassType.ENUM);
    generatedClass = new GeneratedClass(codeModel, enumClass);
    enumClass.annotate(Root.class).param("name", name);
    enumClass.annotate(Namespace.class).param("reference", namespace);

    if (enumBinding == null) {

      // create enumeration without any customization

      for (String enumConstant : values) {
        enumClass.enumConstant(enumConstant);
      }
    } else {

      // create enumeration with the bindings provided

      JMethod enumConstructor = enumClass.constructor(JMod.PRIVATE);

      for (EnumAttribute enumAttribute : enumBinding.getAttributes()) {

        // constructor
        enumConstructor.param(enumAttribute.getTypeClz(), enumAttribute.getName());
        enumConstructor
            .body()
            .assign(JExpr._this().ref(enumAttribute.getName()), JExpr.ref(enumAttribute.getName()));

        // property
        JFieldVar attributeVar =
            enumClass.field(
                JMod.PRIVATE | JMod.FINAL, enumAttribute.getTypeClz(), enumAttribute.getName());

        // getter
        JMethod attributeMethod =
            enumClass.method(JMod.PUBLIC, enumAttribute.getTypeClz(), enumAttribute.getName());
        attributeMethod.body()._return(attributeVar);
      }

      for (EnumAttributeValue attributeValue : enumBinding.getAttributeValues()) {

        JEnumConstant enumConstant = enumClass.enumConstant(attributeValue.getKey());
        List<Object> attributeValues = attributeValue.getAttributes();
        int index = 0;
        for (Object attributeVal : attributeValues) {
          EnumAttribute enumAttribute = enumBinding.getAttributes().get(index);

          // todo - need to find a better way.
          if (enumAttribute.getTypeClz() == String.class) {

            enumConstant.arg(JExpr.lit((String) attributeVal));

          } else if (enumAttribute.getTypeClz() == Integer.class) {

            enumConstant.arg(JExpr.lit((Integer) attributeVal));

          } else if (enumAttribute.getTypeClz() == Float.class) {

            enumConstant.arg(JExpr.lit((Float) attributeVal));

          } else if (enumAttribute.getTypeClz() == Double.class) {

            enumConstant.arg(JExpr.lit((Double) attributeVal));

          } else if (enumAttribute.getTypeClz() == Short.class) {

            enumConstant.arg(JExpr.lit((Short) attributeVal));

          } else if (enumAttribute.getTypeClz() == Boolean.class) {

            enumConstant.arg(JExpr.lit((Boolean) attributeVal));

          } else if (enumAttribute.getTypeClz() == Character.class) {

            enumConstant.arg(JExpr.lit((Character) attributeVal));
          }

          index++;
        }
      }
    }

    generatedClasses.put(qualifiedClassName, generatedClass);
    return generatedClass;
  }
 private void addNewArray(JDefinedClass jclass, JDefinedClass creatorClass) {
   JMethod newArray = creatorClass.method(JMod.PUBLIC, jclass.array(), "newArray");
   newArray.param(int.class, "size");
   newArray.body()._return(JExpr.direct("new " + jclass.name() + "[size]"));
 }