Java Code Examples for com.squareup.javapoet.TypeSpec

The following are top voted examples for showing how to use com.squareup.javapoet.TypeSpec. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: smartkey   File: ServiceHandler.java   View source code 7 votes vote down vote up
void addType(String name, String forName, ClassName serviceType, ClassName builderType, String param) {
    MethodSpec.Builder smartMethod = MethodSpec.methodBuilder("to" + Util.capFirstLetter(name)+ AnnotationConstants.SUFFIX_SERVICE_TARGET)
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .returns(builderType)
            .addStatement("return new $T()", builderType);
    smartTargets.addMethod(smartMethod.build());
    TypeSpec.Builder type = TypeSpec.classBuilder(builderType)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .superclass(ParameterizedTypeName.get(ClazzNames.SERVICE_TARGET, (TypeName)builderType));
    MethodSpec.Builder clazz = MethodSpec.methodBuilder("getServiceClass")
            .addModifiers(Modifier.PROTECTED)
            .returns(ParameterizedTypeName.get(ClazzNames.CLAZZ, serviceType))
            .addStatement("return $T.class", serviceType);
    type.addMethod(clazz.build());
    types.put(forName, type);
}
 
Example 2
Project: smartkey   File: ActivityHandler.java   View source code 6 votes vote down vote up
public void addType(TargetDescriptor des) {
    TypeSpec.Builder type = types.get(des.name);
    if (type == null) {
        ClassName activityType = ClassName.bestGuess(des.name);
        ClassName builderName = ClassName.bestGuess(des.name + AnnotationConstants.SUFFIX_ACTIVITY_TARGET);
        addType(des.getSimpleName(), des.name, activityType, builderName, null);
    }
    if (des.filters.isEmpty() || des.filters.get(0).actions.isEmpty()) {
        return;
    }
    for (TargetFilter filter : des.filters) {
        for(String action : filter.actions) {
            if("android.intent.action.MAIN".equals(action))
                continue;
            addGoActivityMethod(des.name,
                    "goWithAction_" + action.replace('.', '_').replace(" ", "").toUpperCase(),
                    action, filter.categories);
            addGoActivityMethod(des.name,
                    "goForResultWithAction_" + action.replace('.', '_').replace(" ", "").toUpperCase(),
                    action, filter.categories);
        }
    }
}
 
Example 3
Project: smartkey   File: ActivityHandler.java   View source code 6 votes vote down vote up
void addGoActivityMethod(String targetClz, String methodName, String action, ArrayList<String> cats) {
    TypeSpec.Builder type = types.get(targetClz);
    MethodSpec.Builder actionMethod = MethodSpec.methodBuilder(methodName)
            .addModifiers(Modifier.PUBLIC)
            .addStatement("$T in = prepare(src)", ClazzNames.INTENT)
            .addStatement("in.setAction(\"" + action + "\")");
    for (String cat : cats) {
        actionMethod.addStatement("in.addCategory(\"" + cat + "\")");
    }
    if(methodName.contains("ForResult")) {
        actionMethod.addParameter(ClazzNames.ACTIVITY, "src")
                .addParameter(ClassName.INT, "reqCode");
        actionMethod.addStatement("realGoForResult(src, in, reqCode)");
    } else {
        actionMethod.addParameter(ClazzNames.CONTEXT, "src");
        actionMethod.addStatement("realGo(src, in)");
    }
    type.addMethod(actionMethod.build());
}
 
Example 4
Project: GitHub   File: GlideGenerator.java   View source code 6 votes vote down vote up
private MethodSpec overrideGlideWithMethod(
    String packageName, TypeSpec generatedRequestManager, ExecutableElement methodToOverride) {
  ClassName generatedRequestManagerClassName =
      ClassName.get(packageName, generatedRequestManager.name);
  List<? extends VariableElement> parameters = methodToOverride.getParameters();
  Preconditions.checkArgument(
      parameters.size() == 1, "Expected size of 1, but got %s", methodToOverride);
  VariableElement parameter = parameters.iterator().next();
  return MethodSpec.methodBuilder(methodToOverride.getSimpleName().toString())
      .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
      .addJavadoc(processorUtil.generateSeeMethodJavadoc(methodToOverride))
      .returns(generatedRequestManagerClassName)
      .addParameter(ClassName.get(parameter.asType()), parameter.getSimpleName().toString())
      .addStatement("return ($T) $T.$N($L)",
          generatedRequestManagerClassName, glideType,
          methodToOverride.getSimpleName().toString(),
          parameter.getSimpleName())
      .build();
}
 
Example 5
Project: aws-sdk-java-v2   File: AsyncClientClass.java   View source code 6 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    ClassName interfaceClass = poetExtensions.getClientClass(model.getMetadata().getAsyncInterface());
    Builder classBuilder = PoetUtils.createClassBuilder(className)
                                    .addAnnotation(SdkInternalApi.class)
                                    .addModifiers(Modifier.FINAL)
                                    .addField(AsyncClientHandler.class, "clientHandler", Modifier.PRIVATE, Modifier.FINAL)
                                    .addField(protocolSpec.protocolFactory(model))
                                    .addSuperinterface(interfaceClass)
                                    .addJavadoc("Internal implementation of {@link $1T}.\n\[email protected] $1T#builder()",
                                                interfaceClass)
                                    .addMethods(operations())
                                    .addMethod(closeMethod())
                                    .addMethods(protocolSpec.additionalMethods())
                                    .addMethod(protocolSpec.initProtocolFactory(model));

    if (model.getCustomizationConfig().getServiceSpecificClientConfigClass() != null) {
        classBuilder.addMethod(constructorWithAdvancedConfiguration());
    } else {
        classBuilder.addMethod(constructor());
    }

    protocolSpec.createErrorResponseHandler().ifPresent(classBuilder::addMethod);

    return classBuilder.build();
}
 
Example 6
Project: GitHub   File: RequestManagerFactoryGenerator.java   View source code 6 votes vote down vote up
TypeSpec generate(String generatedCodePackageName, TypeSpec generatedRequestManagerSpec) {
  return TypeSpec.classBuilder(GENERATED_REQUEST_MANAGER_FACTORY_SIMPLE_NAME)
      .addModifiers(Modifier.FINAL)
      .addSuperinterface(ClassName.get(requestManagerFactoryInterface))
      .addJavadoc("Generated code, do not modify\n")
      .addMethod(
          MethodSpec.methodBuilder("build")
              .addModifiers(Modifier.PUBLIC)
              .addAnnotation(Override.class)
              .returns(requestManagerClassName)
              .addParameter(ClassName.get(glideType), "glide")
              .addParameter(ClassName.get(lifecycleType), "lifecycle")
              .addParameter(ClassName.get(requestManagerTreeNodeType), "treeNode")
              .addStatement(
                  "return new $T(glide, lifecycle, treeNode)",
                  ClassName.get(generatedCodePackageName, generatedRequestManagerSpec.name))
              .build()
      )
      .build();
}
 
Example 7
Project: GitHub   File: RequestManagerGenerator.java   View source code 6 votes vote down vote up
private MethodSpec generateAsMethod(String generatedCodePackageName, TypeSpec requestBuilder) {
  TypeVariableName resourceType = TypeVariableName.get("ResourceType");
  ParameterizedTypeName classOfResouceType = ParameterizedTypeName
      .get(ClassName.get(Class.class), resourceType);

  ClassName generatedRequestBuilderClassName =
      ClassName.get(generatedCodePackageName, requestBuilder.name);

  ParameterizedTypeName requestBuilderOfResourceType = ParameterizedTypeName
      .get(generatedRequestBuilderClassName, resourceType);

  return MethodSpec.methodBuilder("as")
      .addModifiers(Modifier.PUBLIC)
      .addAnnotation(Override.class)
      .addTypeVariable(TypeVariableName.get("ResourceType"))
      .addParameter(classOfResouceType, "resourceClass")
      .returns(requestBuilderOfResourceType)
      .addStatement("return new $T<>(glide, this, resourceClass)",
          this.generatedRequestBuilderClassName)
      .build();
}
 
Example 8
Project: GitHub   File: IndexerGenerator.java   View source code 6 votes vote down vote up
TypeSpec generate(List<TypeElement> types) {
  List<TypeElement> modules =  new ArrayList<>();
  List<TypeElement> extensions = new ArrayList<>();
  for (TypeElement element : types) {
    if (processorUtil.isExtension(element)) {
      extensions.add(element);
    } else if (processorUtil.isLibraryGlideModule(element)) {
      modules.add(element);
    } else {
      throw new IllegalArgumentException("Unrecognized type: " + element);
    }
  }
  if (!modules.isEmpty() && !extensions.isEmpty()) {
    throw new IllegalArgumentException("Given both modules and extensions, expected one or the "
        + "other. Modules: " + modules + " Extensions: " + extensions);
  }
  if (!modules.isEmpty()) {
    return generate(types, GlideModule.class);
  } else {
    return generate(types, GlideExtension.class);
  }
}
 
Example 9
Project: GitHub   File: IndexerGenerator.java   View source code 6 votes vote down vote up
private static TypeSpec generate(List<TypeElement> libraryModules,
    Class<? extends Annotation> annotation) {
  AnnotationSpec.Builder annotationBuilder =
      AnnotationSpec.builder(Index.class);

  String value = getAnnotationValue(annotation);
  for (TypeElement childModule : libraryModules) {
    annotationBuilder.addMember(value, "$S", ClassName.get(childModule).toString());
  }

  String indexerName = INDEXER_NAME_PREFIX + annotation.getSimpleName() + "_";
  for (TypeElement element : libraryModules) {
    indexerName += element.getQualifiedName().toString().replace(".", "_");
    indexerName += "_";
  }
  indexerName = indexerName.substring(0, indexerName.length() - 1);

  return TypeSpec.classBuilder(indexerName)
      .addAnnotation(annotationBuilder.build())
      .addModifiers(Modifier.PUBLIC)
      .build();
}
 
Example 10
Project: easy-plugins   File: PluginProviderInterfaceFileGenerator.java   View source code 6 votes vote down vote up
@Override
public void generate(UserMarkerAnnotation marker, ProcessorOutputCollection into) {
    TypeName providerTypeName = marker.getServiceInterfaceTypeName();
    TypeSpec.Builder typeBuilder = TypeSpec.interfaceBuilder(marker.getServiceInterfaceProviderName())
            .addModifiers(Modifier.PUBLIC)
            .addMethod(
                    Util.publicAbstractMethod(GET_NAME_METHOD_NAME, STRING_TYPE_NAME)
                            .build())
            .addMethod(
                    Util.publicAbstractMethod(CREATE_NEW_METHOD_NAME, providerTypeName)
                            .build())
            .addMethod(
                    Util.publicAbstractMethod(CREATE_NEW_WITH_CONFIG_METHOD_NAME, providerTypeName)
                            .addParameter(CONFIG_TYPE_NAME, CONFIG_ARG_NAME)
                            .build());

    for (EasyPluginPlugin plugin : Util.getPluginLoader()) {
        plugin.updatePluginProviderInterface(typeBuilder, marker);
    }

    TypeSpec type = typeBuilder.build();

    into.putType(marker.getOutputPackage(elements), type);
}
 
Example 11
Project: Kickback   File: KickbackBoxGenerator.java   View source code 6 votes vote down vote up
public TypeSpec generate() {
    return TypeSpec.classBuilder(getClassName())
            .addJavadoc("Generated by Kickback. (https://github.com/skydoves/Kickback).\n")
            .addModifiers(Modifier.PUBLIC)
            .addSuperinterface(LifecycleObserver.class)
            .addFields(getKickbackFields())
            .addMethods(getSetterMethodSpecs())
            .addMethods(getGetterMethodSpecs())
            .addMethods(getFreeMethodSpecs())
            .addMethod(getBoxNameSpec())
            .addMethods(getElementNameListSpecs())
            .addMethod(getFreeAllSpec())
            .addMethod(setLifecycleObserverSpec())
            .addMethod(getLifecycleObserverSpec())
            .build();
}
 
Example 12
Project: GitHub   File: GlideGenerator.java   View source code 6 votes vote down vote up
private MethodSpec overrideGlideWithMethod(
    String packageName, TypeSpec generatedRequestManager, ExecutableElement methodToOverride) {
  ClassName generatedRequestManagerClassName =
      ClassName.get(packageName, generatedRequestManager.name);
  List<? extends VariableElement> parameters = methodToOverride.getParameters();
  Preconditions.checkArgument(
      parameters.size() == 1, "Expected size of 1, but got %s", methodToOverride);
  VariableElement parameter = parameters.iterator().next();
  return MethodSpec.methodBuilder(methodToOverride.getSimpleName().toString())
      .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
      .addJavadoc(processorUtil.generateSeeMethodJavadoc(methodToOverride))
      .returns(generatedRequestManagerClassName)
      .addParameter(ClassName.get(parameter.asType()), parameter.getSimpleName().toString())
      .addStatement("return ($T) $T.$N($L)",
          generatedRequestManagerClassName, glideType,
          methodToOverride.getSimpleName().toString(),
          parameter.getSimpleName())
      .build();
}
 
Example 13
Project: shortbread   File: CodeGenerator.java   View source code 6 votes vote down vote up
void generate() {
    TypeSpec shortbread = TypeSpec.classBuilder("ShortbreadGenerated")
            .addAnnotation(AnnotationSpec.builder(suppressLint)
                    .addMember("value", "$S", "NewApi")
                    .addMember("value", "$S", "ResourceType")
                    .build())
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(createShortcuts())
            .addMethod(callMethodShortcut())
            .build();

    JavaFile javaFile = JavaFile.builder("shortbread", shortbread)
            .indent("    ")
            .build();

    try {
        javaFile.writeTo(filer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 14
Project: GitHub   File: RequestManagerGenerator.java   View source code 6 votes vote down vote up
private MethodSpec generateAsMethod(String generatedCodePackageName, TypeSpec requestBuilder) {
  TypeVariableName resourceType = TypeVariableName.get("ResourceType");
  ParameterizedTypeName classOfResouceType = ParameterizedTypeName
      .get(ClassName.get(Class.class), resourceType);

  ClassName generatedRequestBuilderClassName =
      ClassName.get(generatedCodePackageName, requestBuilder.name);

  ParameterizedTypeName requestBuilderOfResourceType = ParameterizedTypeName
      .get(generatedRequestBuilderClassName, resourceType);

  return MethodSpec.methodBuilder("as")
      .addModifiers(Modifier.PUBLIC)
      .addAnnotation(Override.class)
      .addTypeVariable(TypeVariableName.get("ResourceType"))
      .addParameter(classOfResouceType, "resourceClass")
      .addAnnotation(AnnotationSpec.builder(CHECK_RESULT_CLASS_NAME).build())
      .returns(requestBuilderOfResourceType)
      .addStatement("return new $T<>(glide, this, resourceClass, context)",
          this.generatedRequestBuilderClassName)
      .build();
}
 
Example 15
Project: aws-sdk-java-v2   File: AwsServiceBaseRequestSpec.java   View source code 6 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    TypeSpec.Builder builder = TypeSpec.classBuilder(className())
            .addAnnotation(PoetUtils.GENERATED)
            .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
            .superclass(ClassName.get(AwsRequest.class))
            .addMethod(MethodSpec.constructorBuilder()
                    .addModifiers(Modifier.PROTECTED)
                    .addParameter(className().nestedClass("Builder"), "builder")
                    .addStatement("super(builder)")
                    .build())
            .addMethod(MethodSpec.methodBuilder("toBuilder")
                    .addAnnotation(Override.class)
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                    .returns(className().nestedClass("Builder"))
                    .build())
            .addType(builderInterfaceSpec())
            .addType(builderImplSpec());
    return builder.build();
}
 
Example 16
Project: Barricade   File: CodeGenerator.java   View source code 6 votes vote down vote up
private static TypeSpec generateEndpointsResponsesInnerClass(String endpoint,
    List<BarricadeResponse> responses) {
  TypeSpec.Builder classBuilder =
      classBuilder(StringUtils.toCamelCase(endpoint)).addModifiers(PUBLIC, STATIC, FINAL);
  int count = 0;
  for (BarricadeResponse response : responses) {
    FieldSpec valuesField = FieldSpec.builder(int.class,
        StringUtils.removeAllSpecialCharactersAndExtensions(response.responseFileName).toUpperCase())
        .addModifiers(PUBLIC, STATIC, FINAL)
        .initializer("$L", count)
        .build();
    classBuilder.addField(valuesField);
    count++;
  }
  return classBuilder.build();
}
 
Example 17
Project: DaggerAutoInject   File: DaggerAutoInjectProcessor.java   View source code 6 votes vote down vote up
private void constructActivityModule() {
    final TypeSpec.Builder builder = TypeSpec.classBuilder(Constants.ACTIVITY_MODULE)
            .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
            .addAnnotation(Constants.DAGGER_MODULE);

    for (ActivityHolder activityHolder : activityHolders.values()) {
        builder.addMethod(MethodSpec.methodBuilder(Constants.METHOD_CONTRIBUTE + activityHolder.className)
                .addAnnotation(Constants.DAGGER_ANDROID_ANNOTATION)
                .addModifiers(Modifier.ABSTRACT)
                .returns(activityHolder.classNameComplete)
                .build()
        );
    }

    final TypeSpec newClass = builder.build();
    final JavaFile javaFile = JavaFile.builder(Constants.PACKAGE_NAME, newClass).build();

    try {
        javaFile.writeTo(System.out);
        javaFile.writeTo(filer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 18
Project: auto-adapter   File: ViewHolderFactoryGenerator.java   View source code 6 votes vote down vote up
private void addFields(final TypeSpec.Builder classBuilder) {
    FieldSpec.Builder viewIdsField = FieldSpec.builder(int[].class, "viewIds", Modifier.PRIVATE, Modifier.STATIC,
            Modifier.FINAL);
    StringBuilder sb = new StringBuilder();
    sb.append("{");
    for (Integer id : viewIds) {
        sb.append(id).append(",");
    }

    if (viewIds.size() > 0) {
        sb.deleteCharAt(sb.length() - 1);
    }

    sb.append("}");
    viewIdsField.initializer(CodeBlock.of(sb.toString()));
    classBuilder.addField(viewIdsField.build());

}
 
Example 19
Project: autoproxy   File: CommonClassGenerator.java   View source code 6 votes vote down vote up
@NonNull
protected TypeSpec.Builder createClass(@NonNull final FieldSpec... members) {
    final TypeSpec.Builder builder = TypeSpec.classBuilder("Proxy_" + type.flatClassName)
            .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT);

    // TODO: mimic annotations of the super type

    if (ElementKind.INTERFACE == type.element.getKind()) {
        builder.addSuperinterface(superType);
    } else if (ElementKind.CLASS == type.element.getKind()) {
        builder.superclass(superType);
    } else {
        final String message = "Unsupported data type: " + type.element.getKind() + ", " + type.elementType;
        errors.write(message + "\n");

        throw new UnsupportedOperationException(message);
    }

    for (final FieldSpec member : members) {
        builder.addField(member);
    }

    return builder;
}
 
Example 20
Project: autoproxy   File: CommonClassGenerator.java   View source code 6 votes vote down vote up
/** */
protected void createMethods(@NonNull final TypeSpec.Builder classSpec) throws Exception {
    // compose methods
    RuntimeException runtimeError = null;
    for (final Element method : type.methods) {
        if (!(method instanceof Symbol.MethodSymbol)) {
            final String message = "Unexpected method type: " + method.getClass().getSimpleName();
            errors.write(message + "\n");

            runtimeError = new UnsupportedOperationException(message);
            continue;
        }

        classSpec.addMethod(createMethod((Symbol.MethodSymbol) method).build());
    }

    // if were detected exception, throw it
    if (null != runtimeError) {
        throw runtimeError;
    }
}
 
Example 21
Project: RxRetroJsoup   File: RetroJsoupProcessor.java   View source code 6 votes vote down vote up
public void construct(JsoupModelHolder modelHolder) {

        final TypeSpec.Builder builder = TypeSpec.classBuilder(modelHolder.className + Constants.PARSER)
                .addModifiers(Modifier.PUBLIC);

        for (JsoupModelFieldHolder field : modelHolder.fields) {
            builder.addMethod(MethodSpec.methodBuilder(field.name.replace("-","_").replace(" ","_"))
                    .addModifiers(Modifier.PUBLIC)
                    .returns(TypeName.VOID)
                    .addParameter(modelHolder.classNameComplete, "item")
                    .addParameter(TypeName.get(String.class), "value")
                    .addStatement("item.$L = value", field.name)
                    .build());
        }

        final TypeSpec newClass = builder.build();

        final JavaFile javaFile = JavaFile.builder(modelHolder.classNameComplete.packageName(), newClass).build();

        try {
            javaFile.writeTo(System.out);
            javaFile.writeTo(filer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
Example 22
Project: flowr   File: DeepLinkAnnotationCompiler.java   View source code 6 votes vote down vote up
/**
 * Generate a new deep link handler implementation class with the specified package name,
 * class name and the constructor body.
 *
 * @param packageName        the name of the package to use for the generated class.
 * @param className          the name to be used for the implementation class.
 * @param constructorBuilder the constructor body builder for the class.
 */
private void generateDeepLinkHandler(String packageName, String className,
                                     MethodSpec.Builder constructorBuilder) {
    TypeSpec classObject = getClassObject(className)
            .addMethod(constructorBuilder.build())
            .build();

    JavaFile javaFile = JavaFile.builder(packageName, classObject)
            .build();

    try {
        javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 23
Project: aws-sdk-java-v2   File: EnumClass.java   View source code 6 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    Builder enumBuilder = createEnumBuilder(className)
        .addField(String.class, VALUE, Modifier.PRIVATE, Modifier.FINAL)
        .addMethod(toStringBuilder().addStatement("return $T.valueOf($N)", String.class, VALUE).build())
        .addMethod(fromValueSpec())
        .addMethod(knownValuesSpec())
        .addMethod(createConstructor());

    addDeprecated(enumBuilder::addAnnotation, shape);
    addJavadoc(enumBuilder::addJavadoc, shape);

    shape.getEnums().forEach(
        e -> enumBuilder.addEnumConstant(e.getName(), TypeSpec.anonymousClassBuilder("$S", e.getValue()).build())
    );
    enumBuilder.addEnumConstant(UNKNOWN_TO_SDK_VERSION, TypeSpec.anonymousClassBuilder("null").build());

    return enumBuilder.build();
}
 
Example 24
Project: data-mediator   File: TypeAdapterInsertDelegate.java   View source code 5 votes vote down vote up
@Override
public void addClassAnnotation(TypeSpec.Builder typeBuilder) {
    if(!getClassInfo().isGenerateJsonAdapter() || !GlobalConfig.getInstance().isJsonAdapterEnabled()){
        return ;
    }
    ClassName cn_type_adapter = ClassName.get(getClassInfo().getPackageName(),
            Util.getTypeAdapterName(getClassInfo().getDirectParentInterfaceName()));
    typeBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get(PKG_GSON_ANNO, SN_GSON_JSON_ADAPTER))
            .addMember("value", "$T.class", cn_type_adapter)
            .build());
}
 
Example 25
Project: json2java4idea   File: ClassBuilder.java   View source code 5 votes vote down vote up
@Nonnull
@CheckReturnValue
public TypeSpec build(@Nonnull String name) {
    final TypeSpec.Builder classBuilder = TypeSpec.classBuilder(name);
    buildAnnotations().forEach(classBuilder::addAnnotation);
    buildModifiers().forEach(classBuilder::addModifiers);
    buildSuperClass().ifPresent(classBuilder::superclass);
    buildInterfaces().forEach(classBuilder::addSuperinterface);
    buildFields().forEach(classBuilder::addField);
    buildMethods().forEach(classBuilder::addMethod);
    buildInnerTypes().forEach(classBuilder::addType);
    return classBuilder.build();
}
 
Example 26
Project: GankReader   File: OnceClickProcessor.java   View source code 5 votes vote down vote up
private void createJavaFile(ProxyInfo proxyInfo, TypeSpec typeSpec) {
    JavaFile javaFile = JavaFile.builder(proxyInfo.getPackageName(), typeSpec).build();
    try {
        javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 27
Project: RIBs   File: InteractorTestGenerator.java   View source code 5 votes vote down vote up
@Override
public void generate(InteractorAnnotatedClass annotatedInteractor) throws IOException {
  if (annotatedInteractor.isCodeGenerated()) {
    return;
  }

  String interactorTestBaseClassName =
      Constants.INTERACTOR_TEST_CREATOR_PREFIX
          + annotatedInteractor.getRootName()
          + Constants.INTERACTOR_TEST_CREATOR_SUFFIX;

  MethodSpec constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build();

  MethodSpec createInteractor = createMethodSpec(annotatedInteractor);

  TypeSpec testBaseClass =
      TypeSpec.classBuilder(interactorTestBaseClassName)
          .addMethod(constructor)
          .addMethod(createInteractor)
          .addModifiers(Modifier.PUBLIC)
          .build();

  String packageName = CompilerUtils.packageNameOf(annotatedInteractor.getTypeElement());
  JavaFile.builder(packageName, testBaseClass)
      .build()
      .writeTo(getProcessingEnvironment().getFiler());

  annotatedInteractor.setCodeGenerated(true);
}
 
Example 28
Project: GitHub   File: ExtensionProcessor.java   View source code 5 votes vote down vote up
boolean processExtensions(Set<? extends TypeElement> set, RoundEnvironment env) {
  List<TypeElement> elements = processorUtil.getElementsFor(GlideExtension.class, env);
  processorUtil.debugLog("Processing types : " + elements);
  for (TypeElement typeElement : elements) {
    GlideExtensionValidator.validateExtension(typeElement);
    processorUtil.debugLog("Processing elements: " + typeElement.getEnclosedElements());
  }

  if (elements.isEmpty()) {
    return false;
  }
  TypeSpec spec = indexerGenerator.generate(elements);
  processorUtil.writeIndexer(spec);
  return true;
}
 
Example 29
Project: D-Router   File: RouterTableGenerator.java   View source code 5 votes vote down vote up
private TypeSpec getRouterTableClassTypeSpec(FieldSpec tableFieldSpec, MethodSpec initTableMethodSpec, MethodSpec queryTableMethodSpec, MethodSpec constructorMethodSpec, MethodSpec addRouterMethodSpec) {
    return TypeSpec.classBuilder(Constants.ROUTER_TABLE_CLASS_NAME)
            .addModifiers(Modifier.PUBLIC)
            .addField(tableFieldSpec)
            .addMethod(initTableMethodSpec)
            .addMethod(queryTableMethodSpec)
            .addMethod(constructorMethodSpec)
            .addMethod(addRouterMethodSpec)
            .build();
}
 
Example 30
Project: jso-builder   File: SerializerGenerator.java   View source code 5 votes vote down vote up
public TypeSpec createSerializer(ClassName className) {
    return TypeSpec.classBuilder(className)
            .addModifiers(Modifier.STATIC)
            .superclass(className.peerClass("Serializer"))
            .addMethod(createToJSONMethod())
            .addMethod(createIsJsObject())
            .addMethod(createWriteJSONMethod())
            .addMethod(createWriteValueMethod())
            .build();
}
 
Example 31
Project: json2java4idea   File: SuppressWarningsAnnotationPolicyTest.java   View source code 5 votes vote down vote up
@Test
public void applyShouldAddGeneratedAnnotation() throws Exception {
    // setup
    final TypeSpec.Builder builder = TypeSpec.classBuilder("Test");

    // exercise
    underTest.apply(builder);

    // verify
    assertThat(builder.build())
            .hasName("Test")
            .hasAnnotation(AnnotationSpec.builder(SuppressWarnings.class)
                    .addMember("value", "$S", "all")
                    .build());
}
 
Example 32
Project: aws-sdk-java-v2   File: AwsServiceBaseRequestSpec.java   View source code 5 votes vote down vote up
private TypeSpec builderImplSpec() {
    return TypeSpec.classBuilder("BuilderImpl")
            .addModifiers(Modifier.PROTECTED, Modifier.STATIC, Modifier.ABSTRACT)
            .addSuperinterface(className().nestedClass("Builder"))
            .superclass(ClassName.get(AwsRequest.class).nestedClass("BuilderImpl"))
            .addMethod(MethodSpec.constructorBuilder()
                    .addModifiers(Modifier.PROTECTED)
                    .build())
            .addMethod(MethodSpec.constructorBuilder()
                    .addModifiers(Modifier.PROTECTED)
                    .addParameter(className(), "request")
                    .addStatement("super(request)")
                    .build())
            .build();
}
 
Example 33
Project: resourceprovider   File: RpCodeGenerator.java   View source code 5 votes vote down vote up
TypeSpec generateDimensionProviderClass() {
    MethodSpec constructor = MethodSpec.constructorBuilder()
                                       .addModifiers(PUBLIC)
                                       .addParameter(contextClassName, "context")
                                       .addStatement("this.context = context")
                                       .build();

    TypeSpec.Builder classBuilder = classBuilder("DimensionProvider")
            .addModifiers(PUBLIC)
            .addField(contextField)
            .addMethod(constructor)
            .addAnnotation(suppressLint);


    for (String var : rClassDimenVars) {
        try {
            classBuilder.addMethod(MethodSpec.methodBuilder("get" + getterSuffix(var) + "PixelSize")
                                             .addModifiers(Modifier.PUBLIC)
                                             .returns(INT)
                                             .addStatement("return context.getResources().getDimensionPixelSize(R.dimen." + var + ")")
                                             .varargs(false)
                                             .addJavadoc("Returns the dimension R.dimen." + var + " in pixels")
                                             .build());
        } catch (IllegalArgumentException e) {
            System.out.println("\n\nResourceProvider Compiler Error: " + e.getMessage() + ".\n\nUnable to generate API for R.dimen." + var + "\n\n") ;
        }

    }

    return classBuilder.build();
}
 
Example 34
Project: auto-nav   File: NavProcessor.java   View source code 5 votes vote down vote up
private void createNavigator(Set<ActivityIntentModel> activityModels) {

        TypeSpec.Builder navigatorBuilder = TypeSpec.classBuilder(navigatorClassName)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL);

        for (ActivityIntentModel model : activityModels) {
            createActivityIntent(model);

            /**
             *         public static MainActivityIntent toMainActivity(Context context){
             *             MainActivityIntent intent = new MainActivityIntent(context, "com.com.MainActivity");
             *             return intent;
             *         }
             */

            ClassName returnType = ClassName.get(model.getPackageName(), model.getIntentClzName());
            MethodSpec.Builder methodSpecBuilder = MethodSpec
                    .methodBuilder(METHOD_PREFIX + model.getClzName());
            methodSpecBuilder.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                    .addParameter(classContext, "context")
                    .returns(ClassName.get(model.getPackageName(), model.getIntentClzName()))
                    .addStatement("$T intent = new $T($L,$S)", returnType, returnType, "context", model.getQualifiedName())
                    .addStatement("return intent");

            navigatorBuilder.addMethod(methodSpecBuilder.build());
        }

        addPreGoListener(navigatorBuilder);


        try {
            JavaFile.builder(navigatorPackageName, navigatorBuilder.build()).build().writeTo(filer);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
 
Example 35
Project: aws-sdk-java-v2   File: MemberCopierSpec.java   View source code 5 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    TypeSpec.Builder builder = TypeSpec.classBuilder(className())
            .addModifiers(Modifier.FINAL)
            .addAnnotation(PoetUtils.GENERATED)
            .addMethod(copyMethod());

    if (serviceModelCopiers.requiresBuilderCopier(memberModel)) {
        builder.addMethod(builderCopyMethod());
    }

    return builder.build();
}
 
Example 36
Project: jso-builder   File: JSOBuilderProcessor.java   View source code 5 votes vote down vote up
private TypeSpec createJsonInterface() {
    return TypeSpec.classBuilder("JSON")
            .addModifiers(Modifier.STATIC, Modifier.FINAL)
            .addAnnotation(AnnotationSpec.builder(ClassNames.JSINTEROP_JSTYPE)
                    .addMember("isNative", "true")
                    .addMember("namespace", "$T.GLOBAL", ClassNames.JSINTEROP_JSPACKAGE)
                    .addMember("name", "$S", "JSON")
                    .build())
            .addMethod(MethodSpec.methodBuilder("stringify")
                    .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.NATIVE)
                    .addParameter(Object.class, "object")
                    .returns(String.class)
                    .build())
            .build();
}
 
Example 37
Project: domino   File: PresenterCommandSourceWriter.java   View source code 5 votes vote down vote up
@Override
public String write() throws IOException {
    TypeSpec contributionRequest = DominoTypeBuilder.build(className, PresenterCommandProcessor.class)
            .addAnnotation(Command.class)
            .superclass(ParameterizedTypeName.get(ClassName.get(PresenterCommand.class), presenterType))
            .build();

    StringBuilder asString = new StringBuilder();
    JavaFile.builder(targetPackage, contributionRequest).skipJavaLangImports(true).build().writeTo(asString);
    return asString.toString();
}
 
Example 38
Project: easy-plugins   File: ProcessorOutputCollection.java   View source code 5 votes vote down vote up
public void writeContents(Filer filer) {
    for (Map.Entry<String, Set<TypeSpec>> newTypes : outputClasses.entrySet()) {
        for (TypeSpec type : newTypes.getValue()) {
            type = type.toBuilder().addJavadoc(Constants.AUTOGEN_COMMENT).build();
            writeFile(filer,
                    JavaFile.builder(newTypes.getKey(), type).build());
        }
    }

    for (Map.Entry<String, Set<String>> service : serviceProviders.entrySet()) {
        Util.writeMetaInfServices(service.getKey(), service.getValue(), filer);
    }
}
 
Example 39
Project: GitHub   File: GlideGenerator.java   View source code 5 votes vote down vote up
private List<MethodSpec> generateOverridesForGlideMethods(
    final String generatedCodePackageName, final TypeSpec generatedRequestManager) {
  return Lists.transform(discoverGlideMethodsToOverride(),
      new Function<ExecutableElement, MethodSpec>() {
        @Override
        public MethodSpec apply(ExecutableElement input) {
          if (isGlideWithMethod(input)) {
            return overrideGlideWithMethod(
                generatedCodePackageName, generatedRequestManager, input);
          } else {
            return overrideGlideStaticMethod(input);
          }
        }
      });
}
 
Example 40
Project: GitHub   File: ProcessorUtil.java   View source code 5 votes vote down vote up
void writeClass(String packageName, TypeSpec clazz) {
  try {
    debugLog("Writing class:\n" + clazz);
    JavaFile.builder(packageName, clazz).build().writeTo(processingEnv.getFiler());
  } catch (Throwable e) {
    throw new RuntimeException(e);
  }
}