List of usage examples for javax.tools JavaFileObject openWriter
Writer openWriter() throws IOException;
From source file:android.databinding.tool.writer.AnnotationJavaFileWriter.java
@Override public void writeToFile(String canonicalName, String contents) { Writer writer = null;/* w ww . ja v a2s .c o m*/ try { L.d("writing file %s", canonicalName); JavaFileObject javaFileObject = mProcessingEnvironment.getFiler().createSourceFile(canonicalName); writer = javaFileObject.openWriter(); writer.write(contents); } catch (IOException e) { L.e(e, "Could not write to %s", canonicalName); } finally { if (writer != null) { IOUtils.closeQuietly(writer); } } }
From source file:ch.rasc.constgen.ConstAnnotationProcessor.java
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { this.processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Running " + getClass().getSimpleName()); if (roundEnv.processingOver() || annotations.size() == 0) { return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS; }//from w ww. ja v a2 s. c om if (roundEnv.getRootElements() == null || roundEnv.getRootElements().isEmpty()) { this.processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "No sources to process"); return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS; } for (TypeElement annotation : annotations) { Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(annotation); boolean bsoncodecProject = annotation.getQualifiedName() .contentEquals("ch.rasc.bsoncodec.annotation.BsonDocument"); for (Element element : elements) { try { TypeElement typeElement = (TypeElement) element; CodeGenerator codeGen = new CodeGenerator(typeElement, this.processingEnv.getElementUtils(), bsoncodecProject); JavaFileObject jfo = this.processingEnv.getFiler() .createSourceFile(codeGen.getPackageName() + "." + codeGen.getClassName()); try (Writer writer = jfo.openWriter()) { codeGen.generate(writer); } } catch (Exception e) { this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage()); } } } return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS; }
From source file:net.pkhsolutions.ceres.common.builder.processor.BuildableAP.java
private void createSourceFile(String fileName, Template template, VelocityContext vc) { try {//w w w. j ava 2s . c o m JavaFileObject jfo = processingEnv.getFiler().createSourceFile(fileName); Writer writer = jfo.openWriter(); template.merge(vc, writer); writer.close(); } catch (IOException e) { throw new RuntimeException("Could not create source file", e); } }
From source file:com.github.cchacin.JsonSchemaProcessor.java
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (final Element element : roundEnv.getElementsAnnotatedWith(JsonSchema.class)) { final TypeElement classElement = (TypeElement) element; final PackageElement packageElement = (PackageElement) classElement.getEnclosingElement(); processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "annotated class: " + classElement.getQualifiedName(), element); final String fqClassName = classElement.getQualifiedName().toString(); final String className = classElement.getSimpleName().toString(); final String packageName = packageElement.getQualifiedName().toString(); final JsonSchema jsonSchema = element.getAnnotation(JsonSchema.class); try {//from www . ja va2 s .c o m final JsonNode node = new ObjectMapper().readTree( Thread.currentThread().getContextClassLoader().getResourceAsStream(jsonSchema.path())); vc.put("display", new DisplayTool()); vc.put("json", node); vc.put("className", className); vc.put("packageName", packageName); final JavaFileObject jfo = filer.createSourceFile(fqClassName + "JsonSchema"); processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "creating source file: " + jfo.toUri()); final Writer writer = jfo.openWriter(); processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "applying velocity template: " + vt.getName()); vt.merge(vc, writer); writer.close(); } catch (IOException e) { e.printStackTrace(); } } return false; }
From source file:io.realm.processor.RealmProxyMediatorGenerator.java
public void generate() throws IOException { String qualifiedGeneratedClassName = String.format("%s.%sMediator", REALM_PACKAGE_NAME, className); JavaFileObject sourceFile = processingEnvironment.getFiler().createSourceFile(qualifiedGeneratedClassName); JavaWriter writer = new JavaWriter(new BufferedWriter(sourceFile.openWriter())); writer.setIndent(" "); writer.emitPackage(REALM_PACKAGE_NAME); writer.emitEmptyLine();// w w w . ja va2s .c o m writer.emitImports("android.util.JsonReader", "java.io.IOException", "java.util.ArrayList", "java.util.Collections", "java.util.List", "java.util.Map", "io.realm.exceptions.RealmException", "io.realm.internal.ImplicitTransaction", "io.realm.internal.RealmObjectProxy", "io.realm.internal.RealmProxyMediator", "io.realm.internal.Table", "org.json.JSONException", "org.json.JSONObject"); writer.emitImports(qualifiedModelClasses); writer.emitEmptyLine(); writer.emitAnnotation(RealmModule.class); writer.beginType(qualifiedGeneratedClassName, // full qualified name of the item to generate "class", // the type of the item Collections.<Modifier>emptySet(), // modifiers to apply "RealmProxyMediator"); // class to extend writer.emitEmptyLine(); emitFields(writer); emitCreateTableMethod(writer); emitValidateTableMethod(writer); emitGetFieldNamesMethod(writer); emitGetTableNameMethod(writer); emitNewInstanceMethod(writer); emitGetClassModelList(writer); emitGetColumnIndices(writer); emitCopyToRealmMethod(writer); emitCreteOrUpdateUsingJsonObject(writer); emitCreateUsingJsonStream(writer); writer.endType(); writer.close(); }
From source file:com.thoratou.exact.processors.ExactProcessor.java
private void writeSources(HashMap<String, List<PathStep>> mergedMap) throws IOException, ClassNotFoundException, ExactException { //use all annotation data to generate parsing files for (Map.Entry<String, List<PathStep>> entryList : mergedMap.entrySet()) { VelocityEngine engine = new VelocityEngine(); //needed it avoid global instead of local variable modification engine.setProperty(RuntimeConstants.VM_CONTEXT_LOCALSCOPE, true); //read file into JAR InputStream configStream = getClass().getResourceAsStream("/xmlreader.vm"); BufferedReader configReader = new BufferedReader(new InputStreamReader(configStream, "UTF-8")); String className = entryList.getKey(); List<PathStep> steps = entryList.getValue(); VelocityContext context = new VelocityContext(); context.put("class", className); //logger.info("class : "+className); //ugly temp code String[] split = className.split("\\."); StringBuffer packageBuffer = new StringBuffer(); for (int i = 0; i < split.length - 1; i++) { packageBuffer.append(split[i]); if (i != split.length - 2) { packageBuffer.append("."); }/*from w w w.j av a2 s. co m*/ } String packageName = packageBuffer.toString(); //logger.info("package : "+packageName); context.put("package", packageName); String simpleName = split[split.length - 1]; //logger.info("simpleclass : "+simpleName); context.put("simpleclass", simpleName); context.put("steps", steps); context.put("kindmap", PathStep.ReverseKindMap); context.put("startmap", PathStep.ReverseStartMap); context.put("typemap", PathStep.ReverseTypeMap); context.put("listtypemap", PathStep.ReverseListTypeMap); context.put("indentutil", new IndentUtil()); context.put("processingutil", new ProcessingUtil()); Set<String> bomList = new HashSet<String>(); registerBomListFromSteps(steps, bomList); context.put("bomlist", bomList); Set<String> extensionList = new HashSet<String>(); Map<String, ExtensionVelocityData> extensionMap = new HashMap<String, ExtensionVelocityData>(); registerExtensionListFromSteps(steps, extensionList, extensionMap); context.put("extensionlist", extensionList); context.put("extensionmap", extensionMap); logger.info("input velocity data : " + className + " , " + steps.toString()); //StringWriter writer = new StringWriter(); //String packagePath = packageName.replace(".","/"); //String fullFile = packagePath+"/"+simpleName+"XmlReader.java"; //logger.info(fullFile); Filer filer = processingEnv.getFiler(); JavaFileObject sourceFile = filer.createSourceFile(className + "XmlReader"); Writer sourceWriter = sourceFile.openWriter(); engine.evaluate(context, sourceWriter, "", configReader); sourceWriter.close(); sourceFile.delete(); //logger.info("final velocity data : "+writer.getBuffer().toString()); } }
From source file:org.shredzone.commons.taglib.processor.TaglibProcessor.java
/** * Generates a proxy class that connects to Spring and allows all Spring features like * dependency injection in the implementing tag class. * * @param tag//from w ww . j a v a 2 s . c o m * {@link TagBean} that describes the tag. * @throws IOException * when the generated Java code could not be saved. */ private void generateProxyClass(TagBean tag) throws IOException { String beanFactoryReference = tag.getBeanFactoryReference(); if (beanFactoryReference == null) { beanFactoryReference = taglib.getBeanFactoryReference(); } JavaFileObject src = processingEnv.getFiler().createSourceFile(tag.getProxyClassName()); String packageName = null; int packPos = tag.getClassName().lastIndexOf('.'); if (packPos >= 0) { packageName = tag.getClassName().substring(0, packPos); } String proxyClass = PROXY_MAP.get(tag.getType()); try (PrintWriter out = new PrintWriter(src.openWriter())) { if (packageName != null) { out.printf("package %s;\n", packageName).println(); } out.print("@javax.annotation.Generated(\""); out.print(TaglibProcessor.class.getName()); out.println("\")"); out.printf("public class %s extends %s<%s> %s {", StringUtils.unqualify(tag.getProxyClassName()), proxyClass, tag.getClassName(), (tag.isTryCatchFinally() ? "implements javax.servlet.jsp.tagext.TryCatchFinally" : "")) .println(); if (beanFactoryReference != null) { out.println( " protected org.springframework.beans.factory.BeanFactory getBeanFactory(javax.servlet.jsp.JspContext jspContext) {"); out.printf(" java.lang.Object beanFactory = jspContext.findAttribute(\"%s\");", beanFactoryReference).println(); out.println(" if (beanFactory == null) {"); out.printf(" throw new java.lang.NullPointerException(\"attribute '%s' not set\");", beanFactoryReference).println(); out.println(" }"); out.println(" return (org.springframework.beans.factory.BeanFactory) beanFactory;"); out.println(" }"); } out.println(" protected java.lang.String getBeanName() {"); out.printf(" return \"%s\";", tag.getBeanName()).println(); out.println(" }"); for (AttributeBean attr : new TreeSet<AttributeBean>(tag.getAttributes())) { out.printf(" public void set%s(%s _%s) {", StringUtils.capitalize(attr.getName()), attr.getType(), attr.getName()).println(); out.printf(" getTargetBean().set%s(_%s);", StringUtils.capitalize(attr.getName()), attr.getName()).println(); out.println(" }"); } out.println("}"); } }
From source file:fr.xebia.extras.selma.codegen.MapperClassGenerator.java
public void build() throws IOException { boolean firstMethod = true; JavaWriter writer = null;//from ww w . j a v a 2s. c om JavaFileObject sourceFile = null; final TypeElement type = processingEnv.getElementUtils().getTypeElement(origClasse); final String packageName = getPackage(type).getQualifiedName().toString(); final String strippedTypeName = strippedTypeName(type.getQualifiedName().toString(), packageName); final String adapterName = new StringBuilder(packageName).append('.') .append(strippedTypeName.replace('.', '_')).append(SelmaConstants.MAPPER_CLASS_SUFFIX).toString(); for (MethodWrapper mapperMethod : methodWrappers) { if (firstMethod) { sourceFile = processingEnv.getFiler().createSourceFile(adapterName, type); writer = new JavaWriter(sourceFile.openWriter()); writer.emitSingleLineComment(GENERATED_BY_SELMA); writer.emitPackage(packageName); writer.emitEmptyLine(); switch (mapper.ioC) { case SPRING: if (mapper.ioCServiceName != "") { writer.emitAnnotation("org.springframework.stereotype.Service", "\"" + mapper.ioCServiceName + "\""); } else { writer.emitAnnotation("org.springframework.stereotype.Service"); } break; case CDI: writer.emitAnnotation("javax.enterprise.context.ApplicationScoped"); break; default: break; } openClassBlock(writer, adapterName, strippedTypeName); writer.emitEmptyLine(); firstMethod = false; } // Write mapping method MapperMethodGenerator mapperMethodGenerator = new MapperMethodGenerator(writer, mapperMethod, mapper); mapperMethodGenerator.build(); mapper.collectMaps(mapperMethodGenerator.maps()); writer.emitEmptyLine(); } buildConstructor(writer, adapterName); writer.endType(); writer.close(); mapper.reportUnused(); }
From source file:auto.parse.processor.AutoParseProcessor.java
private void writeSourceFile(String className, String text, TypeElement originatingType) { try {/*from w w w . j a va 2 s . co m*/ note(text); JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(className, originatingType); Writer writer = sourceFile.openWriter(); try { writer.write(text); } finally { writer.close(); } } catch (IOException e) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Could not write generated class " + className + ": " + e); } }
From source file:io.realm.processor.RealmProxyClassGenerator.java
public void generate() throws IOException, UnsupportedOperationException { elementUtils = processingEnvironment.getElementUtils(); typeUtils = processingEnvironment.getTypeUtils(); realmObject = elementUtils.getTypeElement("io.realm.RealmObject").asType(); realmList = typeUtils.getDeclaredType(elementUtils.getTypeElement("io.realm.RealmList"), typeUtils.getWildcardType(null, null)); String qualifiedGeneratedClassName = String.format("%s.%s", Constants.REALM_PACKAGE_NAME, Utils.getProxyClassName(className)); JavaFileObject sourceFile = processingEnvironment.getFiler().createSourceFile(qualifiedGeneratedClassName); JavaWriter writer = new JavaWriter(new BufferedWriter(sourceFile.openWriter())); // Set source code indent to 4 spaces writer.setIndent(" "); writer.emitPackage(Constants.REALM_PACKAGE_NAME).emitEmptyLine(); ArrayList<String> imports = new ArrayList<String>(); imports.add("android.util.JsonReader"); imports.add("android.util.JsonToken"); imports.add("io.realm.RealmObject"); imports.add("io.realm.exceptions.RealmException"); imports.add("io.realm.exceptions.RealmMigrationNeededException"); imports.add("io.realm.internal.ColumnType"); imports.add("io.realm.internal.RealmObjectProxy"); imports.add("io.realm.internal.Table"); imports.add("io.realm.internal.TableOrView"); imports.add("io.realm.internal.ImplicitTransaction"); imports.add("io.realm.internal.LinkView"); imports.add("io.realm.internal.android.JsonUtils"); imports.add("java.io.IOException"); imports.add("java.util.ArrayList"); imports.add("java.util.Collections"); imports.add("java.util.List"); imports.add("java.util.Arrays"); imports.add("java.util.Date"); imports.add("java.util.Map"); imports.add("java.util.HashMap"); imports.add("org.json.JSONObject"); imports.add("org.json.JSONException"); imports.add("org.json.JSONArray"); imports.add(metadata.getFullyQualifiedClassName()); for (VariableElement field : metadata.getFields()) { String fieldTypeName = ""; if (typeUtils.isAssignable(field.asType(), realmObject)) { // Links fieldTypeName = field.asType().toString(); } else if (typeUtils.isAssignable(field.asType(), realmList)) { // LinkLists fieldTypeName = ((DeclaredType) field.asType()).getTypeArguments().get(0).toString(); }/*from w w w . j av a2 s. c o m*/ if (!fieldTypeName.isEmpty() && !imports.contains(fieldTypeName)) { imports.add(fieldTypeName); } } Collections.sort(imports); writer.emitImports(imports); writer.emitEmptyLine(); // Begin the class definition writer.beginType(qualifiedGeneratedClassName, // full qualified name of the item to generate "class", // the type of the item EnumSet.of(Modifier.PUBLIC), // modifiers to apply className, // class to extend "RealmObjectProxy") // interfaces to implement .emitEmptyLine(); emitClassFields(writer); emitAccessors(writer); emitInitTableMethod(writer); emitValidateTableMethod(writer); emitGetTableNameMethod(writer); emitGetFieldNamesMethod(writer); emitGetColumnIndicesMethod(writer); emitCreateOrUpdateUsingJsonObject(writer); emitCreateUsingJsonStream(writer); emitCopyOrUpdateMethod(writer); emitCopyMethod(writer); emitUpdateMethod(writer); emitToStringMethod(writer); emitHashcodeMethod(writer); emitEqualsMethod(writer); // End the class definition writer.endType(); writer.close(); }