FileDocCategorySizeDatePackage
Javac.javaAPI DocApache Axis 1.411589Sat Apr 22 18:57:26 BST 2006org.apache.axis.components.compiler

Javac

public class Javac extends AbstractCompiler
This class wraps the Sun's Javac Compiler.
author
Davanum Srinivas
author
Stefano Mazzocchi
since
2.0

Fields Summary
protected static Log
log
public static final String
CLASSIC_CLASS
public static final String
MODERN_CLASS
private boolean
modern
Constructors Summary
public Javac()


      
        ClassLoader cl = getClassLoader();
        try {
            ClassUtils.forName(MODERN_CLASS, true, cl);
            modern = true;
        } catch (ClassNotFoundException e) {
            log.debug(Messages.getMessage("noModernCompiler"));
            try {
                ClassUtils.forName(CLASSIC_CLASS, true, cl);
                modern = false;
            } catch (Exception ex) {
                log.error(Messages.getMessage("noCompiler00"), ex);
                throw new RuntimeException(Messages.getMessage("noCompiler00"));
            }
        }
        log.debug(Messages.getMessage("compilerClass",
                (modern ? MODERN_CLASS : CLASSIC_CLASS)));
    
Methods Summary
public booleancompile()
Compile a source file yielding a loadable class file.

exception
IOException If an error occurs during compilation

        ByteArrayOutputStream err = new ByteArrayOutputStream();
        boolean result = false;

        try {
            // Create an instance of the compiler, redirecting output to err
            Class c = ClassUtils.forName(modern ? MODERN_CLASS : CLASSIC_CLASS, 
                                         true,
                                         getClassLoader());

            Constructor cons;
            Object compiler;
            if (modern) {
                PrintWriter pw = new PrintWriter(new OutputStreamWriter(err));
                cons = 
                    c.getConstructor(new Class[] { String.class,
                                                   PrintWriter.class});
       
                compiler = cons.newInstance(new Object[] { "javac", pw });
            }
            else {
                cons =
                    c.getConstructor(new Class[] { OutputStream.class,
                                                   String.class });
                compiler = cons.newInstance(new Object[] { err, "javac" });
        
            }
              
            // Call the compile() method
            Method compile = c.getMethod("compile",
                                         new Class [] { String[].class });

            if (modern) {
                int compilationResult = 
                    ((Integer)compile.invoke(compiler, new Object[] 
                        {
                            toStringArray(fillArguments
                                          (new ArrayList()))})).intValue();

                result = (compilationResult == 0);        
                log.debug("Compilation Returned: " 
                          + Integer.toString(compilationResult));
            }
            else {
                Boolean ok = 
                    (Boolean)compile.invoke(compiler, new Object[] 
                        {toStringArray(fillArguments(new ArrayList()))});
        
                result = ok.booleanValue();
            }
        } catch (Exception cnfe){
            log.error(Messages.getMessage("noCompiler00"), cnfe);
            throw new RuntimeException(Messages.getMessage("noCompiler00"));
        }

        this.errors = new ByteArrayInputStream(err.toByteArray());
        return result;
    
private java.lang.ClassLoadergetClassLoader()

        // Use reflection to be able to build on all JDKs
        ClassLoader cl = Thread.currentThread().getContextClassLoader();

        URL toolsURL = null;
        String tools = System.getProperty("java.home");
        if (tools != null) {
            File f = new File(tools + "/../lib/tools.jar");
            if (f.exists()) {
                try {
                    toolsURL = f.toURL();
                    cl = new URLClassLoader(new URL[]{toolsURL}, cl);
                } catch (MalformedURLException e) {
                }
            }
        }
        
        return cl;
    
private CompilerErrorparseClassicError(java.lang.String error)
Parse an individual compiler error message with classic style.

param
error The error text
return
A messaged CompilerError

        StringTokenizer tokens = new StringTokenizer(error, ":");
        try {
            String file = tokens.nextToken();
            if (file.length() == 1) {
                file = new StringBuffer(file).append(":").
                        append(tokens.nextToken()).toString();
            }
            int line = Integer.parseInt(tokens.nextToken());

            String last = tokens.nextToken();
            // In case the message contains ':', it should be reassembled
            while (tokens.hasMoreElements()) {
                last += tokens.nextToken();
            }
            tokens = new StringTokenizer(last.trim(), "\n");
            String message = tokens.nextToken();
            String context = tokens.nextToken();
            String pointer = tokens.nextToken();
            int startcolumn = pointer.indexOf("^");
            int endcolumn = context.indexOf(" ", startcolumn);
            if (endcolumn == -1) endcolumn = context.length();

            return new CompilerError(srcDir + File.separator + file, true,
                    line, startcolumn, line, endcolumn, message);
        } catch(NoSuchElementException nse) {
            return new CompilerError(Messages.getMessage("noMoreTokens",
                    error));
        } catch(Exception nse) {
            return new CompilerError(Messages.getMessage("cantParse", error));
        }
    
protected java.util.ListparseClassicStream(java.io.BufferedReader input)
Parse the compiler error stream to produce a list of CompilerErrors

param
input The error stream
return
The list of compiler error messages
exception
IOException If an error occurs during message collection

        List errors = null;
        String line = null;
        StringBuffer buffer = null;

        while (true) {
            // cleanup the buffer
            buffer = new StringBuffer(); // this is faster than clearing it

            // each error has 3 lines
            for (int i = 0; i < 3 ; i++) {
                if ((line = input.readLine()) == null) return errors;
                log.debug(line);
                buffer.append(line);
                buffer.append('\n");
            }

            // if error is found create the vector
            if (errors == null) errors = new ArrayList();

            // add the error bean
            errors.add(parseClassicError(buffer.toString()));
        }
    
private CompilerErrorparseModernError(java.lang.String error)
Parse an individual compiler error message with modern style.

param
error The error text
return
A messaged CompilerError

        StringTokenizer tokens = new StringTokenizer(error, ":");
        try {
            String file = tokens.nextToken();
            if (file.length() == 1) file = new StringBuffer(file).append(":").append(tokens.nextToken()).toString();
            int line = Integer.parseInt(tokens.nextToken());

            String message = tokens.nextToken("\n").substring(1);
            String context = tokens.nextToken("\n");
            String pointer = tokens.nextToken("\n");
            int startcolumn = pointer.indexOf("^");
            int endcolumn = context.indexOf(" ", startcolumn);
            if (endcolumn == -1) endcolumn = context.length();
            return new CompilerError(file, false, line, startcolumn, line, endcolumn, message);
        } catch(NoSuchElementException nse) {
            return new CompilerError(Messages.getMessage("noMoreTokens", error));
        } catch(Exception nse) {
            return new CompilerError(Messages.getMessage("cantParse", error));
        }
    
protected java.util.ListparseModernStream(java.io.BufferedReader input)
Parse the compiler error stream to produce a list of CompilerErrors

param
input The error stream
return
The list of compiler error messages
exception
IOException If an error occurs during message collection

        List errors = new ArrayList();
        String line = null;
        StringBuffer buffer = null;

        while (true) {
            // cleanup the buffer
            buffer = new StringBuffer(); // this is quicker than clearing it

            // most errors terminate with the '^' char
            do {
                if ((line = input.readLine()) == null)
                {
                    if (buffer.length() > 0) {
                        // There's an error which doesn't end with a '^'
                        errors.add(new CompilerError("\n" + buffer.toString()));
                    }
                    return errors;
                }
                log.debug(line);
                buffer.append(line);
                buffer.append('\n");
            } while (!line.endsWith("^"));

            // add the error bean
            errors.add(parseModernError(buffer.toString()));
        }
    
protected java.util.ListparseStream(java.io.BufferedReader input)
Parse the compiler error stream to produce a list of CompilerErrors

param
input The error stream
return
The list of compiler error messages
exception
IOException If an error occurs during message collection

        if (modern) {
            return parseModernStream(input);
        } else {
            return parseClassicStream(input);
        }
    
public java.lang.StringtoString()

        return Messages.getMessage("sunJavac");