Search in sources :

Example 91 with ParameterSpec

use of com.squareup.javapoet.ParameterSpec in project ChidoriX by Chihiro23333.

the class AutowiredProcessor method generateHelper.

private void generateHelper() throws IOException, IllegalAccessException {
    TypeElement type_ISyringe = elements.getTypeElement(Constants.ISYRINGE);
    TypeElement type_JsonService = elements.getTypeElement(Constants.JSON_SERVICE);
    TypeMirror activityTm = elements.getTypeElement(Constants.ACTIVITY).asType();
    TypeMirror fragmentTm = elements.getTypeElement(Constants.FRAGMENT).asType();
    TypeMirror fragmentTmV4 = elements.getTypeElement(Constants.FRAGMENT_V4).asType();
    TypeMirror bundleTm = elements.getTypeElement(Constants.BUNDLE).asType();
    // Build input param name.
    ParameterSpec objectParamSpec = ParameterSpec.builder(TypeName.OBJECT, "target").build();
    ParameterSpec bundleParamSpec = AnnoUtils.generateMethodParameterSpec(bundleTm, "bundle");
    if (MapUtils.isNotEmpty(parentAndChild)) {
        for (Map.Entry<TypeElement, List<Element>> entry : parentAndChild.entrySet()) {
            // Build method : 'inject'
            MethodSpec.Builder injectMethodBuilder = MethodSpec.methodBuilder("inject").addAnnotation(Override.class).addModifiers(PUBLIC).addParameter(objectParamSpec);
            // Build method: void preCondition(Bundle bundle);
            MethodSpec.Builder preConditionMethodBuilder = MethodSpec.methodBuilder("preCondition").addAnnotation(Override.class).addModifiers(PUBLIC).addException(ParamException).addParameter(bundleParamSpec);
            TypeElement parent = entry.getKey();
            List<Element> children = entry.getValue();
            String qualifiedName = parent.getQualifiedName().toString();
            String packageName = qualifiedName.substring(0, qualifiedName.lastIndexOf("."));
            String fileName = parent.getSimpleName() + SUFFIX_AUTOWIRED;
            logger.info(">>> Start process " + children.size() + " field in " + parent.getSimpleName() + " ... <<<");
            TypeSpec.Builder helper = TypeSpec.classBuilder(fileName).addJavadoc("Auto generated by " + TAG).addSuperinterface(ClassName.get(type_ISyringe)).addModifiers(PUBLIC);
            FieldSpec jsonServiceField = FieldSpec.builder(TypeName.get(type_JsonService.asType()), "jsonService", Modifier.PRIVATE).build();
            helper.addField(jsonServiceField);
            logger.info("======== inject jsonservice");
            injectMethodBuilder.addStatement("jsonService = $T.Factory.getSingletonImpl()", ClassName.get(type_JsonService));
            injectMethodBuilder.addStatement("$T substitute = ($T)target", ClassName.get(parent), ClassName.get(parent));
            // Generate method body, start inject.
            for (Element element : children) {
                Autowired fieldConfig = element.getAnnotation(Autowired.class);
                String fieldName = element.getSimpleName().toString();
                String originalValue = "substitute." + fieldName;
                String statement = "substitute." + fieldName + " = substitute.";
                boolean isActivity = false;
                if (types.isSubtype(parent.asType(), activityTm)) {
                    // Activity, then use getIntent()
                    isActivity = true;
                    statement += "getIntent().";
                } else if (types.isSubtype(parent.asType(), fragmentTm) || types.isSubtype(parent.asType(), fragmentTmV4)) {
                    // Fragment, then use getArguments()
                    statement += "getArguments().";
                } else {
                    throw new IllegalAccessException("The field [" + fieldName + "] need " + "autowired from intent, its parent must be activity or fragment!");
                }
                statement = buildStatement(originalValue, statement, typeUtils.typeExchange(element), isActivity);
                if (statement.startsWith("jsonService.")) {
                    // Not mortals
                    injectMethodBuilder.beginControlFlow("if (null != jsonService)");
                    injectMethodBuilder.addStatement("substitute." + fieldName + " = " + statement, (StringUtils.isEmpty(fieldConfig.name()) ? fieldName : fieldConfig.name()), ClassName.get(element.asType()));
                    injectMethodBuilder.nextControlFlow("else");
                    injectMethodBuilder.addStatement("$T.e(\"" + TAG + "\", \"You want automatic inject the field '" + fieldName + "' in class '$T' ," + " but JsonService not found in Router\")", AndroidLog, ClassName.get(parent));
                    injectMethodBuilder.endControlFlow();
                } else {
                    injectMethodBuilder.addStatement(statement, StringUtils.isEmpty(fieldConfig.name()) ? fieldName : fieldConfig.name());
                }
                // Validator
                if (fieldConfig.required() && !element.asType().getKind().isPrimitive()) {
                    // Primitive wont be check.
                    injectMethodBuilder.beginControlFlow("if (null == substitute." + fieldName + ")");
                    injectMethodBuilder.addStatement("$T.e(\"" + TAG + "\", \"The field '" + fieldName + "' is null," + "field description is:" + fieldConfig.desc() + ",in class '\" + $T.class.getName() + \"!\")", AndroidLog, ClassName.get(parent));
                    if (fieldConfig.throwOnNull()) {
                        injectMethodBuilder.addStatement("throw new $T(" + "\"The field '" + fieldName + "' is null," + "field description is:" + fieldConfig.desc() + ",in class '\" + $T.class.getName() + \"!\")", NullPointerException, ClassName.get(parent));
                    }
                    injectMethodBuilder.endControlFlow();
                }
                if (fieldConfig.required()) {
                    preConditionMethodBuilder.beginControlFlow("if (!bundle.containsKey(\"" + fieldName + "\"))");
                    preConditionMethodBuilder.addStatement("throw new $T(" + "\"" + fieldName + "\")", ParamException);
                    preConditionMethodBuilder.endControlFlow();
                }
            }
            helper.addMethod(injectMethodBuilder.build());
            // //////////////
            helper.addMethod(preConditionMethodBuilder.build());
            // Generate autowire helper
            JavaFile.builder(packageName, helper.build()).build().writeTo(mFiler);
            logger.info(">>> " + parent.getSimpleName() + " has been processed, " + fileName + " has been generated. <<<");
        }
        logger.info(">>> Autowired processor stop. <<<");
    }
}
Also used : ParameterSpec(com.squareup.javapoet.ParameterSpec) MethodSpec(com.squareup.javapoet.MethodSpec) TypeElement(javax.lang.model.element.TypeElement) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) FieldSpec(com.squareup.javapoet.FieldSpec) Autowired(com.luojilab.router.facade.annotation.Autowired) TypeMirror(javax.lang.model.type.TypeMirror) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 92 with ParameterSpec

use of com.squareup.javapoet.ParameterSpec in project easy-modeling by easymodeling.

the class BuilderGenerator method builderConstructor.

private MethodSpec builderConstructor() {
    final ParameterSpec constructorParameter = ParameterSpec.builder(className, "model").build();
    final MethodSpec.Builder builder = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).addParameter(constructorParameter);
    fields.stream().map(StatementProvider::constructorStatement).forEach(builder::addStatement);
    return builder.build();
}
Also used : ParameterSpec(com.squareup.javapoet.ParameterSpec) MethodSpec(com.squareup.javapoet.MethodSpec)

Example 93 with ParameterSpec

use of com.squareup.javapoet.ParameterSpec in project auto-matter by danielnorberg.

the class AutoMatterProcessor method valueConstructor.

private MethodSpec valueConstructor(final Descriptor d) {
    MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(PRIVATE);
    assertFieldsNotNull(d, constructor);
    for (ExecutableElement field : d.fields()) {
        String fieldName = fieldName(field);
        AnnotationSpec annotation = AnnotationSpec.builder(AutoMatter.Field.class).addMember("value", "$S", fieldName).build();
        ParameterSpec parameter = ParameterSpec.builder(fieldType(d, field), fieldName).addAnnotation(annotation).build();
        constructor.addParameter(parameter);
        final ClassName collectionsType = ClassName.get(Collections.class);
        if (shouldEnforceNonNull(field) && isCollection(field)) {
            final TypeName itemType = genericArgument(d, field, 0);
            constructor.addStatement("this.$N = ($N != null) ? $N : $T.<$T>$L()", fieldName, fieldName, fieldName, collectionsType, itemType, emptyCollection(field));
        } else if (shouldEnforceNonNull(field) && isMap(field)) {
            final TypeName keyType = genericArgument(d, field, 0);
            final TypeName valueType = genericArgument(d, field, 1);
            constructor.addStatement("this.$N = ($N != null) ? $N : $T.<$T, $T>$L()", fieldName, fieldName, fieldName, collectionsType, keyType, valueType, emptyCollection(field));
        } else {
            constructor.addStatement("this.$N = $N", fieldName, fieldName);
        }
    }
    d.checkMethod().ifPresent(checkMethod -> {
        if (checkMethod.getModifiers().contains(STATIC)) {
            constructor.addCode("$L.$N(this);\n", d.valueTypeName(), checkMethod.getSimpleName());
        } else if (checkMethod.getModifiers().contains(DEFAULT)) {
            constructor.addCode("$N();\n", checkMethod.getSimpleName());
        }
    });
    return constructor.build();
}
Also used : TypeName(com.squareup.javapoet.TypeName) WildcardTypeName(com.squareup.javapoet.WildcardTypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) ArrayTypeName(com.squareup.javapoet.ArrayTypeName) MethodSpec(com.squareup.javapoet.MethodSpec) ParameterSpec(com.squareup.javapoet.ParameterSpec) ExecutableElement(javax.lang.model.element.ExecutableElement) ClassName(com.squareup.javapoet.ClassName) AutoMatter(io.norberg.automatter.AutoMatter) AnnotationSpec(com.squareup.javapoet.AnnotationSpec) Builder(com.squareup.javapoet.MethodSpec.Builder)

Example 94 with ParameterSpec

use of com.squareup.javapoet.ParameterSpec in project metaschema-java by usnistgov.

the class AbstractTypeInfo method build.

@Override
public Set<@NotNull INamedModelDefinition> build(@NotNull TypeSpec.Builder builder, ITypeResolver typeResolver) {
    FieldSpec.Builder field = FieldSpec.builder(getJavaFieldType(), getJavaFieldName()).addModifiers(Modifier.PRIVATE);
    final Set<@NotNull INamedModelDefinition> retval = buildField(field);
    FieldSpec valueField = ObjectUtils.notNull(field.build());
    builder.addField(valueField);
    {
        MethodSpec.Builder method = MethodSpec.methodBuilder("get" + getPropertyName()).returns(getJavaFieldType()).addModifiers(Modifier.PUBLIC);
        buildGetter(method, valueField);
        builder.addMethod(method.build());
    }
    {
        ParameterSpec valueParam = ParameterSpec.builder(getJavaFieldType(), "value").build();
        MethodSpec.Builder method = MethodSpec.methodBuilder("set" + getPropertyName()).addModifiers(Modifier.PUBLIC).addParameter(valueParam);
        buildSetter(method, valueParam, valueField);
        builder.addMethod(method.build());
    }
    buildExtraMethods(builder, valueField, typeResolver);
    return retval;
}
Also used : INamedModelDefinition(gov.nist.secauto.metaschema.model.common.INamedModelDefinition) ParameterSpec(com.squareup.javapoet.ParameterSpec) FieldSpec(com.squareup.javapoet.FieldSpec)

Example 95 with ParameterSpec

use of com.squareup.javapoet.ParameterSpec in project metaschema-java by usnistgov.

the class ModelInstanceTypeInfoImpl method buildExtraMethods.

@Override
public void buildExtraMethods(@NotNull TypeSpec.Builder builder, @NotNull FieldSpec valueField, @NotNull ITypeResolver typeResolver) {
    INamedModelInstance instance = getInstance();
    int maxOccurance = instance.getMaxOccurs();
    if (maxOccurance == -1 || maxOccurance > 1) {
        TypeName itemType = getJavaItemType();
        ParameterSpec valueParam = ParameterSpec.builder(itemType, "item").build();
        String itemPropertyName = ClassUtils.toPropertyName(getItemBaseName());
        if (JsonGroupAsBehavior.KEYED.equals(instance.getJsonGroupAsBehavior())) {
            IFlagInstance jsonKey = instance.getJsonKeyFlagInstance();
            if (jsonKey == null) {
                throw new IllegalStateException(String.format("JSON key not defined for property: %s", instance.toCoordinates()));
            }
            // get the json key property on the instance's definition
            INamedModelDefinitionTypeInfo instanceTypeInfo = typeResolver.getTypeInfo(instance.getDefinition());
            IFlagInstanceTypeInfo jsonKeyTypeInfo = instanceTypeInfo.getFlagInstanceTypeInfo(jsonKey);
            if (jsonKeyTypeInfo == null) {
                throw new IllegalStateException(String.format("Unable to identify JSON key for property: %s", instance.toCoordinates()));
            }
            {
                // create add method
                MethodSpec.Builder method = MethodSpec.methodBuilder("add" + itemPropertyName).addParameter(valueParam).returns(itemType).addModifiers(Modifier.PUBLIC).addJavadoc("Add a new {@link $T} item to the underlying collection.\n", itemType).addJavadoc("@param item the item to add\n").addJavadoc("@return the existing {@link $T} item in the collection or {@code null} if not item exists\n", itemType).addStatement("$1T value = $2T.requireNonNull($3N,\"$3N value cannot be null\")", itemType, ObjectUtils.class, valueParam).addStatement("$1T key = $2T.requireNonNull($3N.$4N(),\"$3N key cannot be null\")", String.class, ObjectUtils.class, valueParam, "get" + jsonKeyTypeInfo.getPropertyName()).beginControlFlow("if ($N == null)", valueField).addStatement("$N = new $T<>()", valueField, LinkedHashMap.class).endControlFlow().addStatement("return $N.put(key, value)", valueField);
                builder.addMethod(method.build());
            }
            {
                // create remove method
                MethodSpec.Builder method = MethodSpec.methodBuilder("remove" + itemPropertyName).addParameter(valueParam).returns(TypeName.BOOLEAN).addModifiers(Modifier.PUBLIC).addJavadoc("Remove the {@link $T} item from the underlying collection.\n", itemType).addJavadoc("@param item the item to remove\n").addJavadoc("@return {@code true} if the item was removed or {@code false} otherwise\n").addStatement("$1T value = $2T.requireNonNull($3N,\"$3N value cannot be null\")", itemType, ObjectUtils.class, valueParam).addStatement("$1T key = $2T.requireNonNull($3N.$4N(),\"$3N key cannot be null\")", String.class, ObjectUtils.class, valueParam, "get" + jsonKeyTypeInfo.getPropertyName()).addStatement("return $1N == null ? false : $1N.remove(key, value)", valueField);
                builder.addMethod(method.build());
            }
        } else {
            {
                // create add method
                MethodSpec.Builder method = MethodSpec.methodBuilder("add" + itemPropertyName).addParameter(valueParam).returns(TypeName.BOOLEAN).addModifiers(Modifier.PUBLIC).addJavadoc("Add a new {@link $T} item to the underlying collection.\n", itemType).addJavadoc("@param item the item to add\n").addJavadoc("@return {@code true}\n").addStatement("$T value = $T.requireNonNull($N,\"$N cannot be null\")", itemType, ObjectUtils.class, valueParam, valueParam).beginControlFlow("if ($N == null)", valueField).addStatement("$N = new $T<>()", valueField, LinkedList.class).endControlFlow().addStatement("return $N.add(value)", valueField);
                builder.addMethod(method.build());
            }
            {
                // create remove method
                MethodSpec.Builder method = MethodSpec.methodBuilder("remove" + itemPropertyName).addParameter(valueParam).returns(TypeName.BOOLEAN).addModifiers(Modifier.PUBLIC).addJavadoc("Remove the first matching {@link $T} item from the underlying collection.\n", itemType).addJavadoc("@param item the item to remove\n").addJavadoc("@return {@code true} if the item was removed or {@code false} otherwise\n").addStatement("$T value = $T.requireNonNull($N,\"$N cannot be null\")", itemType, ObjectUtils.class, valueParam, valueParam).addStatement("return $1N == null ? false : $1N.remove(value)", valueField);
                builder.addMethod(method.build());
            }
        }
    }
}
Also used : ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) ParameterSpec(com.squareup.javapoet.ParameterSpec) INamedModelInstance(gov.nist.secauto.metaschema.model.common.INamedModelInstance) ObjectUtils(gov.nist.secauto.metaschema.model.common.util.ObjectUtils) LinkedList(java.util.LinkedList) LinkedHashMap(java.util.LinkedHashMap) IFlagInstance(gov.nist.secauto.metaschema.model.common.IFlagInstance)

Aggregations

ParameterSpec (com.squareup.javapoet.ParameterSpec)97 MethodSpec (com.squareup.javapoet.MethodSpec)59 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)40 ArrayList (java.util.ArrayList)34 TypeName (com.squareup.javapoet.TypeName)30 ClassName (com.squareup.javapoet.ClassName)27 TypeSpec (com.squareup.javapoet.TypeSpec)26 Map (java.util.Map)26 CodeBlock (com.squareup.javapoet.CodeBlock)23 FieldSpec (com.squareup.javapoet.FieldSpec)22 List (java.util.List)20 HashMap (java.util.HashMap)18 AnnotationSpec (com.squareup.javapoet.AnnotationSpec)17 JavaFile (com.squareup.javapoet.JavaFile)13 Modifier (javax.lang.model.element.Modifier)13 TypeElement (javax.lang.model.element.TypeElement)13 Collectors (java.util.stream.Collectors)12 IOException (java.io.IOException)11 Element (javax.lang.model.element.Element)11 TypeMirror (javax.lang.model.type.TypeMirror)11