Java Code Examples for com.squareup.javapoet.ClassName

The following are top voted examples for showing how to use com.squareup.javapoet.ClassName. 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: aws-sdk-java-v2   File: AwsServiceModel.java   View source code 6 votes vote down vote up
private List<TypeName> modelSuperInterfaces() {
    List<TypeName> interfaces = new ArrayList<>();

    if (implementStructuredPojoInterface()) {
        interfaces.add(ClassName.get(StructuredPojo.class));
    }

    switch (shapeModel.getShapeType()) {
        case Exception:
        case Model:
        case Request:
        case Response:
            interfaces.add(toCopyableBuilderInterface());
            break;
        default:
            break;
    }

    return interfaces;
}
 
Example 2
Project: GitHub   File: BindingSet.java   View source code 6 votes vote down vote up
static Builder newBuilder(TypeElement enclosingElement) {
  TypeMirror typeMirror = enclosingElement.asType();

  boolean isView = isSubtypeOfType(typeMirror, VIEW_TYPE);
  boolean isActivity = isSubtypeOfType(typeMirror, ACTIVITY_TYPE);
  boolean isDialog = isSubtypeOfType(typeMirror, DIALOG_TYPE);

  TypeName targetType = TypeName.get(typeMirror);
  if (targetType instanceof ParameterizedTypeName) {
    targetType = ((ParameterizedTypeName) targetType).rawType;
  }

  String packageName = getPackage(enclosingElement).getQualifiedName().toString();
  String className = enclosingElement.getQualifiedName().toString().substring(
      packageName.length() + 1).replace('.', '$');
  ClassName bindingClassName = ClassName.get(packageName, className + "_ViewBinding");

  boolean isFinal = enclosingElement.getModifiers().contains(Modifier.FINAL);
  return new Builder(targetType, bindingClassName, isFinal, isView, isActivity, isDialog);
}
 
Example 3
Project: butterknife-parent   File: BindingSet.java   View source code 6 votes vote down vote up
private BindingSet(TypeName targetTypeName, ClassName bindingClassName, boolean isFinal,
                   boolean isView, boolean isActivity,boolean isFragment, boolean isDialog, ImmutableList<ViewBinding> viewBindings,
                   ImmutableList<FieldCollectionViewBinding> collectionBindings,
                   ImmutableList<ResourceBinding> resourceBindings, BindingSet parentBinding, @LayoutRes int layoutId) {
    this.isFinal = isFinal;
    this.targetTypeName = targetTypeName;
    this.bindingClassName = bindingClassName;
    this.isView = isView;
    this.isActivity = isActivity;
    this.isFragment = isFragment;
    this.isDialog = isDialog;
    this.viewBindings = viewBindings;
    this.collectionBindings = collectionBindings;
    this.resourceBindings = resourceBindings;
    this.parentBinding = parentBinding;
    this.layoutId = layoutId;
}
 
Example 4
Project: react4j   File: Generator.java   View source code 6 votes vote down vote up
@Nonnull
private static TypeSpec buildDaggerModule( @Nonnull final ComponentDescriptor descriptor )
{
  final TypeSpec.Builder builder = TypeSpec.classBuilder( "DaggerModule" );

  builder.addModifiers( Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL );
  builder.addAnnotation( ClassName.bestGuess( Constants.DAGGER_MODULE_CLASSNAME ) );

  final MethodSpec.Builder method =
    MethodSpec.methodBuilder( "provideComponent" ).
      addAnnotation( ClassName.bestGuess( Constants.DAGGER_PROVIDES_CLASSNAME ) ).
      addModifiers( Modifier.STATIC ).
      addParameter( descriptor.getClassNameToConstruct(), "component", Modifier.FINAL ).
      returns( COMPONENT_CLASSNAME ).
      addStatement( "return component" );
  builder.addMethod( method.build() );

  return builder.build();
}
 
Example 5
Project: domino   File: EndpointsRegisterMethodWriter.java   View source code 6 votes vote down vote up
@Override
protected void registerItem(EndpointsEntry entry, MethodSpec.Builder methodBuilder) {
    final FullClassName handlerEndpoint = new FullClassName(entry.element.fullQualifiedNoneGenericName() + "EndpointHandler");
    String path = entry.element.getAnnotation(Handler.class).value();

    ClassName handlerEndpointType = ClassName.get(handlerEndpoint.asPackage(), handlerEndpoint.asSimpleName());
    MethodSpec getMethod = MethodSpec.methodBuilder("get")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(handlerEndpointType)
            .addStatement("return new $T()", handlerEndpointType)
            .build();

    TypeSpec factoryType = TypeSpec.anonymousClassBuilder("")
            .addSuperinterface(ParameterizedTypeName.get(ClassName.get(Supplier.class), handlerEndpointType.box()))
            .addMethod(getMethod)
            .build();
    methodBuilder.addStatement("registry.registerEndpoint(\"" + path + "\", $L)", factoryType);
}
 
Example 6
Project: data-mediator   File: SharedPropertiesNGenerator.java   View source code 6 votes vote down vote up
public static boolean generateSharedProperties(Collection<FieldData> fields,
                                               Elements elements, Filer filer, ProcessorPrinter pp){
    final ClassName cn_sp = ClassName.get(PKG_DM_INTERNAL, SIMPLE_NAME_SHARED_PROP);
    CodeBlock.Builder staticBuilder = CodeBlock.builder();
    for(FieldData fd : fields){
        staticBuilder.add("$T.putToCache($S, $S, $L);\n", cn_sp, fd.getTypeCompat().toString(),
                fd.getPropertyName(), fd.getComplexType());
    }
    String classSimpleName = SIMPLE_NAME_SHARED_PROP + "_" + findBestIndex(elements);
    TypeSpec typeSpec = TypeSpec.classBuilder(classSimpleName)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addStaticBlock(staticBuilder.build())
            .addJavadoc(CodeBlock.of(DOC))
            .build();

    try {
        JavaFile javaFile = JavaFile.builder(PKG_DM_INTERNAL, typeSpec)
                .build();
       // System.out.println(javaFile.toString());
        javaFile.writeTo(filer);
    } catch (IOException e) {
        pp.error(TAG, "generateSharedProperties", Util.toString(e));
        return false;
    }
    return true;
}
 
Example 7
Project: butterknife-parent   File: ButterKnifeProcessor.java   View source code 6 votes vote down vote up
private void parseCompiledR(String respectivePackageName, TypeElement rClass) {
  for (Element element : rClass.getEnclosedElements()) {
    String innerClassName = element.getSimpleName().toString();
    if (SUPPORTED_TYPES.contains(innerClassName)) {
      for (Element enclosedElement : element.getEnclosedElements()) {
        if (enclosedElement instanceof VariableElement) {
          VariableElement variableElement = (VariableElement) enclosedElement;
          Object value = variableElement.getConstantValue();

          if (value instanceof Integer) {
            int id = (Integer) value;
            ClassName rClassName =
                ClassName.get(elementUtils.getPackageOf(variableElement).toString(), "R",
                    innerClassName);
            String resourceName = variableElement.getSimpleName().toString();
            QualifiedId qualifiedId = new QualifiedId(respectivePackageName, id);
            symbols.put(qualifiedId, new Id(id, rClassName, resourceName));
          }
        }
      }
    }
  }
}
 
Example 8
Project: aws-sdk-java-v2   File: MemberCopierSpec.java   View source code 6 votes vote down vote up
private MethodSpec builderCopyMethodForList() {
    TypeName keyType = typeProvider.getTypeNameForSimpleType(memberModel.getMapModel().getKeyModel()
                                                                        .getVariable().getVariableType());
    ClassName valueParameter = poetExtensions.getModelClass(memberModel.getMapModel().getValueModel().getC2jShape());
    ClassName builderForParameter = valueParameter.nestedClass("Builder");
    TypeName parameterType =
        ParameterizedTypeName.get(ClassName.get(Map.class), keyType, WildcardTypeName.subtypeOf(builderForParameter));

    CodeBlock code =
        CodeBlock.builder()
                 .beginControlFlow("if ($N == null)", memberParamName())
                 .addStatement("return null")
                 .endControlFlow()
                 .addStatement("return $N($N.entrySet().stream().collect(toMap($T::getKey, e -> e.getValue().build())))",
                               serviceModelCopiers.copyMethodName(),
                               memberParamName(),
                               Map.Entry.class)
                 .build();

    return MethodSpec.methodBuilder(serviceModelCopiers.builderCopyMethodName())
                     .addModifiers(Modifier.STATIC)
                     .addParameter(parameterType, memberParamName())
                     .returns(typeProvider.fieldType(memberModel))
                     .addCode(code)
                     .build();
}
 
Example 9
Project: json2java4idea   File: JavaConverter.java   View source code 6 votes vote down vote up
@Nonnull
private TypeName generateListType(@Nonnull String className, @Nonnull JsonValue value, @Nonnull ClassBuilder builder) {
    if (value.isArray()) {
        final JsonValue firstValue = value.asArray()
                .stream()
                .findFirst()
                .orElse(new JsonNull());
        final TypeName type = generateListType(className, firstValue, builder);
        return ParameterizedTypeName.get(ClassName.get(List.class), type);
    }

    if (value.isObject()) {
        final TypeSpec innerClass = fromObject(className, value.asObject(), Modifier.PUBLIC, Modifier.STATIC);
        builder.addInnerType(innerClass);

        final TypeName innerClassType = ClassName.bestGuess(innerClass.name);
        return ParameterizedTypeName.get(ClassName.get(List.class), innerClassType);
    }

    return ParameterizedTypeName.get(ClassName.get(List.class), value.getType().box());
}
 
Example 10
Project: KiiAnnotation   File: BuilderGenerator.java   View source code 6 votes vote down vote up
public static MethodSpec builderBuild(ClassName className, List<MethodSpec> methodSpecList, List<FieldSpec> fieldSpecList) {
    String name = className.simpleName();
    CodeBlock.Builder codeBlock = CodeBlock.builder();

    for (int i = 0; i < methodSpecList.size(); i++) {
        codeBlock.add("$N.$N(this.$N);\n", name.toLowerCase(), methodSpecList.get(i).name, fieldSpecList.get(i).name);
    }

    return MethodSpec
            .methodBuilder("build")
            .addModifiers(Modifier.PUBLIC)
            .addStatement("$N $N = new $N()", name, name.toLowerCase(), name)
            .addCode(codeBlock.build())
            .returns(className)
            .addStatement("return $N", name.toLowerCase())
            .build();
}
 
Example 11
Project: dataenum   File: MatchMethods.java   View source code 6 votes vote down vote up
private MethodSpec.Builder createFoldVoidSignature(
    Iterable<TypeVariableName> availableTypeVariables) throws ParserException {
  MethodSpec.Builder builder =
      MethodSpec.methodBuilder("match").addModifiers(Modifier.PUBLIC).returns(void.class);

  for (OutputValue arg : values) {
    TypeName visitor =
        ParameterizedTypeName.get(
            ClassName.get(Consumer.class),
            withoutMissingTypeVariables(arg.parameterizedOutputClass(), availableTypeVariables));

    builder.addParameter(
        ParameterSpec.builder(visitor, asCamelCase(arg.name()))
            .addAnnotation(Nonnull.class)
            .build());
  }

  return builder;
}
 
Example 12
Project: prefpin   File: PrefPinProcessor.java   View source code 6 votes vote down vote up
private void writeBinding(String targetClassName, Set<Element> annotationFields)
    throws IOException {
  String packageName = null;
  int lastDot = targetClassName.lastIndexOf('.');
  if (lastDot > 0) {
    packageName = targetClassName.substring(0, lastDot);
  }

  String targetSimpleClassName = targetClassName.substring(lastDot + 1);
  String bindingClassName = targetClassName + "_PrefBinding";
  String bindingSimpleClassName = bindingClassName.substring(lastDot + 1);

  ClassName targetClass = ClassName.get(packageName, targetSimpleClassName);

  TypeSpec binding = TypeSpec.classBuilder(bindingSimpleClassName)
      .addModifiers(Modifier.PUBLIC)
      .addMethod(buildConstructor(targetClass, annotationFields))
      .build();

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

  javaFile.writeTo(processingEnv.getFiler());
}
 
Example 13
Project: GitHub   File: RequestManagerGenerator.java   View source code 6 votes vote down vote up
private MethodSpec generateAdditionalRequestManagerMethodNew(
    ExecutableElement extensionMethod) {
   String returnType = processorUtil.findClassValuesFromAnnotationOnClassAsNames(extensionMethod,
      GlideType.class).iterator().next();
  ClassName returnTypeClassName = ClassName.bestGuess(returnType);
  ParameterizedTypeName parameterizedTypeName =
      ParameterizedTypeName.get(generatedRequestBuilderClassName, returnTypeClassName);

  return MethodSpec.methodBuilder(extensionMethod.getSimpleName().toString())
      .addModifiers(Modifier.PUBLIC)
      .returns(parameterizedTypeName)
      .addJavadoc(processorUtil.generateSeeMethodJavadoc(extensionMethod))
      .addStatement(
          "return ($T) $T.$N(this.as($T.class))",
          parameterizedTypeName,
          extensionMethod.getEnclosingElement(),
          extensionMethod.getSimpleName(),
          returnTypeClassName)
      .build();
}
 
Example 14
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 15
Project: PreferenceRoom   File: PreferenceComponentGenerator.java   View source code 6 votes vote down vote up
private List<MethodSpec> getSuperMethodSpecs() {
    List<MethodSpec> methodSpecs = new ArrayList<>();
    this.annotatedClazz.annotatedElement.getEnclosedElements().stream()
            .filter(element -> element instanceof ExecutableElement)
            .map(element -> (ExecutableElement) element)
            .forEach(method -> {
                ClassName preferenceRoom = ClassName.get(PreferenceRoom.class);
                MethodSpec.Builder builder = MethodSpec.overriding(method);
                MethodSpec methodSpec = builder.addStatement("$T.inject($N)", preferenceRoom, method.getParameters().get(0).getSimpleName()).build();
                if(methodSpec.returnType != TypeName.get(Void.TYPE)) {
                    throw new VerifyException(String.format("Returned '%s'. only return type can be void.", methodSpec.returnType.toString()));
                }
                methodSpecs.add(methodSpec);
            });
    return methodSpecs;
}
 
Example 16
Project: GitHub   File: RequestManagerGenerator.java   View source code 6 votes vote down vote up
RequestManagerGenerator(ProcessingEnvironment processingEnv, ProcessorUtil processorUtil) {
  this.processingEnv = processingEnv;
  this.processorUtil = processorUtil;

  Elements elementUtils = processingEnv.getElementUtils();

  requestManagerType = elementUtils.getTypeElement(REQUEST_MANAGER_QUALIFIED_NAME);
  requestManagerClassName = ClassName.get(requestManagerType);

  lifecycleType = elementUtils.getTypeElement(LIFECYCLE_QUALIFIED_NAME);
  requestManagerTreeNodeType =
      elementUtils.getTypeElement(REQUEST_MANAGER_TREE_NODE_QUALIFIED_NAME);

  requestBuilderType =
      elementUtils.getTypeElement(RequestBuilderGenerator.REQUEST_BUILDER_QUALIFIED_NAME);

  glideType = elementUtils.getTypeElement(GLIDE_QUALIFIED_NAME);
}
 
Example 17
Project: aws-sdk-java-v2   File: SyncClientBuilderInterface.java   View source code 5 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    return PoetUtils.createInterfaceBuilder(builderInterfaceName)
                    .addSuperinterface(ParameterizedTypeName.get(ClassName.get(SyncClientBuilder.class),
                                                                 builderInterfaceName, clientInterfaceName))
                    .addSuperinterface(ParameterizedTypeName.get(baseBuilderInterfaceName,
                                                                 builderInterfaceName, clientInterfaceName))
                    .addJavadoc(getJavadoc())
                    .build();
}
 
Example 18
Project: RxAndroidOrm   File: ModelEntityProxyGenerator.java   View source code 5 votes vote down vote up
public TypeSpec generate() {
    String idFieldName = Constants.FIELD_ID;
    Element idField = ProcessUtils.getIdField(element);
    if (idField != null)
        idFieldName = ProcessUtils.getObjectName(idField);

    TypeSpec.Builder builder = TypeSpec.classBuilder(ProcessUtils.getObjectName(element) + Constants.MODEL_ENTITY_PROXY)
            .addModifiers(Modifier.PUBLIC)
            .superclass(TypeName.get(element.asType()))
            .addSuperinterface(ClassName.get(Constants.DAO_PACKAGE, Constants.MODEL_ENTITY_PROXY_INTERFACE));

    if (idField == null) {
        builder.addField(TypeName.LONG, Constants.FIELD_ID);
    }

    builder.addMethod(MethodSpec.methodBuilder(Constants.MODEL_ENTITY_PROXY_GET_ID_METHOD)
            .addModifiers(Modifier.PUBLIC)
            .returns(TypeName.LONG)
            .addStatement("return $L", idFieldName)
            .build())
            .addMethod(MethodSpec.methodBuilder(Constants.MODEL_ENTITY_PROXY_SET_ID_METHOD)
                    .addModifiers(Modifier.PUBLIC)
                    .returns(TypeName.VOID)
                    .addParameter(TypeName.LONG, "id")
                    .addStatement("this.$L = id", idFieldName)
                    .build());

    return builder.build();
}
 
Example 19
Project: Spyglass   File: TestGetPlaceholderMethodGenerator.java   View source code 5 votes vote down vote up
@Test
public void testGenerateFor_parameterWithUseShort() {
	final VariableElement parameter = avatarRule.getElementWithUniqueId("short");
	final AnnotationMirror useAnnotation = UseAnnoRetriever.getAnnotation(parameter);

	final MethodSpec generatedMethod = generator.generateFor(useAnnotation, 0);

	checkSignature(generatedMethod, ClassName.get(Number.class));
	checkCompiles(generatedMethod);
}
 
Example 20
Project: PreferenceRoom   File: PreferenceFieldMethodGenerator.java   View source code 5 votes vote down vote up
private MethodSpec generateObjectSetter() {
    ClassName converterClazz = ClassName.get(keyField.converterPackage, keyField.converter);
    return MethodSpec.methodBuilder(getSetterPrefixName())
            .addModifiers(PUBLIC)
            .addParameter(keyField.typeName, keyField.keyName.toLowerCase())
            .addStatement("$T $N = new $T()", converterClazz, INSTANCE_CONVERTER, converterClazz)
            .addStatement(getSetterStatement(), preference, EDIT_METHOD, keyField.keyName, INSTANCE_CONVERTER + ".convertObject(" + keyField.keyName.toLowerCase() + ")", APPLY_METHOD)
            .build();
}
 
Example 21
Project: vxrifa   File: SenderGenerator.java   View source code 5 votes vote down vote up
SenderGenerator generateHandler() {

        MethodSpec.Builder handlerBuilder = MethodSpec.methodBuilder("handle");

        TypeVariableName Tvariable = TypeVariableName.get("T");

        handlerBuilder.addModifiers(Modifier.PRIVATE)
                .addTypeVariable(Tvariable)
                .addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build());

        ParameterSpec futureParameter = ParameterSpec.builder(ParameterizedTypeName.get(ClassName.get(io.vertx.core.Future.class), Tvariable), "future").build();
        ParameterSpec asyncResultParameter = ParameterSpec.builder(
                ParameterizedTypeName.get(ClassName.get(io.vertx.core.AsyncResult.class),
                        ParameterizedTypeName.get(ClassName.get(io.vertx.core.eventbus.Message.class), TypeName.get(Object.class))),
                "asyncResult").build();

        handlerBuilder.addParameter(futureParameter)
                .addParameter(asyncResultParameter)
                .beginControlFlow("if ($N.succeeded())", asyncResultParameter)
                .addStatement("$T reply = ($T) $N.result().body()", RIFAMessage.class, RIFAMessage.class, asyncResultParameter)
                .addStatement("$N.complete(($T) reply.get(0))", futureParameter, Tvariable)
                .nextControlFlow("else")
                .addStatement("$N.fail($N.cause().getMessage())", futureParameter, asyncResultParameter)
                .endControlFlow()
                .returns(TypeName.VOID);

        classBuilder.addMethod(handlerBuilder.build());

        return this;

    }
 
Example 22
Project: aws-sdk-java-v2   File: QueryXmlProtocolSpec.java   View source code 5 votes vote down vote up
@Override
public List<CodeBlock> errorUnmarshallers(IntermediateModel model) {
    List<ShapeModel> exceptions = model.getShapes()
                                       .values()
                                       .stream()
                                       .filter(s -> s.getType().equals("Exception"))
                                       .collect(Collectors.toList());

    return exceptions.stream().map(s -> {
        ClassName exceptionClass = poetExtensions.getTransformClass(s.getShapeName() + "Unmarshaller");
        return CodeBlock.builder()
                        .add("unmarshallers.add(new $T());", exceptionClass).build();
    }).collect(Collectors.toList());
}
 
Example 23
Project: aws-sdk-java-v2   File: AwsServiceModel.java   View source code 5 votes vote down vote up
private MethodSpec serializableBuilderClass() {
    return MethodSpec.methodBuilder("serializableBuilderClass")
                     .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                     .returns(ParameterizedTypeName.get(ClassName.get(Class.class),
                                                        WildcardTypeName.subtypeOf(modelBuilderSpecs.builderInterfaceName())))
                     .addStatement("return $T.class", modelBuilderSpecs.builderImplName())
                     .build();
}
 
Example 24
Project: Spyglass   File: TestGetDefaultMethodGenerator.java   View source code 5 votes vote down vote up
@Test
public void testGenerateFor_defaultToDimensionAnnotationSupplied() {
	final Element element = avatarRule.getElementWithUniqueId("dimension");
	final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, DefaultToDimension.class);

	final MethodSpec generatedMethod = generator.generateFor(mirror);

	assertThat(generatedMethod, is(notNullValue()));
	checkMethodSignature(generatedMethod, ClassName.get(Number.class));
	checkCompiles(generatedMethod);
}
 
Example 25
Project: limitjson   File: LimitJSONTypeArray.java   View source code 5 votes vote down vote up
public void addStatement(MethodSpec.Builder builder, LIMITJSONVariable variable) {
    builder.beginControlFlow("if (root.has($S))", variable.jsonName());
    builder.addStatement("$T array = root.optJSONArray($S)", ClassName.bestGuess("org.json.JSONArray"), variable.jsonName());
    builder.addStatement("int size = array.length()");
    builder.addStatement("thisObj.$N = new $N[size]", variable.variableName(), type);
    builder.beginControlFlow("for (int i = 0; i < size; i++)");
    builder.addStatement(String.format("thisObj.$N[i] = array.%s(i)", format), variable.variableName());
    builder.endControlFlow();
    builder.endControlFlow();
}
 
Example 26
Project: jdoocsoup   File: DataClassBuilderHandler.java   View source code 5 votes vote down vote up
private void parseDataFromDescriptor() {
    if (descriptor.getElementKind() == ElementKind.CLASS) {
        for (VariableElement var : descriptor.getFields()) {

            if (checkIfFieldForProcessing(var)) {
                continue;
            }

            DataClassBuilder.MethodDocs builderMethodDocsAnnotation = var.getAnnotation(DataClassBuilder.MethodDocs.class);
            DataClassBuilder.HasDefault hasDefaultAnnotation = var.getAnnotation(DataClassBuilder.HasDefault.class);

            FieldSpec.Builder fieldSpec = FieldSpec.builder(TypeName.get(var.asType()), var.getSimpleName().toString()).addModifiers(Modifier.PRIVATE);

            if (hasDefaultAnnotation != null) {
                fieldSpec.initializer(CodeBlock.of("$L", hasDefaultAnnotation.value()));
            }

            MethodSpec.Builder methodSpec = MethodSpec.methodBuilder(var.getSimpleName().toString()).addModifiers(Modifier.PUBLIC)
                    .addParameter(ParameterSpec.builder(TypeName.get(var.asType()), var.getSimpleName().toString()).build())
                    .addStatement("this.$N = $N", var.getSimpleName(), var.getSimpleName())
                    .addStatement("return this")
                    .returns(ClassName.get(descriptor.getPackageName(), descriptor.getDataClassBuilderName()));

            if (builderMethodDocsAnnotation != null) {
                methodSpec.addJavadoc(builderMethodDocsAnnotation.value() + "\n");
            }

            builderClassSpecBuilder.addField(fieldSpec.build());
            builderClassSpecBuilder.addMethod(methodSpec.build());
        }
    }

    builderClassSpecBuilder.addMethod(createBuilderMethodSpec());
    builderClassSpecBuilder.addMethod(createBuildMethodSpec());
    builderClassSpecBuilder.addMethod(createPrivateConstructor());
}
 
Example 27
Project: Hannibai   File: HandleImplGenerator.java   View source code 5 votes vote down vote up
private MethodSpec createRemoveMethodSpec(Element enclosedElement, String formatName,
                                          AnnotationSpec submitAnnotation) {
    if (enclosedElement.getAnnotation(Commit.class) == null) {
        return MethodSpec.methodBuilder(REMOVE + formatName)
                .addModifiers(Modifier.PUBLIC)
                .returns(TypeName.VOID)
                .addAnnotation(submitAnnotation)
                .addJavadoc(String.format(REMOVE_METHOD_JAVA_DOC,
                        enclosedElement.getSimpleName())
                )
                .addStatement("$T.remove1($N, $L, $S)",
                        ClassName.get(PACKAGE_NAME, HANNIBAI),
                        "mSharedPreferencesName",
                        "mId",
                        enclosedElement.getSimpleName())
                .build();
    } else {
        return MethodSpec.methodBuilder(REMOVE + formatName)
                .addModifiers(Modifier.PUBLIC)
                .returns(TypeName.BOOLEAN)
                .addAnnotation(submitAnnotation)
                .addJavadoc(String.format(REMOVE_METHOD_JAVA_DOC,
                        enclosedElement.getSimpleName())
                )
                .addStatement("return $T.remove2($N, $L, $S)",
                        ClassName.get(PACKAGE_NAME, HANNIBAI),
                        "mSharedPreferencesName",
                        "mId",
                        enclosedElement.getSimpleName())
                .build();
    }
}
 
Example 28
Project: remoter   File: FieldBuilder.java   View source code 5 votes vote down vote up
private void addCommonFields(TypeSpec.Builder classBuilder) {
    //Add descriptor
    classBuilder.addField(FieldSpec.builder(ClassName.get(String.class), "DESCRIPTOR")
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
            .initializer("\"" + getRemoterInterfacePackageName() + "." + getRemoterInterfaceClassName() + "\"")
            .build());
    classBuilder.addField(FieldSpec.builder(TypeName.INT, "REMOTER_EXCEPTION_CODE")
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
            .initializer("-99999")
            .build());

}
 
Example 29
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 30
Project: raml-java-tools   File: ObjectTypeHandlerTest.java   View source code 5 votes vote down vote up
@Test
public void usingComposedTypes() throws Exception {

    final Api api = RamlLoader.load(this.getClass().getResourceAsStream("using-composed-type.raml"), ".");
    ObjectTypeHandler handler = new ObjectTypeHandler(RamlLoader.findTypes("foo", api.types()));

    CreationResult r = handler.create(createGenerationContext(api));

    System.err.println(r.getInterface().toString());
    System.err.println(r.getImplementation().toString());

    assertThat(r.getInterface(), is(allOf(
            name(equalTo("Foo")),
            methods(contains(
                    allOf(methodName(equalTo("getName")), returnType(equalTo(ClassName.get("", "Composed")))),
                    allOf(methodName(equalTo("setName")), parameters(contains(type(equalTo(ClassName.get("", "Composed"))))))
            ))
    )));

    assertThat(r.getImplementation().get(), is(allOf(
            name(equalTo("FooImpl")),
            fields(contains(
                    allOf(fieldName(equalTo("name")), fieldType(equalTo(ClassName.get("", "Composed"))))
            )),
            methods(contains(
                    allOf(methodName(equalTo("getName")), returnType(equalTo(ClassName.get("", "Composed")))),
                    allOf(methodName(equalTo("setName")), parameters(contains(type(equalTo(ClassName.get("", "Composed")))))))
            ))
    ));
}
 
Example 31
Project: auto-adapter   File: AnnotatedModel.java   View source code 5 votes vote down vote up
private ClassName getViewBinderClassName(final TypeElement model) {
    if (annotationValue.isPresent()) {
        Object value = annotationValue.get().getValue();
        if (value instanceof String) {
            return ClassName.bestGuess((String) value);
        } else {
            TypeMirror mirror = (TypeMirror) annotationValue.get().getValue();
            return getClassNameFrom(typeUtils.asElement(mirror));
        }

    } else {
        return ClassName.get(LIBRARY_PACKAGE, model.getSimpleName() + "ViewBinder");
    }
}
 
Example 32
Project: remoter   File: ClassBuilder.java   View source code 5 votes vote down vote up
public JavaFile.Builder buildProxyClass() {
    ClassName proxyClassName = getProxyClassName();

    TypeSpec.Builder proxyClassBuilder = TypeSpec
            .classBuilder(proxyClassName.simpleName())
            .addModifiers(Modifier.PUBLIC)
            .addSuperinterface(TypeName.get(getRemoterInterfaceElement().asType()));


    for (TypeParameterElement typeParameterElement : ((TypeElement) getRemoterInterfaceElement()).getTypeParameters()) {
        proxyClassBuilder.addTypeVariable(TypeVariableName.get(typeParameterElement.toString()));
    }

    //constructor
    proxyClassBuilder.addMethod(MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addJavadoc("Initialize this {@link " + getProxyClassName().simpleName() + "} with the given {@link IBinder}\n\n")
            .addJavadoc("@param binder An {@link IBinder} that exposes a remote {@link " + getRemoterInterfaceClassName() + "}\n")
            .addParameter(ClassName.get("android.os", "IBinder"), "binder")
            .addStatement("this.mRemote = binder").build());


    getBindingManager().getFieldBuilder(getRemoterInterfaceElement()).addProxyFields(proxyClassBuilder);
    getBindingManager().getMethoddBuilder(getRemoterInterfaceElement()).addProxyMethods(proxyClassBuilder);

    proxyClassBuilder.addJavadoc("Wraps a remote {@link IBinder} that implements {@link " + getRemoterInterfaceClassName() + "} interface\n");
    proxyClassBuilder.addJavadoc("<p>\n");
    proxyClassBuilder.addJavadoc("Autogenerated by <a href=\"https://bit.ly/Remoter\">Remoter</a>\n");
    proxyClassBuilder.addJavadoc("@see " + getStubClassName().simpleName() + "\n");

    return JavaFile.builder(proxyClassName.packageName(), proxyClassBuilder.build());
}
 
Example 33
Project: gwt-jackson-apt   File: DeserializerGenerator.java   View source code 5 votes vote down vote up
public String generate(TypeMirror beanType, String packageName, Name beanName) {
    String generatedClassName = Type.deserializerName(packageName, beanName.toString());
    if (!TypeRegistry.containsDeserializer(beanType.toString())) {
        try {
            new AptDeserializerBuilder(beanType, filer)
                    .generate(beanName, packageName);
            TypeRegistry.registerDeserializer(beanType.toString(), ClassName.bestGuess(generatedClassName));
        } catch (IOException e) {
            throw new DeserializerGenerator.DeserializerGenerationFailedException(beanType.toString());
        }
    }
    return generatedClassName;
}
 
Example 34
Project: arez   File: ComponentDescriptor.java   View source code 5 votes vote down vote up
@Nonnull
private MethodSpec buildPreDisposeMethod()
{
  return MethodSpec.methodBuilder( "preDispose" ).
    addModifiers( Modifier.FINAL ).
    addAnnotation( ClassName.bestGuess( Constants.PRE_DISPOSE_ANNOTATION_CLASSNAME ) ).
    addStatement( "this.$N.forEach( e -> $T.dispose( e ) )",
                  ENTITYLIST_FIELD_NAME,
                  GeneratorUtil.DISPOSABLE_CLASSNAME ).
    addStatement( "this.$N.clear()", ENTITIES_FIELD_NAME ).
    addStatement( "$N().reportChanged()", GET_OBSERVABLE_METHOD ).
    build();
}
 
Example 35
Project: smartkey   File: SharePreferenceGenerator.java   View source code 5 votes vote down vote up
void processGet(ElementDescription elem, MethodSpec.Builder builder) {
    if(elem.code != null && elem.code.isGeneric()) {
        String[] types = elem.code.genericTypes();
        Object[] args = new Object[types.length + 2];
        args[0] = ClazzNames.GSON_HELPER;
        args[1] = ClazzNames.STORAGE_HELPER;
        args[2] = ClazzNames.TYPE_TOKEN;
        for (int i=3; i<args.length; i++) {
            args[i] = ClassName.bestGuess(types[i-2]);
        }
        builder.addStatement("return $T.fromJson($T.get(app, \""
                + elem.key + "\"), new $T<" + elem.code.genericTypes()[0]+">(){}.getType())",
                args);
    } else if(isBool(elem)) {
        builder.addStatement("return $T.getBoolean(app, \"" + elem.key + "\")", ClazzNames.STORAGE_HELPER);
    } else if(isFloat(elem)) {
        builder.addStatement("return $T.getFloat(app, \"" + elem.key + "\")", ClazzNames.STORAGE_HELPER);
    } else if(isInt(elem)) {
        builder.addStatement("return $T.getInt(app, \"" + elem.key + "\")", ClazzNames.STORAGE_HELPER);
    } else if(isLong(elem)) {
        builder.addStatement("return $T.getLong(app, \"" + elem.key + "\")", ClazzNames.STORAGE_HELPER);
    } else if(isString(elem)) {
        builder.addStatement("return $T.get(app, \"" + elem.key + "\")", ClazzNames.STORAGE_HELPER);
    } else if(isStringSet(elem)) {
        builder.addStatement("return $T.getStringSet(app, \"" + elem.key + "\")", ClazzNames.STORAGE_HELPER);
    } else {
        builder.addStatement("return $T.fromJson($T.get(app, \""
                + elem.key + "\"), " + elem.fieldType.toString()+".class)",
                ClazzNames.GSON_HELPER,
                ClazzNames.STORAGE_HELPER);
    }
}
 
Example 36
Project: Spyglass   File: TestGetDefaultMethodGenerator.java   View source code 5 votes vote down vote up
@Test
public void testGenerateFor_defaultToStringResourceAnnotationSupplied() {
	final Element element = avatarRule.getElementWithUniqueId("string resource");
	final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(
			element,
			DefaultToStringResource.class);

	final MethodSpec generatedMethod = generator.generateFor(mirror);

	assertThat(generatedMethod, is(notNullValue()));
	checkMethodSignature(generatedMethod, ClassName.get(String.class));
	checkCompiles(generatedMethod);
}
 
Example 37
Project: GitHub   File: AppModuleGenerator.java   View source code 5 votes vote down vote up
private MethodSpec generateGetExcludedModuleClasses(Set<String> excludedClassNames) {
  TypeName wildCardOfObject = WildcardTypeName.subtypeOf(Object.class);
  ParameterizedTypeName classOfWildcardOfObjet =
      ParameterizedTypeName.get(ClassName.get(Class.class), wildCardOfObject);
  ParameterizedTypeName setOfClassOfWildcardOfObject =
      ParameterizedTypeName.get(ClassName.get(Set.class), classOfWildcardOfObjet);
  ParameterizedTypeName hashSetOfClassOfWildcardOfObject =
      ParameterizedTypeName.get(ClassName.get(HashSet.class), classOfWildcardOfObjet);
  MethodSpec.Builder builder = MethodSpec.methodBuilder("getExcludedModuleClasses")
      .addModifiers(Modifier.PUBLIC)
      .addAnnotation(Override.class)
      .returns(setOfClassOfWildcardOfObject);

  if (excludedClassNames.isEmpty()) {
    builder.addStatement("return $T.emptySet()", Collections.class);
  } else {
    builder.addStatement(
        "$T excludedClasses = new $T()", setOfClassOfWildcardOfObject,
        hashSetOfClassOfWildcardOfObject);
    for (String excludedClassName : excludedClassNames) {
      // TODO: Remove this when we no longer support manifest parsing.
      // Using a Literal ($L) instead of a type ($T) to get a fully qualified import that allows
      // us to suppress deprecation warnings. Aimed at deprecated GlideModules.
      builder.addStatement("excludedClasses.add($L.class)", excludedClassName);
    }
    builder.addStatement("return excludedClasses");
  }

  return builder.build();
}
 
Example 38
Project: GitHub   File: JsonObjectHolder.java   View source code 5 votes vote down vote up
public TypeName getParameterizedParentTypeName() {
    if (parentUsedTypeParameters.size() > 0) {
        List<TypeName> usedParameters = new ArrayList<>();
        for (String parameter : parentUsedTypeParameters) {
            if (parameter.indexOf(".") > 0) {
                usedParameters.add(ClassName.bestGuess(parameter));
            } else {
                usedParameters.add(TypeVariableName.get(parameter));
            }
        }
        return ParameterizedTypeName.get((ClassName)parentTypeName, usedParameters.toArray(new TypeName[usedParameters.size()]));
    } else {
        return parentTypeName;
    }
}
 
Example 39
Project: Spyglass   File: GetDefaultMethodGenerator.java   View source code 5 votes vote down vote up
@Override
public MethodSpec supplyFor(final AnnotationMirror anno) {
	final String enumClass = getLiteralFromAnnotation(anno, "enumClass");
	final String enumClassName = enumClass.substring(0, enumClass.lastIndexOf(".class"));

	final CodeBlock body = CodeBlock
			.builder()
			.addStatement("final int ordinal = $L", getLiteralFromAnnotation(anno, "ordinal"))
			.add("\n")
			.beginControlFlow(
					"if (ordinal < 0 || $1T.values().length - 1 < ordinal)",
					ClassName.bestGuess(enumClassName))
			.addStatement(
					"throw new $T($L)",
					RuntimeException.class,
					"\"Ordinal \" + ordinal + \" is out of bounds for enum " + enumClassName + "\"")
			.endControlFlow()
			.add("\n")
			.addStatement(
					"return $T.values()[ordinal]",
					ClassName.bestGuess(enumClassName))
			.build();

	return getBaseMethodSpec()
			.returns(ClassName.bestGuess(enumClassName))
			.addCode(body)
			.build();
}
 
Example 40
Project: limitjson   File: LJSONAnnotatedClass.java   View source code 5 votes vote down vote up
public static void toWrite(ProcessorHelper helper, LJSONTypeElement ljsonElement, Filer filer) throws IOException {

        // create common ClassName
        ClassName thisObj = ClassName.bestGuess(ljsonElement.getTypeName());
        ClassName jsonObject = ClassName.get("org.json", "JSONObject");

        MethodSpec.Builder createMethod = MethodSpec.methodBuilder("create")
                .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                .returns(thisObj)
                .addParameter(ClassName.get(String.class), "json", Modifier.FINAL)
                .addParameter(TypeName.BOOLEAN, "allowNull", Modifier.FINAL)
                .addStatement("$T thisObj = new $T()", thisObj, thisObj)
                .beginControlFlow("try")
                .addStatement("$T root = new $T(json)", jsonObject, jsonObject);

        List<LIMITJSONVariable> ljsonVariableElements = ljsonElement.getVariableElements();
        addLJSONVariable(helper, createMethod, ljsonVariableElements);

        createMethod.nextControlFlow("catch (Exception e)")
                .beginControlFlow("if (allowNull)")
                .addStatement("return null")
                .endControlFlow()
                .endControlFlow();

        createMethod.addStatement("return thisObj");
        // generate whole class
        TypeSpec finderClass = TypeSpec.classBuilder(ljsonElement.getTypeName() + "$$CREATOR")
                .addModifiers(Modifier.PUBLIC)
//                .addSuperinterface(ParameterizedTypeName.get(ClassName.get(CORE_PACKAGE_NAME, "Core"), TypeName.get(classElement.asType())))
                .addMethod(createMethod.build())
//                .addMethod(parseIntentBuilder.build())
//                .addMethod(saveInstanceStateBuilder.build())
                .build();

        String packageName = ljsonElement.getTypePackageName();
        // generate file
        JavaFile.builder(packageName, finderClass).build().writeTo(filer);
    }