Java Code Examples for com.squareup.javapoet.ParameterizedTypeName

The following are top voted examples for showing how to use com.squareup.javapoet.ParameterizedTypeName. 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: GitHub   File: RequestManagerGenerator.java   Source Code and License 6 votes vote down vote up
private MethodSpec generateAdditionalRequestManagerMethod(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(
          "$T requestBuilder = this.as($T.class)", parameterizedTypeName, returnTypeClassName)
      .addStatement("$T.$N(requestBuilder)",
          extensionMethod.getEnclosingElement(), extensionMethod.getSimpleName())
      .addStatement("return requestBuilder")
      .build();
}
 
Example 2
Project: GitHub   File: RequestBuilderGenerator.java   Source Code and License 6 votes vote down vote up
private List<MethodSpec> generateConstructors() {
  ParameterizedTypeName classOfTranscodeType =
      ParameterizedTypeName.get(ClassName.get(Class.class), transcodeTypeName);

  TypeName wildcardOfObject = WildcardTypeName.subtypeOf(Object.class);
  ParameterizedTypeName requestBuilderOfWildcardOfObject =
      ParameterizedTypeName.get(ClassName.get(requestBuilderType), wildcardOfObject);

  MethodSpec firstConstructor =
      MethodSpec.constructorBuilder()
          .addParameter(classOfTranscodeType, "transcodeClass")
          .addParameter(requestBuilderOfWildcardOfObject, "other")
      .addStatement("super($N, $N)", "transcodeClass", "other")
      .build();

  ClassName glide = ClassName.get("com.bumptech.glide", "Glide");
  ClassName requestManager = ClassName.get("com.bumptech.glide", "RequestManager");
  MethodSpec secondConstructor =
      MethodSpec.constructorBuilder()
          .addParameter(glide, "glide")
          .addParameter(requestManager, "requestManager")
          .addParameter(classOfTranscodeType, "transcodeClass")
          .addStatement("super($N, $N ,$N)", "glide", "requestManager", "transcodeClass")
          .build();
  return ImmutableList.of(firstConstructor, secondConstructor);
}
 
Example 3
Project: GitHub   File: RequestManagerGenerator.java   Source Code and License 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 4
Project: GitHub   File: RequestManagerGenerator.java   Source Code and License 6 votes vote down vote up
private MethodSpec generateAdditionalRequestManagerMethodLegacy(
    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(
          "$T requestBuilder = this.as($T.class)", parameterizedTypeName, returnTypeClassName)
      .addStatement("$T.$N(requestBuilder)",
          extensionMethod.getEnclosingElement(), extensionMethod.getSimpleName())
      .addStatement("return requestBuilder")
      .build();
}
 
Example 5
Project: arez   File: ComponentDescriptor.java   Source Code and License 6 votes vote down vote up
@Nonnull
private MethodSpec buildGetByQueryMethod()
{
  final TypeName entityType = TypeName.get( getElement().asType() );
  final ParameterizedTypeName queryType =
    ParameterizedTypeName.get( ClassName.get( Predicate.class ), entityType );
  return MethodSpec.methodBuilder( "getByQuery" ).
    addModifiers( Modifier.PUBLIC, Modifier.FINAL ).
    addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).
    addParameter( ParameterSpec.builder( queryType, "query", Modifier.FINAL ).
      addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).build() ).
    returns( entityType ).
    addStatement( "final $T entity = findByQuery( query )", entityType ).
    addCode( CodeBlock.builder().
      beginControlFlow( "if ( null == entity )" ).
      addStatement( "throw new $T()", GeneratorUtil.NO_RESULT_EXCEPTION_CLASSNAME ).
      endControlFlow().
      build() ).
    addStatement( "return entity" ).
    build();
}
 
Example 6
Project: auto-value-bundle   File: GsonDeserializer.java   Source Code and License 6 votes vote down vote up
@Override
public String deserializeUnknownParameterizedObject(
        String readFromBundle,
        ParameterizedTypeName parameterizedTypeName,
        VariableElement deserializerElement) {
    StringBuilder typeToken = new StringBuilder("new ")
            .append(TYPE_TOKEN_FULLY_QUALIFIED)
            .append("<")
            .append(parameterizedTypeName.rawType.simpleName())
            .append("<");
    for (TypeName typeName : parameterizedTypeName.typeArguments) {
        typeToken.append(deserializeParameterizedObject(typeName))
                .append(", ");
    }
    typeToken.deleteCharAt(typeToken.length() - 1);
    typeToken.deleteCharAt(typeToken.length() - 1);

    typeToken.append(">(){}.getType()");

    return CodeBlock.builder()
            .add("$L.$L($L, $L)", deserializerElement.getSimpleName().toString(), "fromJson", readFromBundle,
                    typeToken)
            .build()
            .toString();
}
 
Example 7
Project: json-log-domain   File: LoggerGenerator.java   Source Code and License 6 votes vote down vote up
public static JavaFile logger(Domain ontology) {
	ClassName name = ClassName.get(ontology.getTargetPackage(), ontology.getName() + LOGGER);

	ClassName statementName = ClassName.get(ontology.getTargetPackage(), ontology.getName() + STATEMENT);

	ParameterSpec loggerParameter = ParameterSpec.builder(org.slf4j.Logger.class, "logger").build();

	return JavaFile.builder(name.packageName(), TypeSpec.classBuilder(name)
		.superclass(ParameterizedTypeName.get(ClassName.get(AbstractDomainLogger.class), statementName))				
		.addJavadoc(composeJavadoc(ontology, name))
		.addModifiers(Modifier.PUBLIC)
		.addMethod(MethodSpec.constructorBuilder()
			.addModifiers(Modifier.PUBLIC)
			.addParameter(loggerParameter)
			.addStatement("super($N)", loggerParameter)
	        .build())
		.addMethod(getCreateLogStatementMethod(statementName)).build()).build();
}
 
Example 8
Project: Witch-Android   File: OnBindPropertySetter.java   Source Code and License 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 9
Project: java-code-templates   File: Validator.java   Source Code and License 6 votes vote down vote up
@Override
public Void visitVariableAsField(VariableElement element, Trees trees) {

	if (isForEachVariable(element) && Util.hasInitializer(element, trees) && retainTypeFromTemplate(element)) {
		// If we are retaining the type from the template of a static final field,
		// the value has to be initialized with a value passed to a descriptor
		// initialization annotation, which limits the types that can be used.
		TypeName fieldType = TypeName.get(element.asType());
		if (fieldType instanceof ParameterizedTypeName) {
			fieldType = ((ParameterizedTypeName)fieldType).rawType;
		}
		assertThat(fieldType.isPrimitive()
				|| STRING_CLASS_NAME.equals(fieldType)
				|| CLASS_CLASS_NAME.equals(fieldType), element,
				ValidationMessages.TEMPLATE_INITIALIZED_FOREACH_FIELDS);
	}

	return null;
}
 
Example 10
Project: aws-sdk-java-v2   File: AsyncClientInterface.java   Source Code and License 6 votes vote down vote up
/**
 * Generates the traditional method for an operation (i.e. one that takes a request and returns a response).
 */
private MethodSpec.Builder traditionalMethod(OperationModel opModel) {
    ClassName responsePojoType = getPojoResponseType(opModel);
    ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType());

    MethodSpec.Builder builder = methodSignatureWithReturnType(opModel)
            .addParameter(requestType, opModel.getInput().getVariableName())
            .addJavadoc(opModel.getDocs(model, ClientType.ASYNC));

    if (opModel.hasStreamingInput()) {
        builder.addParameter(ClassName.get(AsyncRequestProvider.class), "requestProvider");
    }
    if (opModel.hasStreamingOutput()) {
        builder.addTypeVariable(STREAMING_TYPE_VARIABLE);
        final ParameterizedTypeName asyncResponseHandlerType = ParameterizedTypeName
                .get(ClassName.get(AsyncResponseHandler.class), responsePojoType, STREAMING_TYPE_VARIABLE);
        builder.addParameter(asyncResponseHandlerType, "asyncResponseHandler");
    }

    return operationBody(builder, opModel);
}
 
Example 11
Project: dataenum   File: MapMethods.java   Source Code and License 6 votes vote down vote up
private MethodSpec.Builder createFoldSignature(Iterable<TypeVariableName> availableTypeVariables)
    throws ParserException {
  MethodSpec.Builder builder =
      MethodSpec.methodBuilder("map")
          .addTypeVariable(FOLD_RETURN_TYPE)
          .addModifiers(Modifier.PUBLIC)
          .returns(FOLD_RETURN_TYPE);

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

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

  return builder;
}
 
Example 12
Project: dataenum   File: MatchMethods.java   Source Code and License 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 13
Project: aws-sdk-java-v2   File: AbstractMemberSetters.java   Source Code and License 6 votes vote down vote up
protected ParameterSpec memberAsBeanStyleParameter() {
    if (memberModel.hasBuilder()) {
        TypeName builderName = poetExtensions.getModelClass(memberModel.getC2jShape()).nestedClass("BuilderImpl");
        return ParameterSpec.builder(builderName, fieldName()).build();
    }
    if (memberModel.isList() && hasBuilder(memberModel.getListModel().getListMemberModel())) {
        TypeName memberName = poetExtensions.getModelClass(memberModel.getListModel().getListMemberModel().getC2jShape())
                                            .nestedClass("BuilderImpl");
        TypeName listType = ParameterizedTypeName.get(ClassName.get(Collection.class), memberName);
        return ParameterSpec.builder(listType, fieldName()).build();
    }
    if (memberModel.isMap() && hasBuilder(memberModel.getMapModel().getValueModel())) {
        TypeName keyType = typeProvider.getTypeNameForSimpleType(memberModel.getMapModel().getKeyModel()
                                                                            .getVariable().getVariableType());
        TypeName valueType = poetExtensions.getModelClass(memberModel.getMapModel().getValueModel().getC2jShape())
                                           .nestedClass("BuilderImpl");
        TypeName mapType = ParameterizedTypeName.get(ClassName.get(Map.class), keyType, valueType);
        return ParameterSpec.builder(mapType, fieldName()).build();
    }

    return memberAsParameter();
}
 
Example 14
Project: json2java4idea   File: JavaConverter.java   Source Code and License 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 15
Project: domino   File: EndpointsRegisterMethodWriter.java   Source Code and License 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 16
Project: auto-nav   File: NavProcessor.java   Source Code and License 5 votes vote down vote up
private void addPreGoListener(TypeSpec.Builder navigatorBuilder){
    MethodSpec onPreGo = MethodSpec.methodBuilder("onPreGo")
            .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
            .returns(boolean.class)
            .addParameter(classContext,"fromContext")
            .addParameter(classIntent, "intent")
            .build();

    TypeSpec preListenerType = TypeSpec.interfaceBuilder(listenerName)
            .addModifiers(Modifier.PUBLIC)
            .addMethod(onPreGo).build();

    TypeName listenerType = ClassName.get(navigatorPackageName, navigatorClassName, listenerName);
    TypeName listenerList = ParameterizedTypeName.get(ClassName.get(ArrayList.class), listenerType);
    navigatorBuilder.addType(preListenerType);
    navigatorBuilder.addField(
            listenerList,
            "preGoListeners",
            Modifier.PRIVATE, Modifier.STATIC);
    navigatorBuilder.addStaticBlock(
            CodeBlock.of(
                    "preGoListeners = new $T();\n" +
                            "$T.setPreGoListeners(preGoListeners);\n", listenerList, ClassName.get("nav.base","BaseIntent")));

    MethodSpec add = MethodSpec.methodBuilder("addPreGoListener").addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .addParameter(listenerType,"listener")
            .addCode("if(listener != null){ preGoListeners.add(listener);}\n")
            .build();

    MethodSpec remove = MethodSpec.methodBuilder("removePreGoListener").addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .addParameter(listenerType,"listener")
            .addCode("if(listener != null){ preGoListeners.remove(listener);}\n")
            .build();

    navigatorBuilder.addMethod(add).addMethod(remove);

}
 
Example 17
Project: GitHub   File: FieldCollectionViewBinding.java   Source Code and License 5 votes vote down vote up
CodeBlock render() {
  CodeBlock.Builder builder = CodeBlock.builder()
      .add("target.$L = $T.$L(", name, UTILS, kind.factoryName);
  for (int i = 0; i < ids.size(); i++) {
    if (i > 0) {
      builder.add(", ");
    }
    builder.add("\n");

    boolean requiresCast = requiresCast(type);
    if (!requiresCast && !required) {
      builder.add("source.findViewById($L)", ids.get(i).code);
    } else {
      builder.add("$T.find", UTILS);
      builder.add(required ? "RequiredView" : "OptionalView");
      if (requiresCast) {
        builder.add("AsType");
      }
      builder.add("(source, $L, \"field '$L'\"", ids.get(i).code, name);
      if (requiresCast) {
        TypeName rawType = type;
        if (rawType instanceof ParameterizedTypeName) {
          rawType = ((ParameterizedTypeName) rawType).rawType;
        }
        builder.add(", $T.class", rawType);
      }
      builder.add(")");
    }
  }
  return builder.add(")").build();
}
 
Example 18
Project: aws-sdk-java-v2   File: TypeProvider.java   Source Code and License 5 votes vote down vote up
public TypeName mapEntryType(MapModel mapModel) {
    TypeName keyType;
    if (mapModel.getKeyModel().isSimple()) {
        keyType = getTypeNameForSimpleType(mapModel.getKeyModel().getVariable().getVariableType());
    } else {
        keyType = parameterType(mapModel.getKeyModel());
    }

    TypeName valueType = parameterType(mapModel.getValueModel());
    if (mapModel.getValueModel().isList()) {
        valueType = WildcardTypeName.subtypeOf(valueType);
    }

    return ParameterizedTypeName.get(ClassName.get(Map.Entry.class), keyType, valueType);
}
 
Example 19
Project: aws-sdk-java-v2   File: EnumClass.java   Source Code and License 5 votes vote down vote up
private MethodSpec knownValuesSpec() {
    return MethodSpec.methodBuilder("knownValues")
                     .returns(ParameterizedTypeName.get(ClassName.get(Set.class), className))
                     .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                     .addJavadoc("Use this in place of {@link #values()} to return a {@link Set} of all values known to the "
                                 + "SDK.\n"
                                 + "This will return all known enum values except {@link #$N}.\n\n"
                                 + "@return a {@link $T} of known {@link $T}s", UNKNOWN_TO_SDK_VERSION, Set.class, className)
                     .addStatement("return $T.of(values()).filter(v -> v != $N).collect(toSet())",
                                   Stream.class,
                                   UNKNOWN_TO_SDK_VERSION)
                     .build();
}
 
Example 20
Project: arez   File: ComponentDescriptor.java   Source Code and License 5 votes vote down vote up
@Nonnull
private MethodSpec buildFindByQueryMethod()
{
  final ParameterizedTypeName queryType =
    ParameterizedTypeName.get( ClassName.get( Predicate.class ), TypeName.get( getElement().asType() ) );
  return MethodSpec.methodBuilder( "findByQuery" ).
    addModifiers( Modifier.PUBLIC, Modifier.FINAL ).
    addAnnotation( GeneratorUtil.NULLABLE_CLASSNAME ).
    addParameter( ParameterSpec.builder( queryType, "query", Modifier.FINAL ).
      addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).build() ).
    returns( TypeName.get( getElement().asType() ) ).
    addStatement( "return entities().stream().filter( query ).findFirst().orElse( null )", Collectors.class ).
    build();
}
 
Example 21
Project: GitHub   File: RequestManagerGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * Generates overrides of existing RequestManager methods so that they return our generated
 * RequestBuilder subtype.
 */
private MethodSpec generateRequestManagerMethodOverride(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));

  return MethodSpec.overriding(methodToOverride)
      .returns(generatedRequestBuilderOfType)
      .addCode(CodeBlock.builder()
          .add("return ($T) super.$N(",
              generatedRequestBuilderOfType, methodToOverride.getSimpleName())
          .add(FluentIterable.from(methodToOverride.getParameters())
              .transform(new Function<VariableElement, String>() {
                @Override
                public String apply(VariableElement input) {
                  return input.getSimpleName().toString();
                }
              })
              .join(Joiner.on(", ")))
          .add(");\n")
          .build())
      .build();
}
 
Example 22
Project: arez   File: ComponentDescriptor.java   Source Code and License 5 votes vote down vote up
@Nonnull
private MethodSpec buildFindAllByQueryMethod()
{
  final ParameterizedTypeName queryType =
    ParameterizedTypeName.get( ClassName.get( Predicate.class ), TypeName.get( getElement().asType() ) );
  return MethodSpec.methodBuilder( "findAllByQuery" ).
    addModifiers( Modifier.PUBLIC, Modifier.FINAL ).
    addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).
    addParameter( ParameterSpec.builder( queryType, "query", Modifier.FINAL ).
      addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).build() ).
    returns( ParameterizedTypeName.get( ClassName.get( List.class ), TypeName.get( getElement().asType() ) ) ).
    addStatement( "return toList( entities().stream().filter( query ) )", Collectors.class ).
    build();
}
 
Example 23
Project: GitHub   File: RequestBuilderGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * Overrides the protected downloadOnly method in {@link com.bumptech.glide.RequestBuilder} to
 * return our generated subclass instead.
 */
private MethodSpec generateDownloadOnlyRequestMethod() {
  ParameterizedTypeName generatedRequestBuilderOfFile
      = ParameterizedTypeName.get(generatedRequestBuilderClassName, ClassName.get(File.class));
  return MethodSpec.methodBuilder("getDownloadOnlyRequest")
      .addAnnotation(Override.class)
      .returns(generatedRequestBuilderOfFile)
      .addModifiers(Modifier.PROTECTED)
      .addStatement("return new $T<>($T.class, $N).apply($N)",
          generatedRequestBuilderClassName, File.class, "this",
          "DOWNLOAD_ONLY_OPTIONS")
      .build();
}
 
Example 24
Project: MRouter   File: ProcessorUtils.java   Source Code and License 5 votes vote down vote up
public static TypeName getTypeName(TypeElement enclosingElement) {
    TypeName targetType = TypeName.get(enclosingElement.asType());
    if (targetType instanceof ParameterizedTypeName) {
        targetType = ((ParameterizedTypeName) targetType).rawType;
    }
    return targetType;
}
 
Example 25
Project: GitHub   File: DelegateClassGenerator.java   Source Code and License 5 votes vote down vote up
@Override
public JavaFile build() {
    TypeSpec.Builder result =
            TypeSpec.classBuilder(getClassName()).addModifiers(Modifier.PUBLIC)
                    .addSuperinterface(
                            ParameterizedTypeName.get(VIEW_DELEGATE, viewClass,
                                                      getPresenterFactoryTypeName()));
    decorator.build(result);
    return JavaFile.builder(getPackageName(), result.build())
            .addFileComment("Generated class from EasyMVP. Do not modify!").build();
}
 
Example 26
Project: GitHub   File: CustomViewDecorator.java   Source Code and License 5 votes vote down vote up
@Override
protected MethodSpec.Builder getOnLoaderResetMethod(ParameterizedTypeName loader) {
    return getCallbacksMethod(METHOD_ON_LOADER_RESET)
            .returns(TypeName.VOID)
            .addParameter(loader, "loader")
            .addStatement("delegate.get().detachView()")
            .addStatement("delegate.get().$L = null", FIELD_PRESENTER);
}
 
Example 27
Project: GitHub   File: PresenterLoaderGenerator.java   Source Code and License 5 votes vote down vote up
@Override
public JavaFile build() {
    TypeSpec.Builder result =
            TypeSpec.classBuilder(getClassName()).addModifiers(Modifier.PUBLIC)
                    .addTypeVariable(TypeVariableName.get("P", Presenter.class))
                    .superclass(ParameterizedTypeName.get(AndroidLoaderUtils.getLoader(supportLibrary),
                                                          TypeVariableName.get("P")));
    addConstructor(result);
    addFields(result);
    addMethods(result);
    return JavaFile.builder(getPackageName(), result.build())
            .addFileComment("Generated class from EasyMVP. Do not modify!").build();
}
 
Example 28
Project: android-auto-mapper   File: TypeUtil.java   Source Code and License 5 votes vote down vote up
public static Element getGenericElement(Element child, Elements elementUtils) {
    TypeName typeName = (TypeName.get(child.asType()));
    if (typeName instanceof ParameterizedTypeName) {
        List<TypeName> typeNames = ((ParameterizedTypeName) typeName).typeArguments;
        if (typeNames != null && typeNames.size() > 0) {
            child = elementUtils.getTypeElement(typeNames.get(0).toString());
        }
    }
    return child;
}
 
Example 29
Project: arez   File: ComponentDescriptor.java   Source Code and License 5 votes vote down vote up
@Nonnull
private MethodSpec buildEntitiesMethod()
{
  return MethodSpec.methodBuilder( "entities" ).
    addModifiers( Modifier.PROTECTED ).
    addAnnotation( AnnotationSpec.builder( ClassName.bestGuess( Constants.OBSERVABLE_ANNOTATION_CLASSNAME ) ).
      addMember( "expectSetter", "false" ).build() ).
    addJavadoc( "Return the raw collection of entities in the repository.\n" +
                "This collection should not be exposed to the user but may be used be repository extensions when\n" +
                "they define custom queries. NOTE: use of this method marks the list as observed.\n" ).
    addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).
    returns( ParameterizedTypeName.get( ClassName.get( Collection.class ), TypeName.get( getElement().asType() ) ) ).
    addStatement( "return $N", ENTITYLIST_FIELD_NAME ).
    build();
}
 
Example 30
Project: GitHub   File: AppModuleGenerator.java   Source Code and License 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 31
Project: aws-sdk-java-v2   File: PaginatorResponseClassSpec.java   Source Code and License 5 votes vote down vote up
/**
 * A {@link MethodSpec} for the overridden iterator() method which is inherited
 * from the interface.
 */
private MethodSpec iteratorMethod() {
    return MethodSpec.methodBuilder("iterator")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(ParameterizedTypeName.get(ClassName.get(Iterator.class), responseType()))
            .addStatement("return new $T($L)", PaginatedResponsesIterator.class, NEXT_PAGE_FETCHER_MEMBER)
            .build();
}
 
Example 32
Project: GitHub   File: JsonObjectHolder.java   Source Code and License 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 33
Project: aws-sdk-java-v2   File: JsonProtocolSpec.java   Source Code and License 5 votes vote down vote up
@Override
public Optional<MethodSpec> createErrorResponseHandler() {
    ClassName httpResponseHandler = ClassName.get(HttpResponseHandler.class);
    ClassName sdkBaseException = ClassName.get(SdkServiceException.class);
    TypeName responseHandlerOfException = ParameterizedTypeName.get(httpResponseHandler, sdkBaseException);

    return Optional.of(MethodSpec.methodBuilder("createErrorResponseHandler")
                                 .returns(responseHandlerOfException)
                                 .addModifiers(Modifier.PRIVATE)
                                 .addStatement("return protocolFactory.createErrorResponseHandler(new $T())",
                                               JsonErrorResponseMetadata.class)
                                 .build());
}
 
Example 34
Project: json-log-domain   File: MdcGenerator.java   Source Code and License 5 votes vote down vote up
public static JavaFile statement(Domain ontology) {
	
	ClassName name = ClassName.get(ontology.getTargetPackage(), ontology.getName() + MARKER_MDC);

	ClassName markerName = MarkerGenerator.getName(ontology);
	
    TypeName wildcard = WildcardTypeName.subtypeOf(DomainMarker.class);
    TypeName classOfAny = ParameterizedTypeName.get(ClassName.get(Class.class), wildcard);
    
	ParameterSpec type = ParameterSpec.builder(classOfAny, "type").build();

	return JavaFile.builder(name.packageName(), TypeSpec.classBuilder(name)
				.superclass(ParameterizedTypeName.get( ClassName.get(DomainMdc.class), markerName))
				.addModifiers(Modifier.PUBLIC)
				.addMethod(MethodSpec.constructorBuilder()
					.addModifiers(Modifier.PUBLIC)
					.addStatement("super($T.QUALIFIER)", markerName)
					.build()
				)
				.addMethod(MethodSpec.methodBuilder("createMarker")
						.addModifiers(Modifier.PUBLIC)
						.addStatement("return new $T()", markerName)
						.returns(markerName)
						.build()
					)
				.addMethod(MethodSpec.methodBuilder("supports")
						.addModifiers(Modifier.PUBLIC)
						.addParameter(type)
						.addStatement("return $T.class == $N", markerName, type)
						.returns(boolean.class)
						.build()
					)
				.build())
			
			.build();
}
 
Example 35
Project: react4j   File: Generator.java   Source Code and License 5 votes vote down vote up
private static FieldSpec.Builder buildProviderField( final @Nonnull ComponentDescriptor descriptor )
{
  return FieldSpec.builder( ParameterizedTypeName.get( PROVIDER_CLASSNAME,
                                                       TypeName.get( descriptor.getDeclaredType() ) ),
                            "c_provider",
                            Modifier.STATIC,
                            Modifier.PRIVATE );
}
 
Example 36
Project: aws-sdk-java-v2   File: BeanGetterHelper.java   Source Code and License 5 votes vote down vote up
private MethodSpec mapOfBuildersGetter(MemberModel memberModel) {
    TypeName keyType = typeProvider.getTypeNameForSimpleType(memberModel.getMapModel().getKeyModel()
                                                                        .getVariable().getVariableType());
    ClassName valueType = poetExtensions.getModelClass(memberModel.getMapModel().getValueModel().getC2jShape());
    TypeName returnType = ParameterizedTypeName.get(ClassName.get(Map.class), keyType, valueType.nestedClass("Builder"));

    return basicGetter(memberModel,
                       returnType,
                       "return $1N != null ? $2T.mapValues($1N, $3T::toBuilder) : null",
                       memberModel.getVariable().getVariableName(),
                       CollectionUtils.class,
                       valueType);
}
 
Example 37
Project: react4j   File: Generator.java   Source Code and License 5 votes vote down vote up
@Nonnull
private static MethodSpec.Builder buildSetProviderMethod( @Nonnull final ComponentDescriptor descriptor )
{
  return MethodSpec.methodBuilder( "setProvider" ).
    addModifiers( Modifier.STATIC ).
    addParameter( ParameterizedTypeName.get( PROVIDER_CLASSNAME,
                                             TypeName.get( descriptor.getDeclaredType() ) ),
                  "provider",
                  Modifier.FINAL ).
    addStatement( "c_provider = provider" );
}
 
Example 38
Project: react4j   File: Generator.java   Source Code and License 5 votes vote down vote up
@Nonnull
private static MethodSpec.Builder buildGetProviderMethod( @Nonnull final ComponentDescriptor descriptor )
{
  return MethodSpec.methodBuilder( "getProvider" ).
    addModifiers( Modifier.PRIVATE, Modifier.STATIC ).
    returns( ParameterizedTypeName.get( PROVIDER_CLASSNAME, TypeName.get( descriptor.getDeclaredType() ) ) ).
    addStatement( "$T.invariant( () -> null != c_provider, () -> \"Attempted to create an instance of the React4j " +
                  "component named '$N' before the dependency injection provider has been initialized. Please see " +
                  "the documentation at https://react4j.github.io/dependency_injection for directions how to " +
                  "configure dependency injection.\" )",
                  GUARDS_CLASSNAME,
                  descriptor.getName() ).
    addStatement( "return c_provider" );
}
 
Example 39
Project: Witch-Android   File: NewViewBinderInstance.java   Source Code and License 5 votes vote down vote up
@Override
public TypeSpec.Builder builder() {
    return TypeSpec.anonymousClassBuilder("$L", viewId)
            .addSuperinterface(ParameterizedTypeName.get(VIEW_BINDER, targetTypeName, viewTypeName, valueTypeName, viewHolderTypeName))
            .addField(TypeUtils.BINDER, "binder", Modifier.PROTECTED);

}
 
Example 40
Project: auto-adapter   File: ViewBinderGenerator.java   Source Code and License 5 votes vote down vote up
private TypeSpec.Builder createClassBuilder(final TypeElement model, final ClassName viewBinderClassName) {
    TypeName modelType = ParameterizedTypeName.get(model.asType());
    ParameterizedTypeName viewHolderBinderTypeName = ParameterizedTypeName.get(VIEW_BINDER_NAME, modelType);

    return TypeSpec.classBuilder(viewBinderClassName).addModifiers(Modifier.FINAL).addSuperinterface(
            viewHolderBinderTypeName);
}
 
Example 41
Project: ActivityBuilder   File: BuilderGenerator.java   Source Code and License 5 votes vote down vote up
public BuilderGenerator(TypeElement activity, TypeElement targetActivity,
    PackageElement targetPackage,
    List<ParameterWriter> parameterList,
    List<ResultModel> resultList, TypeElement baseActivityBuilder,
    TypeSpec consumer) {
  super(activity, targetActivity, targetPackage);
  this.parameterList = parameterList;
  this.resultList = resultList;
  this.baseActivityBuilder = baseActivityBuilder;

  builderClass = ClassName.get(targetPackage.getQualifiedName().toString(),
      targetActivity.getSimpleName() + "Builder");
  builderWithParameter = ParameterizedTypeName.get(builderClass, TypeVariableName.get("A"));
  this.consumer = consumer;
}
 
Example 42
Project: ActivityBuilder   File: BuilderGenerator.java   Source Code and License 5 votes vote down vote up
private MethodSpec buildGetConsumer() {
  TypeName consumerType = ParameterizedTypeName.get(
      ClassName.get(targetPackage.getQualifiedName().toString(), consumer.name),
      TypeVariableName.get("A"));

  return MethodSpec.methodBuilder("getConsumer")
      .addAnnotation(Override.class)
      .addModifiers(Modifier.PROTECTED)
      .returns(consumerType)
      .beginControlFlow("if($L == null)", "consumer")
      .addStatement("$L = new $L<>()", "consumer", consumer.name)
      .endControlFlow()
      .addStatement("return ($T) $L", consumerType, "consumer").build();
}
 
Example 43
Project: butterknife-parent   File: BindingSet.java   Source Code and License 5 votes vote down vote up
private static TypeName bestGuess(String type) {
    switch (type) {
        case "void":
            return TypeName.VOID;
        case "boolean":
            return TypeName.BOOLEAN;
        case "byte":
            return TypeName.BYTE;
        case "char":
            return TypeName.CHAR;
        case "double":
            return TypeName.DOUBLE;
        case "float":
            return TypeName.FLOAT;
        case "int":
            return TypeName.INT;
        case "long":
            return TypeName.LONG;
        case "short":
            return TypeName.SHORT;
        default:
            int left = type.indexOf('<');
            if (left != -1) {
                ClassName typeClassName = ClassName.bestGuess(type.substring(0, left));
                List<TypeName> typeArguments = new ArrayList<>();
                do {
                    typeArguments.add(WildcardTypeName.subtypeOf(Object.class));
                    left = type.indexOf('<', left + 1);
                } while (left != -1);
                return ParameterizedTypeName.get(typeClassName,
                        typeArguments.toArray(new TypeName[typeArguments.size()]));
            }
            return ClassName.bestGuess(type);
    }
}
 
Example 44
Project: ActivityBuilder   File: BuilderUtilGenerator.java   Source Code and License 5 votes vote down vote up
private MethodSpec buildCreateBuilder() {
  return MethodSpec.methodBuilder("createBuilder")
      .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
      .addTypeVariable(TypeVariableName.get("A", ClassName.get(activity)))
      .returns(ParameterizedTypeName.get(ClassName.get(baseActivityBuilder),
          WildcardTypeName.subtypeOf(ClassName.get(baseActivityBuilder)),
          TypeVariableName.get("A")))
      .addParameter(TypeVariableName.get("A"), "activity")
      .addParameter(ParameterizedTypeName.get(ClassName.get(Class.class),
          WildcardTypeName.subtypeOf(ClassName.get(activity))), "clazz")
      .addStatement("return $T.create($L, $L)", ClassName.get(baseActivityBuilder), "activity",
          "clazz")
      .build();
}
 
Example 45
Project: ActivityBuilder   File: BuilderUtilGenerator.java   Source Code and License 5 votes vote down vote up
private MethodSpec buildCreateBuilderWithIntent() {
  return MethodSpec.methodBuilder("createBuilder")
      .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
      .addTypeVariable(TypeVariableName.get("A", ClassName.get(activity)))
      .returns(ParameterizedTypeName.get(ClassName.get(baseActivityBuilder),
          WildcardTypeName.subtypeOf(ClassName.get(baseActivityBuilder)),
          TypeVariableName.get("A")))
      .addParameter(TypeVariableName.get("A"), "activity")
      .addParameter(ClassName.get(Intent.class), "intent")
      .addStatement("return $T.create($L, $L)", ClassName.get(baseActivityBuilder), "activity",
          "intent")
      .build();
}
 
Example 46
Project: ActivityBuilder   File: BuilderUtilGenerator.java   Source Code and License 5 votes vote down vote up
private MethodSpec buildSmallCreate(MethodSpec createBuilder) {
  MethodSpec.Builder builder = MethodSpec.methodBuilder("smallCreate")
      .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
      .addTypeVariable(TypeVariableName.get("A", ClassName.get(activity)))
      .addTypeVariable(TypeVariableName.get("T",
          ParameterizedTypeName.get(ClassName.get(baseActivityBuilder), TypeVariableName.get("T"),
              TypeVariableName.get("A"))))
      .returns(TypeVariableName.get("T"))
      .addParameter(TypeVariableName.get("A"), "activity")
      .addParameter(ParameterizedTypeName.get(ClassName.get(Class.class),
          WildcardTypeName.subtypeOf(ClassName.get(activity))), "clazz");

  builder.beginControlFlow("if ($L.containsKey($L))", "sBuilderMap", "clazz")
      .beginControlFlow("try")
      .addStatement("return (T) $L.get($L).getMethod($S, $T.class).invoke(null,$L)",
          "sBuilderMap", "clazz", "create", ClassName.get(activity), "activity")
      .endControlFlow() // try
      .beginControlFlow("catch ($T e)", ClassName.get(NoSuchMethodException.class))
      .addStatement("e.printStackTrace()")
      .endControlFlow()
      .beginControlFlow("catch ($T e)", ClassName.get(IllegalAccessException.class))
      .addStatement("e.printStackTrace()")
      .endControlFlow()
      .beginControlFlow("catch ($T e)", ClassName.get(InvocationTargetException.class))
      .addStatement("e.printStackTrace()")
      .endControlFlow()
      .endControlFlow() // if
      .addStatement("return (T) $N($L,$L)", createBuilder, "activity", "clazz");

  return builder.build();
}
 
Example 47
Project: ActivityBuilder   File: ResultModel.java   Source Code and License 5 votes vote down vote up
public TypeName getConsumerType() throws IOException {
  int count = getParameters().size();
  if (count > 0) {
    TypeName[] types = new TypeName[count];
    for (int i = 0; i < count; i++) {

      types[i] = TypeName.get(getParameters().get(i).getObjectType());
    }
    return ParameterizedTypeName
        .get(ConsumerHelper.get(count), types);
  } else {
    return ConsumerHelper.get(0);
  }
}
 
Example 48
Project: ActivityBuilder   File: ResultModel.java   Source Code and License 5 votes vote down vote up
public TypeName getConsumerTypeWithContext() throws IOException {
  int count = getParameters().size() + 1;
  TypeName[] types = new TypeName[count];
  types[0] = TypeVariableName.get("A");
  for (int i = 1; i < count; i++) {
    types[i] = TypeName.get(getParameters().get(i - 1).getObjectType());
  }
  return ParameterizedTypeName
      .get(ConsumerHelper.get(count), types);
}
 
Example 49
Project: dataenum   File: TypeVariableUtils.java   Source Code and License 5 votes vote down vote up
static TypeName withoutMissingTypeVariables(
    TypeName typeName, Iterable<TypeVariableName> availableTypeVariables) throws ParserException {
  if (!(typeName instanceof ParameterizedTypeName) || availableTypeVariables == null) {
    return typeName;
  }

  ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName;

  List<TypeName> adjustedArguments = new ArrayList<>();
  for (TypeName argument : parameterizedTypeName.typeArguments) {
    if (argument instanceof ParameterizedTypeName) {
      // Recursive call
      adjustedArguments.add(withoutMissingTypeVariables(argument, availableTypeVariables));
    } else if (argument instanceof TypeVariableName) {
      TypeVariableName variable = (TypeVariableName) argument;
      if (Iterables.contains(availableTypeVariables, variable)) {
        adjustedArguments.add(variable);
      } else {
        if (variable.bounds.size() == 0) {
          adjustedArguments.add(TypeName.OBJECT);
        } else if (variable.bounds.size() == 1) {
          adjustedArguments.add(variable.bounds.get(0));
        } else {
          throw new ParserException("More than one generic type bound is not supported");
        }
      }
    } else {
      adjustedArguments.add(argument);
    }
  }

  TypeName[] adjustedArgumentsArr = adjustedArguments.toArray(new TypeName[] {});
  return ParameterizedTypeName.get(parameterizedTypeName.rawType, adjustedArgumentsArr);
}
 
Example 50
Project: dataenum   File: OutputValueFactory.java   Source Code and License 5 votes vote down vote up
private static TypeName withParametersFromOther(ClassName className, TypeName other) {
  if (other instanceof ParameterizedTypeName) {
    List<TypeName> typeArguments = ((ParameterizedTypeName) other).typeArguments;
    TypeName[] typeArgumentsArr = typeArguments.toArray(new TypeName[] {});
    return ParameterizedTypeName.get(className, typeArgumentsArr);
  }
  return className;
}
 
Example 51
Project: DDComponentForAndroid   File: AnnoUtils.java   Source Code and License 5 votes vote down vote up
public static ParameterSpec generateMethodParameterSpec(TypeMirror typeMirror,
                                                        String paramName) {
    TypeName tn =
            ParameterizedTypeName.get(typeMirror);

    return ParameterSpec.builder(tn, paramName).build();
}
 
Example 52
Project: dataenum   File: OutputValue.java   Source Code and License 5 votes vote down vote up
public TypeName parameterizedOutputClass() {
  if (!hasTypeVariables()) {
    return outputClass();
  }

  TypeName[] typeNames = Iterables.toArray(typeVariables(), TypeVariableName.class);
  return ParameterizedTypeName.get(outputClass(), typeNames);
}
 
Example 53
Project: dataenum   File: OutputSpec.java   Source Code and License 5 votes vote down vote up
public TypeName parameterizedOutputClass() {
  if (!hasTypeVariables()) {
    return outputClass();
  }

  TypeName[] typeNames = Iterables.toArray(typeVariables(), TypeVariableName.class);
  return ParameterizedTypeName.get(outputClass(), typeNames);
}
 
Example 54
Project: java-code-templates   File: TemplateSubstitutionVisitor.java   Source Code and License 5 votes vote down vote up
private TypeSubstitution applyDeclaredTypeSubstitution(final TypeElement element) {
	assertThat(isDeclaredType(element), "Invalid type substitution: %s is not a declared type", element.getQualifiedName());
	final TypeName result = templateInventory.applyTypeSubstitution(element.asType());
	assertThat(result instanceof ClassName || result instanceof ParameterizedTypeName,
			"Failed type substitution: %s is not a ClassName or a ParameterizedTypeName", result);

	if (result instanceof ClassName) {
		return new TypeSubstitution() {
			@Override public ClassName raw() { return (ClassName)result; }
			@Override public List<TypeVariableName> typeParameters() {
				return ImmutableList.of();
			}
		};
	} else {
		final ParameterizedTypeName parameterized = (ParameterizedTypeName)result;
		return new TypeSubstitution() {
			@Override public ClassName raw() {
				return parameterized.rawType;
			}

			@Override
			public List<TypeVariableName> typeParameters() {
				return parameterized.typeArguments
						.stream()
						.map(TypeVariableName.class::cast)
						.collect(toImmutableList());
			}
		};
	}
}
 
Example 55
Project: aws-sdk-java-v2   File: AwsServiceModel.java   Source Code and License 5 votes vote down vote up
private MethodSpec getValueForField() {
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("getValueForField")
                                                 .addModifiers(Modifier.PUBLIC)
                                                 .addTypeVariable(TypeVariableName.get("T"))
                                                 .returns(ParameterizedTypeName.get(ClassName.get(Optional.class),
                                                                                    TypeVariableName.get("T")))
                                                 .addParameter(String.class, "fieldName")
                                                 .addParameter(ParameterizedTypeName.get(ClassName.get(Class.class),
                                                                                         TypeVariableName.get("T")),
                                                               "clazz");

    if (shapeModel.getNonStreamingMembers().isEmpty()) {
        methodBuilder.addStatement("return $T.empty()", Optional.class);
        return methodBuilder.build();
    }


    methodBuilder.beginControlFlow("switch ($L)", "fieldName");

    shapeModel.getNonStreamingMembers().forEach(m -> methodBuilder.addCode("case $S:", m.getC2jName())
                                                                  .addStatement("return $T.of(clazz.cast($L()))",
                                                                                Optional.class,
                                                                                m.getFluentGetterMethodName()));

    methodBuilder.addCode("default:");
    methodBuilder.addStatement("return $T.empty()", Optional.class);
    methodBuilder.endControlFlow();

    return methodBuilder.build();
}
 
Example 56
Project: json2java4idea   File: JsonValueTest.java   Source Code and License 5 votes vote down vote up
@Test
public void wrapShouldReturnJsonArrayWhenList() throws Exception {
    // setup
    final List<String> value = ImmutableList.of("foo", "bar", "baz");

    // exercise
    final JsonValue actual = JsonValue.wrap(value);

    // verify
    assertThat(actual)
            .isJsonArray()
            .hasType(ParameterizedTypeName.get(List.class, Object.class))
            .hasValue(value);
}
 
Example 57
Project: json2java4idea   File: JsonValueTest.java   Source Code and License 5 votes vote down vote up
@Test
public void wrapShouldReturnJsonObjectWhenMap() throws Exception {
    // setup
    final Map<String, String> value = ImmutableMap.of("foo", "bar", "baz", "qux");

    // exercise
    final JsonValue actual = JsonValue.wrap(value);

    // verify
    assertThat(actual)
            .isJsonObject()
            .hasType(ParameterizedTypeName.get(Map.class, String.class, Object.class))
            .hasValue(value);
}
 
Example 58
Project: aws-sdk-java-v2   File: JsonProtocolSpec.java   Source Code and License 5 votes vote down vote up
@Override
public CodeBlock executionHandler(OperationModel opModel) {
    TypeName responseType = poetExtensions.getModelClass(opModel.getReturnType().getReturnType());
    ClassName requestType = poetExtensions.getModelClass(opModel.getInput().getVariableType());
    ClassName marshaller = poetExtensions.getRequestTransformClass(opModel.getInputShape().getShapeName() + "Marshaller");

    final CodeBlock.Builder codeBlock = CodeBlock
            .builder()
            .add("\n\nreturn clientHandler.execute(new $T<$T, $T>()\n" +
                 ".withResponseHandler($N)\n" +
                 ".withErrorResponseHandler($N)\n" +
                 ".withInput($L)\n",
                 ClientExecutionParams.class,
                 requestType,
                 responseType,
                 "responseHandler",
                 "errorResponseHandler",
                 opModel.getInput().getVariableName());

    if (opModel.hasStreamingInput()) {
        return codeBlock.add(".withMarshaller(new $T(new $T(protocolFactory), requestBody)));",
                             ParameterizedTypeName.get(ClassName.get(StreamingRequestMarshaller.class), requestType),
                             marshaller)
                        .build();
    }

    return codeBlock.add(".withMarshaller(new $T(protocolFactory))$L);", marshaller,
                         opModel.hasStreamingOutput() ? ", streamingResponseHandler" : "")
                    .build();
}
 
Example 59
Project: json2java4idea   File: JsonObjectTest.java   Source Code and License 5 votes vote down vote up
@Test
public void getType() throws Exception {
    //exercise
    final TypeName actual = underTest.getType();

    // verify
    assertThat(actual)
            .isEqualTo(ParameterizedTypeName.get(Map.class, String.class, Object.class));
}
 
Example 60
Project: json2java4idea   File: JsonParserImplTest.java   Source Code and License 5 votes vote down vote up
@Test
public void parseShouldReturnJsonArrayWhenArray() throws Exception {
    // exercise
    final JsonValue value = underTest.parse("[]");

    // verify
    assertThat(value)
            .isJsonArray()
            .hasType(ParameterizedTypeName.get(List.class, Object.class))
            .hasValue(Collections.emptyList());
}