Java Code Examples for com.squareup.javapoet.MethodSpec

The following examples show how to use com.squareup.javapoet.MethodSpec. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: domino-jackson   Source File: AbstractMapperGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>makeNewDeserializerMethod.</p>
 * <p>
 * Creates method for build corresponding deserializer for  given beanType. If beanType is
 * basic type, generated code utilize existing deserializers. Otherwise, it creates instances
 * of newly generated ones.
 *
 * @param element
 * @param beanType
 * @return
 */
protected MethodSpec makeNewDeserializerMethod(Element element, TypeMirror beanType) {
    CodeBlock.Builder builder = CodeBlock.builder();
    if (Type.isBasicType(typeUtils.erasure(beanType))) {
        builder.addStatement("return $L", new FieldDeserializersChainBuilder(packageName, getElementType(element)).getInstance(getElementType(element)));
    } else {
        builder.addStatement("return new " + deserializerName(beanType));
    }

    return MethodSpec.methodBuilder("newDeserializer")
            .addModifiers(Modifier.PROTECTED)
            .addAnnotation(Override.class)
            .returns(ParameterizedTypeName.get(ClassName.get(JsonDeserializer.class),
                    ClassName.get(getElementType(element))))
            .addCode(builder.build())
            .build();

}
 
Example 2
Source Project: auto-matter   Source File: AutoMatterProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private MethodSpec collectionVarargSetter(final Descriptor d, final ExecutableElement field) {
  String fieldName = fieldName(field);
  TypeName itemType = genericArgument(d, field, 0);

  MethodSpec.Builder setter = MethodSpec.methodBuilder(fieldName)
      .addModifiers(PUBLIC)
      .addParameter(ArrayTypeName.of(itemType), fieldName)
      .varargs()
      .returns(builderType(d));

  ensureSafeVarargs(setter);

  collectionNullGuard(setter, field);

  setter.addStatement("return $N($T.asList($N))", fieldName, ClassName.get(Arrays.class), fieldName);
  return setter.build();
}
 
Example 3
Source Project: web3j   Source File: SolidityFunctionWrapperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildFunctionConstantSingleValueReturn() throws Exception {
    AbiDefinition functionDefinition =
            new AbiDefinition(
                    true,
                    Arrays.asList(new AbiDefinition.NamedType("param", "uint8")),
                    "functionName",
                    Arrays.asList(new AbiDefinition.NamedType("result", "int8")),
                    "type",
                    false);

    MethodSpec methodSpec = solidityFunctionWrapper.buildFunction(functionDefinition);

    String expected =
            "public org.web3j.protocol.core.RemoteFunctionCall<java.math.BigInteger> functionName(java.math.BigInteger param) {\n"
                    + "  final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_FUNCTIONNAME, \n"
                    + "      java.util.Arrays.<org.web3j.abi.datatypes.Type>asList(new org.web3j.abi.datatypes.generated.Uint8(param)), \n"
                    + "      java.util.Arrays.<org.web3j.abi.TypeReference<?>>asList(new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.generated.Int8>() {}));\n"
                    + "  return executeRemoteCallSingleValueReturn(function, java.math.BigInteger.class);\n"
                    + "}\n";

    assertEquals(methodSpec.toString(), (expected));
}
 
Example 4
Source Project: client-sdk-java   Source File: WasmFunctionWrapper.java    License: Apache License 2.0 6 votes vote down vote up
private static MethodSpec buildDeployWithParams(MethodSpec.Builder methodBuilder, String className, String inputParams, String authName,
		boolean isPayable, boolean withGasProvider) {
	methodBuilder.addStatement("$T encodedConstructor = $T.encodeConstructor($L, $T.asList($L))", String.class, WasmFunctionEncoder.class, BINARY,
			Arrays.class, inputParams);

	if (isPayable && !withGasProvider) {
		methodBuilder.addStatement("return deployRemoteCall($L.class, $L, $L, $L, $L, encodedConstructor, $L)", className, WEB3J, authName,
				GAS_PRICE, GAS_LIMIT, INITIAL_VALUE);
		methodBuilder.addAnnotation(Deprecated.class);
	} else if (isPayable && withGasProvider) {
		methodBuilder.addStatement("return deployRemoteCall($L.class, $L, $L, $L, encodedConstructor, $L)", className, WEB3J, authName,
				CONTRACT_GAS_PROVIDER, INITIAL_VALUE);
	} else if (!isPayable && !withGasProvider) {
		methodBuilder.addStatement("return deployRemoteCall($L.class, $L, $L, $L, $L, encodedConstructor)", className, WEB3J, authName, GAS_PRICE,
				GAS_LIMIT);
		methodBuilder.addAnnotation(Deprecated.class);
	} else {
		methodBuilder.addStatement("return deployRemoteCall($L.class, $L, $L, $L, encodedConstructor)", className, WEB3J, authName,
				CONTRACT_GAS_PROVIDER);
	}
	return methodBuilder.build();
}
 
Example 5
Source Project: Moxy   Source File: ViewStateClassGenerator.java    License: MIT License 6 votes vote down vote up
private TypeSpec generateCommandClass(ViewMethod method, TypeName viewTypeName) {
	MethodSpec applyMethod = MethodSpec.methodBuilder("apply")
			.addAnnotation(Override.class)
			.addModifiers(Modifier.PUBLIC)
			.addParameter(viewTypeName, "mvpView")
			.addExceptions(method.getExceptions())
			.addStatement("mvpView.$L($L)", method.getName(), method.getArgumentsString())
			.build();

	TypeSpec.Builder classBuilder = TypeSpec.classBuilder(method.getCommandClassName())
			.addModifiers(Modifier.PUBLIC) // TODO: private and static
			.addTypeVariables(method.getTypeVariables())
			.superclass(ParameterizedTypeName.get(ClassName.get(ViewCommand.class), viewTypeName))
			.addMethod(generateCommandConstructor(method))
			.addMethod(applyMethod);

	for (ParameterSpec parameter : method.getParameterSpecs()) {
		// TODO: private field
		classBuilder.addField(parameter.type, parameter.name, Modifier.PUBLIC, Modifier.FINAL);
	}

	return classBuilder.build();
}
 
Example 6
Source Project: spring-init   Source File: InitializerSpec.java    License: Apache License 2.0 6 votes vote down vote up
private void addBeanMethods(MethodSpec.Builder builder, TypeElement type) {
	boolean conditional = utils.hasAnnotation(type, SpringClassNames.CONDITIONAL.toString());
	if (this.hasEnabled) {
		builder.beginControlFlow("if ($T.enabled)", this.className);
	}
	if (conditional) {
		builder.addStatement("$T conditions = context.getBeanFactory().getBean($T.class)",
				SpringClassNames.CONDITION_SERVICE, SpringClassNames.CONDITION_SERVICE);
		builder.beginControlFlow("if (conditions.matches($T.class))", type);
	}
	builder.beginControlFlow("if (context.getBeanFactory().getBeanNamesForType($T.class).length==0)", type);
	boolean conditionsAvailable = addScannedComponents(builder, conditional);
	addNewBeanForConfig(builder, type);
	for (ExecutableElement method : getBeanMethods(type)) {
		conditionsAvailable |= createBeanMethod(builder, method, type, conditionsAvailable);
	}
	addResources(builder);
	addRegistrarInvokers(builder);
	builder.endControlFlow();
	if (conditional) {
		builder.endControlFlow();
	}
	if (this.hasEnabled) {
		builder.endControlFlow();
	}
}
 
Example 7
Source Project: sqlitemagic   Source File: ModelPersistingGenerator.java    License: Apache License 2.0 6 votes vote down vote up
static void addTransactionEndBlock(@NonNull MethodSpec.Builder builder,
                                   @NonNull Set<TableElement> allTableTriggers,
                                   @NonNull CodeBlock successStatement,
                                   @NonNull CodeBlock returnStatement,
                                   @NonNull String failReturnStatement,
                                   boolean closeOpHelper) {
  builder.addStatement("$L.markSuccessful()", TRANSACTION_VARIABLE)
      .addCode(successStatement)
      .addCode(returnStatement)
      .nextControlFlow("catch ($T e)", OPERATION_FAILED_EXCEPTION);
  addOperationFailedLoggingStatement(builder);
  if (!Strings.isNullOrEmpty(failReturnStatement)) {
    builder.addStatement(failReturnStatement);
  }
  builder.nextControlFlow("finally")
      .addStatement("$L.end()", TRANSACTION_VARIABLE)
      .beginControlFlow("if (success)");
  addTableTriggersSendingStatement(builder, allTableTriggers);
  builder.endControlFlow();
  if (closeOpHelper) {
    builder.addStatement("$L.close()", OPERATION_HELPER_VARIABLE);
  }
  builder.endControlFlow();
}
 
Example 8
Source Project: gwt-jackson   Source File: BeanJsonDeserializerCreator.java    License: Apache License 2.0 6 votes vote down vote up
private Optional<MethodSpec> buildInitAnySetterDeserializerMethod( PropertyInfo anySetterPropertyInfo )
        throws UnableToCompleteException {

    FieldAccessor fieldAccessor = anySetterPropertyInfo.getSetterAccessor().get();
    JType type = fieldAccessor.getMethod().get().getParameterTypes()[1];

    JDeserializerType deserializerType;
    try {
        deserializerType = getJsonDeserializerFromType( type );
    } catch ( UnsupportedTypeException e ) {
        logger.log( Type.WARN, "Method '" + fieldAccessor.getMethod().get()
                .getName() + "' annotated with @JsonAnySetter has an unsupported type" );
        return Optional.absent();
    }

    return Optional.of( MethodSpec.methodBuilder( "initAnySetterDeserializer" )
            .addModifiers( Modifier.PROTECTED )
            .addAnnotation( Override.class )
            .returns( ParameterizedTypeName.get(
                    ClassName.get( AnySetterDeserializer.class ), typeName( beanInfo.getType() ), DEFAULT_WILDCARD ) )
            .addStatement( "return $L", buildDeserializer( anySetterPropertyInfo, type, deserializerType ) )
            .build() );
}
 
Example 9
Source Project: anno4j   Source File: RDFSPropertySpecTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSetter() throws Exception {
    BuildableRDFSProperty loadCap = getPropertyFromModel("http://example.de/ont#load_capacity");
    assertNotNull(loadCap);

    MethodSpec loadCapSpec = loadCap.buildSetter(declaringClass, generationConfig);

    // Test signature:
    assertEquals("setMaximumLoadCapacities", loadCapSpec.name);
    assertTrue(loadCapSpec.modifiers.contains(Modifier.PUBLIC));
    assertEquals(1, loadCapSpec.parameters.size());
    ClassName setClass = ClassName.get("java.util", "Set");
    assertEquals(ParameterizedTypeName.get(setClass, ClassName.get(Float.class)), loadCapSpec.parameters.get(0).type);

    // Test JavaDoc:
    assertNotNull(loadCapSpec.javadoc);
    assertTrue(loadCapSpec.javadoc.toString().startsWith("Ladung in Tonnen"));

    // Test annotation:
    assertEquals(1, loadCapSpec.annotations.size()); // @Iri annotation was moved to private field. Setters must not have an annotation.
}
 
Example 10
Source Project: litho   Source File: SimpleNameDelegateGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public static TypeSpecDataHolder generate(LayoutSpecModel specModel) {
  final String delegatesToPropName = specModel.getSimpleNameDelegate();
  final TypeSpecDataHolder.Builder builder = TypeSpecDataHolder.newBuilder();
  if (delegatesToPropName == null || delegatesToPropName.isEmpty()) {
    return builder.build();
  }

  MethodSpec.Builder getDelegateComponentBuilder =
      MethodSpec.methodBuilder("getSimpleNameDelegate")
          .addAnnotation(Override.class)
          .addModifiers(Modifier.PROTECTED)
          .returns(ClassNames.COMPONENT)
          .addStatement("return $L", delegatesToPropName);
  builder.addMethod(getDelegateComponentBuilder.build());

  return builder.build();
}
 
Example 11
Source Project: Barricade   Source File: CodeGenerator.java    License: Apache License 2.0 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 12
private void appendBody(final MethodSpec.Builder pMethodBuilder) {
    pMethodBuilder.addCode("$T.d(", Log.class);
    pMethodBuilder.addCode("$S, $S", mClassElement.getQualifiedName() + "." + mMethodElement.getSimpleName(), "called");

    if (!mIsStaticMethod) {
        pMethodBuilder.addCode(" + $S + $N", " on ", "instance");
    }

    pMethodBuilder.addCode(" + $S", " with ");

    final Iterator<? extends VariableElement> lIterator = mMethodElement.getParameters().iterator();
    while (lIterator.hasNext()) {
        final VariableElement lParamElement = lIterator.next();
        // add "key=" + value
        pMethodBuilder.addCode(" + $S + $N", lParamElement.getSimpleName() + "=", lParamElement.getSimpleName());
        // add "," for next parameter
        if (lIterator.hasNext()) {
            pMethodBuilder.addCode(" + $S", ", ");
        }
    }

    pMethodBuilder.addCode(");\n");
}
 
Example 13
Source Project: tinkerpop   Source File: GremlinDslProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private MethodSpec constructMethod(final Element element, final ClassName returnClazz, final String parent,
                                   final Modifier... modifiers) {
    final ExecutableElement templateMethod = (ExecutableElement) element;
    final String methodName = templateMethod.getSimpleName().toString();

    final TypeName returnType = getReturnTypeDefinition(returnClazz, templateMethod);
    final MethodSpec.Builder methodToAdd = MethodSpec.methodBuilder(methodName)
            .addModifiers(modifiers)
            .addAnnotation(Override.class)
            .addExceptions(templateMethod.getThrownTypes().stream().map(TypeName::get).collect(Collectors.toList()))
            .returns(returnType);

    templateMethod.getTypeParameters().forEach(tp -> methodToAdd.addTypeVariable(TypeVariableName.get(tp)));

    final String parentCall = parent.isEmpty() ? "" : parent + ".";
    final String body = "return ($T) " + parentCall + "super.$L(";
    addMethodBody(methodToAdd, templateMethod, body, ")", returnClazz, methodName);

    return methodToAdd.build();
}
 
Example 14
Source Project: litho   Source File: MatcherGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private static TypeSpecDataHolder generateFactoryMethods(final SpecModel specModel) {
  final TypeSpecDataHolder.Builder dataHolder = TypeSpecDataHolder.newBuilder();

  final MethodSpec.Builder factoryMethod =
      MethodSpec.methodBuilder("matcher")
          .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
          .returns(getMatcherType(specModel))
          .addParameter(specModel.getContextClass(), "c")
          .addStatement("return new $T(c)", BUILDER_CLASS_NAME);

  if (!specModel.getTypeVariables().isEmpty()) {
    factoryMethod.addTypeVariables(specModel.getTypeVariables());
  }

  return dataHolder.addMethod(factoryMethod.build()).build();
}
 
Example 15
@Test
public void testBuildFunctionConstantSingleValueReturn() throws Exception {
    AbiDefinition functionDefinition = new AbiDefinition(
            true,
            Arrays.asList(
                    new AbiDefinition.NamedType("param", "uint8")),
            "functionName",
            Arrays.asList(
                    new AbiDefinition.NamedType("result", "int8")),
            "type",
            false);

    MethodSpec methodSpec = solidityFunctionWrapper.buildFunction(functionDefinition);

    //CHECKSTYLE:OFF
    String expected =
            "public org.web3j.protocol.core.RemoteCall<java.math.BigInteger> functionName(java.math.BigInteger param) {\n"
                    + "  final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_FUNCTIONNAME, \n"
                    + "      java.util.Arrays.<org.web3j.abi.datatypes.Type>asList(new org.web3j.abi.datatypes.generated.Uint8(param)), \n"
                    + "      java.util.Arrays.<org.web3j.abi.TypeReference<?>>asList(new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.generated.Int8>() {}));\n"
                    + "  return executeRemoteCallSingleValueReturn(function, java.math.BigInteger.class);\n"
                    + "}\n";
    //CHECKSTYLE:ON

    assertThat(methodSpec.toString(), is(expected));
}
 
Example 16
Source Project: evosql   Source File: JUnitGeneratorHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Builds a utility function for building a Map from a list of strings.
 *
 * @return An instance of a method specification for mapMaker.
 */
public MethodSpec buildMapMaker() {
    MethodSpec.Builder mapMaker = MethodSpec.methodBuilder(METHOD_MAP_MAKER)
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC)
            .returns(ParameterizedTypeName.get(HashMap.class, String.class, String.class))
            .addParameter(String[].class, "strings")
            .varargs()
            .addJavadoc("Generates a string map from a list of strings.\n");

    mapMaker.addStatement("$T<$T, $T> result = new $T<>()", HashMap.class, String.class, String.class, HashMap.class)
            .beginControlFlow("for(int i = 0; i < strings.length; i += 2)")
            .addStatement("result.put(strings[i], strings[i + 1])")
            .endControlFlow()
            .addStatement("return result");
    return mapMaker.build();
}
 
Example 17
Source Project: auto-matter   Source File: AutoMatterProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private MethodSpec optionalSetter(final Descriptor d, final ExecutableElement field) {
  String fieldName = fieldName(field);
  TypeName valueType = genericArgument(d, field, 0);
  ClassName optionalType = ClassName.bestGuess(optionalType(field));
  TypeName parameterType = ParameterizedTypeName.get(optionalType, subtypeOf(valueType));

  AnnotationSpec suppressUncheckedAnnotation = AnnotationSpec.builder(SuppressWarnings.class)
      .addMember("value", "$S", "unchecked")
      .build();

  MethodSpec.Builder setter = MethodSpec.methodBuilder(fieldName)
      .addAnnotation(suppressUncheckedAnnotation)
      .addModifiers(PUBLIC)
      .addParameter(parameterType, fieldName)
      .returns(builderType(d));

  if (shouldEnforceNonNull(field)) {
    assertNotNull(setter, fieldName);
  }

  setter.addStatement("this.$N = ($T)$N", fieldName, fieldType(d, field), fieldName);

  return setter.addStatement("return this").build();
}
 
Example 18
Source Project: litho   Source File: TriggerGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private static MethodSpec generateDeprecatedStaticGetTrigger(
    ClassName contextClassName,
    SpecMethodModel<EventMethod, EventDeclarationModel> eventMethodModel) {

  MethodSpec.Builder triggerMethod =
      MethodSpec.methodBuilder(
              ComponentBodyGenerator.getEventTriggerInstanceName(eventMethodModel.name))
          .returns(ClassNames.EVENT_TRIGGER)
          .addModifiers(Modifier.PUBLIC, Modifier.STATIC);

  triggerMethod
      .addJavadoc("@Deprecated Do not use this method to trigger events.")
      .addAnnotation(java.lang.Deprecated.class)
      .addParameter(contextClassName, "c")
      .addParameter(ClassNames.STRING, "key")
      .addStatement(
          "return $L(c, key, null)",
          ComponentBodyGenerator.getEventTriggerInstanceName(eventMethodModel.name));

  return triggerMethod.build();
}
 
Example 19
Source Project: bazel   Source File: AutoCodecProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private String buildDeserializeBodyWithBuilder(
    TypeElement encodedType,
    TypeElement builderType,
    MethodSpec.Builder builder,
    List<ExecutableElement> fields,
    ExecutableElement builderCreationMethod)
    throws SerializationProcessingFailedException {
  String builderVarName = "objectBuilder";
  builder.addStatement(
      "$T $L = $T.$L()",
      builderCreationMethod.getReturnType(),
      builderVarName,
      encodedType,
      builderCreationMethod.getSimpleName());
  for (ExecutableElement getter : fields) {
    String paramName = getNameFromGetter(getter) + "_";
    marshallers.writeDeserializationCode(
        new Marshaller.Context(builder, getter.getReturnType(), paramName));
    setValueInBuilder(builderType, getter, paramName, builderVarName, builder);
  }
  return builderVarName;
}
 
Example 20
Source Project: aws-sdk-java-v2   Source File: AwsServiceModel.java    License: Apache License 2.0 6 votes vote down vote up
private Stream<MethodSpec> memberGetters(MemberModel member) {
    List<MethodSpec> result = new ArrayList<>();

    if (shouldGenerateEnumGetter(member)) {
        result.add(enumMemberGetter(member));
    }

    member.getAutoConstructClassIfExists()
          .ifPresent(autoConstructClass -> result.add(existenceCheckGetter(member, autoConstructClass)));

    if (shouldGenerateDeprecatedNameGetter(member)) {
        result.add(deprecatedMemberGetter(member));
    }

    result.add(memberGetter(member));

    return result.stream();
}
 
Example 21
Source Project: firebase-android-sdk   Source File: ToStringMethod.java    License: Apache License 2.0 6 votes vote down vote up
static MethodSpec generate(TypeElement element) {
  ClassName.get(element).reflectionName();
  Builder result =
      MethodSpec.methodBuilder("toString")
          .addModifiers(Modifier.PUBLIC)
          .returns(String.class)
          .addAnnotation(Override.class)
          .addCode(
              CodeBlock.builder()
                  .add(
                      "StringBuilder sb = new StringBuilder(\"@$L\");\n",
                      ClassName.get(element).reflectionName().replace('$', '.'))
                  .build());
  List<ExecutableElement> methods = ElementFilter.methodsIn(element.getEnclosedElements());
  if (!methods.isEmpty()) {
    result.addCode("sb.append('(');\n");
  }
  for (ExecutableElement method : methods) {
    result.addCode("sb.append(\"$1L=\").append($1L);\n", method.getSimpleName());
  }
  if (!methods.isEmpty()) {
    result.addCode("sb.append(')');\n");
  }
  result.addCode("return sb.toString();\n");
  return result.build();
}
 
Example 22
Source Project: toothpick   Source File: FactoryGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void emitHasReleasableAnnotation(TypeSpec.Builder builder) {
  boolean hasReleasableAnnotation = constructorInjectionTarget.hasReleasableAnnotation;
  MethodSpec.Builder hasScopeAnnotationBuilder =
      MethodSpec.methodBuilder("hasReleasableAnnotation")
          .addAnnotation(Override.class)
          .addModifiers(Modifier.PUBLIC)
          .returns(TypeName.BOOLEAN)
          .addStatement("return $L", hasReleasableAnnotation);
  builder.addMethod(hasScopeAnnotationBuilder.build());
}
 
Example 23
Source Project: kripton   Source File: BindDataSourceBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generate constructor.
 *
 * @param schema
 *            the schema
 */
private void generateConstructor(SQLiteDatabaseSchema schema) {
	// constructor
	MethodSpec.Builder methodBuilder = MethodSpec.constructorBuilder()
			.addParameter(DataSourceOptions.class, "options").addModifiers(Modifier.PROTECTED);
	if (schema.generateLog) {
		methodBuilder.addStatement("super($S, $L, options)", schema.fileName, schema.version);
	} else {
		methodBuilder.addStatement("super($S, $L, $T.builder().createFrom(options).log(false).build())",
				schema.fileName, schema.version, DataSourceOptions.class);
	}

	classBuilder.addMethod(methodBuilder.build());
}
 
Example 24
Source Project: data-mediator   Source File: ImplInfo.java    License: Apache License 2.0 5 votes vote down vote up
public void addImplMethods(TypeSpec.Builder curBuilder){
      for(MethodInfo info : getMethodInfo()){
          MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(info.getMethodName())
                  .addModifiers(Modifier.PUBLIC)
                  .returns(info.getReturnType());

          final List<ParamInfo> paramInfos = info.getParamInfos();
          final Object[] params = new Object[ 3 + paramInfos.size()]; //implClass + implName + module + dependProp + other params.
          params[0] = info.getImplClass().getTypeName();
          params[1] = info.getImplMethodName();
          params[2] = "this";

          StringBuilder sb = new StringBuilder();
          sb.append( "$T.$N( $N " );

          if(!paramInfos.isEmpty()){
              int i = 3;
              for (ParamInfo pInfo : paramInfos){
                  sb.append(", ").append("$N");
                  params[i++] = pInfo.paramName;
                  methodBuilder.addParameter(pInfo.paramType, pInfo.paramName);
              }
          }
          sb.append(")");
          if(info.isReturnVoid()){
              methodBuilder.addStatement(sb.toString(), params);
          }else{
              methodBuilder.addStatement("return " + sb.toString(), params);
          }
          curBuilder.addMethod(methodBuilder.build());
      }
}
 
Example 25
Source Project: dart   Source File: NavigationModelBinderGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void emitBind(TypeSpec.Builder builder) {
  MethodSpec.Builder bindBuilder =
      MethodSpec.methodBuilder("bind")
          .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
          .addParameter(get(Dart.Finder.class), "finder")
          .addParameter(bestGuess(target.getFQN()), "target");

  bindBuilder.addStatement(
      "target.$L = new $T()",
      target.navigationModelFieldName,
      get(target.navigationModelPackage, target.navigationModelClass));

  bindBuilder.addStatement(
      "$T.bind(finder, target.$L, target)",
      get(target.navigationModelPackage, target.navigationModelClass + Dart.EXTRA_BINDER_SUFFIX),
      target.navigationModelFieldName);

  if (target.parentPackage != null) {
    // Emit a call to the superclass binder, if any.
    bindBuilder.addStatement(
        "$T.assign(target, target.$L)",
        bestGuess(target.getParentFQN() + NAVIGATION_MODEL_BINDER_SUFFIX),
        target.navigationModelFieldName);
  }

  builder.addMethod(bindBuilder.build());
}
 
Example 26
Source Project: nalu   Source File: ModuleGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void generateLoadShellFactory(TypeSpec.Builder typeSpec) {
  // generate method 'generateLoadShells()'
  MethodSpec.Builder loadShellFactoryMethodBuilder = MethodSpec.methodBuilder("loadShellFactory")
                                                               .addModifiers(Modifier.PUBLIC)
                                                               .addAnnotation(Override.class);
  this.metaModel.getShells()
                .forEach(shellModel -> {
                  // add return statement
                  loadShellFactoryMethodBuilder.addComment("create ShellCreator for: " +
                                                           shellModel.getShell()
                                                                     .getPackage() +
                                                           "." +
                                                           shellModel.getShell()
                                                                     .getSimpleName())
                                               .addStatement("$T.get().registerShell($S, new $L(router, moduleContext, eventBus))",
                                                             ClassName.get(ShellFactory.class),
                                                             shellModel.getShell()
                                                                       .getPackage() +
                                                             "." +
                                                             shellModel.getShell()
                                                                       .getSimpleName(),
                                                             ClassName.get(shellModel.getShell()
                                                                                     .getPackage(),
                                                                           shellModel.getShell()
                                                                                     .getSimpleName() + ProcessorConstants.CREATOR_IMPL));

                });
  typeSpec.addMethod(loadShellFactoryMethodBuilder.build());
}
 
Example 27
Source Project: spring-init   Source File: InitializerSpec.java    License: Apache License 2.0 5 votes vote down vote up
private MethodSpec createInitializer() {
	MethodSpec.Builder builder = MethodSpec.methodBuilder("initialize");
	builder.addAnnotation(Override.class);
	builder.addModifiers(Modifier.PUBLIC);
	builder.addParameter(SpringClassNames.GENERIC_APPLICATION_CONTEXT, "context");
	addBeanMethods(builder, configurationType);
	return builder.build();
}
 
Example 28
Source Project: aws-sdk-java-v2   Source File: SyncResponseClassSpec.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * A {@link MethodSpec} for the overridden iterator() method which is inherited
 * from the interface.
 */
protected MethodSpec iteratorMethod() {
    return MethodSpec.methodBuilder(ITERATOR_METHOD)
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(ParameterizedTypeName.get(ClassName.get(Iterator.class), responseType()))
            .addStatement("return $1T.builder().$2L($3L).build()", PaginatedResponsesIterator.class,
                          NEXT_PAGE_FETCHER_MEMBER, nextPageFetcherArgument())
            .build();
}
 
Example 29
Source Project: OkDeepLink   Source File: DeepLinkInjectProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private MethodSpec geneInjectServiceMethod(TypeElement targetElement, List<Element> fieldElements) {

        MethodSpec.Builder injectMethodBuilder = MethodSpec.methodBuilder("onCreateService")
                .addModifiers(PUBLIC)
                .addException(Throwable.class)
                .addAnnotation(AnnotationSpec.builder(Around.class).addMember("value", "$S", "execution(* " + targetElement.getQualifiedName() + ".onCreate(..))").build())
                .addParameter(ProceedingJoinPoint.class, "joinPoint");

        CodeBlock.Builder injectServiceCodeBuilder = CodeBlock.builder();
        injectServiceCodeBuilder.add("$T target = ($T)joinPoint.getTarget();\n", targetElement, targetElement);
        List<TypeName> serviceTypeNames = new ArrayList<>();

        for (Element queryElement : fieldElements) {
            if (queryElement.getAnnotation(Service.class) != null) {
                TypeName className = TypeName.get(queryElement.asType());
                if (serviceTypeNames.contains(className)) {
                    logger.error("The inject " + className + " cannot be Duplicate", queryElement);
                }
                serviceTypeNames.add(className);
                injectServiceCodeBuilder.add("target.$L=  new $T(target).build($T.class);\n ", queryElement, DeepLinkServiceProcessor.DEEP_LINK_CLIENT, queryElement);

            }
        }
        injectServiceCodeBuilder.add("joinPoint.proceed();\n");
        injectMethodBuilder.addCode(injectServiceCodeBuilder.build());

        return injectMethodBuilder.build();
    }
 
Example 30
Source Project: aws-sdk-java-v2   Source File: BaseClientBuilderClass.java    License: Apache License 2.0 5 votes vote down vote up
private MethodSpec serviceNameMethod() {
    return MethodSpec.methodBuilder("serviceName")
                     .addAnnotation(Override.class)
                     .addModifiers(PROTECTED, FINAL)
                     .returns(String.class)
                     .addCode("return $S;", model.getMetadata().getServiceName())
                     .build();
}