Search in sources :

Example 6 with CodeBlock

use of com.squareup.javapoet.CodeBlock in project pixel-dungeon-remix by NYRDS.

the class PdAnnotationProcessor method process.

@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
    Map<Element, Set<Element>> fieldsByClass = new HashMap<>();
    Map<Element, String> defaultValues = new HashMap<>();
    // for each javax.lang.model.element.Element annotated with the CustomAnnotation
    for (Element element : roundEnvironment.getElementsAnnotatedWith(Packable.class)) {
        Element parent = element.getEnclosingElement();
        String defaultValue = element.getAnnotation(Packable.class).defaultValue();
        if (!defaultValue.isEmpty()) {
            defaultValues.put(element, defaultValue);
        }
        if (fieldsByClass.get(parent) == null) {
            fieldsByClass.put(parent, new HashSet<Element>());
        }
        fieldsByClass.get(parent).add(element);
    }
    TypeSpec BundleHelper = TypeSpec.classBuilder("BundleHelper").addModifiers(Modifier.PUBLIC, Modifier.FINAL).build();
    MethodSpec pack = MethodSpec.methodBuilder("Pack").addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(void.class).addParameter(ClassName.get("com.watabou.utils", "Bundlable"), "arg").addParameter(ClassName.get("com.watabou.utils", "Bundle"), "bundle").beginControlFlow("try").build();
    MethodSpec unpack = MethodSpec.methodBuilder("UnPack").addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(void.class).addParameter(ClassName.get("com.watabou.utils", "Bundlable"), "arg").addParameter(ClassName.get("com.watabou.utils", "Bundle"), "bundle").beginControlFlow("try").build();
    for (Element clazz : fieldsByClass.keySet()) {
        CodeBlock packerBlock = CodeBlock.builder().beginControlFlow("if(arg instanceof $T)", TypeName.get(clazz.asType())).build();
        CodeBlock unpackerBlock = CodeBlock.builder().beginControlFlow("if(arg instanceof $T)", TypeName.get(clazz.asType())).build();
        for (Element field : fieldsByClass.get(clazz)) {
            String fieldName = field.getSimpleName().toString();
            packerBlock = packerBlock.toBuilder().addStatement("$T $L = $T.class.getDeclaredField($S)", Field.class, fieldName, TypeName.get(clazz.asType()), fieldName).addStatement("$L.setAccessible(true)", fieldName).addStatement("bundle.put($S,($T)$L.get(arg))", fieldName, TypeName.get(field.asType()), fieldName).build();
            unpackerBlock = unpackerBlock.toBuilder().addStatement("$T $L = $T.class.getDeclaredField($S)", Field.class, fieldName, TypeName.get(clazz.asType()), fieldName).addStatement("$L.setAccessible(true)", fieldName).build();
            String fieldType = TypeName.get(field.asType()).toString();
            String defaultValue = defaultValues.get(field);
            if (fieldType.equals("int")) {
                if (defaultValue == null || defaultValue.isEmpty()) {
                    defaultValue = "0";
                }
                unpackerBlock = unpackerBlock.toBuilder().addStatement("$L.setInt(arg,bundle.optInt($S,$L))", fieldName, fieldName, defaultValue).build();
                continue;
            }
            if (fieldType.equals("boolean")) {
                if (defaultValue == null || defaultValue.isEmpty()) {
                    defaultValue = "false";
                }
                unpackerBlock = unpackerBlock.toBuilder().addStatement("$L.setBoolean(arg,bundle.optBoolean($S,$L))", fieldName, fieldName, defaultValue).build();
                continue;
            }
            if (fieldType.equals("float")) {
                if (defaultValue == null || defaultValue.isEmpty()) {
                    defaultValue = "0.0f";
                }
                unpackerBlock = unpackerBlock.toBuilder().addStatement("$L.setFloat(arg,bundle.optFloat($S,$L))", fieldName, fieldName, defaultValue).build();
                continue;
            }
            if (fieldType.equals("java.lang.String")) {
                if (defaultValue == null || defaultValue.isEmpty()) {
                    defaultValue = "Unknown";
                }
                unpackerBlock = unpackerBlock.toBuilder().addStatement("$L.set(arg,bundle.optString($S,$S))", fieldName, fieldName, defaultValue).build();
                continue;
            }
            Set<Class<?>> fieldInterfaces = new HashSet<>();
            Collections.addAll(fieldInterfaces, field.getClass().getInterfaces());
            Set<String> fieldInterfaceNames = new HashSet<>();
            for (Class<?> clazzz : fieldInterfaces) {
                fieldInterfaceNames.add(clazzz.getSimpleName());
            }
            /*
				if(fieldType.equals("Collection")) {
					unpackerBlock = unpackerBlock.toBuilder()
							.addStatement("$L.set(arg,bundle.getCollection($S,$S))", fieldName,fieldName,fieldType+".class")
							.build();
					continue;
				}
*/
            if (fieldType.equals("Bundlable")) {
                unpackerBlock = unpackerBlock.toBuilder().addStatement("($S)$L.set(arg,bundle.get($S))", fieldType + ".class", fieldName, fieldName).build();
                continue;
            }
        }
        packerBlock = packerBlock.toBuilder().endControlFlow().build();
        unpackerBlock = unpackerBlock.toBuilder().endControlFlow().build();
        pack = pack.toBuilder().addCode(packerBlock).build();
        unpack = unpack.toBuilder().addCode(unpackerBlock).build();
    }
    pack = pack.toBuilder().nextControlFlow("catch ($T e)", NoSuchFieldException.class).addStatement("throw new $T(e)", ClassName.get("com.nyrds.android.util", "TrackedRuntimeException")).nextControlFlow("catch ($T e)", IllegalAccessException.class).addStatement("throw new $T(e)", ClassName.get("com.nyrds.android.util", "TrackedRuntimeException")).endControlFlow().build();
    unpack = unpack.toBuilder().nextControlFlow("catch ($T e)", NoSuchFieldException.class).addStatement("throw new $T(e)", ClassName.get("com.nyrds.android.util", "TrackedRuntimeException")).nextControlFlow("catch ($T e)", IllegalAccessException.class).addStatement("throw new $T(e)", ClassName.get("com.nyrds.android.util", "TrackedRuntimeException")).endControlFlow().build();
    BundleHelper = BundleHelper.toBuilder().addMethod(pack).addMethod(unpack).build();
    JavaFile javaFile = JavaFile.builder("com.nyrds.generated", BundleHelper).build();
    try {
        // write the file
        JavaFileObject source = processingEnv.getFiler().createSourceFile("com.nyrds.generated.BundleHelper");
        Writer writer = source.openWriter();
        javaFile.writeTo(writer);
        writer.flush();
        writer.close();
    } catch (IOException e) {
    // Note: calling e.printStackTrace() will print IO errors
    // that occur from the file already existing after its first run, this is normal
    }
    return true;
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) MethodSpec(com.squareup.javapoet.MethodSpec) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) CodeBlock(com.squareup.javapoet.CodeBlock) IOException(java.io.IOException) Field(java.lang.reflect.Field) JavaFileObject(javax.tools.JavaFileObject) JavaFile(com.squareup.javapoet.JavaFile) Writer(java.io.Writer) TypeSpec(com.squareup.javapoet.TypeSpec) HashSet(java.util.HashSet)

Example 7 with CodeBlock

use of com.squareup.javapoet.CodeBlock in project arez by arez.

the class ComponentDescriptor method buildSetNullOnDisposeDepsMethod.

@Nonnull
private MethodSpec buildSetNullOnDisposeDepsMethod() throws ArezProcessorException {
    final MethodSpec.Builder builder = MethodSpec.methodBuilder(GeneratorUtil.SET_NULL_ON_DISPOSE_METHOD_NAME);
    builder.addModifiers(Modifier.PRIVATE, Modifier.FINAL);
    final AtomicInteger count = new AtomicInteger(1);
    getSetNullOnDisposeDependencies().forEach(d -> {
        final String varName = "dependency" + count.get();
        count.incrementAndGet();
        builder.addStatement("final $T $N = $N()", d.getMethod().getReturnType(), varName, d.getMethod().getSimpleName().toString());
        final CodeBlock.Builder codeBlock = CodeBlock.builder();
        codeBlock.beginControlFlow("if ( !$T.observe( $N ) ) ", GeneratorUtil.COMPONENT_OBSERVABLE_CLASSNAME, varName);
        codeBlock.addStatement("$N( null )", d.getObservable().getSetter().getSimpleName().toString());
        codeBlock.endControlFlow("");
        builder.addCode(codeBlock.build());
    });
    return builder.build();
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CodeBlock(com.squareup.javapoet.CodeBlock) Nonnull(javax.annotation.Nonnull)

Example 8 with CodeBlock

use of com.squareup.javapoet.CodeBlock in project arez by arez.

the class ObservableDescriptor method buildObservableSetter.

/**
 * Generate the setter that reports that ensures that the access is reported as Observable.
 */
@Nonnull
private MethodSpec buildObservableSetter() throws ArezProcessorException {
    assert null != _setter;
    assert null != _setterType;
    assert null != _getter;
    final MethodSpec.Builder builder = MethodSpec.methodBuilder(_setter.getSimpleName().toString());
    ProcessorUtil.copyAccessModifiers(_setter, builder);
    ProcessorUtil.copyExceptions(_setterType, builder);
    ProcessorUtil.copyTypeParameters(_setterType, builder);
    ProcessorUtil.copyDocumentedAnnotations(_setter, builder);
    builder.addAnnotation(Override.class);
    // actually changed
    if (null == _setter.getAnnotation(Deprecated.class) && null != _getter.getAnnotation(Deprecated.class)) {
        builder.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "deprecation").build());
    }
    final TypeMirror parameterType = _setterType.getParameterTypes().get(0);
    final VariableElement element = _setter.getParameters().get(0);
    final String paramName = element.getSimpleName().toString();
    final TypeName type = TypeName.get(parameterType);
    final ParameterSpec.Builder param = ParameterSpec.builder(type, paramName, Modifier.FINAL);
    ProcessorUtil.copyDocumentedAnnotations(element, param);
    builder.addParameter(param.build());
    GeneratorUtil.generateNotDisposedInvariant(_componentDescriptor, builder);
    final CodeBlock.Builder codeBlock = CodeBlock.builder();
    final boolean abstractObservables = getGetter().getModifiers().contains(Modifier.ABSTRACT);
    if (type.isPrimitive()) {
        if (abstractObservables) {
            codeBlock.beginControlFlow("if ( $N != this.$N )", paramName, getDataFieldName());
        } else {
            codeBlock.beginControlFlow("if ( $N != super.$N() )", paramName, _getter.getSimpleName());
        }
    } else {
        if (abstractObservables) {
            codeBlock.beginControlFlow("if ( !$T.equals( $N, this.$N ) )", Objects.class, paramName, getDataFieldName());
        } else {
            codeBlock.beginControlFlow("if ( !$T.equals( $N, super.$N() ) )", Objects.class, paramName, _getter.getSimpleName());
        }
    }
    codeBlock.addStatement("this.$N.preReportChanged()", getFieldName());
    if (abstractObservables) {
        codeBlock.addStatement("this.$N = $N", getDataFieldName(), paramName);
    } else {
        codeBlock.addStatement("super.$N($N)", _setter.getSimpleName(), paramName);
    }
    codeBlock.addStatement("this.$N.reportChanged()", getFieldName());
    codeBlock.endControlFlow();
    builder.addCode(codeBlock.build());
    return builder.build();
}
Also used : ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) MethodSpec(com.squareup.javapoet.MethodSpec) TypeMirror(javax.lang.model.type.TypeMirror) ParameterSpec(com.squareup.javapoet.ParameterSpec) CodeBlock(com.squareup.javapoet.CodeBlock) VariableElement(javax.lang.model.element.VariableElement) Nonnull(javax.annotation.Nonnull)

Example 9 with CodeBlock

use of com.squareup.javapoet.CodeBlock in project RxBus by ViTess.

the class ProxyBuilder method createMethodCode.

private CodeBlock createMethodCode(MethodBinder binder) {
    CodeBlock.Builder builder = CodeBlock.builder();
    Set<String> tags = binder.getTags();
    for (String tag : tags) {
        ClassName thread = getRxThread(binder.getThreadType());
        TypeMirror paramType = binder.getParamType();
        TypeName typeName;
        if (paramType == null) {
            typeName = DEFAULT_OBJECT;
        } else {
            if (paramType.getKind().isPrimitive()) {
                typeName = TypeName.get(paramType);
                if (!typeName.isBoxedPrimitive())
                    typeName = typeName.box();
            } else
                typeName = ClassName.get(paramType);
        }
        CodeBlock.Builder b = CodeBlock.builder();
        b.addStatement("createMethod($S\n,$T()\n,$T.class,$L)", tag, thread, typeName, createProxyAction(binder));
        builder.add(b.build());
    }
    return builder.build();
}
Also used : ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) TypeMirror(javax.lang.model.type.TypeMirror) CodeBlock(com.squareup.javapoet.CodeBlock) ClassName(com.squareup.javapoet.ClassName)

Example 10 with CodeBlock

use of com.squareup.javapoet.CodeBlock in project auto by google.

the class FactoryWriter method addFactoryMethods.

private void addFactoryMethods(TypeSpec.Builder factory, FactoryDescriptor descriptor, ImmutableSet<TypeVariableName> factoryTypeVariables) {
    for (FactoryMethodDescriptor methodDescriptor : descriptor.methodDescriptors()) {
        MethodSpec.Builder method = methodBuilder(methodDescriptor.name()).addTypeVariables(getMethodTypeVariables(methodDescriptor, factoryTypeVariables)).returns(TypeName.get(methodDescriptor.returnType())).varargs(methodDescriptor.isVarArgs());
        if (methodDescriptor.overridingMethod()) {
            method.addAnnotation(Override.class);
        }
        if (methodDescriptor.publicMethod()) {
            method.addModifiers(PUBLIC);
        }
        method.addExceptions(methodDescriptor.exceptions().stream().map(TypeName::get).collect(toList()));
        CodeBlock.Builder args = CodeBlock.builder();
        method.addParameters(parameters(methodDescriptor.passedParameters()));
        Iterator<Parameter> parameters = methodDescriptor.creationParameters().iterator();
        for (int argumentIndex = 1; parameters.hasNext(); argumentIndex++) {
            Parameter parameter = parameters.next();
            boolean checkNotNull = !parameter.nullable().isPresent();
            CodeBlock argument;
            if (methodDescriptor.passedParameters().contains(parameter)) {
                argument = CodeBlock.of(parameter.name());
                if (parameter.isPrimitive()) {
                    checkNotNull = false;
                }
            } else {
                ProviderField provider = requireNonNull(descriptor.providers().get(parameter.key()));
                argument = CodeBlock.of(provider.name());
                if (parameter.isProvider()) {
                    // Providers are checked for nullness in the Factory's constructor.
                    checkNotNull = false;
                } else {
                    argument = CodeBlock.of("$L.get()", argument);
                }
            }
            if (checkNotNull) {
                argument = CodeBlock.of("checkNotNull($L, $L)", argument, argumentIndex);
            }
            args.add(argument);
            if (parameters.hasNext()) {
                args.add(", ");
            }
        }
        method.addStatement("return new $T($L)", methodDescriptor.returnType(), args.build());
        factory.addMethod(method.build());
    }
}
Also used : TypeName(com.squareup.javapoet.TypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) MethodSpec(com.squareup.javapoet.MethodSpec) CodeBlock(com.squareup.javapoet.CodeBlock)

Aggregations

CodeBlock (com.squareup.javapoet.CodeBlock)42 MethodSpec (com.squareup.javapoet.MethodSpec)19 TypeMirror (javax.lang.model.type.TypeMirror)13 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)11 TypeName (com.squareup.javapoet.TypeName)10 CompilationAbstractTest (com.google.auto.value.extension.serializable.serializer.utils.CompilationAbstractTest)8 ClassName (com.squareup.javapoet.ClassName)8 WireField (com.squareup.wire.WireField)8 Field (com.squareup.wire.schema.Field)8 ByteString (okio.ByteString)8 Test (org.junit.Test)8 JvmLanguages.builtInAdapterString (com.squareup.wire.schema.internal.JvmLanguages.builtInAdapterString)7 ArrayList (java.util.ArrayList)7 Serializer (com.google.auto.value.extension.serializable.serializer.interfaces.Serializer)6 ParameterSpec (com.squareup.javapoet.ParameterSpec)6 AnnotationSpec (com.squareup.javapoet.AnnotationSpec)4 TypeSpec (com.squareup.javapoet.TypeSpec)3 Element (javax.lang.model.element.Element)3 Predicate (com.google.common.base.Predicate)2 FieldSpec (com.squareup.javapoet.FieldSpec)2