Using JavaCompiler in a Servlet

Currently I am developing a tool in which Java Source Files are created based on a XSD file with help of a tool named Castor.
After the generation of the files the files need to be compiled in order to be used by the program. This used to be done with a Library named XMLBean, however I do not wish to use this library anymore.
As a alternative I ended up using the Java compiler that comes with the JDK in the tools.jar file. This resulted in a problem, which made me search for a other solution. This way I ended up working with the javax.tools.JavaCompiler. However compilation still failed due to the same problem.
So what is this problem?
Initially I tested my code generation logic and compile logic in a normal application. The Java code got generated fine using castor, the compilation using both methods I described also went fine.
The problem occurs when I attempt to use the same logic in a web application (Behind a servlet) I am developing to run on Tomcat. The Code generation goes fine (since the castor library is included in the project) however the compilation goes wrong and results in the following error:
"package org.exolab.castor.xml does not exist"
In other words, the compiler does not understand one of the imports of the source file (refering to a namespace in Castor, a library that was used to generate the file, and is included in the web project).
Does anyone know why compilation fails in a web application but goes well in a normal application? Does anyone know how this problem can be solved, or does anyone know better component for compilation?
Thanks a lot.
This is the code I currently use for compilation:
public void compileJavaSource(String[] sourceFilePaths)
          System.out.println("Begin Compiling of Source Files");
          JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); // Line 1.
          DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<JavaFileObject>();
          StandardJavaFileManager fileManager  = compiler.getStandardFileManager(diagnosticsCollector, null, null); // Line 3.
          Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjectsFromStrings(Arrays.asList(sourceFilePaths)); // Line 5
          CompilationTask task = compiler.getTask(null, fileManager, diagnosticsCollector, null, null, fileObjects); // Line 6
          Boolean result = task.call(); // Line 7
          List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticsCollector.getDiagnostics();
          for(int i=0; i < diagnostics.size(); i++){
               Diagnostic<? extends JavaFileObject> d = diagnostics.get(i);
               System.out.println(d.getMessage(null));
          if(result == true) {
               System.out.println("Compilation has succeeded");
          else {
               System.out.println("Compilation fails.");
          System.out.println("Done Compiling of Source Files");
     } Initially I used this:
com.sun.tools.javac.Main.compile(sourceFilePaths);

Cross posted. (Sorry about that)
To avoid people spending time looking for an answer, here is the solution I found myself:
First off all, for ANT to work, 2 libraries have to be imported in the web project.
The libraries are: ant.jar and ant-launcher.jar
Next to that, the library's Xerces (xercesImpl.jar) and xml-apis.jar (also included in ANT). There Library's are also needed to get Castor to work.
To compile the code of my generated Java Classes I use the following ANT Build file code:
<project default="build" basedir=".">
     <path id="classpath">
        <fileset dir="WEB-INF/lib" includes="**/*.jar"/>
    </path>
     <target name="build">
        <javac srcdir="src" destdir="WEB-INF/classes" debug="true" includes="**/*.java" classpathref="classpath"/>
     </target>
</project>The file basically reads every .java file from my "src" folder. Which is the folder I choose to put my generated class files, and compiles them to the WEB-INF/classes folder. This is the folder were Tomcat stores all its classes.
What went wrong with the compilation I attempted in the opening post, is that javac could not find the Castor Library, even after I added it in my classpath environment variable. Fortunately, with ANT I can define a classpath for the application, which is the WEB-INF/lib folder. This is the folder where Tomcat stores its Library's. Hence, javac can find the Castor Library from then on.
Finally I call the ant task using the following Java Code:
public void compileJavaSource(String buildFilePath)
          System.out.println("Start Compilation");
          File buildFile = new File(buildFilePath);
          Project p = new Project();
          p.setUserProperty("ant.file", buildFilePath);
          p.init();
          ProjectHelper helper = ProjectHelper.getProjectHelper();
          p.addReference("ant.projectHelper", helper);
          helper.parse(p, buildFile);
          p.executeTarget(p.getDefaultTarget());
          System.out.println("Compilation Finished");
     }This took care of the problem pretty nicely.

Similar Messages

  • Using a class or servlet that implements Serializable

    Hello everyone,
    Can someone please help me. I need to make a program that uses a class or servlet that implements Serializable and then use the values of the variables in servlets.
    The first is using it to validate login. then changing the color of the background, header and footer of each servlet.
    the variables in the Serialized file are all Strings for color, username, password, header text and footer text.
    I tried using the applet tag to run the class in the servlet but it is not working.

    It's not working because you seem to be making random guesses what servlets, serialization and files are

  • How to upload a file into server using j2ee jsp and servlet with bean?

    How to upload a file into server using j2ee jsp and servlet with bean? Please give me the reference or url about how to do that. If related to struts is more suitable.
    Anyone help me please!

    u don't need j2ee and struts to do file uploading. An example is as such
    in JSP. u use the <input> file tag like
    <input type="file"....>You need a bean to capture the file contents like
    class FileUploadObj {
        private FormFile srcFile;
        private byte[] fileContent;
        // all the getter and setter methods
    }Then in the servlet, you process the file for uploading
        * The following loads the uploaded binary data into a byte Array.
        FileUploadObj form = new FileUploadObj();
        byte[] byteArr = null;
        if (form.signFile != null) {
            int filesize = form.srcFile.getFileSize();
            byteArr = new byte[filesize];
            ByteArrayInputStream bytein = new ByteArrayInputStream (form.srcFile.getFileData());
            bytein.read(byteArr);
            bytein.close();
            form.setFileContent(byteArr);
        // Write file content using Writer class into the destination file in the server.
        ...

  • Java6: How to compile java using JavaCompiler class

    Hi all,
    Using JavaCompiler, we can run the java program thru programmaticaly using run() method.
    Could anyone please tell me how to compile a java program using JavaCompailer class? Or calling run() itself will compile java file?
    Thanks
    Shagil

    import spoon.support.input.SpoonInputStream;
    import com.sun.tools.javac.code.Symbol.ClassSymbol;
    import com.sun.tools.javac.comp.Attr;
    import com.sun.tools.javac.comp.AttrContext;
    import com.sun.tools.javac.comp.Enter;
    import com.sun.tools.javac.comp.Env;
    import com.sun.tools.javac.comp.Todo;
    import com.sun.tools.javac.tree.Tree;
    import com.sun.tools.javac.tree.Tree.ClassDef;
    import com.sun.tools.javac.tree.Tree.TopLevel;
    import com.sun.tools.javac.util.Abort;
    import com.sun.tools.javac.util.Context;
    import com.sun.tools.javac.util.List;
    import com.sun.tools.javac.util.ListBuffer;
    import com.sun.tools.javac.util.Log;
    import com.sun.tools.javac.util.Name;
    * The Spoon compiler (uses javac).
    public class SpoonCompiler extends com.sun.tools.javac.main.JavaCompiler {
         Attr attr;
         Enter enter;
         boolean hasBeenUsed = false;
         Log log;
         Todo todo;
         public SpoonCompiler(Context arg0) {
              super(arg0);
              enter = Enter.instance(arg0);
              todo = Todo.instance(arg0);
              log = Log.instance(arg0);
              attr = Attr.instance(arg0);
              sourceOutput=true;
          * Main method: compile a list of files, return all compiled classes
          * @param filenames
          *            The names of all files to be compiled.
         @SuppressWarnings("unused")
         public List<Tree> parseAndAttribute(List<SpoonInputStream> filenames)
                   throws Throwable {
              // as a JavaCompiler can only be used once, throw an exception if
              // it has been used before.
              assert !hasBeenUsed : "attempt to reuse JavaCompiler";
              hasBeenUsed = true;
              long msec = System.currentTimeMillis();
              ListBuffer<ClassSymbol> classes = new ListBuffer<ClassSymbol>();
              try {
                   // parse all files
                   ListBuffer<Tree> trees = new ListBuffer<Tree>();
                   for (List<SpoonInputStream> l = filenames; l.nonEmpty(); l = l.tail) {
                        trees.append(parse(l.head.getFileName(),l.head.getStream()));
                   // enter symbols for all files
                   List<Tree> roots = trees.toList();
                   if (errorCount() == 0)
                        enter.main(roots);
                   // If generating source, remember the classes declared in
                   // the original compilation units listed on the command line.
                   List<ClassDef> rootClasses = null;
                   if (sourceOutput || stubOutput) {
                        ListBuffer<ClassDef> cdefs = new ListBuffer<ClassDef>();
                        for (List<Tree> l = roots; l.nonEmpty(); l = l.tail) {
                             for (List<Tree> defs = ((TopLevel) l.head).defs; defs
                                       .nonEmpty(); defs = defs.tail) {
                                  if (defs.head instanceof ClassDef)
                                       cdefs.append((ClassDef) defs.head);
                        rootClasses = cdefs.toList();
                   while (todo.nonEmpty()) {
                        Env<AttrContext> env = todo.next();
                        // save tree prior to rewriting
                        Tree untranslated = env.tree;
                        // attribution phase
                        if (verbose)
                             printVerbose("checking.attribution", env.enclClass.sym);
                        Name prev = log.useSource(env.enclClass.sym.sourcefile);
                        attr.attribClass(env.tree.pos, env.enclClass.sym);
                   return trees.toList();
              } catch (Abort ex) {
                   ex.printStackTrace();
              if (verbose)
                   printVerbose("total", Long.toString(System.currentTimeMillis()
                             - msec));
              int errCount = errorCount();
              if (errCount == 1)
                   printerCount("error", errCount);
              else
                   printerCount("error.plural", errCount);
              if (log.nwarnings == 1)
                   printerCount("warn", log.nwarnings);
              else
                   printerCount("warn.plural", log.nwarnings);
              return null;
         private void printerCount(String str, int val) {
              System.err.println(str + " - " + val);
         private void printVerbose(String arg0, Object obj) {
              System.out.println(arg0 + " - " + obj.toString());
    --- NEW FILE: CtBuilder.java ---
    package spoon.support.builder;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.util.Stack;
    import java.util.TreeSet;
    import spoon.query.Query;
    import spoon.query.TypeFilter;
    import spoon.reflect.CtFactory;
    import spoon.reflect.code.BinaryOperatorKind;
    import spoon.reflect.code.CtAbstractInvocation;
    import spoon.reflect.code.CtArrayAccess;
    import spoon.reflect.code.CtAssert;
    import spoon.reflect.code.CtAssignment;
    import spoon.reflect.code.CtBinaryOperator;
    [...1760 lines suppressed...]
                var.setSimpleName(tree.sym.name.toString());
                var.setModifiers(getModifiers(tree.mods.flags));
                enter(var, tree);
                scan(tree.init);
                exit(var, tree);
        @Override
        public void visitWhileLoop(WhileLoop tree) {
            CtWhile whileLoop = new CtWhileImpl();
            enter(whileLoop, tree);
            builderContext.loopParameter = 1;
            scan(tree.cond);
            builderContext.loopParameter = 0;
            scan(tree.body);
            exit(whileLoop, tree);
    }

  • Using JDO in a Servlet container/app server

    Hi,
    I was just wondering what Solarmetric recommends when using Kodo in a
    servlet container/app server. Specifically the following:
    1. Should each user session maintain a PersistenceManager or should the
    PM be created per request? I am thinking it might be expensive to
    maintain PMs across requests since you may have idle sessions and the
    PMs may hold database resources? But since PMs aren't pooled in Kodo is
    creating/closing a PM per request expensive or is it offset by Kodo's
    connection pooling?
    2. Is it advisable to store data to be displayed on a JSP by storing the
    JDO instances themselves or serializable proxies (simple data beans) of
    these objects in a user's session?
    3. If you can store the JDO instances in the session, do you need to
    make them transient instances using makeTransient() and call close() the
    PersistenceManager?
    Thanks in advance,
    Khamsouk

    These are all very good questions. There really is no one right answer to any
    of them, so I'll just try to educate you on the issues involved and you can
    make your own decision. Hopefully other people who are actually using Kodo
    in a servlet/JSP environment will chime in too.
    1. Should each user session maintain a PersistenceManager or should the
    PM be created per request? I am thinking it might be expensive to
    maintain PMs across requests since you may have idle sessions and the
    PMs may hold database resources? But since PMs aren't pooled in Kodo is
    creating/closing a PM per request expensive or is it offset by Kodo's
    connection pooling?As long as you are outside of a datastore transaction, a PM does not maintain
    any database resources. The only significant state it maintains is a soft
    cache of persistent objects that have already been instantiated. If you are
    using Kodo 2.3 RC1 and have no set the
    com.solarmetric.kodo.DefaultFetchThreshold property to -1, then some
    large collections you obtain from query results or relation traversals may be
    scrollable result sets on the back-end, in which case they obviously maintain
    some database resources.
    2. Is it advisable to store data to be displayed on a JSP by storing the
    JDO instances themselves or serializable proxies (simple data beans) of
    these objects in a user's session?
    3. If you can store the JDO instances in the session, do you need to
    make them transient instances using makeTransient() and call close() the
    PersistenceManager?I'll address these together. JDO fully supports serialization, and in fact
    I think you'll find it does so in exactly the way that you want. If you choose
    to store serialized persistent objects in the session, then during
    serialization the objects will transparently pull in all of their persistent
    state and relations, so the entire object graph is serialized. When you
    deserialize, the objects will no longer be attached to their persistence
    manager -- they will be transient.
    Another options is to store the object IDs in the session, and re-retrieve
    the persistent objects for each web request.
    One design pattern that can probably net very good performance is to maintain
    a global read-only persistence manager that you use to dereference these IDs.
    Of course, if you ever want to change an object, you'll have to re-fetch it
    in a new persistence manager, and evict it from the global manager's cache.
    I hope this helps.

  • Can I use XSQL pages & XSQL Servlet for oracle 7.3 ?

    Can I use XSQL pages & XSQL Servlet
    for oracle 7.3 or not?,if it is possible
    please give me reply.
    Thanks.
    Ramesh Nallapu.

    Can I use XSQL pages & XSQL Servlet
    for oracle 7.3 or not?,if it is possible
    please give me reply.
    Thanks.
    Ramesh Nallapu.
    null

  • Why we should use JSP instead of Servlet ?

    I want to know what are the advantages to use JSP over Servlet.

    hi
    Servlets are server exctension ( like CGI ) separate executable
    modules to serve any request efficiently.
    Servlets are pure java classes, u can use them the write an html code to browser.
    u have to compile the servlet before u use it.
    JSP page, is a text-base document , u can type html inside it , and u can use java as scripting language, so it is more easy to use jsp rather than servlet as each jsp page is translated into a servlet by JSP engine.
    Hope this will help
    Good luck
    Mohammed

  • Get Javascript values and use them in a servlet?

    Hey
    I have a HTML which has Javascript scripts which I have to get values from (a array to be exact) and pass them to a servlet so I can process the information in a certain way. I cant seem to find a way to do this properly as the servlet is server side and Javascript is client side. How can I implement this?
    Using a quick example example I have
    C:/index.html
    C:/js/script.js
    Index.html contains:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <script type="text/javascript" src="js/script.js">
    </script>
    </head>
    <body>
    a href="javascript:void(0);" id="add"><img src="images/menunew.png" alt="plus" border="0" />
    /a>
    </body>
    </html>
    Script.js contains:
    var Script = Class.create({
    a:4,
    b:5,
    add: function(){       
    return (this.a + this.b);
    (Ignore syntaxis errors as this is a quick example I wrote up just to see if you can give me a practical example on how to read it.)
    How can from a Java servlet access a and b from the script.js file (which contains a class named Script) and also access the function add which returns that value?
    Thank you for the help
    Edited by: 902756 on 16-dic-2011 0:18

    DrClap wrote:
    902756 wrote:
    1: Yes, it seems like the logically answer but Im not too up on AJAX and even less on mixing it up with servlets. Do you mind giving me a simple add (function) sample or something similar?You are looking at it the wrong way. What you actually want to do is to have the browser send a request (which somehow contains that Javascript data) to a URL which causes the servlet to receive the data. There's no "mixing it up" going on there. The client and the server are entirely separate.
    And since that request would be an HTTP request, it's just text. There's no concept in HTTP of transmitting objects, whether they be Javascript objects or Java objects. Anything you want to transmit has to be converted into text by the sender and converted back into objects by the receiver.
    So there's no such thing as "a simple add function". You're going to have to stop thinking in that way and start thinking of client-server systems in the way they actually are.The thing is I want to start simple to grab a simple concept....
    Im trying a AJAX route and I have the following:
    /index.html
    /js/Adding.js
    Index contains:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
         <title></title>
         <script type="text/javascript" src="js/Adding.js"></script>
    </head>
    <body>
    <select name="num1">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    </select>
    <select name="num2">
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    </select>
    <form method="get" name="adding">
    Do
    <span id="res"></span>
    </form>
    </body>
    </html>
    Adding.js contains
    var Adding = Class.create({
    x: null,
    y: null,
    add: function()
         var xmlHttp = new XMLHttpRequest();
         var value1 = document.getElementById("num1").value;
    var value2 = document.getElementById("num2").value;
         xmlHttp.open("GET", "index.html", false);
         xmlHttp.send(value1 + value2);
         var result = document.getElementById("res");
         result.innerHTML = xmlHttp.responseText;
    This shows 2 comboboxes full of numbers and link saying "Do" which calls the javascript function and adds the two numbers in the comboboxs and shows them on the screen without refreshing the page. This does not work and I would like this to work before I continue onto the bigger picture.

  • Use jdbc to connect servlet to oracle 8.1.6 database on win2k

    The code is below:
    package moreservlets;
    import java.sql.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    /** Simple servlet used to test JDBC connection. */
    public class TitleQueries extends HttpServlet {
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Connecting to Database";
    DriverManager.registerDriver (new
    oracle.jdbc.driver.OracleDriver());
    Connection conn = DriverManager.getConnection
    ("jdbc:oracle:thin:@pc840:1521:orcl", "scott", "tiger");
    Statement stmt = conn.createStatement();
    ResultSet rset = stmt.executeQuery
    ("select ename from emp");
    while (rset.next()) {
    String name = rset.getString("ename");
    out.println(ServletUtilities.headWithTitle(title) +
    "<body bgcolor=\"#FDF5E6\">\n" +
    "<h1 align=\"center\">" + name + "</h1>\n" +
    "</body></html>");
    CLASSPATH=.;C:\J2ee;C:\j2sdkee1.3.1\lib\cloudscape;C:\Program Files\Apache Tomcat 4.0\common\lib\servlet.jar;C:\Oracle\Ora81\orb\classes\yoj.jar;C:\Oracle\Ora81\orb\classes\share.zip
    My code cannot find the JDBC driver. Any suggestions?
    Thanks.
    I get the following errors:
    C:\J2ee\moreservlets>javac -d "C:\Program Files\Apache Tomcat 4.0\webapps\ROOT\
    EB-INF\classes" TitleQueries.java
    TitleQueries.java:19: package oracle.jdbc.driver does not exist
    oracle.jdbc.driver.OracleDriver());
    ^
    TitleQueries.java:31: cannot resolve symbol
    symbol : variable name
    location: class moreservlets.TitleQueries
    "<h1 align=\"center\">" + name + "</h1>\n" +
    ^
    2 errors

    I changed my classpath variable and my servlet
    compiles okay with the:
    "import oracle.jdbc.driver.*" statement.
    However, I still get the following error.
    Why can't it find the jdbc driver, since it finds the
    import statement?
    Apache Tomcat/4.0.3
    Error loading driver: java.lang.ClassNotFoundException: oracle.jdbc.driver.Oracl
    eDriver
    WebappClassLoader: Resource '/WEB-INF/classes/moreservlets/ServletUtilities.cl
    ass' was modified; Date is now: Tue Jul 02 09:57:26 CDT 2002 Was: Tue Jul 02 09:
    37:20 CDT 2002
    Error loading driver: java.lang.ClassNotFoundException: oracle.jdbc.driver.Oracl
    eDriver
    CLASSPATH=.;C:\J2ee;C:\j2sdkee1.3.1\lib\cloudscape\RmiJdbc;C:\Program Files\Apache Tomcat 4.0\common\lib\servlet.jar;C:\Oracle\Ora81\jdbc\lib\classes12.zip;C:\Oracle\Ora81\orb\classes\yoj.jar;C:\Program Files\Oracle\JDeveloper 3.2.3\jdbc\lib\oracle8.1.7\classes12.zip;C:\Oracle\Ora81\orb\classes\share.zip
    //code begins here
    package moreservlets;
    import java.sql.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import oracle.jdbc.driver.*;
    public class TitleQueries extends HttpServlet {
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection
    ("jdbc:oracle:thin:@pc840:1521:orcl", "scott", "tiger");
    Statement stmt = conn.createStatement();
    ResultSet rset = stmt.executeQuery
    ("select * from emp");
    out.println(ServletUtilities.headWithTitle(title) +
    "<body bgcolor=\"#FDF5E6\">");
    while (rset.next()) {
    out.println("<h1 align=\"center\">"
    + rset.getString("ename") + "</h1>\n");
    out.println("</body></html>");
    catch(ClassNotFoundException cnfe) {
    System.err.println("Error loading driver: " + cnfe);
    catch(SQLException sqle) {
    System.err.println("Error connecting: " + sqle);
    }

  • How to install eclipse and MyEclipse and use it for jsp-servlet-web service

    hi ,
    please help me to install eclipse 3.1 and How to integrate MyEclipse to do jsp-servlet programming and web services.
    please also help me to include application server like tomcat and axis and use that environment in MyEclipse ide.
    please help me.....

    At the time of installation , you can't change SID XE.
    After installation, you can add another service name
    Check following thread for more details
    Re: How to create service on Oracle 10g XE
    - Virag Sharma
    http://virag.sharma.googlepages.com
    http://viragsharma.blogspot.com

  • Using JavaCompiler Class for Debugging Info Only

    Hello everyone,
    Before I get started into the problem, I'll tell you what it is I'd like to do. I'm building an educational applet that'll allow students learning Java programming to write code on a Web page. My goal is to simulate a compiler environment without having it actually compile code (i.e. I want to tell them if there are any syntactic errors in their code). I've searched around the Web quite a bit for how to do this, and I thought I had something by using the JavaCompiler class. It works perfectly in a command-line version I've developed, but in the applet, when I invoke the compiler, the applet freezes. I've isolated it to the compiler call itself. Here is the init method (yes, I know it's a better idea to do the hard work and GUI building in a separate class; but right now, I'm just checking if it all works).
    @Override
    public void init()
    output = new JTextArea(5, 30);
    this.getContentPane().add(output);
    PrintWriter out = new PrintWriter(new TextAreaWriter(output));
    out.print("Hello!");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    String program = "class Test{" + " public static void main (String [] args){"
    + " System.out.printl (\"Hello, World\");"
    + " System.out.println (args.length);" + " }" + "}";
    Iterable<? extends JavaFileObject> fileObjects;
    fileObjects = getJavaSourceFromString(program);
    compiler.getTask(null, null, null, getOptions(), null, fileObjects).call();
    If I exclude the bold line of code, the applet runs. Otherwise it hangs and does nothing. I imagine this has something to do with the execution environment, permissions, etc. If you'd like to see more of the code I'm using, let me know.
    My questions are these: is there an easier way to go about this? Is there a way to invoke the compiler to get its output only, WITHOUT directly compiling a class? Is there a Magic Library designed for this that I've somehow overlooked? I know JDB only works on already-compiled class files; there's a tool called Checkstyle that seems to be more for formatting and subtle issues of style (hence, the name) than actual error checking (not to mention, it requires compiled code as well).
    Any thoughts would be greatly appreciated, all. :) Let me know if you need more info.

    >
    I checked the console after the freeze; it's handing me a NullPointerException for that line, which would be understandable except all of the arguments to call() can deal with null values. ( http://download.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html )
    From the javadoc for ToolProvider.getSystemJavaCompiler():
        Returns:
            the compiler provided with this platform or null if no compiler is providedSo it's definitely possible that compiler.getTask(null, null, null, getOptions(), null, fileObjects) returns null.
    Indeed that's what I would expect from a browser's JVM (which includes only a JRE, and not a JDK).
    Edited by: jduprez on Apr 29, 2011 2:56 PM
    Ah, ah, I missed your latest edit while I was reading the API Javadoc :o)
    Glad you found out!

  • Using JavaCompiler together with a Library

    Currently I am developing a tool in which Java Source Files are created based on a XSD file with help of a tool named Castor.
    After the generation of the files the files need to be compiled in order to be used by the program. This used to be done with a Library named XMLBean, however I do not wish to use this library anymore.
    As a alternative I ended up using the Java compiler that comes with the JDK in the tools.jar file. This resulted in a problem, which made me search for a other solution. This way I ended up working with the javax.tools.JavaCompiler. However compilation still failed due to the same problem.
    So what is this problem?
    Initially I tested my code generation logic and compile logic in a normal application. The Java code got generated fine using castor, the compilation using both methods I described also went fine.
    The problem occurs when I attempt to use the same logic in a web application I am developing to run on Tomcat. The Code generation goes fine (since the castor library is included in the project) however the compilation goes wrong and results in the following error:
    "package org.exolab.castor.xml does not exist"
    In other words, the compiler does not understand one of the imports of the source file (refering to a namespace in Castor, a library that was used to generate the file, and is included in the web project).
    Does anyone know why compilation fails in a web application but goes well in a normal application? Does anyone know how this problem can be solved, or does anyone know better component for compilation?
    Thanks a lot.
    This is the code I currently use for compilation:
    public void compileJavaSource(String[] sourceFilePaths)
              System.out.println("Begin Compiling of Source Files");
              JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); // Line 1.
              DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<JavaFileObject>();
              StandardJavaFileManager fileManager  = compiler.getStandardFileManager(diagnosticsCollector, null, null); // Line 3.
              Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjectsFromStrings(Arrays.asList(sourceFilePaths)); // Line 5
              CompilationTask task = compiler.getTask(null, fileManager, diagnosticsCollector, null, null, fileObjects); // Line 6
              Boolean result = task.call(); // Line 7
              List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticsCollector.getDiagnostics();
              for(int i=0; i < diagnostics.size(); i++){
                   Diagnostic<? extends JavaFileObject> d = diagnostics.get(i);
                   System.out.println(d.getMessage(null));
              if(result == true) {
                   System.out.println("Compilation has succeeded");
              else {
                   System.out.println("Compilation fails.");
              System.out.println("Done Compiling of Source Files");
         } Initially I used this:
    com.sun.tools.javac.Main.compile(sourceFilePaths);

    Cross posted. (Sorry about that)
    To avoid people spending time looking for an answer, here is the solution I found myself:
    First off all, for ANT to work, 2 libraries have to be imported in the web project.
    The libraries are: ant.jar and ant-launcher.jar
    Next to that, the library's Xerces (xercesImpl.jar) and xml-apis.jar (also included in ANT). There Library's are also needed to get Castor to work.
    To compile the code of my generated Java Classes I use the following ANT Build file code:
    <project default="build" basedir=".">
         <path id="classpath">
            <fileset dir="WEB-INF/lib" includes="**/*.jar"/>
        </path>
         <target name="build">
            <javac srcdir="src" destdir="WEB-INF/classes" debug="true" includes="**/*.java" classpathref="classpath"/>
         </target>
    </project>The file basically reads every .java file from my "src" folder. Which is the folder I choose to put my generated class files, and compiles them to the WEB-INF/classes folder. This is the folder were Tomcat stores all its classes.
    What went wrong with the compilation I attempted in the opening post, is that javac could not find the Castor Library, even after I added it in my classpath environment variable. Fortunately, with ANT I can define a classpath for the application, which is the WEB-INF/lib folder. This is the folder where Tomcat stores its Library's. Hence, javac can find the Castor Library from then on.
    Finally I call the ant task using the following Java Code:
    public void compileJavaSource(String buildFilePath)
              System.out.println("Start Compilation");
              File buildFile = new File(buildFilePath);
              Project p = new Project();
              p.setUserProperty("ant.file", buildFilePath);
              p.init();
              ProjectHelper helper = ProjectHelper.getProjectHelper();
              p.addReference("ant.projectHelper", helper);
              helper.parse(p, buildFile);
              p.executeTarget(p.getDefaultTarget());
              System.out.println("Compilation Finished");
         }This took care of the problem pretty nicely.

  • How to use Oracle Procedures with Servlet page

    Hi all
    I'm working on Servlet pages and I need to insert and select some records from Oracle database but it has to be done by calling some already written Procedures. I've never really used them before so I'm little lost. I know where the queries are used it'll be Procedures but what is the syntax for it.Can anyone put me in right direction please.
    Thanks

    Just google it. You will find lots of examples. Here are some :
    [http://java.sun.com/docs/books/tutorial/jdbc/basics/sql.html|http://java.sun.com/docs/books/tutorial/jdbc/basics/sql.html]
    [http://onjava.com/pub/a/onjava/2003/08/13/stored_procedures.html|http://onjava.com/pub/a/onjava/2003/08/13/stored_procedures.html]

  • How can I use URLConnection to use applet communication with servlet?

    I want to send a String to a servlet in applet.I now use URLConnection to communicat between applet and servlet.
    ====================the applet code below=========================
    import java.io.*;
    import java.applet.Applet;
    import java.awt.*;
    import java.net.*;
    //I have tested that in applet get data from servlet is OK!
    //Still I will change to test in applet post data to a servlet.
    public class TestDataStreamApplet extends Applet
    String response;
    String baseurl;
    double percentUsed;
    String total;
    public void init()
    try
    java.net.URL url = new java.net.URL(getDocumentBase(),"/servlet/dataStreamEcho");
    //String currenturl=new String("http://lib.nju.edu.cn");
    java.net.URLConnection con = url.openConnection();
    //URL currentPage=getCodeBase();
    // String protocol=currentPage.getProtocol();
    // String host=currentPage.getHost();
    //int port=currentPage.getPort();
    // String urlSuffix="/servlet/dataStreamEcho";
    // URL url=new URL(protocol,host,port,urlSuffix);
    // URLConnection con=url.openConnection();
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    ByteArrayOutputStream byteout = new ByteArrayOutputStream();
    PrintWriter out=new PrintWriter(byteout,true);
    String currenturl=new String("http://lib.nju.edu.cn");
    String var1=this.encodedValue(currenturl); //encode the data
    String data="currenturl="+var1;
    out.print(data);
    out.flush();
    con.setRequestProperty("Content-Length",String.valueOf(byteout.size()));
    con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    byteout.writeTo(con.getOutputStream());
    BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line;
    while((line=in.readLine())!=null)
         System.out.println(line);
    catch (Exception e)
    e.printStackTrace();
    private String encodedValue(String rawValue)
         return(URLEncoder.encode(rawValue));
    =========================The servlet code below=====================
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class DataStreamEcho extends HttpServlet
    {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          res.setContentType("text/plain");
          PrintWriter out = res.getWriter();
          Runtime rt = Runtime.getRuntime();
          out.println(rt.freeMemory());
          out.println(rt.totalMemory());
          response.setContentType("text/html; charset=GBK");     
          request.setCharacterEncoding("GBK");
          PrintWriter out = response.getWriter();
          HttpSession session=request.getSession();
          ServletContext application=this.getServletContext();
          String currenturl=(String)session.getAttribute("currenturl");
          out.print(currenturl);
    =============================================================
    I have done up,but I found the program don't run as I have thought.
    Can you help me to find where is wrong?Very thank!

    You are trying to pass the current URL to the servlet
    from the applet, right?
    Well, what I put was correct. Your servlet code is
    trying to read some information from session data.
    request.getInputStream() is not the IP address of
    anything...see
    http://java.sun.com/products/servlet/2.2/javadoc/javax
    servlet/ServletRequest.html#getInputStream()
    Please read
    http://www.j-nine.com/pubs/applet2servlet/Applet2Servle
    .htmlNo,you all don't understand I.
    I want to send an Object to the server from a applet on a client.not url only.I maybe want to send a JPEG file instead.
    All I want is how to communicate with a servlet from an applet,send message to servlet from client's applet.
    for example,Now I have a method get the desktop picture of my client .and I want to send it to a server with a servlet to done it.How can I write the applet and servlet program?
    Now my program is down,But can only do string,can't not done Object yet.Can anyone help me?
    =======================applet=============================
    public void init()
    try
    java.net.URL url = new java.net.URL(getDocumentBase(),"/servlet/dataStreamEcho");
    //String currenturl=new String("http://lib.nju.edu.cn");
    java.net.URLConnection con = url.openConnection();
    //URL currentPage=getCodeBase();
    // String protocol=currentPage.getProtocol();
    // String host=currentPage.getHost();
    //int port=currentPage.getPort();
    // String urlSuffix="/servlet/dataStreamEcho";
    // URL url=new URL(protocol,host,port,urlSuffix);
    // URLConnection con=url.openConnection();
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    ByteArrayOutputStream byteout = new ByteArrayOutputStream();
    PrintWriter out=new PrintWriter(byteout,true);
    String currenturl=new String("http://lib.nju.edu.cn");
    String var1=this.encodedValue(currenturl); //encode the data
    String data="currenturl="+var1;
    out.print(data);
    out.flush();
    con.setRequestProperty("Content-Length",String.valueOf(byteout.size()));
    con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    byteout.writeTo(con.getOutputStream());
    con.connect();
    BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line;
    while((line=in.readLine())!=null)
         System.out.println(line);
    catch (Exception e)
    e.printStackTrace();
    =======================servlet=============================
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
         response.setContentType("text/html; charset=GBK");
    //request.setCharacterEncoding("GBK");
    PrintWriter out = response.getWriter();
    HttpSession session=request.getSession();
    ServletContext application=this.getServletContext();
    //String currenturl=(String)session.getAttribute("currenturl");
    String currenturl=(String)request.getParameter("currenturl");
    out.print(currenturl);
    File fileName=new File("c:\\noname.txt");
    fileName.createNewFile();
    FileOutputStream f=new FileOutputStream(fileName); //I just write the String data get from
    //applet to a file for a test.
    byte[] b=currenturl.getBytes();
    f.write(b);
    f.close();
    }

  • Why do we use jap instead of servlet

    why do we use jap instead of servlet

    JSPs are compiled into servlets. Use them to more conveniently generate presentation code such as HTML. With a JSP, you can code the HTML directly, no need for lots of "out.println" statements. JSPs can be written by non-programmers who don't know Java using the built-in JSP features plus custom tags libraries.

Maybe you are looking for

  • Quicktime will not play .mov files since Lion installation

    When using Quicktime 10.6, I am receiving the error message "...file could not be opened. A required codec isn't available." when attempting to open .mov files.  Prior to installing OS X Lion, there were no issues with playing .mov files.

  • Unable to retrive the back files on comp...

    Hi all, i am taking the back up of all the files through the desktop software and it is getting save in one folder named Blackberry. but i am not able to retrieve the files. when i m opening the files ,something 2 is coming, not the readable material

  • Does Intune Company Portal in mobile devices notify app updates?

    Hi, Does Intune Company Portal in mobile devices notify app updates? And if we retire the devices from company portal, the apps we just previously installed from the company portal app will be uninstalled automatically?

  • Cant install oracle 8i in windows 2003 server

    hi, I am a newbie in Oracle.While Im trying to install Oracle 8i in Windows 2003 server , setup is not running.It didn't show anything.When trying to run from auto run, after splash screen nothing came.I formatted hard disk,changed two more hard disk

  • Importing Keyboard Shortcuts

    Is there a way to import keyboard settings from cs6 into cc?