Java Code Examples for com.squareup.javapoet.MethodSpec

The following are top voted examples for showing how to use com.squareup.javapoet.MethodSpec. 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: Spyglass   File: TestSpecificValueIsAvailableMethodGenerator.java   View source code 6 votes vote down vote up
private void checkCompiles(final MethodSpec method) {
	final TypeSpec wrapperTypeSpec = CallerDef
			.getNewCallerSubclassPrototype("Wrapper", TypeName.OBJECT)
			.addMethod(CallerDef.getNewCallMethodPrototype().build())
			.addMethod(CallerDef.getNewConstructorPrototype(TypeName.OBJECT).build())
			.addMethod(method)
			.build();

	final JavaFile wrapperJavaFile = JavaFile
			.builder("", wrapperTypeSpec)
			.build();

	final Set<JavaFile> filesToCompile = new HashSet<>();
	filesToCompile.add(wrapperJavaFile);
	filesToCompile.add(CallerDef.SRC_FILE);

	CompileChecker.checkCompiles(filesToCompile);
}
 
Example 2
Project: GitHub   File: ObjectMapperInjector.java   View source code 6 votes vote down vote up
private MethodSpec getParseFieldMethod() {
    MethodSpec.Builder builder = MethodSpec.methodBuilder("parseField")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .addParameter(mJsonObjectHolder.objectTypeName, "instance")
            .addParameter(String.class, "fieldName")
            .addParameter(JsonParser.class, JSON_PARSER_VARIABLE_NAME)
            .addException(IOException.class);

    int parseFieldLines = addParseFieldLines(builder);

    if (mJsonObjectHolder.hasParentClass()) {
        if (parseFieldLines > 0) {
            builder.nextControlFlow("else");
            builder.addStatement("$L.parseField(instance, fieldName, $L)", PARENT_OBJECT_MAPPER_VARIABLE_NAME, JSON_PARSER_VARIABLE_NAME);
        } else {
            builder.addStatement("$L.parseField(instance, fieldName, $L)", PARENT_OBJECT_MAPPER_VARIABLE_NAME, JSON_PARSER_VARIABLE_NAME);
        }
    }

    if (parseFieldLines > 0) {
        builder.endControlFlow();
    }

    return builder.build();
}
 
Example 3
Project: GeneratorX   File: CodeGenerator.java   View source code 6 votes vote down vote up
/**
 * 生成set方法
 * @param variable
 * @return String getS(String s)
 */
protected MethodSpec makeSetMethod(String variable) {

    //方法内的几行code this.variable = var;
    StringBuilder builder = new StringBuilder();
    builder.append(String.format("this.%s", variable));
    builder.append(" = " + variable);

    //方法的 头 和 尾
    return methodBuilder(
            "set" + com.androidyuan.Helper.ClsHelper.bigFirstString(variable)).addModifiers(
            PUBLIC).returns(
            TypeName.VOID)//public void setField
            .addParameter(getFiledType(variable), variable)//(String variableNames)
            .addStatement(builder.toString())// 添加方法内的几行代码到这里
            .build();
}
 
Example 4
Project: autoproxy   File: RetNumberGenerator.java   View source code 6 votes vote down vote up
public boolean compose(@NonNull final Type returnType,
                       @NonNull @RetNumber final String type,
                       @NonNull final MethodSpec.Builder builder) {
    final Class<?> output = PRIMITIVES.get(returnType.toString());

    if (RetNumber.MAX.equals(type)) {
        builder.addStatement("return $T.MAX_VALUE", output);

        return true;
    } else if (RetNumber.MIN.equals(type)) {
        builder.addStatement("return $T.MIN_VALUE", output);

        return true;
    } else if (RetNumber.MINUS_ONE.equals(type)) {
        builder.addStatement("return -1");

        return true;
    } else if (RetNumber.ZERO.equals(type)) {
        builder.addStatement("return 0");

        return true;
    }

    return false;
}
 
Example 5
Project: Jerkoff   File: PojoCreatorImpl.java   View source code 6 votes vote down vote up
/**
 * genera il metodo di test per method di clazz
 * 
 * @param count
 * @param method
 * @param clazz
 * @param infoFromMongoDb
 * @param methodOutput
 * @return
 */
private MethodSpec getMethodSpec(int count, Method method, Class<?> clazz, Document methodInputs,
		Document methodOutput) {
	String result = getAssignmentOfMethodResult(method);
	String expected = getExpectedResultAsBooleanAssert(method, methodOutput);
	MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getName() + count + TEST);
	/*
	 * for non spring test
	 */
	String invokerName = getInvokerName(method, clazz, methodInputs, methodBuilder);
	String params = getParams(method, methodBuilder, methodInputs);
	AnnotationSpec.Builder annSpecBuilder = AnnotationSpec.builder(Test.class);
	addExpectedExceptionIfAny(methodInputs, annSpecBuilder);
	AnnotationSpec annTestSpec = annSpecBuilder.build();
	methodBuilder.addAnnotation(annTestSpec)
			.addStatement(result + invokerName + ".$N(" + params + ")", method.getName())
			.addModifiers(Modifier.PUBLIC);
	methodBuilder.addStatement("$L.assertTrue(" + expected + ")", Assert.class.getName());
	methodBuilder.addJavadoc("\n");
	return methodBuilder.build();
}
 
Example 6
Project: DeeplinkRouter   File: DeeplinkRouterProcessor.java   View source code 6 votes vote down vote up
private void innerGenerateRouterInit(MethodSpec.Builder methodBuilder)
{
    TypeSpec routerInit = TypeSpec.classBuilder(ROUTER_INIT_CLASS_NAME)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addSuperinterface(ClassName.get(ROUTER_API_PACKAGE_NAME, ROUTER_INIT_INTERFACE_NAME))
            .addMethod(methodBuilder.build())
            .build();
    try
    {
        JavaFile.builder(ROUTER_API_PACKAGE_NAME, routerInit)
                .build()
                .writeTo(mFiler);
    }
    catch (Exception e)
    {
        error("Failed to generate file %s", routerInit.name);
    }
}
 
Example 7
Project: remoter   File: RemoteBuilder.java   View source code 6 votes vote down vote up
/**
 * Recursevely Visit extended elements
 */
private int processRemoterElements(TypeSpec.Builder classBuilder, Element element, int methodIndex, ElementVisitor elementVisitor, MethodSpec.Builder methodBuilder) {
    if (element instanceof TypeElement) {
        for (TypeMirror typeMirror : ((TypeElement) element).getInterfaces()) {
            if (typeMirror instanceof DeclaredType) {
                Element superElement = ((DeclaredType) typeMirror).asElement();
                methodIndex = processRemoterElements(classBuilder, superElement, methodIndex, elementVisitor, methodBuilder);
            }
        }
        for (Element member : element.getEnclosedElements()) {
            if (member.getKind() == ElementKind.METHOD) {
                elementVisitor.visitElement(classBuilder, member, methodIndex, methodBuilder);
                methodIndex++;
            }
        }
    }
    return methodIndex;
}
 
Example 8
Project: aws-sdk-java-v2   File: SyncClientInterface.java   View source code 6 votes vote down vote up
private List<MethodSpec> operationMethodSpec(OperationModel opModel) {
    List<MethodSpec> methods = new ArrayList<>();

    if (opModel.getInputShape().isSimpleMethod()) {
        methods.add(simpleMethod(opModel));
    }

    methods.add(operationMethodSignature(model, opModel)
                        .addModifiers(Modifier.DEFAULT)
                        .addStatement("throw new $T()", UnsupportedOperationException.class)
                        .build());

    if (!opModel.isStreaming()) {
        methods.add(operationBuilderConsumer(model, opModel));
    }
    methods.addAll(streamingSimpleMethods(opModel));
    methods.addAll(paginatedMethods(opModel));

    return methods;
}
 
Example 9
Project: Spyglass   File: GetDefaultMethodGenerator.java   View source code 6 votes vote down vote up
@Override
public MethodSpec supplyFor(final AnnotationMirror anno) {
	final CodeBlock body = CodeBlock
			.builder()
			.addStatement(
					"return $T.getColorStateList($N(), $L)",
					AndroidClassNames.CONTEXT_COMPAT,
					CallerDef.GET_CONTEXT,
					getLiteralFromAnnotation(anno, "resId"))
			.build();

	return getBaseMethodSpec()
			.returns(AndroidClassNames.COLOR_STATE_LIST)
			.addCode(body)
			.build();
}
 
Example 10
Project: aws-sdk-java-v2   File: BaseClientBuilderClass.java   View source code 6 votes vote down vote up
private MethodSpec serviceDefaultsMethod() {
    String requestHandlerDirectory = Utils.packageToDirectory(model.getMetadata().getFullClientPackageName());
    String requestHandlerPath = String.format("%s/execution.interceptors", requestHandlerDirectory);

    boolean crc32FromCompressedDataEnabled = model.getCustomizationConfig().isCalculateCrc32FromCompressedData();

    return MethodSpec.methodBuilder("serviceDefaults")
                     .addAnnotation(Override.class)
                     .addModifiers(Modifier.PROTECTED, Modifier.FINAL)
                     .returns(ClientConfigurationDefaults.class)
                     .addCode("return $T.builder()\n", ServiceBuilderConfigurationDefaults.class)
                     .addCode("         .defaultSignerProvider(this::defaultSignerProvider)\n")
                     .addCode("         .addRequestHandlerPath($S)\n", requestHandlerPath)
                     .addCode("         .crc32FromCompressedDataEnabled($L)\n", crc32FromCompressedDataEnabled)
                     .addCode("         .build();\n")
                     .build();
}
 
Example 11
Project: Witch-Android   File: OnBindPropertySetter.java   View source code 6 votes vote down vote up
@Override
public String create() {
    MethodSpec method = MethodSpec.methodBuilder("onBind")
            .addModifiers(Modifier.PUBLIC)
            .addParameter(viewType, "target")
            .addParameter(valueType, "value")
            .returns(void.class)
            .addStatement("$N.$N(value)", "target", getPropertySetter(property))
            .build();

    TypeSpec anonymous = TypeSpec.anonymousClassBuilder("")
            .addSuperinterface(ParameterizedTypeName.get(TypeUtils.SYNC_ON_BIND, viewType, valueType))
            .addMethod(method)
            .build();

    return anonymous.toString();
}
 
Example 12
Project: Barricade   File: CodeGenerator.java   View source code 6 votes vote down vote up
private static MethodSpec.Builder generateConstructorBuilder(
    HashMap<String, BarricadeResponseSet> values, Messager messager) {
  MethodSpec.Builder methodBuilder = MethodSpec.constructorBuilder().addModifiers(PUBLIC);
  methodBuilder.addStatement("configs = new HashMap<>()");

  for (Map.Entry<String, BarricadeResponseSet> entry : values.entrySet()) {
    BarricadeResponseSet barricadeResponseSet = entry.getValue();

    String listName = "barricadeResponsesFor" + entry.getKey();

    methodBuilder.addStatement("$T<$T> " + listName + " = new $T<>()", List.class,
        BarricadeResponse.class, ArrayList.class);

    for (BarricadeResponse barricadeResponse : barricadeResponseSet.responses) {
      methodBuilder.addStatement(listName + ".add(new $T($L, $S, $S))", BarricadeResponse.class,
          barricadeResponse.statusCode, barricadeResponse.responseFileName,
          barricadeResponse.contentType);
    }

    methodBuilder.addStatement(
        "configs.put($S, new $T(" + listName + ", " + barricadeResponseSet.defaultIndex + "))",
        entry.getKey(), TYPE_BARRICADE_RESPONSE_SET);
  }
  return methodBuilder;
}
 
Example 13
Project: aws-sdk-java-v2   File: SyncClientInterface.java   View source code 6 votes vote down vote up
private static MethodSpec.Builder operationBaseSignature(IntermediateModel model,
                                                         OperationModel opModel,
                                                         Consumer<MethodSpec.Builder> addFirstParameter,
                                                         SimpleMethodOverload simpleMethodOverload,
                                                         String methodName) {

    TypeName responseType = ClassName.get(model.getMetadata().getFullModelPackageName(),
                                          opModel.getReturnType().getReturnType());
    TypeName returnType = opModel.hasStreamingOutput() ? STREAMING_TYPE_VARIABLE : responseType;

    final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName)
                                                       .returns(returnType)
                                                       .addModifiers(Modifier.PUBLIC)
                                                       .addJavadoc(opModel.getDocs(model, ClientType.SYNC,
                                                                                   simpleMethodOverload))
                                                       .addExceptions(getExceptionClasses(model, opModel));

    addFirstParameter.accept(methodBuilder);
    streamingMethod(methodBuilder, opModel, responseType);

    return methodBuilder;
}
 
Example 14
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 15
Project: GitHub   File: RequestManagerGenerator.java   View source code 6 votes vote down vote up
/**
 * Generates overrides of existing RequestManager methods so that they return our generated
 * RequestBuilder subtype.
 */
private MethodSpec generateRequestManagerRequestBuilderMethodOverride(
    ExecutableElement methodToOverride) {
   // We've already verified that this method returns a RequestBuilder and RequestBuilders have
  // exactly one type argument, so this is safe unless those assumptions change.
  TypeMirror typeArgument =
      ((DeclaredType) methodToOverride.getReturnType()).getTypeArguments().get(0);

  ParameterizedTypeName generatedRequestBuilderOfType =
      ParameterizedTypeName.get(generatedRequestBuilderClassName, ClassName.get(typeArgument));

  MethodSpec.Builder builder = ProcessorUtil.overriding(methodToOverride)
      .returns(generatedRequestBuilderOfType)
      .addCode(
          ProcessorUtil.generateCastingSuperCall(
              generatedRequestBuilderOfType, methodToOverride));

  for (AnnotationMirror mirror : methodToOverride.getAnnotationMirrors()) {
    builder.addAnnotation(AnnotationSpec.get(mirror));
  }
  return builder.build();
}
 
Example 16
Project: Spyglass   File: GetDefaultMethodGenerator.java   View source code 6 votes vote down vote up
@Override
public MethodSpec supplyFor(final AnnotationMirror anno) {
	final String unitFull = getLiteralFromAnnotation(anno, "unit");
	final String unitShort = unitFull.substring(unitFull.lastIndexOf(".") + 1);

	final CodeBlock body = CodeBlock
			.builder()
			.addStatement(
					"$T metrics = $N().getResources().getDisplayMetrics()",
					AndroidClassNames.DISPLAY_METRICS,
					CallerDef.GET_CONTEXT)
			.addStatement(
					"return $1T.applyDimension($1T.$2L, $3L, metrics)",
					AndroidClassNames.TYPED_VALUE,
					getComplexUnitLiteral(unitShort),
					getLiteralFromAnnotation(anno, "value"))
			.build();

	return getBaseMethodSpec()
			.returns(Number.class)
			.addCode(body)
			.build();
}
 
Example 17
Project: aws-sdk-java-v2   File: AsyncClientInterface.java   View source code 6 votes vote down vote up
/**
 * @param opModel Operation to generate simple methods for.
 * @return All simple method overloads for a given operation.
 */
private List<MethodSpec.Builder> addMethodOverloads(OperationModel opModel) {
    List<MethodSpec.Builder> methodOverloads = new ArrayList<>();
    if (opModel.getInputShape().isSimpleMethod()) {
        methodOverloads.add(noArgSimpleMethod(opModel));
    }
    if (opModel.hasStreamingInput()) {
        methodOverloads.add(streamingInputFileSimpleMethod(opModel));
    }
    if (opModel.hasStreamingOutput()) {
        methodOverloads.add(streamingOutputFileSimpleMethod(opModel));
    }
    if (!opModel.isStreaming()) {
        methodOverloads.add(builderConsumerMethod(opModel));
    }
    return methodOverloads;
}
 
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: shoebill   File: ShoebillProcessor.java   View source code 5 votes vote down vote up
private MethodSpec getSingletonGetterMethod(ClassName className, FieldSpec singletonField) {
    return MethodSpec
            .methodBuilder("getInstance")
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .returns(className)
            .addStatement("return $N", singletonField)
            .build();
}
 
Example 20
Project: PreferenceRoom   File: PreferenceFieldMethodGenerator.java   View source code 5 votes vote down vote up
private MethodSpec generateGetter() {
    return MethodSpec.methodBuilder(getGetterPrefixName())
            .addModifiers(PUBLIC)
            .addStatement("return " + getGetterStatement(), preference, keyField.keyName, keyField.value)
            .returns(keyField.typeName)
            .build();
}
 
Example 21
Project: aws-sdk-java-v2   File: NonCollectionSetters.java   View source code 5 votes vote down vote up
public MethodSpec fluentConvenience(TypeName returnType, ConvenienceTypeOverload overload) {
    return MethodSpec.methodBuilder(memberModel().getFluentSetterMethodName())
                     .addModifiers(Modifier.PUBLIC)
                     .addParameter(PoetUtils.classNameFromFqcn(overload.getConvenienceType()), memberAsParameter().name)
                     .addStatement("$L(new $T().adapt($L))",
                                   memberModel().getFluentSetterMethodName(),
                                   PoetUtils.classNameFromFqcn(overload.getTypeAdapterFqcn()),
                                   memberAsParameter().name)
                     .addStatement("return this")
                     .returns(returnType)
                     .build();
}
 
Example 22
Project: MRouter   File: AutowireRouteClass.java   View source code 5 votes vote down vote up
private void addInitStatement(MethodSpec.Builder result, AutowireField field) {
    CodeBlock.Builder builder = CodeBlock.builder();
    if (field.getTypeKind() == FieldTypeKind.PARCELABLE_ARRAY) {
        builder.add("android.os.Parcelable[] parcelables = target.$L;\n",
                CodeBlock.of(field.getAssignStatement(), field.getAnnotationValue()))
                .add("target.$L = java.util.Arrays.copyOf(parcelables,parcelables.length, $T.class)",
                        field.getFieldName(),
                        field.getFieldType());
    } else if (field.getTypeKind() == FieldTypeKind.PROVIDER) {
        builder.add("java.lang.Class $L = $T.getInstance().getRoute($S);"
                , field.getFieldName()
                , RouteJavaFileUtils.ROUTE_MANAGER
                , field.getAnnotationValue());
        builder.add("\nif($L !=null){\n", field.getFieldName());
        builder.add("try {\n$L" +
                        "        } catch (InstantiationException e) {\n" +
                        "            e.printStackTrace();\n" +
                        "        } catch (IllegalAccessException e) {\n" +
                        "            e.printStackTrace();\n" +
                        "        }",
                CodeBlock.of("   target.$L = ($T)$L.newInstance();\n",
                        field.getFieldName(), field.getFieldType(), field.getFieldName()));


        builder.add("}");
    } else {
        builder.add("target.$L = ", field.getFieldName());
        if (field.getTypeKind() == FieldTypeKind.SERIALIZABLE) {
            builder.add("($T)target.$L",
                    field.getFieldType(),
                    CodeBlock.of(field.getAssignStatement(), field.getAnnotationValue()));
        } else {
            builder.add("target.$L",
                    CodeBlock.of(field.getAssignStatement(), field.getAnnotationValue()));
        }
    }
    result.addStatement("$L", builder.build());

}
 
Example 23
Project: aws-sdk-java-v2   File: SyncClientInterface.java   View source code 5 votes vote down vote up
private MethodSpec operationBuilderConsumer(IntermediateModel model,
                                            OperationModel opModel) {
    ClassName requestType = ClassName.get(model.getMetadata().getFullModelPackageName(),
                                          opModel.getInput().getVariableType());
    ClassName builder = requestType.nestedClass("Builder");
    TypeName consumer = ParameterizedTypeName.get(ClassName.get(Consumer.class), builder);

    return operationBaseSignature(model, opModel, b -> b.addParameter(consumer, opModel.getInput().getVariableName()))
        .addModifiers(Modifier.DEFAULT)
        .addStatement("return $L($T.builder().apply($L).build())",
                      opModel.getMethodName(),
                      requestType,
                      opModel.getInput().getVariableName())
        .build();
}
 
Example 24
Project: GitHub   File: BindingSet.java   View source code 5 votes vote down vote up
private void addViewBinding(MethodSpec.Builder result, ViewBinding binding) {
  if (binding.isSingleFieldBinding()) {
    // Optimize the common case where there's a single binding directly to a field.
    FieldViewBinding fieldBinding = binding.getFieldBinding();
    CodeBlock.Builder builder = CodeBlock.builder()
        .add("target.$L = ", fieldBinding.getName());

    boolean requiresCast = requiresCast(fieldBinding.getType());
    if (!requiresCast && !fieldBinding.isRequired()) {
      builder.add("source.findViewById($L)", binding.getId().code);
    } else {
      builder.add("$T.find", UTILS);
      builder.add(fieldBinding.isRequired() ? "RequiredView" : "OptionalView");
      if (requiresCast) {
        builder.add("AsType");
      }
      builder.add("(source, $L", binding.getId().code);
      if (fieldBinding.isRequired() || requiresCast) {
        builder.add(", $S", asHumanDescription(singletonList(fieldBinding)));
      }
      if (requiresCast) {
        builder.add(", $T.class", fieldBinding.getRawType());
      }
      builder.add(")");
    }
    result.addStatement("$L", builder.build());
    return;
  }

  List<MemberViewBinding> requiredBindings = binding.getRequiredBindings();
  if (requiredBindings.isEmpty()) {
    result.addStatement("view = source.findViewById($L)", binding.getId().code);
  } else if (!binding.isBoundToRoot()) {
    result.addStatement("view = $T.findRequiredView(source, $L, $S)", UTILS,
        binding.getId().code, asHumanDescription(requiredBindings));
  }

  addFieldBinding(result, binding);
  addMethodBindings(result, binding);
}
 
Example 25
Project: aws-sdk-java-v2   File: ModelMethodOverrides.java   View source code 5 votes vote down vote up
public MethodSpec equalsMethod(ShapeModel shapeModel) {
    ClassName className = poetExtensions.getModelClass(shapeModel.getShapeName());
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("equals")
                                                 .returns(boolean.class)
                                                 .addAnnotation(Override.class)
                                                 .addModifiers(Modifier.PUBLIC)
                                                 .addParameter(Object.class, "obj")

                                                 .beginControlFlow("if (this == obj)")
                                                 .addStatement("return true")
                                                 .endControlFlow()

                                                 .beginControlFlow("if (obj == null)")
                                                 .addStatement("return false")
                                                 .endControlFlow()

                                                 .beginControlFlow("if (!(obj instanceof $T))", className)
                                                 .addStatement("return false")
                                                 .endControlFlow();

    if (!shapeModel.getNonStreamingMembers().isEmpty()) {
        methodBuilder.addStatement("$T other = ($T) obj", className, className);
    }

    final List<MemberModel> memberModels = shapeModel.getNonStreamingMembers();
    final CodeBlock.Builder memberEqualsStmt = CodeBlock.builder();
    if (memberModels.isEmpty()) {
        memberEqualsStmt.addStatement("return true");
    } else {
        memberEqualsStmt.add("return ");
        memberEqualsStmt.add(memberModels.stream().map(m -> {
            final String getterName = m.getFluentGetterMethodName();
            return CodeBlock.builder().add("$T.equals($N(), other.$N())", Objects.class, getterName, getterName).build();
        }).collect(PoetCollectors.toDelimitedCodeBlock("&&")));
        memberEqualsStmt.add(";");
    }

    return methodBuilder.addCode(memberEqualsStmt.build()).build();
}
 
Example 26
Project: aws-sdk-java-v2   File: AsyncClientInterface.java   View source code 5 votes vote down vote up
private MethodSpec create() {
    return MethodSpec.methodBuilder("create")
                     .returns(className)
                     .addModifiers(Modifier.STATIC, Modifier.PUBLIC)
                     .addJavadoc("Create a {@link $T} with the region loaded from the {@link $T} and credentials loaded "
                                 + "from the {@link $T}.",
                                 className,
                                 DefaultAwsRegionProviderChain.class,
                                 DefaultCredentialsProvider.class)
                     .addStatement("return builder().build()")
                     .build();
}
 
Example 27
Project: domino   File: RegisterSendersMethodWriter.java   View source code 5 votes vote down vote up
@Override
protected void registerItem(SenderEntry entry, MethodSpec.Builder methodBuilder) {
    MethodSpec makeMethod = MethodSpec.methodBuilder("make")
            .addModifiers(Modifier.PROTECTED)
            .addAnnotation(Override.class)
            .returns(RequestRestSender.class)
            .addStatement("return new $T()", ClassName.bestGuess(entry.sender))
            .build();
    TypeSpec lazyLoaderType = TypeSpec.anonymousClassBuilder("")
            .superclass(LazyRequestRestSenderLoader.class)
            .addMethod(makeMethod)
            .build();
    methodBuilder.addStatement("registry.registerRequestRestSender($T.class.getCanonicalName(), $L)",
            ClassName.bestGuess(entry.request), lazyLoaderType);
}
 
Example 28
Project: konohana   File: StoreMethods.java   View source code 5 votes vote down vote up
private static MethodSpec buildGetterSpec(StoreDefinition storeDefinition, KeyDefinition keyDefinition) {
    return MethodSpec.methodBuilder(keyDefinition.getGetterName())
            .returns(keyDefinition.getFieldTypeName())
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(AnnotationTypes.NonNull)
            .addStatement("return $T.get(prefs, $S, $T.$L)",
                    keyDefinition.getPrefsAdapter(), keyDefinition.getPrefsKeyName(), storeDefinition.getInterfaceName(), keyDefinition.getFieldName())
            .build();
}
 
Example 29
Project: Spyglass   File: CastWrapperGenerator.java   View source code 5 votes vote down vote up
private CodeBlock generateCharacterCastWrapperFor(final MethodSpec method, final TypeMirror recipient) {
	final TypeMirror methodReturnType = elementHelper.getTypeElement(method.returnType.toString()).asType();

	if (recipient.toString().equals("char")) {
		return CodeBlock.of("(char) $N()", method);

	} else if (recipient.toString().equals(Character.class.getCanonicalName())) {
		return CodeBlock.of("($T) $N()", Character.class, method);

	} else {
		return CodeBlock.of("($T) $N()", methodReturnType, method);
	}
}
 
Example 30
Project: arez   File: ComponentDescriptor.java   View source code 5 votes vote down vote up
/**
 * Generate the getter for component name.
 */
@Nonnull
private MethodSpec buildComponentNameMethod()
  throws ArezProcessorException
{
  final MethodSpec.Builder builder;
  if ( null == _componentName )
  {
    builder = MethodSpec.methodBuilder( GeneratorUtil.NAME_METHOD_NAME );
  }
  else
  {
    builder = MethodSpec.methodBuilder( _componentName.getSimpleName().toString() );
    ProcessorUtil.copyAccessModifiers( _componentName, builder );
    builder.addModifiers( Modifier.FINAL );
  }

  builder.returns( TypeName.get( String.class ) );
  if ( _nameIncludesId )
  {
    builder.addStatement( "return $S + $N()",
                          _type.isEmpty() ? "" : _type + ".",
                          null == _componentId ? GeneratorUtil.ID_FIELD_NAME : _componentId.getSimpleName() );
  }
  else
  {
    builder.addStatement( "return $S", _type );
  }
  return builder.build();
}
 
Example 31
Project: GitHub   File: RequestManagerGenerator.java   View source code 5 votes vote down vote up
@Nullable
TypeSpec generate(
    String generatedCodePackageName, @Nullable TypeSpec requestOptions, TypeSpec requestBuilder,
    Set<String> glideExtensions) {
  generatedRequestBuilderClassName = ClassName.get(generatedCodePackageName, requestBuilder.name);
  return TypeSpec.classBuilder(GENERATED_REQUEST_MANAGER_SIMPLE_NAME)
       .superclass(requestManagerClassName)
       .addJavadoc("Includes all additions from methods in {@link $T}s\n"
               + "annotated with {@link $T}\n"
               + "\n"
               + "<p>Generated code, do not modify\n",
           GlideExtension.class, GlideType.class)
      .addAnnotation(
          AnnotationSpec.builder(SuppressWarnings.class)
              .addMember("value", "$S", "deprecation")
              .build())
       .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
       .addMethod(generateAsMethod(generatedCodePackageName, requestBuilder))
       .addMethod(generateCallSuperConstructor())
       .addMethods(generateAdditionalRequestManagerMethods(glideExtensions))
       .addMethods(generateRequestManagerMethodOverrides())
       .addMethods(
           FluentIterable.from(
               Collections.singletonList(
                   generateOverrideSetRequestOptions(generatedCodePackageName, requestOptions)))
               .filter(Predicates.<MethodSpec>notNull()))
       .build();
}
 
Example 32
Project: react4j   File: Generator.java   View source code 5 votes vote down vote up
@Nonnull
private static MethodSpec.Builder buildFactoryMethod()
{
  return MethodSpec.methodBuilder( "_create" ).
    addAnnotation( NONNULL_CLASSNAME ).
    addModifiers( Modifier.STATIC ).
    returns( REACT_NODE_CLASSNAME ).
    addStatement( "return $T.createElement( TYPE )", REACT_CLASSNAME );
}
 
Example 33
Project: aws-sdk-java-v2   File: AwsServiceBaseResponseSpec.java   View source code 5 votes vote down vote up
private TypeSpec builderInterfaceSpec() {
    return TypeSpec.interfaceBuilder("Builder")
            .addModifiers(Modifier.PUBLIC)
            .addSuperinterface(ClassName.get(AwsResponse.class).nestedClass("Builder"))

            .addMethod(MethodSpec.methodBuilder("build")
                    .addAnnotation(Override.class)
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                    .returns(className())
                    .build())
            .build();
}
 
Example 34
Project: GitHub   File: RequestManagerGenerator.java   View source code 5 votes vote down vote up
private List<MethodSpec> generateAdditionalRequestManagerMethods(
    Set<String> glideExtensions) {
  List<ExecutableElement> requestManagerExtensionMethods =
      processorUtil.findAnnotatedElementsInClasses(glideExtensions, GlideType.class);

  return Lists.transform(requestManagerExtensionMethods,
      new Function<ExecutableElement, MethodSpec>() {
        @Override
        public MethodSpec apply(ExecutableElement input) {
          return generateAdditionalRequestManagerMethod(input);
        }
      });
}
 
Example 35
Project: remoter   File: DoubleParamBuilder.java   View source code 5 votes vote down vote up
@Override
public void readResultsFromProxy(TypeMirror resultType, MethodSpec.Builder methodBuilder) {
    if (resultType.getKind() == TypeKind.ARRAY) {
        methodBuilder.addStatement("result = reply.createDoubleArray()");
    } else {
        methodBuilder.addStatement("result = reply.readDouble()");
    }
}
 
Example 36
Project: GitHub   File: RequestManagerGenerator.java   View source code 5 votes vote down vote up
/**
 * The {@link com.bumptech.glide.request.RequestOptions} subclass should always be our
 * generated subclass type to avoid inadvertent errors where a different subclass is applied that
 * accidentally wipes out some logic in overidden methods in our generated subclass.
 */
@Nullable
private MethodSpec generateOverrideSetRequestOptions(
    String generatedCodePackageName, @Nullable TypeSpec generatedRequestOptions) {
  if (generatedRequestOptions == null) {
    return null;
  }

  Elements elementUtils = processingEnv.getElementUtils();
  TypeElement requestOptionsType =
          elementUtils.getTypeElement(
              RequestOptionsGenerator.REQUEST_OPTIONS_QUALIFIED_NAME);
  TypeElement androidNonNullType =
          elementUtils.getTypeElement("android.support.annotation.NonNull");

  // This class may have just been generated and therefore may not be found if we try to obtain
  // it via Elements, so use just the String version instead.
  String generatedRequestOptionsQualifiedName =
      generatedCodePackageName + "." + generatedRequestOptions.name;

  String methodName = "setRequestOptions";
  String parameterName = "toSet";

  return MethodSpec.methodBuilder(methodName)
      .addAnnotation(Override.class)
      .addModifiers(Modifier.PROTECTED)
      .addParameter(
          ParameterSpec.builder(ClassName.get(requestOptionsType), parameterName)
              .addAnnotation(ClassName.get(androidNonNullType))
              .build())
      .beginControlFlow("if ($N instanceof $L)",
          parameterName, generatedRequestOptionsQualifiedName)
      .addStatement("super.$N($N)", methodName, parameterName)
      .nextControlFlow("else")
      .addStatement("super.setRequestOptions(new $L().apply($N))",
          generatedRequestOptionsQualifiedName, parameterName)
      .endControlFlow()
      .build();
}
 
Example 37
Project: KiiAnnotation   File: BuilderGenerator.java   View source code 5 votes vote down vote up
public static MethodSpec constructorGroupMethod() {
    ClassName className = ClassName.get("com.kii.cloud.storage", "KiiGroup");
    ParameterSpec parameterSpec = ParameterSpec.builder(className, "kiiGroup").build();

    return MethodSpec
            .constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addParameter(parameterSpec)
            .addStatement("this.kiiGroup = kiiGroup")
            .build();
}
 
Example 38
Project: remoter   File: StringParamBuilder.java   View source code 5 votes vote down vote up
@Override
public void writeParamsToStub(VariableElement param, ParamType paramType, String paramName, MethodSpec.Builder methodBuilder) {
    super.writeParamsToStub(param, paramType, paramName, methodBuilder);
    if (param.asType().getKind() == TypeKind.ARRAY) {
        if (paramType == ParamType.OUT) {
            writeOutParamsToStub(param, paramType, paramName, methodBuilder);
        } else {
            methodBuilder.addStatement(paramName + " = data.createStringArray()");
        }
    } else {
        methodBuilder.addStatement(paramName + " = data.readString()");
    }
}
 
Example 39
Project: PreferenceRoom   File: PreferenceEntityGenerator.java   View source code 5 votes vote down vote up
private MethodSpec getEntityNameMethodSpec() {
    return MethodSpec.methodBuilder("getEntityName")
            .addModifiers(PUBLIC)
            .returns(String.class)
            .addStatement("return $S", annotatedClazz.entityName)
            .build();
}
 
Example 40
Project: gendapter   File: ViewHolderClass.java   View source code 5 votes vote down vote up
private MethodSpec getContextMethod() {
    return MethodSpec.methodBuilder("context")
            .addModifiers(Modifier.PROTECTED)
            .returns(context())
            .addStatement("return context")
            .build();
}