Example #1
0
  /**
   * Creates the getter and setter methods on the supplied class for the supplied name.
   *
   * @param clazz to put getter and setter methods on
   * @param name of the property
   * @param syntaxType of the property
   * @param multivalue whether this property is a collection
   */
  protected void createMutators(
      final JDefinedClass clazz,
      final String name,
      final Class<?> syntaxType,
      final boolean multivalue) {
    final String upperName = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
    if (multivalue) {
      final JClass detailClass = codeModel.ref(syntaxType);
      final JClass collectionClass = codeModel.ref(Collection.class);
      final JClass genericClass = collectionClass.narrow(detailClass);
      final JFieldVar field = clazz.field(JMod.PRIVATE, genericClass, name);
      final JMethod getterMethod = clazz.method(JMod.PUBLIC, genericClass, "get" + upperName);
      getterMethod.body()._return(field);

      final JMethod setterMethod = clazz.method(JMod.PUBLIC, Void.TYPE, "set" + upperName);
      setterMethod.param(genericClass, "c");
      setterMethod.body().assign(JExpr._this().ref(name), JExpr.ref("c"));

    } else {
      final JFieldVar field = clazz.field(JMod.PRIVATE, syntaxType, name);
      final JMethod getterMethod = clazz.method(JMod.PUBLIC, syntaxType, "get" + upperName);
      getterMethod.body()._return(field);

      final JMethod setterMethod = clazz.method(JMod.PUBLIC, Void.TYPE, "set" + upperName);
      setterMethod.param(syntaxType, "s");
      setterMethod.body().assign(JExpr._this().ref(name), JExpr.ref("s"));
    }
  }
Example #2
0
  private static void generateEnum() throws JClassAlreadyExistsException, IOException {
    JCodeModel codeModel = new JCodeModel();
    JDefinedClass enumClass = codeModel._class("com.foo.Bar", ClassType.ENUM);
    // This code creates field within the enum class
    JFieldVar columnField = enumClass.field(JMod.PRIVATE | JMod.FINAL, String.class, "column");
    JFieldVar filterableField =
        enumClass.field(JMod.PRIVATE | JMod.FINAL, codeModel.BOOLEAN, "filterable");

    // Define the enum constructor
    JMethod enumConstructor = enumClass.constructor(JMod.PRIVATE);
    enumConstructor.param(String.class, "column");
    enumConstructor.param(codeModel.BOOLEAN, "filterable");
    enumConstructor.body().assign(JExpr._this().ref("column"), JExpr.ref("column"));
    enumConstructor.body().assign(JExpr._this().ref("filterable"), JExpr.ref("filterable"));

    JMethod getterColumnMethod = enumClass.method(JMod.PUBLIC, String.class, "getColumn");
    getterColumnMethod.body()._return(columnField);
    JMethod getterFilterMethod = enumClass.method(JMod.PUBLIC, codeModel.BOOLEAN, "isFilterable");
    getterFilterMethod.body()._return(filterableField);

    JEnumConstant enumConst = enumClass.enumConstant("FOO_BAR");
    enumConst.arg(JExpr.lit("fooBar"));
    enumConst.arg(JExpr.lit(true));
    codeModel.build(new File("src"));
    /*
     * //creating an enum class within our main class JDefinedClass enumClass =
     * codeModel._class(JMod.PUBLIC, "REPORT_COLUMNS"); //This code creates
     * field within the enum class JFieldVar columnField =
     * enumClass.field(JMod.PRIVATE|JMod.FINAL, String.class, "column");
     * JFieldVar filterableField = enumClass.field(JMod.PRIVATE|JMod.FINAL,
     * codeModel.BOOLEAN, "filterable");
     */
  }
 private void generateCollectionAccessor(final DefinedPropertyOutline fieldOutline) {
   final JFieldVar fieldVar = fieldOutline.getFieldVar();
   if (fieldVar != null) {
     final JMethod modifier =
         this.modifierClass.method(
             JMod.PUBLIC,
             fieldVar.type(),
             ModifierGenerator.GETTER_PREFIX + fieldOutline.getBaseName());
     if (this.implement) {
       final JFieldRef fieldRef =
           new NestedThisRef(this.classOutline.getImplClass()).ref(fieldVar);
       final JConditional ifNull = modifier.body()._if(fieldRef.eq(JExpr._null()));
       ifNull
           ._then()
           .assign(
               fieldRef,
               JExpr._new(
                   this.classOutline
                       .getImplClass()
                       .owner()
                       .ref(ArrayList.class)
                       .narrow(fieldOutline.getElementType())));
       modifier.body()._return(fieldRef);
     }
   }
 }
  @Override
  public void process(Element element, EComponentHolder holder) throws Exception {
    ExecutableElement executableElement = (ExecutableElement) element;
    JMethod delegatingMethod = codeModelHelper.overrideAnnotatedMethod(executableElement, holder);
    JBlock previousBody = codeModelHelper.removeBody(delegatingMethod);
    JDefinedClass anonymousRunnableClass =
        codeModelHelper.createDelegatingAnonymousRunnableClass(holder, previousBody);

    UiThread annotation = element.getAnnotation(UiThread.class);
    long delay = annotation.delay();
    UiThread.Propagation propagation = annotation.propagation();

    if (delay == 0) {
      if (propagation == UiThread.Propagation.REUSE) {
        // Put in the check for the UI thread.
        addUIThreadCheck(delegatingMethod, previousBody, holder);
      }

      delegatingMethod.body().invoke(holder.getHandler(), "post").arg(_new(anonymousRunnableClass));
    } else {
      delegatingMethod
          .body()
          .invoke(holder.getHandler(), "postDelayed")
          .arg(_new(anonymousRunnableClass))
          .arg(lit(delay));
    }
  }
  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())));
  }
 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);
 }
  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());
    }
  }
  private ModifierGenerator(
      final PluginContext pluginContext,
      final DefinedTypeOutline classOutline,
      final String modifierClassName,
      final String modifierInterfaceName,
      final Collection<TypeOutline> interfaces,
      final String modifierMethodName,
      final boolean implement)
      throws JClassAlreadyExistsException {
    this.classOutline = classOutline;
    final JDefinedClass definedClass = classOutline.getImplClass();
    this.implement = implement;
    this.modifierClass =
        definedClass._class(
            JMod.PUBLIC, modifierClassName, classOutline.getImplClass().getClassType());
    if (interfaces != null) {
      for (final TypeOutline interfaceOutline : interfaces) {
        this.modifierClass._implements(
            pluginContext.ref(interfaceOutline.getImplClass(), modifierInterfaceName, true));
      }
    }
    final JFieldRef cachedModifierField;
    if (!"java.lang.Object".equals(definedClass._extends().fullName())) {
      this.modifierClass._extends(
          pluginContext.ref(definedClass._extends(), modifierClassName, false));
      cachedModifierField = JExpr.refthis(ModifierGenerator.MODIFIER_CACHE_FIELD_NAME);
    } else {
      if (implement) {
        cachedModifierField =
            JExpr._this()
                .ref(
                    definedClass.field(
                        JMod.PROTECTED | JMod.TRANSIENT,
                        this.modifierClass,
                        ModifierGenerator.MODIFIER_CACHE_FIELD_NAME));
      } else {
        cachedModifierField = null;
      }
    }

    final JDefinedClass typeDefinition =
        classOutline.isInterface()
                && ((DefinedInterfaceOutline) classOutline).getSupportInterface() != null
            ? ((DefinedInterfaceOutline) classOutline).getSupportInterface()
            : definedClass;
    final JMethod modifierMethod =
        typeDefinition.method(JMod.PUBLIC, this.modifierClass, modifierMethodName);
    if (this.implement) {
      final JConditional ifCacheNull =
          modifierMethod.body()._if(JExpr._null().eq(cachedModifierField));
      ifCacheNull._then().assign(cachedModifierField, JExpr._new(this.modifierClass));
      modifierMethod.body()._return(JExpr.cast(this.modifierClass, cachedModifierField));
    }
  }
  protected void setOnFinishInflate() {
    onFinishInflate = generatedClass.method(PUBLIC, codeModel().VOID, "onFinishInflate");
    onFinishInflate.annotate(Override.class);
    onFinishInflate.javadoc().append(ALREADY_INFLATED_COMMENT);

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

    getInit();
    viewNotifierHelper.invokeViewChanged(ifNotInflated);

    onFinishInflate.body().invoke(JExpr._super(), "onFinishInflate");
  }
  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 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());
  }
Example #12
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);
  }
Example #13
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);
 }
Example #14
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.");
  }
Example #15
0
  public void generateQuery(Feed feed) {
    try {
      JClass transformedType = getTransformedType(feed);
      if (transformedType == null) {
        return;
      }

      JDefinedClass cls =
          pkg._class(JMod.PUBLIC | JMod.FINAL, String.format("%sQuery", feed.getName()));
      cls._extends(parent.narrow(transformedType));

      if (feed.getTitle() != null) {
        cls.javadoc().add(String.format("<p>%s</p>", feed.getTitle()));
      }

      addResourcePath(cls, feed);
      addResultTypeMethod(model, cls, transformedType);
      addConstructor(cls);
      JDefinedClass bldrCls = addBuilderCls(feed, cls);

      cls.method(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, bldrCls, "builder")
          .body()
          ._return(JExpr._new(bldrCls));

      JMethod cpyMthd = cls.method(JMod.PROTECTED | JMod.FINAL, cls, "copy");
      JVar cpyParam = cpyMthd.param(immutableMap.narrow(String.class, Object.class), "params");
      cpyMthd.body()._return(JExpr._new(cls).arg(cpyParam));

    } catch (Exception e) {
      throw new IllegalStateException(e);
    }
  }
  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);
      }
    }
  }
Example #17
0
  private void addConstructors(JDefinedClass jclass, List<String> properties) {

    // no properties to put in the constructor => default constructor is good enough.
    if (properties.isEmpty()) {
      return;
    }

    // add a no-args constructor for serialization purposes
    JMethod noargsConstructor = jclass.constructor(JMod.PUBLIC);
    noargsConstructor.javadoc().add("No args constructor for use in serialization");

    // add the public constructor with property parameters
    JMethod fieldsConstructor = jclass.constructor(JMod.PUBLIC);
    JBlock constructorBody = fieldsConstructor.body();

    Map<String, JFieldVar> fields = jclass.fields();

    for (String property : properties) {
      JFieldVar field = fields.get(property);

      if (field == null) {
        throw new IllegalStateException(
            "Property "
                + property
                + " hasn't been added to JDefinedClass before calling addConstructors");
      }

      fieldsConstructor.javadoc().addParam(property);
      JVar param = fieldsConstructor.param(field.type(), field.name());
      constructorBody.assign(JExpr._this().ref(field), param);
    }
  }
Example #18
0
 private void addResultTypeMethod(JCodeModel model, JDefinedClass cls, JClass transformedType) {
   JClass classCls = model.ref(Class.class);
   JMethod method =
       cls.method(JMod.PROTECTED | JMod.FINAL, classCls.narrow(transformedType), "resultsType");
   method.body()._return(JExpr.dotclass(transformedType));
   method.annotate(Override.class);
 }
Example #19
0
  @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);
  }
Example #20
0
  public static void main(String[] args) throws JClassAlreadyExistsException, IOException {
    JCodeModel codeModel = new JCodeModel();

    Class template = AbstractBaseWrapper.class;

    String packageName = template.getPackage().getName();

    String className = template.getSimpleName().replace("Abstract", "") + "Impl";
    JPackage generatedPackage = codeModel._package(packageName);

    JDefinedClass generatedClass = generatedPackage._class(JMod.FINAL, className); // Creates
    // a
    // new
    // class
    generatedClass._extends(template);

    for (Method method : template.getMethods()) {

      if (Modifier.isAbstract(method.getModifiers())) {
        System.out.println(
            "Found abstract method "
                + Modifier.toString(method.getModifiers())
                + " "
                + method.getName());

        JMethod generatedMethod =
            generatedClass.method(JMod.PUBLIC, method.getReturnType(), method.getName());

        for (Parameter parameter : method.getParameters()) {
          generatedMethod.param(parameter.getModifiers(), parameter.getType(), parameter.getName());
        }

        if (method.getReturnType().equals(Void.TYPE)) {
          generatedMethod.body().add(generateInvocation(method));
        } else {

          generatedMethod.body()._return(generateInvocation(method));
        }
      }
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    codeModel.build(new SingleStreamCodeWriter(out));

    System.out.println(out);
  }
Example #21
0
  private JDefinedClass getMixinEnum(Feed feed) throws JClassAlreadyExistsException {
    String enumName = camel(feed.getName(), true) + "Mixin";
    if (pkg.isDefined(enumName)) {
      return pkg._getClass(enumName);
    }
    JDefinedClass valueEnum = pkg._enum(enumName);

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

    JMethod toString = valueEnum.method(JMod.PUBLIC, String.class, "toString");
    toString.annotate(Override.class);
    toString.body()._return(valField);
    return valueEnum;
  }
Example #22
0
  private void addResourcePath(JDefinedClass cls, Feed feed) {
    JFieldVar field = cls.field(privateStaticFinal, String.class, "RESOURCE_PATH");
    field.init(JExpr.lit(feed.getHref()));

    JMethod method = cls.method(JMod.PROTECTED | JMod.FINAL, String.class, "resourcePath");
    method.annotate(Override.class);
    method.body()._return(field);
  }
Example #23
0
  private JDefinedClass addBuilderCls(Feed feed, JDefinedClass cls)
      throws JClassAlreadyExistsException, ClassNotFoundException {
    JDefinedClass bldrCls = cls._class(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, "Builder");
    JVar paramBuilder =
        bldrCls
            .field(JMod.PRIVATE | JMod.FINAL, immutableMapBldr, "params")
            .init(immutableMap.staticInvoke("builder"));

    for (Filter filter : feed.getFilters().getFilter()) {
      if (!Boolean.TRUE.equals(filter.isDeprecated())) {
        addWithersFor(filter, bldrCls, paramBuilder);
      }
    }

    if (feed.getMixins() != null && feed.getMixins().getMixin() != null) {
      JDefinedClass mixinEnum = getMixinEnum(feed);
      for (Mixin mixin : feed.getMixins().getMixin()) {
        String mixinName = mixin.getName().toUpperCase().replace(' ', '_');
        JEnumConstant mixinCnst = mixinEnum.enumConstant(mixinName);
        mixinCnst.arg(JExpr.lit(mixin.getName().replace(' ', '+')));
      }
      JFieldVar field = cls.field(privateStaticFinal, String.class, "MIXIN");
      field.init(JExpr.lit("mixin"));
      JMethod iterWither = bldrCls.method(JMod.PUBLIC, bldrCls, "withMixins");
      JVar param = iterWither.param(iterable(mixinEnum), "mixins");
      JBlock mthdBody = iterWither.body();
      mthdBody.add(
          paramBuilder
              .invoke("put")
              .arg(field)
              .arg(immutableList.staticInvoke("copyOf").arg(param)));
      mthdBody._return(JExpr._this());
      JMethod varArgWither = bldrCls.method(JMod.PUBLIC, bldrCls, "withMixins");
      param = varArgWither.varParam(mixinEnum, "mixins");
      varArgWither
          .body()
          ._return(JExpr.invoke(iterWither).arg(immutableList.staticInvoke("copyOf").arg(param)));
    }

    JMethod bldMthd = bldrCls.method(JMod.PUBLIC, cls, "build");
    bldMthd.body()._return(JExpr._new(cls).arg(paramBuilder.invoke("build")));

    // TODO: add sorts
    return bldrCls;
  }
  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");
  }
  public JMethod createOnCreate() {
    JMethod onCreate = activity.method(JMod.PROTECTED, void.class, "onCreate");
    onCreate.annotate(Override.class);

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

    return onCreate;
  }
Example #26
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);
 }
Example #27
0
  /**
   * Generates service stubs.
   *
   * @throws GenerationException
   */
  @SuppressWarnings("deprecation")
  public void generate() throws GenerationException {

    preGeneration();

    JDefinedClass serviceCls = generateClass();

    preGenerateClassBody(serviceCls);

    generateClassJavadoc(serviceCls.javadoc());

    if (hasDefaultConstructor()) {
      JMethod defaultConst = generateDefaultConstructor(serviceCls);
      JBlock defaultConstBody = defaultConst.body();
      generateDefaultConstructorBody(defaultConstBody);
    }

    List<String> operationNames = this.serviceDefinition.getOperationNames();

    if (this.logger.isDebugEnabled()) {
      this.logger.debug("Generating service class with operations: " + operationNames);
    }

    for (int i = 0; i < operationNames.size(); i++) {
      String operationName = operationNames.get(i);
      List<ElementType> inputTypes = getInputTypes(operationName);
      generateOperationMethod(serviceCls, operationName, inputTypes, null);

      // add overloaded versions for this method
      int j = 0;
      List<List<ElementType>> overloadedVersions = getOverloadedVersions(operationName);
      for (List<ElementType> overloadedInputTypes : overloadedVersions) {
        generateOperationMethod(serviceCls, operationName, overloadedInputTypes, j++);
      }
    }

    postGenerateClassBody(serviceCls);

    try {
      Folder dir = this.configuration.getOutputDirectory();
      if (dir instanceof LocalFolder) {
        File dest = ((LocalFolder) dir).getLocalFile();
        this.codeModel.build(dest, dest, null);
      } else {
        File f = IOUtils.createTempDirectory("dataService_directory", null);
        this.codeModel.build(f, f, null);
        Folder folder = new LocalFolder(f);
        folder.copyContentsTo(this.configuration.getOutputDirectory());
        IOUtils.deleteRecursive(f);
      }
    } catch (IOException e) {
      throw new GenerationException("Unable to write service stub", e);
    }

    postGeneration();
  }
Example #28
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));
        }
      }
    }
  }
Example #29
0
 private void addVarArgsWither(
     Filter filter, JMethod wither, JDefinedClass bldrCls, JClass paramType)
     throws JClassAlreadyExistsException {
   JMethod method = bldrCls.method(wither.mods().getValue(), wither.type(), wither.name());
   if (filter.getTitle() != null) {
     method.javadoc().add(String.format("<p>%s</p>", filter.getTitle()));
   }
   JVar param = method.varParam(paramType, wither.listParams()[0].name());
   method
       .body()
       ._return(JExpr.invoke(wither).arg(immutableList.staticInvoke("copyOf").arg(param)));
 }
Example #30
0
  private void getter(JDefinedClass clazz, JFieldVar field, String fieldName, String remarks) {
    // getter
    JMethod getter = clazz.method(JMod.PUBLIC, field.type(), "get" + fieldName);

    /* Addign java doc for method */
    JDocComment jDoc = addMethodDoc(getter, remarks + "取得");
    JCommentPart rtn = jDoc.addReturn();
    rtn.add(remarks);

    JBlock block = getter.body();
    block._return(field);
  }