Source Code Cross Referenced for ExternalCompiler.java in  » EJB-Server-resin-3.1.5 » resin » com » caucho » java » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » EJB Server resin 3.1.5 » resin » com.caucho.java 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * Copyright (c) 1998-2008 Caucho Technology -- all rights reserved
003:         *
004:         * This file is part of Resin(R) Open Source
005:         *
006:         * Each copy or derived work must preserve the copyright notice and this
007:         * notice unmodified.
008:         *
009:         * Resin Open Source is free software; you can redistribute it and/or modify
010:         * it under the terms of the GNU General Public License as published by
011:         * the Free Software Foundation; either version 2 of the License, or
012:         * (at your option) any later version.
013:         *
014:         * Resin Open Source is distributed in the hope that it will be useful,
015:         * but WITHOUT ANY WARRANTY; without even the implied warranty of
016:         * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
017:         * of NON-INFRINGEMENT.  See the GNU General Public License for more
018:         * details.
019:         *
020:         * You should have received a copy of the GNU General Public License
021:         * along with Resin Open Source; if not, write to the
022:         *   Free SoftwareFoundation, Inc.
023:         *   59 Temple Place, Suite 330
024:         *   Boston, MA 02111-1307  USA
025:         *
026:         * @author Scott Ferguson
027:         */
028:
029:        package com.caucho.java;
030:
031:        import com.caucho.log.Log;
032:        import com.caucho.server.util.CauchoSystem;
033:        import com.caucho.util.Alarm;
034:        import com.caucho.util.CharBuffer;
035:        import com.caucho.vfs.*;
036:
037:        import java.io.IOException;
038:        import java.io.InputStream;
039:        import java.util.ArrayList;
040:        import java.util.logging.Level;
041:        import java.util.logging.Logger;
042:
043:        /**
044:         * Compiles Java source, returning the loaded class.
045:         */
046:        public class ExternalCompiler extends AbstractJavaCompiler {
047:            protected static final Logger log = Log
048:                    .open(ExternalCompiler.class);
049:
050:            Process _process;
051:            String _userPrefix;
052:            InputStream _errorStream;
053:            InputStream _inputStream;
054:
055:            boolean _isDead;
056:
057:            public ExternalCompiler(JavaCompiler compiler) {
058:                super (compiler);
059:            }
060:
061:            /**
062:             * Compile the configured file.
063:             *
064:             * @param path the path to the java source.
065:             * @param lineMap mapping from the generated source to the original files.
066:             */
067:            protected void compileInt(String[] paths, LineMap lineMap)
068:                    throws IOException {
069:                MemoryStream tempStream = new MemoryStream();
070:                WriteStream error = new WriteStream(tempStream);
071:                _inputStream = null;
072:                _errorStream = null;
073:                boolean chdir = CauchoSystem.isUnix();
074:
075:                _process = null;
076:
077:                try {
078:                    String javac = _compiler.getCompiler();
079:                    String sourceExt = _compiler.getSourceExtension();
080:
081:                    String path = paths[0];
082:                    int tail = path.length() - sourceExt.length();
083:                    String className = path.substring(0, tail);
084:                    Path classFile = _compiler.getClassDir().lookup(
085:                            className + ".class");
086:
087:                    ArrayList<String> argList = new ArrayList<String>();
088:                    argList.add(javac);
089:
090:                    ArrayList<String> args = _compiler.getArgs();
091:                    if (args != null)
092:                        argList.addAll(args);
093:
094:                    ArrayList<String> envList = new ArrayList();
095:
096:                    if (javac.endsWith("jikes") || javac.endsWith("jikes.exe")) {
097:                        // make jikes look in the source path allowing for class dependencies
098:                        // argList.add("+CSO");
099:                        // "emacs" style error messages, understood by JavacErrorParser
100:                        argList.add("+E");
101:
102:                        chdir = false;
103:
104:                        if (_compiler.getEncoding() != null) {
105:                            argList.add("-encoding");
106:                            argList.add(_compiler.getEncoding());
107:                        }
108:                        /*
109:                         * XXX: this encoding is needed for jikes to handle ISO-8859-1,
110:                         * but won't work on several jikes installations.
111:                        else {
112:                          argList.add("-encoding");
113:                          argList.add("LATIN1");
114:                        }
115:                         */
116:                    } else if (_compiler.getEncoding() != null) {
117:                        String encoding = Encoding.getJavaName(_compiler
118:                                .getEncoding());
119:                        argList.add("-encoding");
120:                        argList.add(encoding);
121:                    }
122:
123:                    String classPath = normalizeClassPath(_compiler
124:                            .getClassPath(), !chdir);
125:
126:                    envList.add("CLASSPATH=" + classPath);
127:
128:                    if (_compiler.getCompiler().endsWith("groovyc")) {
129:                        argList.add("--classpath");
130:                        argList.add(classPath);
131:                    } else {
132:                        argList.add("-classpath");
133:                        argList.add(classPath);
134:                    }
135:
136:                    argList.add("-d");
137:                    argList.add(normalizePath(_compiler.getClassDirName(),
138:                            !chdir));
139:
140:                    for (int i = 0; i < paths.length; i++) {
141:                        if (chdir)
142:                            argList.add(paths[i]);
143:                        else {
144:                            Path javaPath = _compiler.getSourceDir().lookup(
145:                                    paths[i]);
146:                            argList.add(javaPath.getNativePath());
147:                        }
148:                    }
149:
150:                    if (log.isLoggable(Level.FINE))
151:                        log.fine(String.valueOf(argList));
152:
153:                    _process = executeCompiler(argList, envList, chdir);
154:                    if (_process != null) {
155:                        _inputStream = _process.getInputStream();
156:                        _errorStream = _process.getErrorStream();
157:                    }
158:
159:                    /*
160:                    Alarm alarm = null;
161:                    
162:                    if (_compiler.getMaxCompileTime() > 1000)
163:                      alarm = new Alarm(this, _maxCompileTime);
164:                     */
165:
166:                    int status = 666;
167:
168:                    try {
169:                        waitForErrors(error, _inputStream, _errorStream);
170:
171:                        if (_process != null) {
172:                            status = _process.waitFor();
173:                            _process = null;
174:                        }
175:                    } catch (Throwable e) {
176:                        if (_isDead)
177:                            throw new JavaCompileException(
178:                                    L
179:                                            .l("The compilation has timed out.  You can increase the timeout value by changing the max-compile-time."));
180:
181:                        throw new IOExceptionWrapper(e);
182:                    }
183:                    /*
184:                    finally {
185:                    
186:                      if (alarm != null)
187:                        alarm.dequeue();
188:                    }
189:                     */
190:
191:                    if (_process != null) {
192:                        status = 666;
193:                    }
194:
195:                    error.close();
196:                    tempStream.close();
197:
198:                    if (log.isLoggable(Level.FINE)) {
199:                        ReadStream read = tempStream.openReadAndSaveBuffer();
200:                        CharBuffer cb = new CharBuffer();
201:                        int ch;
202:
203:                        while ((ch = read.read()) >= 0)
204:                            cb.append((char) ch);
205:                        read.close();
206:                        final String msg = cb.toString();
207:
208:                        new com.caucho.loader.ClassLoaderContext(_compiler
209:                                .getClassLoader()) {
210:                            public void run() {
211:                                log.fine(msg);
212:                            }
213:                        };
214:                    }
215:
216:                    ReadStream read = tempStream.openReadAndSaveBuffer();
217:                    ErrorParser parser;
218:
219:                    // the javac error parser will work with jikes in "emacs" mode
220:                    parser = new JavacErrorParser();
221:
222:                    String errors = parser.parseErrors(read, lineMap);
223:                    read.close();
224:
225:                    if (errors != null)
226:                        errors = errors.trim();
227:
228:                    if (status == 0 && classFile.getLength() > 0) {
229:                        if (errors != null && !errors.equals("")) {
230:                            final String msg = errors;
231:
232:                            new com.caucho.loader.ClassLoaderContext(_compiler
233:                                    .getClassLoader()) {
234:                                public void run() {
235:                                    log.warning(msg);
236:                                }
237:                            };
238:                        }
239:
240:                        return;
241:                    }
242:
243:                    if (errors == null || errors.equals("")) {
244:                        CharBuffer cb = new CharBuffer();
245:
246:                        if (status == 0) {
247:                            cb.append("Compilation for '" + className
248:                                    + "' did not generate a .class file.\n");
249:                            cb
250:                                    .append("Make sure the `package' matches the directory.\n");
251:                        } else
252:                            cb.append("Unknown compiler error executing:\n");
253:
254:                        for (int i = 0; i < argList.size(); i++)
255:                            cb.append(" " + argList.get(i) + "\n");
256:
257:                        read = tempStream.openReadAndSaveBuffer();
258:                        int ch;
259:                        while ((ch = read.read()) >= 0)
260:                            cb.append((char) ch);
261:                        read.close();
262:                        errors = cb.toString();
263:                    } else if (errors.indexOf("command not found") >= 0) {
264:                        throw new JavaCompileException(
265:                                L
266:                                        .l(
267:                                                "Resin can't execute the compiler `{0}'.  This usually means that the compiler is not in the operating system's PATH or the compiler is incorrectly specified in the configuration.  You may need to add the full path to <java compiler='{0}'/>.\n\n{1}",
268:                                                argList.get(0), errors));
269:                    }
270:
271:                    throw new JavaCompileException(errors);
272:                } finally {
273:                    if (_inputStream != null) {
274:                        try {
275:                            _inputStream.close();
276:                        } catch (Throwable e) {
277:                        }
278:                    }
279:
280:                    if (_errorStream != null) {
281:                        try {
282:                            _errorStream.close();
283:                        } catch (Throwable e) {
284:                        }
285:                    }
286:
287:                    if (_process != null) {
288:                        try {
289:                            _process.destroy();
290:                        } catch (Throwable e) {
291:                            log.log(Level.FINE, e.toString(), e);
292:                        }
293:                    }
294:
295:                    tempStream.destroy();
296:                }
297:            }
298:
299:            /**
300:             * Read any errors from the process.
301:             */
302:            private void waitForErrors(WriteStream error,
303:                    InputStream inputStream, InputStream errorStream)
304:                    throws IOException {
305:                byte[] buffer = new byte[256];
306:                int stderrLen;
307:                int stdoutLen;
308:
309:                if (inputStream == null || errorStream == null)
310:                    return;
311:
312:                do {
313:                    while ((stderrLen = errorStream.available()) > 0) {
314:                        stderrLen = errorStream.read(buffer, 0, buffer.length);
315:                        if (stderrLen <= 0)
316:                            break;
317:
318:                        error.write(buffer, 0, stderrLen);
319:                    }
320:
321:                    while ((stdoutLen = inputStream.available()) > 0) {
322:                        stdoutLen = inputStream.read(buffer, 0, buffer.length);
323:                        if (stdoutLen <= 0)
324:                            break;
325:
326:                        error.write(buffer, 0, stdoutLen);
327:                    }
328:
329:                    if (stderrLen < 0 && stdoutLen < 0)
330:                        return;
331:
332:                    if (stderrLen == 0) {
333:                        stderrLen = errorStream.read(buffer, 0, buffer.length);
334:                        if (stderrLen > 0)
335:                            error.write(buffer, 0, stderrLen);
336:                    }
337:
338:                    if (stderrLen < 0 && stdoutLen == 0) {
339:                        stdoutLen = inputStream.read(buffer, 0, buffer.length);
340:                        if (stdoutLen > 0)
341:                            error.write(buffer, 0, stdoutLen);
342:                    }
343:                } while (!_isDead && (stderrLen >= 0 || stdoutLen >= 0));
344:            }
345:
346:            /**
347:             * This callback should only occur if the compiler freezes.  In that
348:             * case we immediately kill the process.
349:             *
350:             * @param alarm the alarm we've been waiting for.
351:             */
352:            public void handleAlarm(Alarm alarm) {
353:                _isDead = true;
354:                abort();
355:            }
356:
357:            /**
358:             * Aborts the compilation.
359:             */
360:            public void abort() {
361:                if (_inputStream != null) {
362:                    try {
363:                        _inputStream.close();
364:                    } catch (Throwable e) {
365:                    }
366:                }
367:
368:                if (_errorStream != null) {
369:                    try {
370:                        _errorStream.close();
371:                    } catch (Throwable e) {
372:                    }
373:                }
374:
375:                if (_process != null) {
376:                    try {
377:                        _process.destroy();
378:                    } catch (Throwable e) {
379:                        log.log(Level.FINE, e.toString(), e);
380:                    }
381:                }
382:            }
383:
384:            /**
385:             * Spawn the process to compile the file.
386:             *
387:             * @param argList compiler arguments.
388:             * @param chdir if true, change to the compilation directory .
389:             * @return a Java Process representing the compiler.
390:             */
391:            private Process executeCompiler(ArrayList<String> argList,
392:                    ArrayList<String> envList, boolean chdir)
393:                    throws IOException {
394:                String[] args;
395:
396:                // For unix, we can use sh to change the directory to get
397:                // automatic compilation of aux files.
398:                // Disabled because it's not needed with the source path?
399:                if (chdir) {
400:                    CharBuffer cb = new CharBuffer();
401:                    cb.append("cd ");
402:                    cb.append(_compiler.getSourceDirName());
403:                    cb.append(";");
404:                    for (int i = 0; i < argList.size(); i++) {
405:                        cb.append(" ");
406:                        cb.append(argList.get(i));
407:                    }
408:                    args = new String[3];
409:                    args[0] = "/bin/sh";
410:                    args[1] = "-c";
411:                    args[2] = cb.toString();
412:                } else {
413:                    args = new String[argList.size()];
414:                    argList.toArray(args);
415:                }
416:
417:                String[] envp = new String[envList.size()];
418:                envList.toArray(envp);
419:
420:                if (log.isLoggable(Level.FINE)) {
421:                    CharBuffer cb = CharBuffer.allocate();
422:
423:                    for (int i = 0; i < args.length; i++) {
424:                        if (i != 0)
425:                            cb.append(" ");
426:                        cb.append(args[i]);
427:                    }
428:                    log.fine(cb.close());
429:                }
430:
431:                Runtime runtime = Runtime.getRuntime();
432:
433:                try {
434:                    return runtime.exec(args);
435:                } catch (Exception e) {
436:                    throw new JavaCompileException(
437:                            L
438:                                    .l(
439:                                            "Resin can't execute the compiler `{0}'.  This usually means that the compiler is not in the operating system's PATH or the compiler is incorrectly specified in the configuration.  You may need to add the full path to <java compiler='{0}'/>.\n\n{1}",
440:                                            args[0], String.valueOf(e)));
441:                }
442:            }
443:
444:            /**
445:             * Converts any relative classpath references to the full path.
446:             */
447:            String normalizeClassPath(String classPath, boolean generateRelative) {
448:                char sep = CauchoSystem.getPathSeparatorChar();
449:                int head = 0;
450:                int tail = 0;
451:
452:                CharBuffer cb = CharBuffer.allocate();
453:
454:                while (head < classPath.length()) {
455:                    tail = classPath.indexOf(sep, head);
456:                    if (tail < 0)
457:                        tail = classPath.length();
458:
459:                    if (tail > head) {
460:                        String segment = classPath.substring(head, tail);
461:
462:                        segment = normalizePath(segment, generateRelative);
463:
464:                        if (segment != null) {
465:                            if (cb.length() != 0)
466:                                cb.append(sep);
467:
468:                            cb.append(segment);
469:                        }
470:                    }
471:
472:                    head = tail + 1;
473:                }
474:
475:                return cb.close();
476:            }
477:
478:            /**
479:             * Normalizes a path.
480:             */
481:            String normalizePath(String segment, boolean generateRelative) {
482:                if (_userPrefix == null) {
483:                    Path userPath = Vfs.lookup(CauchoSystem.getUserDir());
484:                    char sep = CauchoSystem.getFileSeparatorChar();
485:                    _userPrefix = userPath.getNativePath();
486:
487:                    if (_userPrefix.length() == 0
488:                            || _userPrefix.charAt(_userPrefix.length() - 1) != sep) {
489:                        _userPrefix = _userPrefix + sep;
490:                    }
491:                }
492:
493:                Path path = Vfs.lookup(segment);
494:
495:                String nativePath = path.getNativePath();
496:
497:                if (!generateRelative)
498:                    return nativePath;
499:
500:                if (nativePath.startsWith(_userPrefix))
501:                    nativePath = nativePath.substring(_userPrefix.length());
502:
503:                if (nativePath.equals(""))
504:                    return ".";
505:                else
506:                    return nativePath;
507:            }
508:
509:            public static class CompilerThread implements  Runnable {
510:                private volatile boolean _isDone;
511:
512:                public void run() {
513:                    try {
514:                    } finally {
515:                        _isDone = true;
516:
517:                        synchronized (this) {
518:                            notifyAll();
519:                        }
520:                    }
521:                }
522:            }
523:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.