Java Code Examples for javax.lang.model.element.TypeElement.getAnnotation()

The following are Jave code examples for showing how to use getAnnotation() of the javax.lang.model.element.TypeElement class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: GitHub   File: ViewStateProviderClassGenerator.java   Source Code and License Vote up 6 votes
private String getViewStateClassFromAnnotationParams(TypeElement typeElement) {
	InjectViewState annotation = typeElement.getAnnotation(InjectViewState.class);
	String mvpViewStateClassName = "";

	if (annotation != null) {
		TypeMirror value;
		try {
			annotation.value();
		} catch (MirroredTypeException mte) {
			value = mte.getTypeMirror();
			mvpViewStateClassName = value.toString();
		}
	}

	if (mvpViewStateClassName.isEmpty() || DefaultViewState.class.getName().equals(mvpViewStateClassName)) {
		return null;
	}

	return mvpViewStateClassName;
}
 
Example 2
Project: FactoryAnnotation   File: FactoryAnnotatedClass.java   Source Code and License Vote up 6 votes
public FactoryAnnotatedClass(TypeElement classElement) throws IllegalArgumentException {
    this.annotatedClassElement = classElement;
    Factory annotation = classElement.getAnnotation(Factory.class);
    id = annotation.id();

    if (id == null || id.length() == 0) {
        throw new IllegalArgumentException(
                String.format("id() in @%s for class %s is null or empty! that's not allowed",
                        Factory.class.getSimpleName(), classElement.getQualifiedName().toString()));
    }

    // Get the full QualifiedTypeName
    try {
        Class<?> clazz = annotation.type();
        qualifiedSuperClassName = clazz.getCanonicalName();
        simpleTypeName = clazz.getSimpleName();
    } catch (MirroredTypeException mte) {
        DeclaredType classTypeMirror = (DeclaredType) mte.getTypeMirror();
        TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement();
        qualifiedSuperClassName = classTypeElement.getQualifiedName().toString();
        simpleTypeName = classTypeElement.getSimpleName().toString();
    }
}
 
Example 3
Project: alvisnlp   File: ModuleModel.java   Source Code and License Vote up 6 votes
/**
 * Creates a new module class model.
 * @param ctx
 * @param moduleElement type element representing the class of the module.
 * @throws ModelException
 */
ModuleModel(ModelContext ctx, TypeElement moduleElement) throws ModelException {
	if (!ctx.isModuleBase(moduleElement.asType()))
		throw new ModelException("module must inherit from " + ModuleBase.class + ": " + moduleElement.getQualifiedName());
	if (!moduleElement.getTypeParameters().isEmpty())
		throw new ModelException("module cannot be generic: " + moduleElement.getQualifiedName());
	element = moduleElement;
	dataClass = ctx.getModuleDataClass(moduleElement);
	simpleName = moduleElement.getSimpleName().toString();
	fullName = moduleElement.getQualifiedName().toString();
	packageName = fullName.substring(0, fullName.lastIndexOf('.'));
	annotation = moduleElement.getAnnotation(AlvisNLPModule.class);
	bundleName = annotation.docResourceBundle().isEmpty() ? fullName + "Doc" : annotation.docResourceBundle();
	Map<String,ExecutableElement> methods = ctx.getMethodsByName(moduleElement);
	for (ExecutableElement method : methods.values()) {
		Param paramAnnotation = method.getAnnotation(Param.class);
		if (paramAnnotation != null) {
			params.add(new ParamModel(methods, method, paramAnnotation));
			continue;
		}
		TimeThis timeAnnotation = method.getAnnotation(TimeThis.class);
		if (timeAnnotation != null) {
			timedMethods.add(new TimedMethodModel(ctx, method, timeAnnotation));
		}
	}
}
 
Example 4
Project: GitHub   File: Mirrors.java   Source Code and License Vote up 5 votes
@Nullable
private MirrorModel getMirrorModelIfAnnotation() {
  if (this.kind == AttributeTypeKind.ANNOTATION) {
    TypeElement element = toElement(this.type);
    if (element.getAnnotation(Mirror.Annotation.class) != null) {
      return new MirrorModel(element);
    }
  }
  return null;
}
 
Example 5
Project: GitHub   File: MethodProcessor.java   Source Code and License Vote up 5 votes
public boolean isCallbackMethodAnnotationValid(Element element, String annotationName) {
    TypeElement enclosingElement = (TypeElement)element.getEnclosingElement();

    if (enclosingElement.getAnnotation(JsonObject.class) == null) {
        error(enclosingElement, "%s: @%s methods can only be in classes annotated with @%s.", enclosingElement.getQualifiedName(), annotationName, JsonObject.class.getSimpleName());
        return false;
    }

    ExecutableElement executableElement = (ExecutableElement)element;
    if (executableElement.getParameters().size() > 0) {
        error(element, "%s: @%s methods must not take any parameters.", enclosingElement.getQualifiedName(), annotationName);
        return false;
    }

    List<? extends Element> allElements = enclosingElement.getEnclosedElements();
    int methodInstances = 0;
    for (Element enclosedElement : allElements) {
        for (AnnotationMirror am : enclosedElement.getAnnotationMirrors()) {
            if (am.getAnnotationType().asElement().getSimpleName().toString().equals(annotationName)) {
                methodInstances++;
            }
        }
    }
    if (methodInstances != 1) {
        error(element, "%s: There can only be one @%s method per class.", enclosingElement.getQualifiedName(), annotationName);
        return false;
    }

    return true;
}
 
Example 6
Project: OpenJSharp   File: WebServiceAp.java   Source Code and License Vote up 5 votes
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (context.getRound() != 1) {
        return true;
    }
    context.incrementRound();
    WebService webService;
    WebServiceProvider webServiceProvider;
    WebServiceVisitor webServiceVisitor = new WebServiceWrapperGenerator(this, context);
    boolean processedEndpoint = false;
    Collection<TypeElement> classes = new ArrayList<TypeElement>();
    filterClasses(classes, roundEnv.getRootElements());
    for (TypeElement element : classes) {
        webServiceProvider = element.getAnnotation(WebServiceProvider.class);
        webService = element.getAnnotation(WebService.class);
        if (webServiceProvider != null) {
            if (webService != null) {
                processError(WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_AND_WEBSERVICEPROVIDER(element.getQualifiedName()));
            }
            processedEndpoint = true;
        }

        if (webService == null) {
            continue;
        }

        element.accept(webServiceVisitor, null);
        processedEndpoint = true;
    }
    if (!processedEndpoint) {
        if (isCommandLineInvocation) {
            if (!ignoreNoWebServiceFoundWarning) {
                processWarning(WebserviceapMessages.WEBSERVICEAP_NO_WEBSERVICE_ENDPOINT_FOUND());
            }
        } else {
            processError(WebserviceapMessages.WEBSERVICEAP_NO_WEBSERVICE_ENDPOINT_FOUND());
        }
    }
    return true;
}
 
Example 7
Project: alvisnlp   File: ConverterModel.java   Source Code and License Vote up 5 votes
/**
 * Creates a new converter model.
 * @param ctx
 * @param converterElement type element representing the converter class declaration
 * @throws ModelException
 */
ConverterModel(ModelContext ctx, TypeElement converterElement) throws ModelException {
	fullName = converterElement.getQualifiedName().toString();
	targetType = ctx.getTargetType(converterElement);
	Converter annotation = converterElement.getAnnotation(Converter.class);
	bundleName = annotation.docResourceBundle().isEmpty() ? fullName + "Doc" : annotation.docResourceBundle();
}
 
Example 8
Project: openjdk-jdk10   File: ServiceProviderProcessor.java   Source Code and License Vote up 5 votes
private void processElement(TypeElement serviceProvider) {
    if (processed.contains(serviceProvider)) {
        return;
    }

    processed.add(serviceProvider);
    ServiceProvider annotation = serviceProvider.getAnnotation(ServiceProvider.class);
    if (annotation != null) {
        try {
            annotation.value();
        } catch (MirroredTypeException ex) {
            TypeMirror serviceInterface = ex.getTypeMirror();
            if (verifyAnnotation(serviceInterface, serviceProvider)) {
                if (serviceProvider.getNestingKind().isNested()) {
                    /*
                     * This is a simplifying constraint that means we don't have to process the
                     * qualified name to insert '$' characters at the relevant positions.
                     */
                    String msg = String.format("Service provider class %s must be a top level class", serviceProvider.getSimpleName());
                    processingEnv.getMessager().printMessage(Kind.ERROR, msg, serviceProvider);
                } else {
                    serviceProviders.put(serviceProvider, ex.getTypeMirror().toString());
                }
            }
        }
    }
}
 
Example 9
Project: android-auto-mapper   File: AutoMappperProcessor.java   Source Code and License Vote up 5 votes
private void processType(TypeElement type, Map<TypeElement, String> elementTargetNames) {
    TypeElement mapFrom = getClassToMapFrom(type);
    AutoMapper autoMapper = type.getAnnotation(AutoMapper.class);
    if (autoMapper == null) {
        mErrorReporter.abortWithError(
            "annotation processor for @AutoParcel was invoked with a type annotated differently; compiler bug? O_o",
            type
        );
    }
    if (type.getKind() != ElementKind.CLASS) {
        mErrorReporter.abortWithError("@" + AutoMapper.class.getName() + " only applies to classes", type);
    }
    if (ancestorIsAutoParcel(type)) {
        mErrorReporter.abortWithError("One @AutoParcel class shall not extend another", type);
    }

    checkModifiersIfNested(type);

    // get the fully-qualified class name
    String fqClassName = generatedSubclassName(type, 0);
    // class name
    String className = TypeUtil.simpleNameOf(fqClassName);

    String source = generateClass(type, className, type.getSimpleName().toString(), mapFrom, elementTargetNames);
    source = Reformatter.fixup(source);
    writeSourceFile(fqClassName, source, type);

}
 
Example 10
Project: openjdk-jdk10   File: WebServiceVisitor.java   Source Code and License Vote up 5 votes
protected void preProcessWebService(WebService webService, TypeElement element) {
    processedMethods = new HashSet<String>();
    seiContext = context.getSeiContext(element);
    String targetNamespace = null;
    if (webService != null)
        targetNamespace = webService.targetNamespace();
    PackageElement packageElement = builder.getProcessingEnvironment().getElementUtils().getPackageOf(element);
    if (targetNamespace == null || targetNamespace.length() == 0) {
        String packageName = packageElement.getQualifiedName().toString();
        if (packageName == null || packageName.length() == 0) {
            builder.processError(WebserviceapMessages.WEBSERVICEAP_NO_PACKAGE_CLASS_MUST_HAVE_TARGETNAMESPACE(
                    element.getQualifiedName()), element);
        }
        targetNamespace = RuntimeModeler.getNamespace(packageName);
    }
    seiContext.setNamespaceUri(targetNamespace);
    if (serviceImplName == null)
        serviceImplName = seiContext.getSeiImplName();
    if (serviceImplName != null) {
        seiContext.setSeiImplName(serviceImplName);
        context.addSeiContext(serviceImplName, seiContext);
    }
    portName = ClassNameInfo.getName(element.getSimpleName().toString().replace('$', '_'));
    packageName = packageElement.getQualifiedName();
    portName = webService != null && webService.name() != null && webService.name().length() > 0 ?
            webService.name() : portName;
    serviceName = ClassNameInfo.getName(element.getQualifiedName().toString()) + WebServiceConstants.SERVICE.getValue();
    serviceName = webService != null && webService.serviceName() != null && webService.serviceName().length() > 0 ?
            webService.serviceName() : serviceName;
    wsdlNamespace = seiContext.getNamespaceUri();
    typeNamespace = wsdlNamespace;

    SOAPBinding soapBinding = element.getAnnotation(SOAPBinding.class);
    if (soapBinding != null) {
        pushedSoapBinding = pushSoapBinding(soapBinding, element, element);
    } else if (element.equals(typeElement)) {
        pushedSoapBinding = pushSoapBinding(new MySoapBinding(), element, element);
    }
}
 
Example 11
Project: gendapter   File: AdapterAnnotatedClass.java   Source Code and License Vote up 5 votes
public AdapterAnnotatedClass(TypeElement typeElement) {
    annotatedClassName = typeElement.getQualifiedName().toString();
    RecyclerAdapter annotation = typeElement.getAnnotation(RecyclerAdapter.class);
    try {
        Class<?> clazz = annotation.itemType();
        adapterItemType = clazz.getCanonicalName();
    } catch (MirroredTypeException e) {
        DeclaredType classTypeMirror = (DeclaredType) e.getTypeMirror();
        TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement();
        adapterItemType = classTypeElement.getQualifiedName().toString();
    }
}
 
Example 12
Project: remoter   File: BindingManager.java   Source Code and License Vote up 4 votes
/**
 * Returns the {@link ParamBuilder} that knows how to generate code for the given type of parameter
 */
ParamBuilder getBuilderForParam(TypeMirror typeMirror) {
    ParamBuilder paramBuilder = typeBuilderMap.get(typeMirror);
    if (paramBuilder == null) {
        switch (typeMirror.getKind()) {
            case BOOLEAN:
                paramBuilder = new BooleanParamBuilder(messager, null);
                break;
            case BYTE:
                paramBuilder = new ByteParamBuilder(messager, null);
                break;
            case CHAR:
                paramBuilder = new CharParamBuilder(messager, null);
                break;
            case DOUBLE:
                paramBuilder = new DoubleParamBuilder(messager, null);
                break;
            case FLOAT:
                paramBuilder = new FloatParamBuilder(messager, null);
                break;
            case INT:
                paramBuilder = new IntParamBuilder(messager, null);
                break;
            case LONG:
                paramBuilder = new LongParamBuilder(messager, null);
                break;
            case SHORT:
                paramBuilder = new ShortParamBuilder(messager, null);
                break;
            case ARRAY:
                paramBuilder = getBuilderForParam(((ArrayType) typeMirror).getComponentType());
                break;
            case DECLARED:
                TypeElement genericList = getGenericType(typeMirror);
                if (genericList != null) {
                    paramBuilder = new ListOfParcelerParamBuilder(messager, null, genericList);
                } else if (typeUtils.isAssignable(typeMirror, stringTypeMirror)) {
                    paramBuilder = new StringParamBuilder(messager, null);
                } else if (typeUtils.isAssignable(typeMirror, charSequenceTypeMirror)) {
                    paramBuilder = new CharSequenceParamBuilder(messager, null);
                } else if (typeUtils.isAssignable(typeMirror, listTypeMirror) || typeMirror.toString().equals("java.util.List<java.lang.String>")) {
                    paramBuilder = new ListParamBuilder(messager, null);
                } else if (typeUtils.isAssignable(typeMirror, mapTypeMirror)) {
                    paramBuilder = new MapParamBuilder(messager, null);
                } else if (typeUtils.isAssignable(typeMirror, parcellableTypeMirror)) {
                    paramBuilder = new ParcellableParamBuilder(messager, null);
                } else {
                    String typeName = typeMirror.toString();
                    int templateStart = typeName.indexOf('<');
                    if (templateStart != -1) {
                        typeName = typeName.substring(0, templateStart).trim();
                    }
                    TypeElement typeElement = elementUtils.getTypeElement(typeName);
                    if (typeElement != null) {
                        if (typeElement.getKind() == ElementKind.INTERFACE && typeElement.getAnnotation(Remoter.class) != null) {
                            paramBuilder = new BinderParamBuilder(messager, null);
                        } else if (parcelClass != null && typeElement.getAnnotation(parcelClass) != null) {
                            paramBuilder = new ParcelerParamBuilder(messager, null);
                        }
                    }
                }
                break;
        }
        if (paramBuilder != null) {
            paramBuilder.setBindingManager(this);
            typeBuilderMap.put(typeMirror, paramBuilder);
        } else {
            paramBuilder = new GenericParamBuilder(messager, null);
            paramBuilder.setBindingManager(this);
            typeBuilderMap.put(typeMirror, paramBuilder);
        }
    }
    return paramBuilder;
}
 
Example 13
Project: AutoNet   File: AnnotationProcessor.java   Source Code and License Vote up 4 votes
private boolean isAnnotatedWithClass(RoundEnvironment roundEnvironment,
                                     Class<? extends Annotation> clazz) {
    Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(clazz);
    for (Element element : elements) {
        if (isValid(element)) {
            return false;
        }
        if (!element.getKind().isClass()) {
            return false;
        }
        TypeElement typeElement = (TypeElement) element;
        String fullPackageName = typeElement.getQualifiedName().toString();
        String packageName = mElementUtils.getPackageOf(element).getQualifiedName().toString();
        String className = typeElement.getSimpleName().toString();
        Annotation annotation = typeElement.getAnnotation(clazz);

        ProxyInfo proxyInfo = mInfoMap.get(fullPackageName);
        if (proxyInfo == null) {
            proxyInfo = new ProxyInfo();
            mInfoMap.put(fullPackageName, proxyInfo);
        }
        proxyInfo.fullPackageName = fullPackageName;
        proxyInfo.className = className;
        proxyInfo.packageName = packageName;
        proxyInfo.typeElement = typeElement;

        if (fullPackageName != null && fullPackageName.length() > 0) {
            String outClassFullName;
            try {
                outClassFullName = fullPackageName.substring(0, fullPackageName.length() - className.length() - 1);
                if (outClassFullName.equals(packageName)) {
                    outClassFullName = fullPackageName;
                }
            } catch (Exception e) {
                outClassFullName = "";
            }
            proxyInfo.outClassFullPackageName = outClassFullName;
        }


        if (annotation instanceof AutoNetPatternAnontation) {
            autoNetPatternProc(proxyInfo, (AutoNetPatternAnontation) annotation);
        } else if (annotation instanceof AutoNetEncryptionAnontation) {
            autoNetEncryptionProc(proxyInfo, (AutoNetEncryptionAnontation) annotation);
        } else if (annotation instanceof AutoNetBaseUrlKeyAnontation) {
            autoNetBaseUrlKeyProc(proxyInfo, (AutoNetBaseUrlKeyAnontation) annotation);
        } else if (annotation instanceof AutoNetAnontation) {
            autoNetProc(proxyInfo, (AutoNetAnontation) annotation);
        } else if (annotation instanceof AutoNetResponseEntityClass) {
            autoNetResponseEntityClassProc(proxyInfo, (AutoNetResponseEntityClass) annotation, element);
        } else if (annotation instanceof AutoNetTypeAnontation) {
            autoNetReqTypeProc(proxyInfo, (AutoNetTypeAnontation) annotation);
        } else if (annotation instanceof AutoNetMediaTypeAnontation) {
            autoNetMediaTypeProc(proxyInfo, (AutoNetMediaTypeAnontation) annotation);
        } else {
            return false;
        }
    }
    return true;
}
 
Example 14
Project: GitHub   File: ProcessorUtil.java   Source Code and License Vote up 4 votes
boolean isExtension(TypeElement element) {
  return element.getAnnotation(GlideExtension.class) != null;
}
 
Example 15
Project: D-Router   File: ActivityInfo.java   Source Code and License Vote up 4 votes
public ActivityInfo(Element element) {
    TypeElement typeElement = (TypeElement) element;
    Router router = typeElement.getAnnotation(Router.class);
    url = router.value();
    className = ClassName.bestGuess(typeElement.getQualifiedName().toString());
}
 
Example 16
Project: DUnit   File: DUnitProcessor.java   Source Code and License Vote up 4 votes
/**
 * 处理DUnitGroup注解
 */
public MethodSpec processUnitGroupElements(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
	//获取所有被DUnitGroup注解的Element
	Collection<? extends Element> annotatedUnitGroupElements = roundEnvironment.getElementsAnnotatedWith(DUnitGroup.class);

	//查找所有element中类型为Type的Element
	List<TypeElement> originalElementList = ElementFilter.typesIn(annotatedUnitGroupElements);
	//将普通集合变为不可变集合
	List<TypeElement> types = new ImmutableList.Builder<TypeElement>()
			.addAll(originalElementList)
			.build();

	if (types.size() > 0) {
		mErrorReporter.print("process DUnitGroup start...");
		//用于存放所有DunitGroupModel
		ArrayList<DUnitGroupModel> unitGroupModels = new ArrayList<>();

		for (TypeElement type : types) {
			if (type.getKind() != ElementKind.CLASS) {
				mErrorReporter.abortWithError("@" + DUnit.class.getName() + " only applies to classes", type);
			}

			DUnitGroup dUnitGroup = type.getAnnotation(DUnitGroup.class);

			DUnitGroupModel unitGroupModel = mUnitModelUtil.createUnitGroupModel(type, dUnitGroup);
			unitGroupModels.add(unitGroupModel);
		}

		//将模型转换为字符串
		Gson gson = new Gson();
		//unitGroupModels
		String unitGroupModelsString = gson.toJson(unitGroupModels);

		//创建initUnitGroupModels
		MethodSpec initMethod_initUnitGroupModels = InitMethodUtil.createMethodSpec_initUnitGroupModels(unitGroupModelsString);

		mErrorReporter.print("process DUnitGroup end.");
		return initMethod_initUnitGroupModels;
	} else {
		mErrorReporter.print("Waring! no DUnitGroup found.");
	}

	return null;
}
 
Example 17
Project: OpenJSharp   File: WebServiceWrapperGenerator.java   Source Code and License Vote up 4 votes
protected boolean isWSDLException(Collection<MemberInfo> members, TypeElement thrownDecl) {
    WebFault webFault = thrownDecl.getAnnotation(WebFault.class);
    return webFault != null && members.size() == 2 && getFaultInfoMember(members) != null;
}
 
Example 18
Project: OpenJSharp   File: WebServiceWrapperGenerator.java   Source Code and License Vote up 4 votes
private boolean generateExceptionBean(TypeElement thrownDecl, String beanPackage) {
    if (!builder.isServiceException(thrownDecl.asType()))
        return false;

    String exceptionName = ClassNameInfo.getName(thrownDecl.getQualifiedName().toString());
    if (processedExceptions.contains(exceptionName))
        return false;
    processedExceptions.add(exceptionName);
    WebFault webFault = thrownDecl.getAnnotation(WebFault.class);
    String className = beanPackage+ exceptionName + BEAN.getValue();

    Collection<MemberInfo> members = ap_generator.collectExceptionBeanMembers(thrownDecl);
    boolean isWSDLException = isWSDLException(members, thrownDecl);
    String namespace = typeNamespace;
    String name = exceptionName;
    FaultInfo faultInfo;
    if (isWSDLException) {
        TypeMirror beanType =  getFaultInfoMember(members).getParamType();
        faultInfo = new FaultInfo(TypeMonikerFactory.getTypeMoniker(beanType), true);
        namespace = webFault.targetNamespace().length()>0 ?
                           webFault.targetNamespace() : namespace;
        name = webFault.name().length()>0 ?
                      webFault.name() : name;
        faultInfo.setElementName(new QName(namespace, name));
        seiContext.addExceptionBeanEntry(thrownDecl.getQualifiedName(), faultInfo, builder);
        return false;
    }
    if (webFault != null) {
        namespace = webFault.targetNamespace().length()>0 ?
                    webFault.targetNamespace() : namespace;
        name = webFault.name().length()>0 ?
               webFault.name() : name;
        className = webFault.faultBean().length()>0 ?
                    webFault.faultBean() : className;

    }
    JDefinedClass cls = getCMClass(className, CLASS);
    faultInfo = new FaultInfo(className, false);

    if (duplicateName(className)) {
        builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_EXCEPTION_BEAN_NAME_NOT_UNIQUE(
                typeElement.getQualifiedName(), thrownDecl.getQualifiedName()));
    }

    boolean canOverWriteBean = builder.canOverWriteClass(className);
    if (!canOverWriteBean) {
        builder.log("Class " + className + " exists. Not overwriting.");
        seiContext.addExceptionBeanEntry(thrownDecl.getQualifiedName(), faultInfo, builder);
        return false;
    }
    if (seiContext.getExceptionBeanName(thrownDecl.getQualifiedName()) != null)
        return false;

    //write class comment - JAXWS warning
    JDocComment comment = cls.javadoc();
    for (String doc : GeneratorBase.getJAXWSClassComment(ToolVersion.VERSION.MAJOR_VERSION)) {
        comment.add(doc);
    }

    // XmlElement Declarations
    writeXmlElementDeclaration(cls, name, namespace);

    // XmlType Declaration
    //members = sortMembers(members);
    XmlType xmlType = thrownDecl.getAnnotation(XmlType.class);
    String xmlTypeName = (xmlType != null && !xmlType.name().equals("##default")) ? xmlType.name() : exceptionName;
    String xmlTypeNamespace = (xmlType != null && !xmlType.namespace().equals("##default")) ? xmlType.namespace() : typeNamespace;
    writeXmlTypeDeclaration(cls, xmlTypeName, xmlTypeNamespace, members);

    writeMembers(cls, members);

    seiContext.addExceptionBeanEntry(thrownDecl.getQualifiedName(), faultInfo, builder);
    return true;
}
 
Example 19
Project: Router   File: RouteProcessor.java   Source Code and License Vote up 4 votes
/**
 * TargetInterceptors.
 */
private void generateTargetInterceptors(String moduleName, Set<TypeElement> elements) {
    // Map<Class<?>, String[]> map
    ParameterizedTypeName mapTypeName = ParameterizedTypeName.get(
            ClassName.get(Map.class),
            ParameterizedTypeName.get(ClassName.get(Class.class),
                    WildcardTypeName.subtypeOf(Object.class)),
            TypeName.get(String[].class));
    ParameterSpec mapParameterSpec = ParameterSpec.builder(mapTypeName, "map").build();
    MethodSpec.Builder methodHandle = MethodSpec.methodBuilder(HANDLE)
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .addParameter(mapParameterSpec);
    boolean hasInterceptor = false; // flag
    for (TypeElement element : elements) {
        Route route = element.getAnnotation(Route.class);
        String[] interceptors = route.interceptors();
        if (interceptors.length > 1) {
            hasInterceptor = true;
            StringBuilder sb = new StringBuilder();
            for (String interceptor : interceptors) {
                sb.append("\"").append(interceptor).append("\",");
            }
            methodHandle.addStatement("map.put($T.class, new String[]{$L})",
                    ClassName.get(element), sb.substring(0, sb.lastIndexOf(",")));
        } else if (interceptors.length == 1) {
            hasInterceptor = true;
            methodHandle.addStatement("map.put($T.class, new String[]{$S})",
                    ClassName.get(element), interceptors[0]);
        }
    }
    if (!hasInterceptor) { // if there are no interceptors, ignore.
        return;
    }
    TypeSpec type = TypeSpec.classBuilder(capitalize(moduleName) + TABLE_INTERCEPTORS)
            .addSuperinterface(ClassName.get(PACKAGE_NAME, TABLE_INTERCEPTORS))
            .addModifiers(Modifier.PUBLIC)
            .addMethod(methodHandle.build())
            .addJavadoc(CLASS_JAVA_DOC)
            .build();
    try {
        JavaFile.builder(PACKAGE_NAME, type).build().writeTo(processingEnv.getFiler());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 20
Project: openjdk-jdk10   File: WebServiceWrapperGenerator.java   Source Code and License Vote up 4 votes
private boolean generateExceptionBean(TypeElement thrownDecl, String beanPackage) {
    if (!builder.isServiceException(thrownDecl.asType()))
        return false;

    String exceptionName = ClassNameInfo.getName(thrownDecl.getQualifiedName().toString());
    if (processedExceptions.contains(exceptionName))
        return false;
    processedExceptions.add(exceptionName);
    WebFault webFault = thrownDecl.getAnnotation(WebFault.class);
    String className = beanPackage+ exceptionName + BEAN.getValue();

    Collection<MemberInfo> members = ap_generator.collectExceptionBeanMembers(thrownDecl);
    boolean isWSDLException = isWSDLException(members, thrownDecl);
    String namespace = typeNamespace;
    String name = exceptionName;
    FaultInfo faultInfo;
    if (isWSDLException) {
        TypeMirror beanType =  getFaultInfoMember(members).getParamType();
        faultInfo = new FaultInfo(TypeMonikerFactory.getTypeMoniker(beanType), true);
        namespace = webFault.targetNamespace().length()>0 ?
                           webFault.targetNamespace() : namespace;
        name = webFault.name().length()>0 ?
                      webFault.name() : name;
        faultInfo.setElementName(new QName(namespace, name));
        seiContext.addExceptionBeanEntry(thrownDecl.getQualifiedName(), faultInfo, builder);
        return false;
    }
    if (webFault != null) {
        namespace = webFault.targetNamespace().length()>0 ?
                    webFault.targetNamespace() : namespace;
        name = webFault.name().length()>0 ?
               webFault.name() : name;
        className = webFault.faultBean().length()>0 ?
                    webFault.faultBean() : className;

    }
    JDefinedClass cls = getCMClass(className, CLASS);
    faultInfo = new FaultInfo(className, false);

    if (duplicateName(className)) {
        builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_EXCEPTION_BEAN_NAME_NOT_UNIQUE(
                typeElement.getQualifiedName(), thrownDecl.getQualifiedName()));
    }

    boolean canOverWriteBean = builder.canOverWriteClass(className);
    if (!canOverWriteBean) {
        builder.log("Class " + className + " exists. Not overwriting.");
        seiContext.addExceptionBeanEntry(thrownDecl.getQualifiedName(), faultInfo, builder);
        return false;
    }
    if (seiContext.getExceptionBeanName(thrownDecl.getQualifiedName()) != null) {
        return false;
    }

    addGeneratedFile(className);

    //write class comment - JAXWS warning
    JDocComment comment = cls.javadoc();
    for (String doc : GeneratorBase.getJAXWSClassComment(ToolVersion.VERSION.MAJOR_VERSION)) {
        comment.add(doc);
    }

    // XmlElement Declarations
    writeXmlElementDeclaration(cls, name, namespace);

    // XmlType Declaration
    //members = sortMembers(members);
    XmlType xmlType = thrownDecl.getAnnotation(XmlType.class);
    String xmlTypeName = (xmlType != null && !xmlType.name().equals("##default")) ? xmlType.name() : exceptionName;
    String xmlTypeNamespace = (xmlType != null && !xmlType.namespace().equals("##default")) ? xmlType.namespace() : typeNamespace;
    writeXmlTypeDeclaration(cls, xmlTypeName, xmlTypeNamespace, members);

    writeMembers(cls, members);

    seiContext.addExceptionBeanEntry(thrownDecl.getQualifiedName(), faultInfo, builder);
    return true;
}