Beispiel #1
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.");
  }
Beispiel #2
0
 public void putStaticImpl(JMethod method, JMethod staticImpl) {
   instanceToStaticMap.put(method, staticImpl);
   staticToInstanceMap.put(staticImpl, method);
   if (method.isTrace()) {
     staticImpl.setTrace();
   }
 }
  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());
  }
 @Test
 public void testGenerateHashCode() throws ClassNotFoundException {
   plugin.generateHashCodeMethod(aModel, aClass);
   final JMethod generatedMethod = aClass.getMethod("hashCode", new JType[] {});
   assertThat(generatedMethod, not(nullValue()));
   assertThat(generatedMethod.type().fullName(), equalTo("int"));
 }
  @Test
  public void testBasic() throws Exception {
    final JCodeModel cm = new JCodeModel();

    final JDirectClass rClassId = cm.directClass("id.aa.R")._class("id");
    assertEquals("id", rClassId.name());
    assertEquals("id.aa", rClassId._package().name());
    assertEquals("id.aa.R.id", rClassId.fullName());
    final JDirectClass rClassMenu = cm.directClass("id.aa.R")._class("menu");
    assertEquals("menu", rClassMenu.name());
    assertEquals("id.aa", rClassMenu._package().name());
    assertEquals("id.aa.R.menu", rClassMenu.fullName());

    final JFieldRef myItem = rClassId.staticRef("myItem");
    final JFieldRef myMenu = rClassMenu.staticRef("myMenu");

    final JPackage aPkg2 = cm._package("id.aa");
    final JDefinedClass aClassAct = aPkg2._class("HelloAndroidActivity_");
    final JMethod aMethodCreate = aClassAct.method(JMod.PUBLIC, cm.BOOLEAN, "onCreateOptionsMenu");
    aMethodCreate.body().add(JExpr.ref("menuInflater").invoke("inflate").arg(myMenu));
    final JMethod aMethodSelected =
        aClassAct.method(JMod.PUBLIC, cm.BOOLEAN, "onOptionsItemSelected");
    aMethodSelected.body()._if(JExpr.ref("itemId_").eq(myItem));

    CodeModelTestsHelper.parseCodeModel(cm);
  }
Beispiel #6
0
 public JMethod getMethod(String name, int startIndex) {
   for (int i = startIndex; i < methods.size(); i++) {
     JMethod jMethod = (JMethod) methods.elementAt(i);
     if (jMethod.getName().equals(name)) return jMethod;
   }
   return null;
 }
  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())));
  }
Beispiel #8
0
  public static boolean isClinit(JMethod method) {
    JDeclaredType enclosingType = method.getEnclosingType();

    boolean isClinit = enclosingType != null && method == enclosingType.getClinitMethod();
    assert !isClinit || method.getName().equals(GwtAstBuilder.CLINIT_NAME);
    return isClinit;
  }
Beispiel #9
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);
 }
 @Test
 public void testGenerateToString() {
   plugin.generateToStringMethod(aModel, aClass);
   final JMethod generatedMethod = aClass.getMethod("toString", new JType[0]);
   assertThat(generatedMethod, not(nullValue()));
   assertThat(generatedMethod.type().fullName(), equalTo(String.class.getName()));
 }
 @Test
 public void testGenerateEquals() throws ClassNotFoundException {
   plugin.generateEqualsMethod(aModel, aClass);
   final JMethod generatedMethod =
       aClass.getMethod("equals", new JType[] {aModel.parseType("java.lang.Object")});
   assertThat(generatedMethod, not(nullValue()));
   assertThat(generatedMethod.type().fullName(), equalTo("boolean"));
 }
Beispiel #12
0
 /** Adds a method to this type. */
 public final void addMethod(JMethod method) {
   assert method.getEnclosingType() == this;
   assert !method.getName().equals("$clinit") || getMethods().size() == 0
       : "Attempted adding " + "$clinit method with index != 0";
   assert !method.getName().equals("$init") || getMethods().size() == 1
       : "Attempted adding $init " + "method with index != 1";
   methods = Lists.add(methods, method);
 }
Beispiel #13
0
  /**
   * Returns the class initializer method. Can only be called after making sure the class has a
   * class initializer method.
   *
   * @return The class initializer method.
   */
  public final JMethod getClinitMethod() {
    assert getMethods().size() != 0;
    JMethod clinit = this.getMethods().get(0);

    assert clinit != null;
    assert clinit.getName().equals("$clinit");
    return clinit;
  }
Beispiel #14
0
  /**
   * Returns the instance initializer ($init) method. Can only be called after making sure the class
   * has an instance initializer method.
   *
   * @return The instance initializer method.
   */
  public final JMethod getInitMethod() {
    assert getMethods().size() > 1;
    JMethod init = this.getMethods().get(1);

    assert init != null;
    assert init.getName().equals("$init");
    return init;
  }
 private <T extends Annotation> T findAnnotationOnMethodOrEnclosingType(
     final JMethod method, final Class<T> annotationType) {
   T annotation = method.getAnnotation(annotationType);
   if (annotation == null) {
     annotation = method.getEnclosingType().getAnnotation(annotationType);
   }
   return annotation;
 }
 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");
 }
Beispiel #17
0
 public static boolean isClinit(JMethod method) {
   JDeclaredType enclosingType = method.getEnclosingType();
   if ((enclosingType != null) && (method == enclosingType.getClinitMethod())) {
     assert (method.getName().equals("$clinit"));
     return true;
   } else {
     return false;
   }
 }
Beispiel #18
0
 private JMethod getDefaultConstructor() {
   List<JMethod> constructors = getConstructors();
   for (JMethod constructor : constructors) {
     if (constructor.getOriginalParamTypes().size() == 0) {
       return constructor;
     }
   }
   return null;
 }
 private String getRestMethod(JMethod method) throws UnableToCompleteException {
   String restMethod = null;
   if (method.getAnnotation(DELETE.class) != null) {
     restMethod = METHOD_DELETE;
   } else if (method.getAnnotation(GET.class) != null) {
     restMethod = METHOD_GET;
   } else if (method.getAnnotation(HEAD.class) != null) {
     restMethod = METHOD_HEAD;
   } else if (method.getAnnotation(OPTIONS.class) != null) {
     restMethod = METHOD_OPTIONS;
   } else if (method.getAnnotation(POST.class) != null) {
     restMethod = METHOD_POST;
   } else if (method.getAnnotation(PUT.class) != null) {
     restMethod = METHOD_PUT;
   } else if (method.getAnnotation(JSONP.class) != null) {
     restMethod = METHOD_JSONP;
   } else {
     restMethod = method.getName();
     if (!REST_METHODS.contains(restMethod)) {
       getLogger()
           .log(
               ERROR,
               "Invalid rest method. It must either have a lower case rest method name or have a javax rs method annotation: "
                   + method.getReadableDeclaration());
       throw new UnableToCompleteException();
     }
   }
   return restMethod;
 }
Beispiel #20
0
 /**
  * Returns the method with the given signature, if there is one.<br>
  * Optionally can search up the super type chain.
  */
 public JMethod findMethod(String methodSignature, boolean recurse) {
   for (JMethod method : getMethods()) {
     if (method.getSignature().equals(methodSignature)) {
       return method;
     }
   }
   if (recurse && getSuperClass() != null) {
     return getSuperClass().findMethod(methodSignature, true);
   }
   return null;
 }
Beispiel #21
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));
        }
      }
    }
  }
Beispiel #22
0
  public static boolean isInit(JMethod method) {
    JDeclaredType enclosingType = method.getEnclosingType();

    if (method.isStatic()) {
      // Hack, check the name.
      return method.getName().equals(GwtAstBuilder.STATIC_INIT_NAME);
    }

    boolean isInit = enclosingType != null && method == enclosingType.getInitMethod();
    assert !isInit || method.getName().equals(GwtAstBuilder.INIT_NAME);
    return isInit;
  }
  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();
  }
    private void emitBody(SourceWriter w) throws NotFoundException {
      JClassType baseClass =
          context_.getTypeOracle().getType("org.rstudio.core.client.js.JsObjectInjector");
      JClassType c = baseType_.asParameterizationOf(baseClass.isGenericType());
      JType typeToInject = c.isParameterized().getTypeArgs()[0];

      w.print("public native final void injectObject(");
      w.print(typeToInject.getQualifiedSourceName());
      w.println(" value) /*-{");
      w.indent();

      w.println(baseExpression_ + " = {");
      w.indent();

      JMethod[] methods = typeToInject.isClassOrInterface().getMethods();
      for (int i = 0; i < methods.length; i++) {
        JMethod method = methods[i];
        final JParameter[] jParameters = method.getParameters();

        StringBuilder argString = new StringBuilder();
        for (int j = 0; j < jParameters.length; j++) {
          argString.append("_").append(j);
          if (j < jParameters.length - 1) argString.append(", ");
        }

        w.println(method.getName() + ": function(" + argString + ") {");
        w.indent();

        if (!method.getReturnType().getQualifiedSourceName().equals("void")) w.print("return ");
        w.print("value.@");
        w.print(typeToInject.getQualifiedSourceName());
        w.print("::");
        w.print(method.getName());
        w.print("(");
        for (JParameter param : jParameters) w.print(param.getType().getJNISignature());
        w.print(")(");
        w.print(argString.toString());
        w.println(");");

        w.outdent();
        w.print("}");
        w.println((i < methods.length - 1) ? "," : "");
      }

      w.outdent();
      w.println("};");

      w.outdent();
      w.println("}-*/;");
    }
Beispiel #25
0
 public static String getJsniSig(JMethod method, boolean addReturnType) {
   StringBuilder sb = new StringBuilder();
   sb.append(method.getName());
   sb.append("(");
   for (int i = 0; i < method.getOriginalParamTypes().size(); ++i) {
     JType type = method.getOriginalParamTypes().get(i);
     sb.append(type.getJsniSignatureName());
   }
   sb.append(")");
   if (addReturnType) {
     sb.append(method.getOriginalReturnType().getJsniSignatureName());
   }
   return sb.toString();
 }
 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()));
     }
   }
 }
  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()));
    }
  }
  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);
  }
  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);
      }
    }
  }
Beispiel #30
0
 public JType getType() {
   if (overrideReturnType != null) {
     return overrideReturnType;
   } else {
     return method.getType();
   }
 }