1/* 2 * Copyright (c) 2006, 2007, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24import java.io.*; 25import javax.annotation.processing.*; 26import javax.lang.model.element.*; 27import javax.lang.model.type.*; 28import javax.lang.model.util.*; 29import static javax.tools.Diagnostic.Kind.*; 30 31import java.util.Set; 32 33@SupportedAnnotationTypes({"*"}) 34public class HelloWorldAP extends AbstractProcessor { 35 Messager msgr = null; 36 Filer filer = null; 37 boolean DONE=false; 38 39 @Override 40 public void init(ProcessingEnvironment penv) { 41 processingEnv = penv; 42 msgr=penv.getMessager(); 43 filer=penv.getFiler(); 44 } 45 46 public boolean process(Set<? extends TypeElement> tes, RoundEnvironment renv ) { 47 boolean ret = true; 48 if(!renv.processingOver() && !DONE) { 49 msgr.printMessage(NOTE, "running process to create HelloWorld."); 50 try { 51 Writer pw = filer.createSourceFile("HelloWorld").openWriter(); 52 pw.write("public class HelloWorld {\n"); 53 pw.write(" public static void main (String argv[]) {\n"); 54 pw.write(" System.out.println(\"Hello apt world.\");\n"); 55 pw.write(" }\n"); 56 pw.write("}\n"); 57 pw.flush(); 58 pw.close(); 59 60 OutputStream os = filer.createClassFile("HelloWorldAP").openOutputStream(); 61 // the easiest way to create a class file is to copy another one 62 InputStream is = getClass().getResourceAsStream("HelloWorldAP.class"); 63 copy(is, os); 64 is.close(); 65 os.flush(); 66 os.close(); 67 DONE=true; 68 } 69 catch (IOException ioe) { 70 msgr.printMessage(ERROR, ioe.getMessage()); 71 ret = false; 72 } 73 catch (Exception e) { 74 msgr.printMessage(ERROR, e.getMessage()); 75 ret = false; 76 } 77 } 78 return ret; 79 } 80 81 void copy(InputStream is, OutputStream os) throws IOException { 82 byte[] buf = new byte[8192]; 83 int n; 84 while ((n = is.read(buf, 0, buf.length)) > 0) 85 os.write(buf, 0, n); 86 } 87} 88