com.squareup.javapoet.WildcardTypeName Java Examples

The following examples show how to use com.squareup.javapoet.WildcardTypeName. 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: BindingSet.java    From butterknife with Apache License 2.0 6 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 #2
Source File: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 6 votes vote down vote up
private MethodSpec collectionIteratorSetter(final Descriptor d, final ExecutableElement field) {
  String fieldName = fieldName(field);
  ClassName iteratorType = ClassName.get(Iterator.class);
  TypeName itemType = genericArgument(d, field, 0);
  WildcardTypeName extendedType = subtypeOf(itemType);

  MethodSpec.Builder setter = MethodSpec.methodBuilder(fieldName)
      .addModifiers(PUBLIC)
      .addParameter(ParameterizedTypeName.get(iteratorType, extendedType), fieldName)
      .returns(builderType(d));

  collectionNullGuard(setter, field);

  setter.addStatement("this.$N = new $T()", fieldName, collectionImplType(d, field))
      .beginControlFlow("while ($N.hasNext())", fieldName)
      .addStatement("$T item = $N.next()", itemType, fieldName);

  if (shouldEnforceNonNull(field)) {
    assertNotNull(setter, "item", fieldName + ": null item");
  }

  setter.addStatement("this.$N.add(item)", fieldName)
      .endControlFlow();

  return setter.addStatement("return this").build();
}
 
Example #3
Source File: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 6 votes vote down vote up
private MethodSpec collectionIterableSetter(final Descriptor d, final ExecutableElement field) {
  String fieldName = fieldName(field);
  ClassName iterableType = ClassName.get(Iterable.class);
  TypeName itemType = genericArgument(d, field, 0);
  WildcardTypeName extendedType = subtypeOf(itemType);

  MethodSpec.Builder setter = MethodSpec.methodBuilder(fieldName)
      .addModifiers(PUBLIC)
      .addParameter(ParameterizedTypeName.get(iterableType, extendedType), fieldName)
      .returns(builderType(d));

  collectionNullGuard(setter, field);

  ClassName collectionType = ClassName.get(Collection.class);
  setter.beginControlFlow("if ($N instanceof $T)", fieldName, collectionType)
      .addStatement("return $N(($T<$T>) $N)", fieldName, collectionType, extendedType, fieldName)
      .endControlFlow();

  setter.addStatement("return $N($N.iterator())", fieldName, fieldName);
  return setter.build();
}
 
Example #4
Source File: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 6 votes vote down vote up
private MethodSpec collectionCollectionSetter(final Descriptor d, final ExecutableElement field) {
  String fieldName = fieldName(field);
  ClassName collectionType = ClassName.get(Collection.class);
  TypeName itemType = genericArgument(d, field, 0);
  WildcardTypeName extendedType = subtypeOf(itemType);

  MethodSpec.Builder setter = MethodSpec.methodBuilder(fieldName)
      .addModifiers(PUBLIC)
      .addParameter(ParameterizedTypeName.get(collectionType, extendedType), fieldName)
      .returns(builderType(d));

  collectionNullGuard(setter, field);
  if (shouldEnforceNonNull(field)) {
    setter.beginControlFlow("for ($T item : $N)", itemType, fieldName);
    assertNotNull(setter, "item", fieldName + ": null item");
    setter.endControlFlow();
  }

  setter.addStatement("this.$N = new $T($N)", fieldName, collectionImplType(d, field), fieldName);
  return setter.addStatement("return this").build();
}
 
Example #5
Source File: PresenterBinderClassGenerator.java    From Moxy with MIT License 6 votes vote down vote up
private static MethodSpec generateProvidePresenterMethod(TargetPresenterField field,
                                                         ClassName targetClassName) {
	MethodSpec.Builder builder = MethodSpec.methodBuilder("providePresenter")
			.addAnnotation(Override.class)
			.addModifiers(Modifier.PUBLIC)
			.returns(ParameterizedTypeName.get(
					ClassName.get(MvpPresenter.class), WildcardTypeName.subtypeOf(Object.class)))
			.addParameter(targetClassName, "delegated");

	if (field.getPresenterProviderMethodName() != null) {
		builder.addStatement("return delegated.$L()", field.getPresenterProviderMethodName());
	} else {
		boolean hasEmptyConstructor = Util.hasEmptyConstructor((TypeElement) ((DeclaredType) field.getClazz()).asElement());

		if (hasEmptyConstructor) {
			builder.addStatement("return new $T()", field.getTypeName());
		} else {
			builder.addStatement(
					"throw new $T($S + $S)", IllegalStateException.class,
					field.getClazz(), " has not default constructor. You can apply @ProvidePresenter to some method which will construct Presenter. Also you can make it default constructor");
		}
	}

	return builder.build();
}
 
Example #6
Source File: ServiceHolderWriter.java    From Android-Developer-Toolbelt with Apache License 2.0 6 votes vote down vote up
private MethodSpec createStartServices() {
    ClassName memoryServiceConnection = ClassName.get(PACKAGE, "MemoryServiceConnection");

    CodeBlock code = CodeBlock.builder()
            .beginControlFlow("for($T service: $L)", ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(Service.class)), FIELD_SERVICES)
            .addStatement("$T intent = new $T(context, service)", Intent.class, Intent.class)
            .addStatement("context.startService(intent)")
            .add("\n")
            .addStatement("$T connection = new $T()", memoryServiceConnection, memoryServiceConnection)
            .addStatement("context.bindService(intent, connection, Context.BIND_AUTO_CREATE)")
            .endControlFlow()
            .build();

    return MethodSpec.methodBuilder("startServices")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .addParameter(ClassName.get(Context.class), "context")
            .addCode(code)
            .build();
}
 
Example #7
Source File: MemberCopierSpec.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private MethodSpec builderCopyMethodForList() {
    ClassName listParameter = poetExtensions.getModelClass(memberModel.getListModel().getListMemberModel().getC2jShape());
    ClassName builderForParameter = listParameter.nestedClass("Builder");

    TypeName parameterType =
        ParameterizedTypeName.get(ClassName.get(Collection.class), WildcardTypeName.subtypeOf(builderForParameter));

    CodeBlock code = CodeBlock.builder()
                              .beginControlFlow("if ($N == null)", memberParamName())
                              .addStatement("return null")
                              .endControlFlow()
                              .addStatement("return $N($N.stream().map($T::$N).collect(toList()))",
                                            serviceModelCopiers.copyMethodName(),
                                            memberParamName(),
                                            builderForParameter,
                                            "build")
                              .build();

    return MethodSpec.methodBuilder(serviceModelCopiers.builderCopyMethodName())
                     .addModifiers(Modifier.STATIC)
                     .addParameter(parameterType, memberParamName())
                     .returns(typeProvider.fieldType(memberModel))
                     .addCode(code)
                     .build();
}
 
Example #8
Source File: CovariantListPlugin.java    From raml-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public MethodSpec.Builder getterBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration declaration, MethodSpec.Builder incoming, EventType eventType) {

    if ( eventType == EventType.INTERFACE) {

        if (isNotTargetDefaultType(objectPluginContext, declaration, arguments)) return incoming;

            if ( arguments.size() == 1 ) {

                // override.....
                incoming.returns(
                        ParameterizedTypeName.get(
                                ClassName.get(List.class), WildcardTypeName.subtypeOf(ClassName.bestGuess(arguments.get(0)))));
                return incoming;
            }

        MethodSpec build = incoming.build();
        ParameterizedTypeName type = (ParameterizedTypeName) build.returnType;

        incoming.returns(ParameterizedTypeName.get(type.rawType, WildcardTypeName.subtypeOf(type.typeArguments.get(0))));
    }

    return incoming;
}
 
Example #9
Source File: MemberCopierSpec.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private MethodSpec builderCopyMethodForMap() {
    TypeName keyType = typeProvider.getTypeNameForSimpleType(memberModel.getMapModel().getKeyModel()
                                                                        .getVariable().getVariableType());
    ClassName valueParameter = poetExtensions.getModelClass(memberModel.getMapModel().getValueModel().getC2jShape());
    ClassName builderForParameter = valueParameter.nestedClass("Builder");
    TypeName parameterType =
        ParameterizedTypeName.get(ClassName.get(Map.class), keyType, WildcardTypeName.subtypeOf(builderForParameter));

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

    return MethodSpec.methodBuilder(serviceModelCopiers.builderCopyMethodName())
                     .addModifiers(Modifier.STATIC)
                     .addParameter(parameterType, memberParamName())
                     .returns(typeProvider.fieldType(memberModel))
                     .addCode(code)
                     .build();
}
 
Example #10
Source File: RDFSPropertySpecTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoverAll() throws Exception {
    BuildableRDFSProperty loadCap = getPropertyFromModel("http://example.de/ont#load_capacity");
    assertNotNull(loadCap);

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

    // Test signature:
    assertEquals("removeAllMaximumLoadCapacities", loadCapSpec.name);
    assertTrue(loadCapSpec.modifiers.contains(Modifier.PUBLIC));
    assertEquals(1, loadCapSpec.parameters.size());
    ClassName setClass = ClassName.get("java.util", "Set");
    assertEquals(ParameterizedTypeName.get(setClass, WildcardTypeName.subtypeOf(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(0, loadCapSpec.annotations.size());
}
 
Example #11
Source File: RDFSPropertySpecTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testAdderAll() throws Exception {
    BuildableRDFSProperty loadCap = getPropertyFromModel("http://example.de/ont#load_capacity");
    assertNotNull(loadCap);

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

    // Test signature:
    assertEquals("addAllMaximumLoadCapacities", loadCapSpec.name);
    assertTrue(loadCapSpec.modifiers.contains(Modifier.PUBLIC));
    assertEquals(1, loadCapSpec.parameters.size());
    ClassName setClass = ClassName.get("java.util", "Set");
    assertEquals(ParameterizedTypeName.get(setClass, WildcardTypeName.subtypeOf(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(0, loadCapSpec.annotations.size());
}
 
Example #12
Source File: SpaceInjection.java    From vault with Apache License 2.0 6 votes vote down vote up
private void appendTypes(TypeSpec.Builder builder) {
  // Field
  TypeName classTypeName = ParameterizedTypeName.get(ClassName.get(Class.class),
      WildcardTypeName.subtypeOf(Resource.class));

  specTypes =
      createMapWithInitializer("types", LinkedHashMap.class, ClassName.get(String.class),
          classTypeName)
          .addModifiers(Modifier.FINAL)
          .build();

  builder.addField(specTypes);

  // Getter
  builder.addMethod(createGetterImpl(specTypes, "getTypes").build());
}
 
Example #13
Source File: SpaceInjection.java    From vault with Apache License 2.0 6 votes vote down vote up
private void appendModels(TypeSpec.Builder builder) {
  // Field
  TypeName classTypeName = ParameterizedTypeName.get(ClassName.get(Class.class),
      WildcardTypeName.subtypeOf(Object.class));

  TypeName helperTypeName = ParameterizedTypeName.get(ClassName.get(ModelHelper.class),
      WildcardTypeName.subtypeOf(Object.class));

  specModels = createMapWithInitializer("models", LinkedHashMap.class, classTypeName,
      helperTypeName).addModifiers(Modifier.FINAL).build();

  builder.addField(specModels);

  // Getter
  builder.addMethod(createGetterImpl(specModels, "getModels").build());
}
 
Example #14
Source File: AsyncResponseClassSpec.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * A {@link MethodSpec} for the subscribe() method which is inherited from the interface.
 */
private MethodSpec subscribeMethod() {
    return MethodSpec.methodBuilder(SUBSCRIBE_METHOD)
                     .addAnnotation(Override.class)
                     .addModifiers(Modifier.PUBLIC)
                     .addParameter(ParameterizedTypeName.get(ClassName.get(Subscriber.class),
                                                             WildcardTypeName.supertypeOf(responseType())),
                                   SUBSCRIBER)
                     .addStatement("$1L.onSubscribe($2T.builder().$1L($1L).$3L($4L).build())",
                                   SUBSCRIBER, ResponsesSubscription.class,
                                   NEXT_PAGE_FETCHER_MEMBER, nextPageFetcherArgument())
                     .build();
}
 
Example #15
Source File: TypeProvider.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private TypeName mapValueParameterType(MapModel mapModel, boolean preserveEnum) {
    TypeName valueType = parameterType(mapModel.getValueModel(), preserveEnum);
    if (mapModel.getValueModel().isList()) {
        valueType = WildcardTypeName.subtypeOf(valueType);
    }

    return valueType;
}
 
Example #16
Source File: ViewStateProviderClassGenerator.java    From Moxy with MIT License 5 votes vote down vote up
private MethodSpec generateGetViewStateMethod(ClassName presenter, ClassName viewState) {
	MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("getViewState")
			.addAnnotation(Override.class)
			.addModifiers(Modifier.PUBLIC)
			.returns(ParameterizedTypeName.get(ClassName.get(MvpViewState.class), WildcardTypeName.subtypeOf(MvpView.class)));

	if (viewState == null) {
		methodBuilder.addStatement("throw new RuntimeException($S)", presenter.reflectionName() + " should has view");
	} else {
		methodBuilder.addStatement("return new $T()", viewState);
	}

	return methodBuilder.build();
}
 
Example #17
Source File: AdapterNameGenerator.java    From paperparcel with Apache License 2.0 5 votes vote down vote up
private String getNameInternal(TypeName typeName) {
  String adapterName = null;
  if (typeName instanceof WildcardTypeName) {
    WildcardTypeName wildcardTypeName = (WildcardTypeName) typeName;
    String upperBoundsPart = "";
    String lowerBoundsPart = "";
    for (TypeName upperBound : wildcardTypeName.upperBounds) {
      upperBoundsPart += getNameInternal(upperBound);
    }
    for (TypeName lowerBound : wildcardTypeName.lowerBounds) {
      lowerBoundsPart += getNameInternal(lowerBound);
    }
    adapterName = upperBoundsPart + lowerBoundsPart;
  }
  if (typeName instanceof ArrayTypeName) {
    ArrayTypeName arrayTypeName = (ArrayTypeName) typeName;
    adapterName = getNameInternal(arrayTypeName.componentType) + "Array";
  }
  if (typeName instanceof ParameterizedTypeName) {
    ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName;
    String paramPart = "";
    for (TypeName param : parameterizedTypeName.typeArguments) {
      paramPart += getNameInternal(param);
    }
    adapterName = paramPart + parameterizedTypeName.rawType.simpleName();
  }
  if (typeName instanceof ClassName) {
    ClassName className = (ClassName) typeName;
    adapterName = Joiner.on("_").join(className.simpleNames());
  }
  if (typeName.isPrimitive()) {
    adapterName = typeName.toString();
  }
  if (adapterName == null) {
    throw new AssertionError();
  }
  return adapterName;
}
 
Example #18
Source File: EasyType.java    From RapidORM with Apache License 2.0 5 votes vote down vote up
public 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 #19
Source File: EasyType.java    From RapidORM with Apache License 2.0 5 votes vote down vote up
/**
 * @param type
 * @return
 */
public static TypeName bestGuessDeep(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('<');
            int right = type.indexOf('>');
            if (-1 != left && -1 != right) {
                ClassName typeClassName = ClassName.bestGuess(type.substring(0, left));
                List<TypeName> typeArguments = new ArrayList<>();
                do {
                    typeArguments.add(WildcardTypeName.subtypeOf(bestGuess(type.substring(left + 1, right))));
                    left = type.indexOf('<', left + 1);
                    right = type.indexOf('>', right - 1);
                } while (left != -1);
                return ParameterizedTypeName.get(typeClassName,
                        typeArguments.toArray(new TypeName[typeArguments.size()]));
            }
            return ClassName.bestGuess(type);
    }
}
 
Example #20
Source File: ServiceHolderWriter.java    From Android-Developer-Toolbelt with Apache License 2.0 5 votes vote down vote up
private FieldSpec createFieldServices() {
    TypeName type = ParameterizedTypeName.get(ClassName.get(List.class), ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(ClassName.get(Service.class))));

    CodeBlock.Builder builder = CodeBlock.builder()
            .add("new $T(){{\n", ParameterizedTypeName.get(ClassName.get(ArrayList.class), ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(ClassName.get(Service.class)))));

    for (int i = 1; i <= ToolbeltProcessor.NUMBER_OF_SERVICES; i++) {
        builder.addStatement("add($T.class)", ClassName.bestGuess("MemoryService" + i));
    }
    builder.add("}}");

    return FieldSpec.builder(type, FIELD_SERVICES, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
            .initializer(builder.build().toString())
            .build();
}
 
Example #21
Source File: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 5 votes vote down vote up
private MethodSpec collectionSetter(final Descriptor d, final ExecutableElement field) {
  String fieldName = fieldName(field);
  ClassName collectionType = collectionRawType(field);
  TypeName itemType = genericArgument(d, field, 0);
  WildcardTypeName extendedType = subtypeOf(itemType);

  return MethodSpec.methodBuilder(fieldName)
      .addModifiers(PUBLIC)
      .addParameter(ParameterizedTypeName.get(collectionType, extendedType), fieldName)
      .returns(builderType(d))
      .addStatement("return $N((Collection<$T>) $N)", fieldName, extendedType, fieldName)
      .build();
}
 
Example #22
Source File: JTypeName.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
private WildcardTypeName wildcardName( JWildcardType type ) {
    switch ( type.getBoundType() ) {
        case SUPER:
            return WildcardTypeName.supertypeOf( typeName( type.getFirstBound() ) );
        default:
            return WildcardTypeName.subtypeOf( typeName( type.getFirstBound() ) );
    }
}
 
Example #23
Source File: AbiTypesMapperGenerator.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
private void generate(String destinationDir) throws IOException {

        String typesPackageName = "org.fisco.bcos.web3j.abi.datatypes";
        String autoGeneratedTypesPackageName = typesPackageName + ".generated";

        MethodSpec.Builder builder =
                MethodSpec.methodBuilder("getType")
                        .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                        .addParameter(String.class, TYPE)
                        .returns(
                                ParameterizedTypeName.get(
                                        ClassName.get(Class.class),
                                        WildcardTypeName.subtypeOf(Object.class)))
                        .beginControlFlow("switch (type)");

        builder = addTypes(builder, typesPackageName);
        builder = addGeneratedTypes(builder, autoGeneratedTypesPackageName);
        builder =
                builder.addStatement(
                        "default:\nthrow new $T($S\n+ $N)",
                        UnsupportedOperationException.class,
                        "Unsupported type encountered: ",
                        TYPE);
        builder.endControlFlow();

        MethodSpec methodSpec = builder.build();

        MethodSpec constructorSpec =
                MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build();

        TypeSpec typeSpec =
                TypeSpec.classBuilder("AbiTypes")
                        .addJavadoc(buildWarning(AbiTypesMapperGenerator.class))
                        .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                        .addMethod(constructorSpec)
                        .addMethod(methodSpec)
                        .build();

        write(autoGeneratedTypesPackageName, typeSpec, destinationDir);
    }
 
Example #24
Source File: AbiTypesMapperGenerator.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private void generate(String destinationDir) throws IOException {

        String typesPackageName = "org.web3j.abi.datatypes";
        String autoGeneratedTypesPackageName = typesPackageName + ".generated";

        MethodSpec.Builder builder = MethodSpec.methodBuilder("getType")
                .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                .addParameter(String.class, TYPE)
                .returns(
                        ParameterizedTypeName.get(ClassName.get(Class.class),
                                WildcardTypeName.subtypeOf(Object.class))
                )
                .beginControlFlow("switch (type)");

        builder = addTypes(builder, typesPackageName);
        builder = addGeneratedTypes(builder, autoGeneratedTypesPackageName);
        builder = builder.addStatement("default:\nthrow new $T($S\n+ $N)",
                UnsupportedOperationException.class,
                "Unsupported type encountered: ", TYPE);
        builder.endControlFlow();

        MethodSpec methodSpec = builder.build();

        MethodSpec constructorSpec = MethodSpec.constructorBuilder()
                .addModifiers(Modifier.PRIVATE)
                .build();

        TypeSpec typeSpec = TypeSpec
                .classBuilder("AbiTypes")
                .addJavadoc(buildWarning(AbiTypesMapperGenerator.class))
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .addMethod(constructorSpec)
                .addMethod(methodSpec)
                .build();

        write(autoGeneratedTypesPackageName, typeSpec, destinationDir);
    }
 
Example #25
Source File: PsiTypeUtils.java    From litho with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static TypeName getWildcardTypeName(String wildcardTypeName) {
  if (wildcardTypeName.equals("?")) {
    return WildcardTypeName.subtypeOf(Object.class);
  }
  Matcher matcher = SUPER_PATTERN.matcher(wildcardTypeName);
  if (matcher.find()) {
    return WildcardTypeName.supertypeOf(guessClassName(matcher.group(1)));
  }
  matcher = EXTENDS_PATTERN.matcher(wildcardTypeName);
  if (matcher.find()) {
    return WildcardTypeName.subtypeOf(guessClassName(matcher.group(1)));
  }
  return guessClassName(wildcardTypeName);
}
 
Example #26
Source File: BuilderGenerator.java    From litho with Apache License 2.0 5 votes vote down vote up
private static TypeName[] getBuilderGenericTypes(TypeName type, ClassName builderClass) {
  if (builderClass.equals(ClassNames.COMPONENT_BUILDER)
      || builderClass.equals(ClassNames.SECTION_BUILDER)) {
    return new TypeName[] {WildcardTypeName.subtypeOf(TypeName.OBJECT)};
  } else {
    final TypeName typeParameter =
        type instanceof ParameterizedTypeName
                && !((ParameterizedTypeName) type).typeArguments.isEmpty()
            ? ((ParameterizedTypeName) type).typeArguments.get(0)
            : WildcardTypeName.subtypeOf(ClassNames.COMPONENT);

    return new TypeName[] {typeParameter};
  }
}
 
Example #27
Source File: MatcherGenerator.java    From litho with Apache License 2.0 5 votes vote down vote up
private static TypeName[] getBuilderGenericTypes(
    final TypeName type, final ClassName builderClass) {
  final TypeName typeParameter =
      type instanceof ParameterizedTypeName
              && !((ParameterizedTypeName) type).typeArguments.isEmpty()
          ? ((ParameterizedTypeName) type).typeArguments.get(0)
          : WildcardTypeName.subtypeOf(ClassNames.COMPONENT_LIFECYCLE);

  if (builderClass.equals(ClassNames.COMPONENT_BUILDER)) {
    return new TypeName[] {WildcardTypeName.subtypeOf(TypeName.OBJECT)};
  } else {
    return new TypeName[] {typeParameter};
  }
}
 
Example #28
Source File: JsonProtocolSpec.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Add responseHandlers for event streaming operations
 */
private void responseHandlersForEventStreaming(OperationModel opModel, TypeName pojoResponseType,
                                               String protocolFactory, CodeBlock.Builder builder) {
    builder.add("\n\n$T<$T> responseHandler = new $T($L.createResponseHandler(operationMetadata, $T::builder));",
                HttpResponseHandler.class,
                pojoResponseType,
                AttachHttpMetadataResponseHandler.class,
                protocolFactory,
                pojoResponseType);

    builder.add("\n\n$T<$T> voidResponseHandler = $L.createResponseHandler($T.builder()\n" +
                "                                   .isPayloadJson(false)\n" +
                "                                   .hasStreamingSuccessResponse(true)\n" +
                "                                   .build(), $T::builder);",
                HttpResponseHandler.class,
                SdkResponse.class,
                protocolFactory,
                JsonOperationMetadata.class,
                VoidSdkResponse.class);

    ShapeModel eventStream = EventStreamUtils.getEventStreamInResponse(opModel.getOutputShape());
    ClassName eventStreamBaseClass = poetExtensions.getModelClassFromShape(eventStream);
    builder
        .add("\n\n$T<$T> eventResponseHandler = $L.createResponseHandler($T.builder()\n" +
             "                                   .isPayloadJson(true)\n" +
             "                                   .hasStreamingSuccessResponse(false)\n" +
             "                                   .build(), $T.builder()",
             HttpResponseHandler.class,
             WildcardTypeName.subtypeOf(eventStreamBaseClass),
             protocolFactory,
             JsonOperationMetadata.class,
             ClassName.get(EventStreamTaggedUnionPojoSupplier.class));
    EventStreamUtils.getEventMembers(eventStream)
                    .forEach(m -> builder.add(".putSdkPojoSupplier(\"$L\", $T::builder)\n",
                                              m.getC2jName(), poetExtensions.getModelClass(m.getShape().getC2jName())));
    builder.add(".defaultSdkPojoSupplier(() -> new $T($T.UNKNOWN))\n"
                + ".build());\n", SdkPojoBuilder.class, eventStreamBaseClass);
}
 
Example #29
Source File: ValueTypeFactory.java    From dataenum with Apache License 2.0 5 votes vote down vote up
private static TypeName withWildCardTypeParameters(OutputValue value) {
  if (!value.hasTypeVariables()) {
    return value.outputClass();
  }

  TypeName[] wildCards = new TypeName[Iterables.sizeOf(value.typeVariables())];

  Arrays.fill(wildCards, WildcardTypeName.subtypeOf(TypeName.OBJECT));

  return ParameterizedTypeName.get(value.outputClass(), wildCards);
}
 
Example #30
Source File: AwsServiceModel.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private MethodSpec sdkFieldsMethod() {
    ParameterizedTypeName sdkFieldType = ParameterizedTypeName.get(ClassName.get(SdkField.class),
                                                                   WildcardTypeName.subtypeOf(ClassName.get(Object.class)));
    return MethodSpec.methodBuilder("sdkFields")
                     .addModifiers(PUBLIC)
                     .addAnnotation(Override.class)
                     .returns(ParameterizedTypeName.get(ClassName.get(List.class), sdkFieldType))
                     .addCode("return SDK_FIELDS;")
                     .build();
}