List of usage examples for javax.lang.model.element TypeElement getAnnotation
@Override
<A extends Annotation> A getAnnotation(Class<A> annotationType);
From source file:org.kie.workbench.common.forms.adf.processors.FormDefinitionGenerator.java
private List<FormDefinitionFieldData> extracFormFields(TypeElement type, FieldPolicy policy, I18nSettings i18nSettings, Map<String, String> defaultParams) throws Exception { final Types typeUtils = context.getProcessingEnvironment().getTypeUtils(); Collection<FieldInfo> fieldInfos = FormGenerationUtils.extractFieldInfos(type, fieldElement -> filter(fieldElement, policy)); List<FormDefinitionFieldData> fieldSettings = new ArrayList<>(); for (FieldInfo fieldInfo : fieldInfos) { if (fieldInfo.getSetter() != null && fieldInfo.getGetter() != null) { String fieldName = fieldInfo.getFieldElement().getSimpleName().toString(); FormDefinitionFieldData fieldData = new FormDefinitionFieldData(type.getQualifiedName().toString(), fieldName);//ww w . ja v a 2 s. c om fieldData.setLabel(fieldName); fieldData.setBinding(fieldName); fieldData.setMethodName("getFormElement_" + fieldName); boolean isList = false; org.kie.workbench.common.forms.model.TypeKind typeKind = org.kie.workbench.common.forms.model.TypeKind.BASE; boolean overrideI18n = false; TypeMirror finalType = fieldInfo.getFieldElement().asType(); TypeElement finalTypeElement = (TypeElement) typeUtils.asElement(finalType); String fieldModifier = ""; if (finalTypeElement.getKind().equals(ElementKind.CLASS)) { FieldDefinition fieldDefinitionAnnotation = finalTypeElement .getAnnotation(FieldDefinition.class); if (fieldDefinitionAnnotation != null) { // Override the using the i18n mechanism if (fieldDefinitionAnnotation.i18nMode().equals(I18nMode.OVERRIDE_I18N_KEY)) { fieldData.setLabel(finalType.toString() + i18nSettings.separator() + fieldDefinitionAnnotation.labelKeySuffix()); Collection<FieldInfo> labelInfos = FormGenerationUtils.extractFieldInfos( finalTypeElement, fieldElement -> fieldElement.getAnnotation(FieldLabel.class) != null); if (labelInfos != null && labelInfos.size() == 1) { FieldInfo labelInfo = labelInfos.iterator().next(); fieldData.setLabel(finalType.toString() + i18nSettings.separator() + labelInfo.getFieldElement().getSimpleName()); } fieldData.setHelpMessage(finalType.toString() + i18nSettings.separator() + fieldDefinitionAnnotation.helpMessageKeySuffix()); Collection<FieldInfo> helpMessages = FormGenerationUtils.extractFieldInfos( finalTypeElement, fieldElement -> fieldElement.getAnnotation(FieldHelp.class) != null); if (helpMessages != null && helpMessages.size() == 1) { FieldInfo helpInfo = helpMessages.iterator().next(); fieldData.setHelpMessage(finalType.toString() + i18nSettings.separator() + helpInfo.getFieldElement().getSimpleName()); } } Collection<FieldInfo> fieldValue = FormGenerationUtils.extractFieldInfos(finalTypeElement, fieldElement -> fieldElement.getAnnotation(FieldValue.class) != null); if (fieldValue == null || fieldValue.size() != 1) { throw new Exception("Problem processing FieldDefinition [" + finalType + "]: it should have one field marked as @FieldValue"); } FieldInfo valueInfo = fieldValue.iterator().next(); fieldData.setBinding( fieldData.getBinding() + "." + valueInfo.getFieldElement().getSimpleName()); fieldModifier = FormGenerationUtils.fixClassName(finalType.toString()) + "_FieldStatusModifier"; finalType = valueInfo.getFieldElement().asType(); finalTypeElement = (TypeElement) typeUtils.asElement(finalType); overrideI18n = !fieldDefinitionAnnotation.i18nMode().equals(I18nMode.DONT_OVERRIDE); } else { FormDefinition formDefinitionAnnotation = finalTypeElement .getAnnotation(FormDefinition.class); if (formDefinitionAnnotation != null) { fieldData.setLabel( finalType.toString() + i18nSettings.separator() + FieldDefinition.LABEL); Collection<FieldInfo> labelInfos = FormGenerationUtils.extractFieldInfos( finalTypeElement, fieldElement -> fieldElement.getAnnotation(FieldLabel.class) != null); if (labelInfos != null && labelInfos.size() == 1) { FieldInfo labelInfo = labelInfos.iterator().next(); fieldData.setLabel(finalType.toString() + i18nSettings.separator() + labelInfo.getFieldElement().getSimpleName()); overrideI18n = true; } fieldData.setHelpMessage( finalType.toString() + i18nSettings.separator() + FieldDefinition.HELP_MESSAGE); Collection<FieldInfo> helpMessages = FormGenerationUtils.extractFieldInfos( finalTypeElement, fieldElement -> fieldElement.getAnnotation(FieldHelp.class) != null); if (helpMessages != null && helpMessages.size() == 1) { FieldInfo helpInfo = helpMessages.iterator().next(); fieldData.setHelpMessage(finalType.toString() + i18nSettings.separator() + helpInfo.getFieldElement().getSimpleName()); overrideI18n = true; } typeKind = org.kie.workbench.common.forms.model.TypeKind.OBJECT; } } } DeclaredType fieldType = (DeclaredType) finalType; if (typeUtils.isAssignable(finalTypeElement.asType(), listType)) { if (fieldType.getTypeArguments().size() != 1) { throw new IllegalArgumentException("Impossible to generate a field for type " + fieldType.toString() + ". Type should have one and only one Type arguments."); } isList = true; finalType = fieldType.getTypeArguments().get(0); finalTypeElement = (TypeElement) typeUtils.asElement(finalType); if (FormModelPropertiesUtil.isBaseType(finalTypeElement.getQualifiedName().toString())) { typeKind = org.kie.workbench.common.forms.model.TypeKind.BASE; } else if (typeUtils.isAssignable(finalTypeElement.asType(), enumType)) { typeKind = org.kie.workbench.common.forms.model.TypeKind.ENUM; } else { typeKind = org.kie.workbench.common.forms.model.TypeKind.OBJECT; } } else if (typeUtils.isAssignable(finalTypeElement.asType(), enumType)) { typeKind = org.kie.workbench.common.forms.model.TypeKind.ENUM; } fieldData.setType(typeKind.toString()); fieldData.setClassName(finalTypeElement.getQualifiedName().toString()); fieldData.setList(String.valueOf(isList)); fieldData.setFieldModifier(fieldModifier); fieldData.getParams().putAll(defaultParams); FormField settings = fieldInfo.getFieldElement().getAnnotation(FormField.class); if (settings != null) { try { fieldData.setPreferredType(settings.type().getName()); } catch (MirroredTypeException exception) { fieldData.setPreferredType(exception.getTypeMirror().toString()); } fieldData.setAfterElement(settings.afterElement()); if (!overrideI18n && !isEmpty(settings.labelKey())) { fieldData.setLabel(settings.labelKey()); } if (!overrideI18n && !isEmpty(settings.helpMessageKey())) { fieldData.setHelpMessage(settings.helpMessageKey()); } fieldData.setRequired(Boolean.valueOf(settings.required()).toString()); fieldData.setReadOnly(Boolean.valueOf(settings.readonly()).toString()); for (FieldParam fieldParam : settings.settings()) { fieldData.getParams().put(fieldParam.name(), fieldParam.value()); } fieldData.setWrap(Boolean.valueOf(settings.layoutSettings().wrap()).toString()); fieldData.setHorizontalSpan(String.valueOf(settings.layoutSettings().horizontalSpan())); fieldData.setVerticalSpan(String.valueOf(settings.layoutSettings().verticalSpan())); } if (!overrideI18n) { if (!isEmpty(i18nSettings.keyPreffix())) { fieldData.setLabel( i18nSettings.keyPreffix() + i18nSettings.separator() + fieldData.getLabel()); if (!isEmpty(fieldData.getHelpMessage())) { fieldData.setHelpMessage(i18nSettings.keyPreffix() + i18nSettings.separator() + fieldData.getHelpMessage()); } } } extractFieldExtraSettings(fieldData, fieldInfo.getFieldElement()); fieldSettings.add(fieldData); } } return fieldSettings; }
From source file:com.dspot.declex.action.Actions.java
private void createInformationForAction(String actionHolder, boolean isExternal) { TypeElement typeElement = env.getProcessingEnvironment().getElementUtils().getTypeElement(actionHolder); TypeElement generatedHolder = env.getProcessingEnvironment().getElementUtils() .getTypeElement(TypeUtils.getGeneratedClassName(typeElement, env)); ActionFor actionForAnnotation = null; try {//from w w w.j a v a 2s . c o m actionForAnnotation = typeElement.getAnnotation(ActionFor.class); } catch (Exception e) { LOGGER.error("An error occurred processing the @ActionFor annotation", e); } if (actionForAnnotation != null) { for (String name : actionForAnnotation.value()) { ACTION_HOLDER_ELEMENT_FOR_ACTION.put("$" + name, typeElement); //Get model info final ActionInfo actionInfo = new ActionInfo(actionHolder); actionInfo.isGlobal = actionForAnnotation.global(); actionInfo.isTimeConsuming = actionForAnnotation.timeConsuming(); if (isExternal) { actionInfo.generated = false; } //This will work only for cached classes if (generatedHolder != null) { for (Element elem : generatedHolder.getEnclosedElements()) { if (elem instanceof ExecutableElement) { final String elemName = elem.getSimpleName().toString(); final List<? extends VariableElement> params = ((ExecutableElement) elem) .getParameters(); if (elemName.equals("onViewChanged") && params.size() == 1 && params.get(0).asType() .toString().equals(HasViews.class.getCanonicalName())) { actionInfo.handleViewChanges = true; break; } } } } addAction(name, actionHolder, actionInfo, false); String javaDoc = env.getProcessingEnvironment().getElementUtils().getDocComment(typeElement); actionInfo.setReferences(javaDoc); List<DeclaredType> processors = annotationHelper.extractAnnotationClassArrayParameter(typeElement, ActionFor.class.getCanonicalName(), "processors"); //Load processors if (processors != null) { for (DeclaredType processor : processors) { Class<ActionProcessor> processorClass = null; try { ClassLoader loader = classLoaderForProcessor.get(processor.toString()); if (loader != null) { processorClass = (Class<ActionProcessor>) Class.forName(processor.toString(), true, loader); } else { processorClass = (Class<ActionProcessor>) Class.forName(processor.toString()); } } catch (ClassNotFoundException e) { Element element = env.getProcessingEnvironment().getElementUtils() .getTypeElement(processor.toString()); if (element == null) { LOGGER.error("Processor \"" + processor.toString() + "\" couldn't be loaded", typeElement); } else { try { //Get the file from which the class was loaded java.lang.reflect.Field field = element.getClass().getField("classfile"); field.setAccessible(true); JavaFileObject classfile = (JavaFileObject) field.get(element); String jarUrl = classfile.toUri().toURL().toString(); jarUrl = jarUrl.substring(0, jarUrl.lastIndexOf('!') + 2); //Create or use a previous created class loader for the given file ClassLoader loader; if (classLoaderForProcessor.containsKey(jarUrl)) { loader = classLoaderForProcessor.get(jarUrl); } else { loader = new URLClassLoader(new URL[] { new URL(jarUrl) }, Actions.class.getClassLoader()); classLoaderForProcessor.put(processor.toString(), loader); classLoaderForProcessor.put(jarUrl, loader); } processorClass = (Class<ActionProcessor>) Class.forName(processor.toString(), true, loader); } catch (Throwable e1) { LOGGER.error("Processor \"" + processor.toString() + "\" couldn't be loaded: " + e1.getMessage(), typeElement); } } } catch (ClassCastException e) { LOGGER.error("Processor \"" + processor.toString() + "\" is not an Action Processor", typeElement); } if (processorClass != null) { try { actionInfo.processors.add(processorClass.newInstance()); } catch (Throwable e) { LOGGER.info("Processor \"" + processor.toString() + "\" couldn't be instantiated", typeElement); } } } } createInformationForMethods(typeElement, actionInfo); } } }
From source file:auto.parse.processor.AutoParseProcessor.java
private void processType(TypeElement type) throws CompileException { AutoParse autoParse = type.getAnnotation(AutoParse.class); if (autoParse == null) { // This shouldn't happen unless the compilation environment is buggy, // but it has happened in the past and can crash the compiler. abortWithError("annotation processor for @AutoParse was invoked with a type that " + "does not have that annotation; this is probably a compiler bug", type); }/*from w w w . j a va2s . co m*/ if (type.getKind() != ElementKind.CLASS) { abortWithError("@" + AutoParse.class.getName() + " only applies to classes", type); } if (ancestorIsAndroidAutoParse(type)) { abortWithError("One @AutoParse class may not extend another", type); } Map<String, Object> vars = new TreeMap<String, Object>(); vars.put("type", type); vars.put("pkg", TypeSimplifier.packageNameOf(type)); vars.put("origclass", classNameOf(type)); vars.put("simpleclassname", simpleNameOf(classNameOf(type))); vars.put("formaltypes", formalTypeString(type)); vars.put("actualtypes", actualTypeString(type)); vars.put("wildcardtypes", wildcardTypeString(type)); vars.put("subclass", simpleNameOf(generatedSubclassName(type))); vars.put("cacheHashCode", autoParse.cacheHashCode()); defineVarsForType(type, vars); String text = template.rewrite(vars); writeSourceFile(generatedSubclassName(type), text, type); }
From source file:auto.parse.processor.AutoParseProcessor.java
private boolean ancestorIsAndroidAutoParse(TypeElement type) { while (true) { TypeMirror parentMirror = type.getSuperclass(); if (parentMirror.getKind() == TypeKind.NONE) { return false; }//from w w w . j ava 2s . com Types typeUtils = processingEnv.getTypeUtils(); TypeElement parentElement = (TypeElement) typeUtils.asElement(parentMirror); if (parentElement.getAnnotation(AutoParse.class) != null) { return true; } type = parentElement; } }
From source file:org.versly.rest.wsdoc.AnnotationProcessor.java
private String[] getClassLevelUrlPaths(TypeElement cls, RestImplementationSupport implementationSupport) { String basePath = null;/* w w w.j a v a2s . co m*/ DocumentationRestApi api = cls.getAnnotation(DocumentationRestApi.class); RestApiMountPoint mp = cls.getAnnotation(RestApiMountPoint.class); if (null != api) { basePath = api.mount(); } else if (null != mp) { basePath = mp.value(); } else { basePath = "/"; } String[] paths = implementationSupport.getRequestPaths(cls); if (paths.length == 0) { return new String[] { basePath }; } else { for (int i = 0; i < paths.length; i++) { paths[i] = Utils.joinPaths(basePath, paths[i]); } return paths; } }
From source file:org.kie.workbench.common.forms.adf.processors.FormDefinitionsProcessor.java
protected void processFormDefinition(TypeElement formElement) throws Exception { final Messager messager = processingEnv.getMessager(); messager.printMessage(Diagnostic.Kind.NOTE, "Discovered FormDefintion class [" + formElement.getSimpleName() + "]"); boolean checkInheritance = false; FormDefinition defintion = formElement.getAnnotation(FormDefinition.class); checkInheritance = defintion.allowInheritance(); List<Map<String, String>> formElements = new ArrayList<>(); if (checkInheritance) { TypeElement parent = getParent(formElement); formElements.addAll(extractParentFormFields(parent, defintion.policy(), defintion.i18n())); }/* w w w.j a v a 2 s .c o m*/ formElements.addAll(extracFormFields(formElement, defintion.policy(), defintion.i18n())); FormGenerationUtils.sort(defintion.startElement(), formElements); messager.printMessage(Diagnostic.Kind.NOTE, "Discovered " + formElements.size() + " elements for form [" + formElement.getQualifiedName().toString() + "]"); String modelClassName = formElement.getQualifiedName().toString(); String builderClassName = fixClassName(formElement.getQualifiedName().toString()) + "FormBuilder"; Map<String, Object> templateContext = new HashMap<>(); templateContext.put("modelClass", modelClassName); templateContext.put("builderClassName", builderClassName); templateContext.put("startElement", defintion.startElement()); templateContext.put("i18n_bundle", StringUtils.isEmpty(defintion.i18n().bundle()) ? formElement.asType().toString() : defintion.i18n().bundle()); Column[] columns = defintion.layout().value(); List<String> layoutColumns = new ArrayList<>(); if (columns.length == 0) { layoutColumns.add(ColSpan.SPAN_12.getName()); } else { for (Column column : columns) { layoutColumns.add(column.value().getName()); } } templateContext.put("layout_columns", layoutColumns); templateContext.put("elements", formElements); StringBuffer builder = writeTemplate("templates/FormDefinitionSettingsBuilder.ftl", templateContext); Map<String, String> form = new HashMap<>(); form.put("package", ((PackageElement) formElement.getEnclosingElement()).getQualifiedName().toString()); form.put("modelClass", modelClassName); form.put("builderClass", builderClassName); form.put("builderCode", builder.toString()); context.getForms().add(form); }
From source file:com.dspot.declex.server.ServerModelHandler.java
private void getFieldsAndMethods(TypeElement element, Map<String, String> fields, Map<String, String> methods) { List<? extends Element> elems = element.getEnclosedElements(); for (Element elem : elems) { final String elemName = elem.getSimpleName().toString(); final String elemType = elem.asType().toString(); //Static methods are included if (methods != null) { if (elem.getKind() == ElementKind.METHOD) { if (elem.getModifiers().contains(Modifier.PRIVATE)) continue; ExecutableElement executableElement = (ExecutableElement) elem; //One parameter means that the method can be used to update the model if (executableElement.getParameters().size() == 1) { VariableElement param = executableElement.getParameters().get(0); methods.put(elemName, TypeUtils.typeFromTypeString(param.asType().toString(), getEnvironment())); }// w ww . jav a2s .c o m } } if (elem.getModifiers().contains(Modifier.STATIC)) continue; if (fields != null) { if (elem.getKind() == ElementKind.FIELD) { if (elem.getModifiers().contains(Modifier.PRIVATE)) continue; fields.put(elemName, TypeUtils.typeFromTypeString(elemType, getEnvironment())); } } } //Apply to Extensions List<? extends TypeMirror> superTypes = getProcessingEnvironment().getTypeUtils() .directSupertypes(element.asType()); for (TypeMirror type : superTypes) { TypeElement superElement = getProcessingEnvironment().getElementUtils().getTypeElement(type.toString()); if (superElement.getAnnotation(Extension.class) != null) { getFieldsAndMethods(superElement, fields, methods); } break; } }
From source file:co.touchlab.squeaky.processor.AnnotationProcessor.java
private boolean processTableViewQuery(List<DatabaseTableHolder> tableHolders, Element annotatedElement, EntityType entityType) {/* w w w . jav a2 s . co m*/ TypeElement typeElement = (TypeElement) annotatedElement; String fromString; switch (entityType) { case Table: case View: fromString = extractTableName(typeElement); break; case Query: fromString = "(" + typeElement.getAnnotation(DatabaseQuery.class).fromQuery() + ")"; break; default: throw new RuntimeException("No type (this will NEVER happen)"); } List<FieldTypeGen> fieldTypeGens = new ArrayList<FieldTypeGen>(); List<ForeignCollectionHolder> foreignCollectionInfos = new ArrayList<ForeignCollectionHolder>(); // walk up the classes finding the fields TypeElement working = typeElement; while (working != null) { for (Element element : working.getEnclosedElements()) { if (element.getKind().isField()) { if (element.getAnnotation(DatabaseField.class) != null) { FieldTypeGen fieldTypeGen = new FieldTypeGen(annotatedElement, element, typeUtils, messager); fieldTypeGens.add(fieldTypeGen); } else if (element.getAnnotation(ForeignCollectionField.class) != null) { ForeignCollectionField foreignCollectionField = element .getAnnotation(ForeignCollectionField.class); foreignCollectionInfos.add(new ForeignCollectionHolder(foreignCollectionField, (VariableElement) element, messager)); } } } if (working.getSuperclass().getKind().equals(TypeKind.NONE)) { break; } working = (TypeElement) typeUtils.asElement(working.getSuperclass()); } if (fieldTypeGens.isEmpty()) { error(typeElement, "Every class annnotated with %s, %s, or %s must have at least 1 field annotated with %s", DatabaseTable.class.getSimpleName(), DatabaseView.class.getSimpleName(), DatabaseQuery.class.getSimpleName(), DatabaseField.class.getSimpleName()); return true; } List<FieldTypeGen> testFields = fieldTypeGens; List<FieldTypeGen> finalFields = new ArrayList<FieldTypeGen>(); for (FieldTypeGen testField : testFields) { if (testField.finalField) finalFields.add(testField); } ExecutableElement finalConstructor = null; if (!finalFields.isEmpty()) { List<ExecutableElement> executableElements = ElementFilter .constructorsIn(annotatedElement.getEnclosedElements()); for (ExecutableElement executableElement : executableElements) { List<FieldTypeGen> finalFieldsCheck = new ArrayList<FieldTypeGen>(finalFields); List<? extends VariableElement> parameters = executableElement.getParameters(); for (VariableElement parameter : parameters) { String fieldName = parameter.getSimpleName().toString(); String fieldClassname = DataTypeManager.findFieldClassname(parameter); Iterator<FieldTypeGen> iterator = finalFieldsCheck.iterator(); boolean found = false; while (iterator.hasNext()) { FieldTypeGen next = iterator.next(); if (next.fieldName.equals(fieldName) && next.dataTypeClassname.equals(fieldClassname)) { found = true; iterator.remove(); } } if (!found) break; } if (finalFieldsCheck.isEmpty()) { finalConstructor = executableElement; break; } } if (finalConstructor == null) { List<String> allFinals = new ArrayList<String>(); for (FieldTypeGen finalField : finalFields) { allFinals.add(finalField.fieldName); } error(annotatedElement, "Final fields need to be set in constructor %s", StringUtils.join(allFinals, ",")); return true; } } DatabaseTableHolder tableHolder = new DatabaseTableHolder(annotatedElement, fieldTypeGens, foreignCollectionInfos, typeElement, fromString, finalFields, finalConstructor, entityType); tableHolders.add(tableHolder); return false; }
From source file:com.mastfrog.parameters.processor.Processor.java
@Override public boolean process(Set<? extends TypeElement> set, RoundEnvironment re) { SourceVersion sv = processingEnv.getSourceVersion(); if (sv.ordinal() > SourceVersion.RELEASE_7.ordinal()) { optionalType = "java.util.Optional"; } else {/* w ww . j a va 2 s .com*/ TypeElement el = processingEnv.getElementUtils().getTypeElement(optionalType); if (el == null) { optionalType = "com.mastfrog.util.Optional"; } else { optionalType = "com.google.common.base.Optional"; fromNullable = "fromNullable"; } } Set<? extends Element> all = re.getElementsAnnotatedWith(Params.class); List<GeneratedParamsClass> interfaces = new LinkedList<>(); outer: for (Element e : all) { TypeElement te = (TypeElement) e; if (te.getSimpleName().toString().endsWith("__GenPage")) { continue; } PackageElement pkg = findPackage(e); if (pkg == null) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@Params may not be used in the default package", e); continue; } if (!isPageSubtype(te)) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@Params must be used on a subclass of org.apache.wicket.Page", e); continue; } String className = te.getQualifiedName().toString(); Params params = te.getAnnotation(Params.class); Map<String, List<String>> validators = validatorsForParam(e); GeneratedParamsClass inf = new GeneratedParamsClass(className, te, pkg, params, validators); if (!params.useRequestBody()) { checkConstructor(te, inf); } interfaces.add(inf); Set<String> names = new HashSet<>(); for (Param param : params.value()) { // if (param.required() && !param.defaultValue().isEmpty()) { // processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Don't set required to " // + "true if you are providing a default value - required makes it an error not " // + "to have a value, and if there is a default value, that error is an impossibility " // + "because it will always have a value.", e); // continue outer; // } if (param.value().trim().isEmpty()) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Empty parameter name", e); continue outer; } if (!isJavaIdentifier(param.value())) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Not a valid Java identifier: " + param.value(), e); continue outer; } if (!names.add(param.value())) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Duplicate parameter name '" + param.value() + "'", e); continue outer; } for (char c : ";,./*!@&^/\\<>?'\"[]{}-=+)(".toCharArray()) { if (param.value().contains("" + c)) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Param name may not contain the character '" + c + "'", e); } } inf.add(param); } } Filer filer = processingEnv.getFiler(); StringBuilder listBuilder = new StringBuilder(); for (GeneratedParamsClass inf : interfaces) { try { String pth = inf.packageAsPath() + '/' + inf.className; pth = pth.replace('/', '.'); JavaFileObject obj = filer.createSourceFile(pth, inf.el); try (OutputStream out = obj.openOutputStream()) { out.write(inf.toString().getBytes("UTF-8")); } listBuilder.append(inf.className).append('\n'); } catch (Exception ex) { ex.printStackTrace(); processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error processing annotation: " + ex.getMessage(), inf.el); Logger.getLogger(Processor.class.getName()).log(Level.SEVERE, null, ex); } } if (re.processingOver()) { try { FileObject list = filer.createResource(StandardLocation.CLASS_OUTPUT, "", "META-INF/paramanos/bind.list", all.toArray(new Element[0])); try (OutputStream out = list.openOutputStream()) { out.write(listBuilder.toString().getBytes("UTF-8")); } } catch (FilerException ex) { Logger.getLogger(Processor.class.getName()).log(Level.INFO, null, ex); } catch (IOException ex) { Logger.getLogger(Processor.class.getName()).log(Level.SEVERE, null, ex); } } return true; }
From source file:org.kie.workbench.common.forms.adf.processors.FormDefinitionsProcessor.java
private void processFieldDefinition(TypeElement fieldDefinitionElement) throws Exception { final Messager messager = processingEnv.getMessager(); messager.printMessage(Diagnostic.Kind.NOTE, "Discovered FieldDefinition class [" + fieldDefinitionElement.getSimpleName() + "]"); Collection<FieldInfo> fieldInfos = extractFieldInfos(fieldDefinitionElement, null); String modelClassName = fieldDefinitionElement.getQualifiedName().toString(); String fieldModifierName = fixClassName(modelClassName) + "_FieldStatusModifier"; Map<String, String> fieldDefinition = new HashMap<>(); fieldDefinition.put("className", modelClassName); fieldDefinition.put("fieldModifierName", fieldModifierName); Map<String, Object> templateContext = new HashMap<>(); templateContext.put("modelClassName", modelClassName); templateContext.put("fieldModifierName", fieldModifierName); FieldDefinition fieldDefinitionAnnotation = fieldDefinitionElement.getAnnotation(FieldDefinition.class); for (FieldInfo fieldInfo : fieldInfos) { AnnotationMirror annotation = GeneratorUtils.getAnnotation(elementUtils, fieldInfo.fieldElement, FieldValue.class.getName()); if (annotation != null) { if (fieldDefinition.containsKey("value")) { throw new Exception("Problem processing FieldDefinition [" + modelClassName + "]: it should have only one @FieldValue"); }// w w w . j a va2s . com if (fieldInfo.getter == null || fieldInfo.setter == null) { throw new Exception("Problem processing FieldDefinition [" + modelClassName + "]: field marked as @FieldValue should have setter & getter"); } fieldDefinition.put("value", fieldInfo.fieldElement.getSimpleName().toString()); } else { annotation = GeneratorUtils.getAnnotation(elementUtils, fieldInfo.fieldElement, FieldReadOnly.class.getName()); if (annotation != null) { if (templateContext.containsKey("readOnly")) { throw new Exception("Problem processing FieldDefinition [" + modelClassName + "]: it should have only one @FieldReadOnly"); } if (!fieldInfo.fieldElement.asType().getKind().equals(TypeKind.BOOLEAN) && !fieldInfo.fieldElement.asType().toString().equals(Boolean.class.getName())) { throw new Exception("Problem processing FieldDefinition [" + modelClassName + "]: field marked as @FieldReadOnly must be boolean or Boolean"); } if (fieldInfo.getter == null) { throw new Exception("Problem processing FieldDefinition [" + modelClassName + "]: field marked as @FieldReadOnly should have getter"); } templateContext.put("readOnly", fieldInfo.getter); } annotation = GeneratorUtils.getAnnotation(elementUtils, fieldInfo.fieldElement, FieldRequired.class.getName()); if (annotation != null) { if (templateContext.containsKey("required")) { throw new Exception("Problem processing FieldDefinition [" + modelClassName + "]: it should have only one @FieldRequired"); } if (!fieldInfo.fieldElement.asType().getKind().equals(TypeKind.BOOLEAN) && !fieldInfo.fieldElement.asType().toString().equals(Boolean.class.getName())) { throw new Exception("Problem processing FieldDefinition [" + modelClassName + "]: field marked as @FieldRequired must be boolean or Boolean"); } if (fieldInfo.getter == null) { throw new Exception("Problem processing FieldDefinition [" + modelClassName + "]: field marked as @FieldRequired should have getter"); } templateContext.put("required", fieldInfo.getter); } if (fieldDefinitionAnnotation.labelMode().equals(LabelMode.OVERRIDE)) { annotation = GeneratorUtils.getAnnotation(elementUtils, fieldInfo.fieldElement, FieldLabel.class.getName()); if (annotation != null) { if (templateContext.containsKey("label")) { throw new Exception("Problem processing FieldDefinition [" + modelClassName + "]: it should have only one @FieldLabel"); } if (!fieldInfo.fieldElement.asType().toString().equals(String.class.getName())) { throw new Exception("Problem processing FieldDefinition [" + modelClassName + "]: field marked as @FieldLabel must be a String"); } if (fieldInfo.getter == null) { throw new Exception("Problem processing FieldDefinition [" + modelClassName + "]: field marked as @FieldLabel should have getter"); } templateContext.put("label", fieldInfo.getter); } } } } StringBuffer source = writeTemplate("templates/FieldDefinitionModifier.ftl", templateContext); fieldDefinition.put("sourceCode", source.toString()); context.getFieldDefinitions().add(fieldDefinition); }