Java Code Examples for com.squareup.javapoet.TypeName

The following examples show how to use com.squareup.javapoet.TypeName. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: kripton   Author: xcesco   File: ObjectBindTransform.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void generateSerializeOnXml(BindTypeContext context, MethodSpec.Builder methodBuilder, String serializerName, TypeName beanClass, String beanName, BindProperty property) {
	// TODO QUA
	// TypeName typeName = resolveTypeName(property.getParent(),
	// property.getPropertyType().getTypeName());
	TypeName typeName = property.getPropertyType().getTypeName();

	String bindName = context.getBindMapperName(context, typeName);

	// @formatter:off
	if (property.isNullable() && !property.isInCollection()) {
		methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property));
	}
			
	methodBuilder.addStatement("$L.writeStartElement($S)", serializerName, BindProperty.xmlName(property));
	methodBuilder.addStatement("$L.serializeOnXml($L, xmlSerializer, $T.$L)", bindName, getter(beanName, beanClass, property), EventType.class, EventType.START_TAG);
	methodBuilder.addStatement("$L.writeEndElement()", serializerName);

	if (property.isNullable() && !property.isInCollection()) {
		methodBuilder.endControlFlow();
	}
	// @formatter:on
}
 
Example #2
Source Project: gwt-jackson   Author: nmorel   File: JTypeName.java    License: Apache License 2.0 6 votes vote down vote up
private TypeName primitiveName( JPrimitiveType type, boolean boxed ) {
    if ( "boolean".equals( type.getSimpleSourceName() ) ) {
        return boxed ? BOOLEAN_NAME : TypeName.BOOLEAN;
    } else if ( "byte".equals( type.getSimpleSourceName() ) ) {
        return boxed ? BYTE_NAME : TypeName.BYTE;
    } else if ( "short".equals( type.getSimpleSourceName() ) ) {
        return boxed ? SHORT_NAME : TypeName.SHORT;
    } else if ( "int".equals( type.getSimpleSourceName() ) ) {
        return boxed ? INTEGER_NAME : TypeName.INT;
    } else if ( "long".equals( type.getSimpleSourceName() ) ) {
        return boxed ? LONG_NAME : TypeName.LONG;
    } else if ( "char".equals( type.getSimpleSourceName() ) ) {
        return boxed ? CHARACTER_NAME : TypeName.CHAR;
    } else if ( "float".equals( type.getSimpleSourceName() ) ) {
        return boxed ? FLOAT_NAME : TypeName.FLOAT;
    } else if ( "double".equals( type.getSimpleSourceName() ) ) {
        return boxed ? DOUBLE_NAME : TypeName.DOUBLE;
    } else {
        return boxed ? VOID_NAME : TypeName.VOID;
    }
}
 
Example #3
Source Project: motif   Author: johnlcox   File: Tuple2CasesGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  TypeName A = TypeVariableName.get("A");
  TypeName B = TypeVariableName.get("B");
  TypeName t = ParameterizedTypeName.get(ClassName.get(Tuple2.class), A, B);

  Match2MethodSpec tuple2Match = Match2MethodSpec.builder()
      .withName("tuple2").withSummaryJavadoc("Matches a tuple of 2 elements.\n")
      .withMatchExtractor(Tuple2FieldExtractor.class).withParamA(A, "a").withParamB(B, "b")
      .build();

  JavaFile tuple2CasesFile = CasesGenerator.newBuilder(
      "com.leacox.motif.cases", "Tuple2Cases", t)
      .addFileComment(Copyright.COPYRIGHT_NOTICE)
      .addJavadoc("Motif cases for matching a {@link Tuple2}.\n")
      .addMatch2Method(tuple2Match)
      .build().generate();

  try {
    tuple2CasesFile.writeTo(System.out);
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example #4
Source Project: litho   Author: facebook   File: TypeVariablesExtractor.java    License: Apache License 2.0 6 votes vote down vote up
/** Get the type variables from the given {@link TypeElement}. */
public static List<TypeVariableName> getTypeVariables(TypeElement typeElement) {
  final List<? extends TypeParameterElement> typeParameters = typeElement.getTypeParameters();
  final int typeParameterCount = typeParameters.size();

  final List<TypeVariableName> typeVariables = new ArrayList<>(typeParameterCount);
  for (TypeParameterElement typeParameterElement : typeParameters) {
    final int boundTypesCount = typeParameterElement.getBounds().size();

    final TypeName[] boundsTypeNames = new TypeName[boundTypesCount];
    for (int i = 0; i < boundTypesCount; i++) {
      boundsTypeNames[i] = TypeName.get(typeParameterElement.getBounds().get(i));
    }

    final TypeVariableName typeVariable =
        TypeVariableName.get(typeParameterElement.getSimpleName().toString(), boundsTypeNames);
    typeVariables.add(typeVariable);
  }

  return typeVariables;
}
 
Example #5
Source Project: HighLite   Author: jeppeman   File: SQLiteDAOClass.java    License: Apache License 2.0 6 votes vote down vote up
private MethodSpec buildGetSingleByRawQueryMethod() {
    final String cursorVarName = "cursor";
    return MethodSpec.methodBuilder("getSingle")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(getClassNameOfElement())
            .addParameter(CONTEXT, "context", Modifier.FINAL)
            .addParameter(STRING, "rawQueryClause", Modifier.FINAL)
            .addParameter(ArrayTypeName.of(STRING), "rawQueryArgs", Modifier.FINAL)
            .addParameter(TypeName.BOOLEAN, "fetchForeignKeys", Modifier.FINAL)
            .addParameter(TypeName.BOOLEAN, "fetchRelationships", Modifier.FINAL)
            .addParameter(TypeName.BOOLEAN, "fromCache", Modifier.FINAL)
            .addStatement("final $T $L = getReadableDatabase($L)"
                            + ".rawQuery(rawQueryClause, rawQueryArgs)",
                    CURSOR, cursorVarName, "context")
            .beginControlFlow("if (!$L.moveToFirst())", cursorVarName)
            .addStatement("$L.close()", cursorVarName)
            .addStatement("return null")
            .endControlFlow()
            .addStatement("$T ret = instantiateObject(cursor, context, "
                            + "fetchForeignKeys, fetchRelationships, fromCache)",
                    getClassNameOfElement())
            .addStatement("$L.close()", cursorVarName)
            .addStatement("return ret")
            .build();
}
 
Example #6
Source Project: FastAdapter   Author: aizuzi   File: GeneratedBuilderClass.java    License: MIT License 6 votes vote down vote up
private MethodSpec buildSetValuesMethod() {

    final MethodSpec.Builder lBuilder =
        MethodSpec.methodBuilder("setValues")
            .returns(TypeName.VOID)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL);

    for (int i = 0, size = mFields.size(); i < size; i++) {
      AnnotatedField annotatedField = mFields.get(i);
      FastAttribute fastAttribute = annotatedField.getFastAttribute();

      lBuilder.addCode("putValue(" + fastAttribute.bindViewId() + ", " + annotatedField.name);
    }

    return lBuilder.build();
  }
 
Example #7
Source Project: aircon   Author: ironSource   File: EnumsProviderClassBuilder.java    License: MIT License 6 votes vote down vote up
private MethodSpec createRemoteValueGetter(final TypeElement enumClass, final List<VariableElement> consts) {
	final String methodName = NamingUtils.ENUMS_PROVIDER_REMOTE_VALUE_GETTER_METHOD;
	final MethodSpec.Builder builder = MethodSpec.methodBuilder(methodName)
	                                             .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
	                                             .returns(getRemoteValueType(consts));

	builder.addParameter(TypeName.get(enumClass.asType()), PARAMETER_VALUE, Modifier.FINAL);

	final CodeBlockBuilder bodyCodeBuilder = new CodeBlockBuilder();
	bodyCodeBuilder.beginSwitch(PARAMETER_VALUE);

	for (VariableElement variableElement : consts) {
		Object remoteValue = getRemoteValue(variableElement);
		if (consts.indexOf(variableElement) == consts.size() - 1) {
			bodyCodeBuilder.addDefaultSwitchCase(null);
		}
		bodyCodeBuilder.addSwitchCase(variableElement.getSimpleName(), new CodeBlockBuilder().addReturn(remoteValue)
		                                                                                     .build());
	}

	bodyCodeBuilder.endSwitch();

	return builder.addCode(bodyCodeBuilder.build())
	              .build();
}
 
Example #8
Source Project: kripton   Author: xcesco   File: SQLTransformer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get java.util type Transformable
 *
 * @param type
 *            the type
 * @return the util transform
 */

static SQLTransform getUtilTransform(TypeName type) {
	String typeName = type.toString();

	// Integer.class.getCanonicalName().equals(typeName)
	if (Date.class.getCanonicalName().equals(typeName)) {
		return new DateSQLTransform();
	}
	if (Locale.class.getCanonicalName().equals(typeName)) {
		return new LocaleSQLTransform();
	}
	if (Currency.class.getCanonicalName().equals(typeName)) {
		return new CurrencySQLTransform();
	}
	if (Calendar.class.getCanonicalName().equals(typeName)) {
		return new CalendarSQLTransform();
	}
	if (TimeZone.class.getCanonicalName().equals(typeName)) {
		return new TimeZoneSQLTransform();
	}
	return null;
}
 
Example #9
Source Project: auto-value-bundle   Author: uber   File: BundleExtension.java    License: MIT License 6 votes vote down vote up
private static String unbundleElement(
        Context context,
        VariableElement bundleElement,
        VariableElement deserializerElement,
        String key,
        ExecutableElement method) {
    TypeName type = ClassName.get(method.getReturnType());
    boolean isEnum = method.getReturnType().getKind().equals(ElementKind.ENUM);
    String defaultValue = "";

    GCMBundle gcmBundle = context.autoValueClass().getAnnotation(GCMBundle.class);
    if (gcmBundle != null) {
        return bundlables.parseFromString(bundleElement, deserializerElement, type, key, isEnum);
    } else {
        return bundlables.readType(bundleElement, type, key, deserializerElement, isEnum);
    }

}
 
Example #10
Source Project: toothpick   Author: stephanenicolas   File: MemberInjectorGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void emitSuperMemberInjectorFieldIfNeeded(TypeSpec.Builder scopeMemberTypeSpec) {
  if (superClassThatNeedsInjection != null) {
    FieldSpec.Builder superMemberInjectorField =
        FieldSpec.builder(
                ParameterizedTypeName.get(
                    ClassName.get(MemberInjector.class),
                    TypeName.get(typeUtil.erasure(superClassThatNeedsInjection.asType()))),
                "superMemberInjector",
                Modifier.PRIVATE)
            // TODO use proper typing here
            .initializer(
                "new $L__MemberInjector()",
                getGeneratedFQNClassName(superClassThatNeedsInjection));
    scopeMemberTypeSpec.addField(superMemberInjectorField.build());
  }
}
 
Example #11
Source Project: aws-sdk-java-v2   Author: aws   File: JsonProtocolSpec.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CodeBlock responseHandler(IntermediateModel model, OperationModel opModel) {
    TypeName pojoResponseType = getPojoResponseType(opModel, poetExtensions);

    String protocolFactory = protocolFactoryLiteral(model, opModel);
    CodeBlock.Builder builder = CodeBlock.builder();
    builder.add("$T operationMetadata = $T.builder()\n"
                + ".hasStreamingSuccessResponse($L)\n"
                + ".isPayloadJson($L)\n"
                + ".build();", JsonOperationMetadata.class, JsonOperationMetadata.class,
                opModel.hasStreamingOutput(), !opModel.getHasBlobMemberAsPayload());
    if (opModel.hasEventStreamOutput()) {
        responseHandlersForEventStreaming(opModel, pojoResponseType, protocolFactory, builder);
    } else {
        builder.add("\n\n$T<$T> responseHandler = $L.createResponseHandler(operationMetadata, $T::builder);",
                    HttpResponseHandler.class,
                    pojoResponseType,
                    protocolFactory,
                    pojoResponseType);
    }
    return builder.build();
}
 
Example #12
Source Project: gwt-jackson   Author: nmorel   File: BeanJsonDeserializerCreator.java    License: Apache License 2.0 6 votes vote down vote up
private MethodSpec buildInitDeserializersMethod( Map<PropertyInfo, JDeserializerType> properties ) throws UnableToCompleteException {

        TypeName resultType = ParameterizedTypeName.get( ClassName.get( SimpleStringMap.class ),
                ParameterizedTypeName.get( ClassName.get( BeanPropertyDeserializer.class ),
                        typeName( beanInfo.getType() ), DEFAULT_WILDCARD ) );

        MethodSpec.Builder builder = MethodSpec.methodBuilder( "initDeserializers" )
                .addModifiers( Modifier.PROTECTED )
                .addAnnotation( Override.class )
                .returns( resultType )
                .addStatement( "$T map = $T.createObject().cast()", resultType, SimpleStringMap.class );

        for ( Entry<PropertyInfo, JDeserializerType> entry : properties.entrySet() ) {
            PropertyInfo property = entry.getKey();
            JDeserializerType deserializerType = entry.getValue();

            builder.addStatement( "map.put($S, $L)",
                    property.getPropertyName(), buildDeserializer( property, property.getType(), deserializerType ) );
        }

        builder.addStatement( "return map" );
        return builder.build();
    }
 
Example #13
Source Project: lazythreetenbp   Author: gabrielittner   File: JavaWriter.java    License: Apache License 2.0 6 votes vote down vote up
private FieldSpec regionId(Set<String> allRegionIds) {
    CodeBlock.Builder builder = CodeBlock.builder()
            .add("$T.asList(\n$>$>", Arrays.class);
    Iterator<String> iterator = allRegionIds.iterator();
    while (iterator.hasNext()) {
        builder.add("$S", iterator.next());
        if (iterator.hasNext()) {
            builder.add(",\n");
        }
    }
    builder.add("$<$<)");
    TypeName listType = ParameterizedTypeName.get(List.class, String.class);
    return FieldSpec.builder(listType, "REGION_IDS", STATIC, FINAL)
            .initializer(builder.build())
            .build();
}
 
Example #14
Source Project: motif   Author: johnlcox   File: BaseMatchMethodPermutationBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the statement arguments for the match method returns statement.
 */
protected List<TypeName> getReturnStatementArgs(MatchType matchType, TypeName paramType) {
  List<TypeName> extractA;
  if (matchType == MatchType.DECOMPOSE) {
    TypeName u = match(paramType)
        .when(typeOf(TypeVariableName.class)).get(
            x -> (TypeName) TypeVariableName.get("E" + x.name, x))
        .orElse(x -> x)
        .getMatch();

    extractA = ImmutableList.of(u);
  } else if (matchType == MatchType.ANY) {
    extractA = ImmutableList.of(paramType);
  } else {
    extractA = ImmutableList.of();
  }
  return extractA;
}
 
Example #15
Source Project: fit   Author: 2tu   File: FitProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private String genPutMethod(TypeName fieldTypeName) {
  TypeName unboxFieldTypeName = unbox(fieldTypeName);
  String putMethod = "";

  if (stringTypeName.equals(unboxFieldTypeName)) {
    putMethod = "putString";
  } else if (TypeName.BOOLEAN.equals(unboxFieldTypeName)) {
    putMethod = "putBoolean";
  } else if (TypeName.FLOAT.equals(unboxFieldTypeName)) {
    putMethod = "putFloat";
  } else if (TypeName.INT.equals(unboxFieldTypeName)
      || TypeName.BYTE.equals(unboxFieldTypeName)
      || TypeName.SHORT.equals(unboxFieldTypeName)
      || TypeName.CHAR.equals(unboxFieldTypeName)) {
    putMethod = "putInt";
  } else if (TypeName.LONG.equals(unboxFieldTypeName)) {
    putMethod = "putLong";
  } else if (TypeName.DOUBLE.equals(unboxFieldTypeName)) {
    putMethod = "putLong";
  } else if (setOfHoverboards.equals(unboxFieldTypeName) || hashSetOfHoverboards.equals(
      unboxFieldTypeName)) {
    putMethod = "putStringSet";
  }
  return putMethod;
}
 
Example #16
Source Project: auto-value-bundle   Author: uber   File: GsonDeserializer.java    License: MIT License 6 votes vote down vote up
private String deserializeParameterizedObject(TypeName typeName) {
    if (typeName instanceof ParameterizedTypeName) {
        ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName;
        StringBuilder typeToken = new StringBuilder("<")
                .append(parameterizedTypeName.rawType.simpleName());
        for (TypeName internalTypeName : parameterizedTypeName.typeArguments) {
            typeToken.append(deserializeParameterizedObject(internalTypeName))
                    .append(", ");
        }
        return typeToken.deleteCharAt(typeToken.length() - 1)
                .deleteCharAt(typeToken.length() - 1)
                .append(">")
                .toString();
    } else {
        return ((ClassName) typeName).simpleName() + ">";
    }
}
 
Example #17
Source Project: Kratos   Author: ACEMerlin   File: KratosProcessor.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private void parseBindText(Element element, Map<TypeElement, BindingClass> targetClassMap,
                           Set<String> erasedTargetNames) {
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    TypeMirror elementType = element.asType();
    if (elementType.getKind() == TypeKind.TYPEVAR) {
        TypeVariable typeVariable = (TypeVariable) elementType;
        elementType = typeVariable.getUpperBound();
    }
    // Assemble information on the field.
    int[] ids = element.getAnnotation(BindText.class).value();
    BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, false, false);
    for (int id : ids) {
        if (bindingClass != null) {
            KBindings bindings = bindingClass.getKBindings(String.valueOf(id));
            if (bindings != null) {
                Iterator<FieldViewBinding> iterator = bindings.getFieldBindings().iterator();
                if (iterator.hasNext()) {
                    FieldViewBinding existingBinding = iterator.next();
                    error(element, "Attempt to use @%s for an already bound ID %s on '%s'. (%s.%s)",
                            BindText.class.getSimpleName(), id, existingBinding.getName(),
                            enclosingElement.getQualifiedName(), element.getSimpleName());
                    return;
                }
            }
        } else {
            bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, false, false);
        }
        String name = element.getSimpleName().toString();
        TypeName type = TypeName.get(elementType);
        boolean required = isRequiredBinding(element);

        FieldViewBinding binding = new FieldViewBinding(name, type, required);
        bindingClass.addField(String.valueOf(id), binding);
    }

    // Add the type-erased version to the valid binding targets set.
    erasedTargetNames.add(enclosingElement.toString());
}
 
Example #18
Source Project: auto-matter   Author: danielnorberg   File: AutoMatterProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private CodeBlock fieldNotEqualCheck(final ExecutableElement field) throws AutoMatterProcessorException {
  final String name = fieldName(field);
  final CodeBlock.Builder result = CodeBlock.builder();
  final TypeMirror returnType = field.getReturnType();
  switch (returnType.getKind()) {
    case LONG:
    case INT:
    case BOOLEAN:
    case BYTE:
    case SHORT:
    case CHAR:
      result.beginControlFlow("if ($L != that.$L())", name, name);
      break;
    case FLOAT:
    case DOUBLE:
      final TypeName boxed = ClassName.get(returnType).box();
      result.beginControlFlow("if ($T.compare($L, that.$L()) != 0)", boxed, name, name);
      break;
    case ARRAY:
      result.beginControlFlow("if (!$T.equals($L, that.$L()))", ClassName.get(Arrays.class), name, name);
      break;
    case TYPEVAR:
    case DECLARED:
    case ERROR:
      result.beginControlFlow(
          "if ($L != null ? !$L.equals(that.$L()) : that.$L() != null)",
          name, name, name, name);
      break;
    default:
      throw fail("Unsupported type: " + returnType, field);
  }

  result.addStatement("return false").endControlFlow();
  return result.build();
}
 
Example #19
Source Project: litho   Author: facebook   File: EventValidation.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean isFromEventTypeSpecifiedInAnnotation(
    MethodParamModel methodParamModel, TypeName eventFieldType) {
  FromEvent fromEvent =
      (FromEvent) MethodParamModelUtils.getAnnotation(methodParamModel, FromEvent.class);
  TypeName baseClassType;
  try {
    baseClassType = ClassName.get(fromEvent.baseClass());
  } catch (MirroredTypeException mte) {
    baseClassType = ClassName.get(mte.getTypeMirror());
  }
  return baseClassType.equals(eventFieldType);
}
 
Example #20
Source Project: aws-sdk-java-v2   Author: aws   File: JsonProtocolSpec.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<MethodSpec> createErrorResponseHandler() {
    ClassName httpResponseHandler = ClassName.get(HttpResponseHandler.class);
    ClassName sdkBaseException = ClassName.get(AwsServiceException.class);
    TypeName responseHandlerOfException = ParameterizedTypeName.get(httpResponseHandler, sdkBaseException);

    return Optional.of(MethodSpec.methodBuilder("createErrorResponseHandler")
                                 .addParameter(BaseAwsJsonProtocolFactory.class, "protocolFactory")
                                 .addParameter(JsonOperationMetadata.class, "operationMetadata")
                                 .returns(responseHandlerOfException)
                                 .addModifiers(Modifier.PRIVATE)
                                 .addStatement("return protocolFactory.createErrorResponseHandler(operationMetadata)")
                                 .build());
}
 
Example #21
Source Project: Freezer   Author: florent37   File: ProcessUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static TypeName getEnclosedTypeName(Element element) {
    List<TypeName> parameters = getParameters(element);
    if (parameters == null || parameters.isEmpty()) {
        return null;
    } else {
        return parameters.get(0);
    }
}
 
Example #22
Source Project: litho   Author: facebook   File: DiffValidationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDiffModelHasDifferentParameterFromProp() {
  when(mDiffModel.getName()).thenReturn("propName");
  when(mDiffModel.getTypeName())
      .thenReturn(
          ParameterizedTypeName.get(ClassNames.DIFF, TypeName.BOOLEAN.box())
              .annotated(AnnotationSpec.builder(Prop.class).build()));
  when(mDiffModel.getAnnotations()).thenReturn(ImmutableList.of(annotation(Prop.class)));

  List<SpecModelValidationError> validationErrors = DiffValidation.validate(mSpecModel);
  assertSingleError(validationErrors, DiffValidation.PROP_MISMATCH_ERROR);
}
 
Example #23
Source Project: litho   Author: facebook   File: MatcherGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private static MethodSpec sipBuilder(SpecModel specModel, final PropModel prop) {
  final AnnotationSpec spAnnotation =
      AnnotationSpec.builder(ClassNames.DIMENSION)
          .addMember("unit", "$T.SP", ClassNames.DIMENSION)
          .build();

  return builder(
      specModel,
      prop,
      prop.getName() + "Sp",
      Collections.singletonList(parameter(prop, TypeName.FLOAT, "sips", spAnnotation)),
      "$L.sipsToPixels(sips)",
      RESOURCE_RESOLVER);
}
 
Example #24
Source Project: AndServer   Author: yanzhenjie   File: InterceptorProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private Map<String, List<TypeElement>> findAnnotation(RoundEnvironment roundEnv) {
    Set<? extends Element> set = roundEnv.getElementsAnnotatedWith(Interceptor.class);
    Map<String, List<TypeElement>> interceptorMap = new HashMap<>();

    for (Element element : set) {
        if (element instanceof TypeElement) {
            TypeElement typeElement = (TypeElement) element;

            Set<Modifier> modifiers = typeElement.getModifiers();
            Validate.isTrue(modifiers.contains(Modifier.PUBLIC), "The modifier public is missing on %s.",
                typeElement.getQualifiedName());

            List<? extends TypeMirror> interfaces = typeElement.getInterfaces();
            if (CollectionUtils.isEmpty(interfaces)) {
                mLog.w(String.format(
                    "The annotation Interceptor must be used in a subclass of [HandlerInterceptor] on %s.",
                    typeElement.getQualifiedName()));
                continue;
            }
            for (TypeMirror typeMirror : interfaces) {
                if (mInterceptor.equals(TypeName.get(typeMirror))) {
                    String group = getGroup(typeElement);
                    List<TypeElement> elementList = interceptorMap.get(group);
                    if (CollectionUtils.isEmpty(elementList)) {
                        elementList = new ArrayList<>();
                        interceptorMap.put(group, elementList);
                    }
                    elementList.add(typeElement);
                    break;
                } else {
                    mLog.w(String.format(
                        "The annotation Interceptor must be used in a subclass of [HandlerInterceptor] on %s.",
                        typeElement.getQualifiedName()));
                }
            }
        }
    }
    return interceptorMap;
}
 
Example #25
Source Project: litho   Author: facebook   File: BuilderGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private static MethodSpec dynamicValueBuilder(
    SpecModel specModel, PropModel prop, int requiredIndex, TypeName dynamicValueType) {
  return getMethodSpecBuilder(
          specModel,
          prop,
          requiredIndex,
          prop.getName(),
          Arrays.asList(
              parameter(
                  prop,
                  KotlinSpecUtils.getFieldTypeName(specModel, dynamicValueType),
                  prop.getName())),
          prop.getName())
      .build();
}
 
Example #26
Source Project: Mockery   Author: VictorAlbertos   File: TestClass.java    License: Apache License 2.0 5 votes vote down vote up
Method(String name, Element element, TypeName returnType,
    List<Param> params, boolean hasMockery) {
  this.name = name;
  this.element = element;
  this.returnType = returnType;
  this.params = params;
  this.hasMockery = hasMockery;
}
 
Example #27
Source Project: raml-java-tools   Author: mulesoft-labs   File: BoxWhenNotRequiredTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void boxOnNotRequired() {

    when(integerDeclaration.required()).thenReturn(false);

    BoxWhenNotRequired boxWhenNotRequired = new BoxWhenNotRequired(null);
    TypeName tn = boxWhenNotRequired.typeName(null, integerDeclaration, TypeName.INT);
    assertEquals(TypeName.INT.box(), tn);
}
 
Example #28
Source Project: kripton   Author: xcesco   File: PrefsTransformer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get transformer for type.
 *
 * @param property the property
 * @return transform
 */
public static PrefsTransform lookup(PrefsProperty property) {
	TypeMirror typeMirror = property.getElement().asType();

	TypeName typeName = typeName(typeMirror);
	return lookup(typeName);
}
 
Example #29
Source Project: auto   Author: google   File: FactoryWriter.java    License: Apache License 2.0 5 votes vote down vote up
private void addImplementationMethods(
    TypeSpec.Builder factory, FactoryDescriptor descriptor) {
  for (ImplementationMethodDescriptor methodDescriptor :
      descriptor.implementationMethodDescriptors()) {
    MethodSpec.Builder implementationMethod =
        methodBuilder(methodDescriptor.name())
            .addAnnotation(Override.class)
            .returns(TypeName.get(methodDescriptor.returnType()))
            .varargs(methodDescriptor.isVarArgs());
    if (methodDescriptor.publicMethod()) {
      implementationMethod.addModifiers(PUBLIC);
    }
    implementationMethod.addParameters(parameters(methodDescriptor.passedParameters()));
    implementationMethod.addStatement(
        "return create($L)",
        FluentIterable.from(methodDescriptor.passedParameters())
            .transform(
                new Function<Parameter, String>() {
                  @Override
                  public String apply(Parameter parameter) {
                    return parameter.name();
                  }
                })
            .join(ARGUMENT_JOINER));
    factory.addMethod(implementationMethod.build());
  }
}
 
Example #30
Source Project: paperparcel   Author: grandstaish   File: PaperParcelAutoValueExtension.java    License: Apache License 2.0 5 votes vote down vote up
@Override public String generateClass(
    Context context, String simpleName, String classToExtend, boolean isFinal) {

  ClassName className = ClassName.get(context.packageName(), simpleName);
  TypeSpec.Builder subclass = TypeSpec.classBuilder(className)
      .addModifiers(FINAL)
      .addMethod(constructor(context))
      .addAnnotation(PaperParcel.class)
      .addField(creator(className))
      .addMethod(writeToParcel(className));

  ClassName superClass = ClassName.get(context.packageName(), classToExtend);
  List<? extends TypeParameterElement> typeParams = context.autoValueClass().getTypeParameters();
  if (typeParams.isEmpty()) {
    subclass.superclass(superClass);
  } else {
    TypeName[] superTypeVariables = new TypeName[typeParams.size()];
    for (int i = 0, size = typeParams.size(); i < size; i++) {
      TypeParameterElement typeParam = typeParams.get(i);
      subclass.addTypeVariable(TypeVariableName.get(typeParam));
      superTypeVariables[i] = TypeVariableName.get(typeParam.getSimpleName().toString());
    }
    subclass.superclass(ParameterizedTypeName.get(superClass, superTypeVariables));
  }

  if (needsContentDescriptor(context)) {
    subclass.addMethod(describeContents());
  }

  return JavaFile.builder(context.packageName(), subclass.build())
      .build()
      .toString();
}