Search in sources :

Example 1 with Autowired

use of com.luojilab.router.facade.annotation.Autowired in project ChidoriX by Chihiro23333.

the class RouterProcessor method parseRouteNodes.

private void parseRouteNodes(Set<? extends Element> routeElements) {
    TypeMirror type_Activity = elements.getTypeElement(ACTIVITY).asType();
    for (Element element : routeElements) {
        TypeMirror tm = element.asType();
        RouteNode route = element.getAnnotation(RouteNode.class);
        if (types.isSubtype(tm, type_Activity)) {
            // Activity
            logger.info(">>> Found activity route: " + tm.toString() + " <<<");
            Node node = new Node();
            String path = route.path();
            checkPath(path);
            node.setPath(path);
            node.setDesc(route.desc());
            node.setPriority(route.priority());
            node.setNodeType(NodeType.ACTIVITY);
            node.setRawType(element);
            Map<String, Integer> paramsType = new HashMap<>();
            Map<String, String> paramsDesc = new HashMap<>();
            for (Element field : element.getEnclosedElements()) {
                if (field.getKind().isField() && field.getAnnotation(Autowired.class) != null) {
                    Autowired paramConfig = field.getAnnotation(Autowired.class);
                    paramsType.put(StringUtils.isEmpty(paramConfig.name()) ? field.getSimpleName().toString() : paramConfig.name(), typeUtils.typeExchange(field));
                    paramsDesc.put(StringUtils.isEmpty(paramConfig.name()) ? field.getSimpleName().toString() : paramConfig.name(), typeUtils.typeDesc(field));
                }
            }
            node.setParamsType(paramsType);
            node.setParamsDesc(paramsDesc);
            if (!routerNodes.contains(node)) {
                routerNodes.add(node);
            }
        } else {
            throw new IllegalStateException("only activity can be annotated by RouteNode");
        }
    }
}
Also used : Autowired(com.luojilab.router.facade.annotation.Autowired) TypeMirror(javax.lang.model.type.TypeMirror) HashMap(java.util.HashMap) RouteNode(com.luojilab.router.facade.annotation.RouteNode) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) Node(com.luojilab.router.facade.model.Node) RouteNode(com.luojilab.router.facade.annotation.RouteNode)

Example 2 with Autowired

use of com.luojilab.router.facade.annotation.Autowired 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)

Aggregations

Autowired (com.luojilab.router.facade.annotation.Autowired)2 HashMap (java.util.HashMap)2 Element (javax.lang.model.element.Element)2 TypeElement (javax.lang.model.element.TypeElement)2 TypeMirror (javax.lang.model.type.TypeMirror)2 RouteNode (com.luojilab.router.facade.annotation.RouteNode)1 Node (com.luojilab.router.facade.model.Node)1 FieldSpec (com.squareup.javapoet.FieldSpec)1 MethodSpec (com.squareup.javapoet.MethodSpec)1 ParameterSpec (com.squareup.javapoet.ParameterSpec)1 TypeSpec (com.squareup.javapoet.TypeSpec)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Map (java.util.Map)1