Java Code Examples for com.squareup.javapoet.ParameterSpec#Builder

The following examples show how to use com.squareup.javapoet.ParameterSpec#Builder . 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 File: ResourceInterfaceGenerator.java    From spring-openapi with MIT License 6 votes vote down vote up
private ParameterSpec.Builder parseTypeBasedSchema(String parameterName, Schema innerSchema) {
	if (equalsIgnoreCase(innerSchema.getType(), "string")) {
		return ParameterSpec.builder(getStringGenericClassName(innerSchema), parameterName);
	} else if (equalsIgnoreCase(innerSchema.getType(), "integer") || equalsIgnoreCase(innerSchema.getType(), "number")) {
		return getNumberBasedSchemaParameter(parameterName, innerSchema);
	} else if (equalsIgnoreCase(innerSchema.getType(), "boolean")) {
		return createSimpleParameterSpec(JAVA_LANG_PKG, "Boolean", parameterName);
	} else if (equalsIgnoreCase(innerSchema.getType(), "array") && innerSchema instanceof ArraySchema) {
		ArraySchema arraySchema = (ArraySchema) innerSchema;
		ParameterizedTypeName listParameterizedTypeName = ParameterizedTypeName.get(
				ClassName.get("java.util", "List"),
				determineTypeName(arraySchema.getItems())
		);
		return ParameterSpec.builder(listParameterizedTypeName, parameterName);
	} else if (equalsIgnoreCase(innerSchema.getType(), "object") && isFile(innerSchema.getProperties())) {
		return ParameterSpec.builder(ClassName.get(File.class), parameterName);
	}
	return createSimpleParameterSpec(JAVA_LANG_PKG, "Object", parameterName);
}
 
Example 2
Source File: ResourceInterfaceGenerator.java    From spring-openapi with MIT License 6 votes vote down vote up
private ParameterSpec.Builder getNumberBasedSchemaParameter(String fieldName, Schema innerSchema) {
	ParameterSpec.Builder fieldBuilder = createNumberBasedParameterWithFormat(fieldName, innerSchema);
	if (innerSchema.getMinimum() != null) {
		fieldBuilder.addAnnotation(AnnotationSpec.builder(DecimalMin.class)
				.addMember("value", "$S", innerSchema.getMinimum().toString())
				.build()
		);
	}
	if (innerSchema.getMaximum() != null) {
		fieldBuilder.addAnnotation(AnnotationSpec.builder(DecimalMax.class)
				.addMember("value", "$S", innerSchema.getMaximum().toString())
				.build()
		);
	}
	return fieldBuilder;
}
 
Example 3
Source File: ResourceInterfaceGenerator.java    From spring-openapi with MIT License 5 votes vote down vote up
private ParameterSpec.Builder parseProperties(String parameterName, Schema parameterSchema) {
	if (parameterSchema.getType() != null) {
		return parseTypeBasedSchema(parameterName, parameterSchema);
	} else if (parameterSchema.get$ref() != null) {
		// simple no inheritance
		return createSimpleParameterSpec(null, getNameFromRef(parameterSchema.get$ref()), parameterName);
	} else if (parameterSchema instanceof ComposedSchema && CollectionUtils.isNotEmpty(((ComposedSchema) parameterSchema).getAllOf())) {
		return createSimpleParameterSpec(null, determineParentClassNameUsingOneOf(parameterSchema, parameterName, allComponents), parameterName);
	} else {
		throw new IllegalArgumentException("Incorrect schema. One of [type, $ref, discriminator+oneOf] has to be defined in property schema");
	}
}
 
Example 4
Source File: ResourceInterfaceGenerator.java    From spring-openapi with MIT License 5 votes vote down vote up
private ParameterSpec.Builder createNumberBasedParameterWithFormat(String fieldName, Schema innerSchema) {
	if (innerSchema.getFormat() == null || StringUtils.equalsIgnoreCase(innerSchema.getFormat(), "int32")) {
		return createSimpleParameterSpec(JAVA_LANG_PKG, "Integer", fieldName);
	} else if (StringUtils.equalsIgnoreCase(innerSchema.getFormat(), "int64")) {
		return createSimpleParameterSpec(JAVA_LANG_PKG, "Long", fieldName);
	} else if (StringUtils.equalsIgnoreCase(innerSchema.getFormat(), "float")) {
		return createSimpleParameterSpec(JAVA_LANG_PKG, "Float", fieldName);
	} else if (StringUtils.equalsIgnoreCase(innerSchema.getFormat(), "double")) {
		return createSimpleParameterSpec(JAVA_LANG_PKG, "Double", fieldName);
	} else {
		return createSimpleParameterSpec(JAVA_LANG_PKG, "Integer", fieldName);
	}
}
 
Example 5
Source File: GeneratorUtils.java    From litho with Apache License 2.0 5 votes vote down vote up
public static ParameterSpec parameter(
    TypeName type,
    String name,
    List<AnnotationSpec> externalAnnotations,
    AnnotationSpec... extraAnnotations) {
  final ParameterSpec.Builder builder =
      ParameterSpec.builder(type, name).addAnnotations(externalAnnotations);

  for (AnnotationSpec annotation : extraAnnotations) {
    builder.addAnnotation(annotation);
  }

  return builder.build();
}
 
Example 6
Source File: EntityGenerator.java    From requery with Apache License 2.0 5 votes vote down vote up
private void generateConstructors(TypeSpec.Builder builder) {
    // copy the existing constructors
    for (ExecutableElement constructor : ElementFilter.constructorsIn(
            typeElement.getEnclosedElements())) {
        // constructor params
        List<? extends VariableElement> parameters = constructor.getParameters();

        if (!parameters.isEmpty()) {

            MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder();
            constructorBuilder.addModifiers(constructor.getModifiers());

            List<String> parameterNames = new ArrayList<>();
            for (VariableElement parameter : parameters) {
                Modifier[] modifiers = parameter.getModifiers().toArray(
                        new Modifier[parameter.getModifiers().size()]);
                String parameterName = parameter.getSimpleName().toString();
                parameterNames.add(parameterName);
                ParameterSpec.Builder parameterBuilder = ParameterSpec.builder(
                        TypeName.get(parameter.asType()), parameterName, modifiers);
                constructorBuilder.addParameter(parameterBuilder.build());
            }
            // super parameter/arguments
            StringJoiner joiner = new StringJoiner(",", "(", ")");
            parameterNames.forEach(joiner::add);
            constructorBuilder.addStatement("super" + joiner.toString());
            builder.addMethod(constructorBuilder.build());
        }
    }
}
 
Example 7
Source File: PaperParcelAutoValueExtension.java    From paperparcel with Apache License 2.0 5 votes vote down vote up
private MethodSpec constructor(Context context) {
  Types types = context.processingEnvironment().getTypeUtils();
  DeclaredType declaredValueType = MoreTypes.asDeclared(context.autoValueClass().asType());

  ImmutableList.Builder<ParameterSpec> parameterBuilder = ImmutableList.builder();
  for (Map.Entry<String, ExecutableElement> entry : context.properties().entrySet()) {
    ExecutableType resolvedExecutableType =
        MoreTypes.asExecutable(types.asMemberOf(declaredValueType, entry.getValue()));
    TypeName typeName = TypeName.get(resolvedExecutableType.getReturnType());
    ParameterSpec.Builder spec = ParameterSpec.builder(typeName, entry.getKey());
    AnnotationMirror nullableAnnotation =
        Utils.getAnnotationWithSimpleName(entry.getValue(), NULLABLE_ANNOTATION_NAME);
    if (nullableAnnotation != null) {
      spec.addAnnotation(AnnotationSpec.get(nullableAnnotation));
    }
    parameterBuilder.add(spec.build());
  }

  ImmutableList<ParameterSpec> parameters = parameterBuilder.build();
  CodeBlock parameterList = CodeBlocks.join(FluentIterable.from(parameters)
      .transform(new Function<ParameterSpec, CodeBlock>() {
        @Override public CodeBlock apply(ParameterSpec parameterSpec) {
          return CodeBlock.of("$N", parameterSpec.name);
        }
      }), ", ");

  return MethodSpec.constructorBuilder()
      .addParameters(parameters)
      .addStatement("super($L)", parameterList)
      .build();
}
 
Example 8
Source File: AutoBundleWriter.java    From AutoBundle with Apache License 2.0 5 votes vote down vote up
private static MethodSpec createCallBuilderMethod(AutoBundleBindingClass target) {
    ClassName builderClass = getBuilderClassName(target);
    MethodSpec.Builder builder =
            MethodSpec.methodBuilder("builder")
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .addAnnotation(ANNOTATION_NONNULL)
            .returns(builderClass)
            .addCode("return new $T(", builderClass);
    for (int i = 0, count = target.getRequiredArgs().size(); i < count; i++) {
        AutoBundleBindingField arg = target.getRequiredArgs().get(i);
        ParameterSpec.Builder paramBuilder = ParameterSpec.builder(arg.getArgType(),
                arg.getArgKey());
        // annotations
        if (arg.hasAnnotations()) {
            arg.getAnnotations().forEach(paramBuilder::addAnnotation);
        }
        // nonnull
        if (!arg.getArgType().isPrimitive()) {
            paramBuilder.addAnnotation(ANNOTATION_NONNULL);
        }
        // statement
        if (i > 0) {
            builder.addCode(", ");
        }
        builder.addParameter(paramBuilder.build())
                .addCode("$N", arg.getArgKey());
    }
    return builder.addCode(");\n").build();
}
 
Example 9
Source File: AutoBundleWriter.java    From AutoBundle with Apache License 2.0 5 votes vote down vote up
private static MethodSpec createBuilderConstructor(AutoBundleBindingClass target,
                                                   String fieldName) {
    MethodSpec.Builder builder = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addStatement("this.$N = new $T()", fieldName, CLASS_BUNDLE);

    for (AutoBundleBindingField arg : target.getRequiredArgs()) {
        String key = arg.getArgKey();
        TypeName type = arg.getArgType();
        // parameter for constructor
        // support annotation
        ParameterSpec.Builder paramBuilder = ParameterSpec.builder(type, key);
        if (arg.hasAnnotations()) {
            arg.getAnnotations().forEach(paramBuilder::addAnnotation);
        }
        // nonnull
        if (!type.isPrimitive()) {
            paramBuilder.addAnnotation(ANNOTATION_NONNULL);
        }
        builder.addParameter(paramBuilder.build());

        // statement
        String operationName = arg.getOperationName("put");
        if (arg.hasCustomConverter()) {
            TypeName converter = arg.getConverter();
            builder.addStatement("$T $NConverter = new $T()", converter, key, converter)
                    .addStatement("this.$N.$N($S, $NConverter.convert($N) )",
                            fieldName, operationName, key, key, key);
        } else {
            builder.addStatement("this.$N.$N($S, $N)", fieldName, operationName, key, key);
        }
    }

    return builder.build();
}
 
Example 10
Source File: ResourceInterfaceGenerator.java    From spring-openapi with MIT License 4 votes vote down vote up
private ParameterSpec.Builder createSimpleParameterSpec(String packageName, String className, String parameterName) {
	ClassName simpleFieldClassName = packageName == null ? ClassName.bestGuess(targetPackage + "." + className) : ClassName.get(packageName, className);
	return ParameterSpec.builder(simpleFieldClassName, parameterName);
}
 
Example 11
Source File: ValueMethods.java    From dataenum with Apache License 2.0 4 votes vote down vote up
public MethodSpec createFactoryMethod(OutputSpec spec) {
  MethodSpec.Builder factory =
      MethodSpec.methodBuilder(asCamelCase(value.name()))
          .addTypeVariables(spec.typeVariables())
          .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
          .returns(spec.parameterizedOutputClass());

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

  factory.addJavadoc(
      "@return a {@link $T} (see {@link $T#$L} for source)\n",
      value.outputClass(),
      spec.specClass(),
      value.name());

  for (AnnotationSpec annotationSpec : value.annotations()) {
    factory.addAnnotation(annotationSpec);
  }

  StringBuilder newString = new StringBuilder();
  List<Object> newArgs = new ArrayList<>();

  newString.append("return new $T(");
  newArgs.add(value.parameterizedOutputClass());

  boolean first = true;

  for (Parameter parameter : value.parameters()) {
    ParameterSpec.Builder builder = ParameterSpec.builder(parameter.type(), parameter.name());
    if (!parameter.type().isPrimitive()) {
      if (parameter.canBeNull()) {
        builder.addAnnotation(Nullable.class);
      } else {
        builder.addAnnotation(Nonnull.class);
      }
    }

    factory.addParameter(builder.build());

    if (first) {
      newString.append("$L");
      first = false;
    } else {
      newString.append(", $L");
    }

    newArgs.add(parameter.name());
  }

  newString.append(")");

  if (spec.hasTypeVariables()) {
    newString.append(".as$L()");
    newArgs.add(spec.outputClass().simpleName());
  }

  factory.addStatement(newString.toString(), newArgs.toArray());

  return factory.build();
}
 
Example 12
Source File: ResourceMethodExtensionPlugin.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
private ParameterSpec.Builder cloneSingleParamNoAnnotations(ParameterSpec spec){
  ParameterSpec.Builder newSpecBuilder = ParameterSpec.builder(spec.type, spec.name);
  Modifier modifiers[] = new Modifier[spec.modifiers.size()];
  newSpecBuilder.addModifiers(spec.modifiers.toArray(modifiers));
  return newSpecBuilder;
}
 
Example 13
Source File: ResourceMethodExtensionPlugin.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
private Builder generateOverrides(String path, String verb, Builder methodSpec){

    //clone the method without the params as we will need to update params with new / updated
    //annotations and this cannot be done directly on the method as these lists are immutable
    //as java poet allows building code but not editing??
    MethodSpec.Builder ret = cloneMethodWithoutParams(methodSpec);

    //pull out original params and their annotations from here
    MethodSpec spec = methodSpec.build();

    //use this list to remove and then update params whose annotations need changing since
    //the param list on the method in java poet is immutable this is a workaround
    List<ParameterSpec> modifiedParams = new ArrayList<>( spec.parameters );

    //check if url has a param / params associated with it that needs overriding
    Map<String,JsonObject> overrideEntry = overrideMap.row(path);
    if(overrideEntry != null){
      //this endpoint was found in the config file and has an override associated with one of
      //its parameters
      List<ParameterSpec> paramSpec = spec.parameters;
      int []i = new int[]{0};
      for (i[0] = 0; i[0] < paramSpec.size(); i[0]++) {
        //clone the parameter so we can update it
        ParameterSpec.Builder newParam = cloneSingleParamNoAnnotations(paramSpec.get(i[0]));
        List<AnnotationSpec> originalAnnotations = getAnnotationsAsModifiableList(paramSpec.get(i[0]));
        //remove the param, we need to rebuild it and then add it again
        modifiedParams.remove(i[0]);
        Set<Entry<String, JsonObject>> entries = overrideEntry.entrySet();

        entries.forEach( entry -> {
          //iterate through the params of the generated function for this url + verb and look
          //for the parameter whose annotation we need to override
          JsonObject job = entry.getValue();
          String type = job.getString("type");
          Object value = job.getValue(ANNOTATION_VALUE);
          String paramName = job.getString("paramName");
          if(verb.equalsIgnoreCase(job.getString("verb")) &&
            paramName.equalsIgnoreCase(paramSpec.get(i[0]).name)){
            //make sure the verb is aligned
            //we found the parameter that should be overridden, for the path, and for the verb
            //we cannot update the param, so we need to recreate it and then update the list
            //by removing the old and adding the recreated param
            //we need the original annotations so that we can add the ones that were not updated
            for(int j=0; j<originalAnnotations.size(); j++ ){
              if(originalAnnotations.get(j).type.toString() != null
                && Enum2Annotation.getAnnotation(type).endsWith(originalAnnotations.get(j).type.toString())){
                  originalAnnotations.remove(j);
                break;
              }
            }
            try {
              AnnotationSpec aSpec =
                  buildAnnotation(Class.forName(Enum2Annotation.getAnnotation(type)), value, type);
              originalAnnotations.add(aSpec);
            } catch (ClassNotFoundException e) {
              log.error(e.getMessage(), e);
            }
          }
        });
        newParam.addAnnotations(originalAnnotations);
        modifiedParams.add(i[0], newParam.build());
      }
    }
    ret.addParameters(modifiedParams);
    return ret;
  }