Add jar for in-memory compilation by Eclipse Compiler

Hi,
I have a question regarding loading a jar file by the compiler to dynamically compile with a source file. I hope someone can probably offer me an idea on what has been missing or wrong with the source codes I have written for my application.
I am using Eclipse compiler to dynamically compile a class. In the class, I want it to make a reference to a jar file for compilation dynamically.
Here is the source of a test class I wrote:
import javax.servlet.http.HttpServlet;
class MyServlet extends HttpServlet {
}The import statement refers to the class javax.servlet.http.HttpServlet from the jar file C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\lib\\servlet-api.jar placed in the local file system.
In the method called compileClass (shown below), I used the path of the jar file to add to the option -classpath as suggested in another thread (http://forums.sun.com/thread.jspa?threadID=5306520&start=0&tstart=0).
private static CompileClassResult compileClass(Writer out, String className, String classSource) {
          try {
               JavaCompiler javac = new EclipseCompiler();
               StandardJavaFileManager sjfm = javac.getStandardFileManager(null, null, null);
               SpecialClassLoader scl = new SpecialClassLoader();
               SpecialJavaFileManager fileManager = new SpecialJavaFileManager(sjfm, scl);
               List<String> options = new ArrayList<String>();
               options.addAll(Arrays.asList("-classpath", "C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\lib\\servlet-api.jar"));
               List<MemorySource> compilationUnits = Arrays.asList(new MemorySource(className, classSource));
               DiagnosticListener<JavaFileObject> diagnosticListener = null;
               Iterable<String> classes = null;
               if (out == null) {
                    out = new PrintWriter(System.err);
               JavaCompiler.CompilationTask compile = javac.getTask(out, fileManager, diagnosticListener, options, classes, compilationUnits);
               boolean res = compile.call();
               if (res) {
                    //Need to modify the api to return an array of two elements - one classes and other bytecodes for all classes in the same class file.
                    return CompileClassResult.newInstance(scl.findClasses(), scl.findByteCodes());
          } catch (Exception e) {
               e.printStackTrace();               
          return null;
     }I also extended the class ForwardingJavaFileManager as suggested in the thread mentioned above and have it delegated to the StandardJavaFileManager sent to the compiler mentioned in the method compileClass above. The extended class (called SpecialJavaFileManager) is as follows:
public class SpecialJavaFileManager extends ForwardingJavaFileManager<StandardJavaFileManager> {
     private SpecialClassLoader xcl;
     public SpecialJavaFileManager(StandardJavaFileManager sjfm, SpecialClassLoader xcl) {
          super(sjfm);
          System.out.println("SpecialJavaFileManager");
          this.xcl = xcl;
     public JavaFileObject getJavaFileForOutput(Location location, String name, JavaFileObject.Kind kind, FileObject sibling) throws IOException {
          System.out.println("getJavaFileForOutput");
          MemoryByteCode mbc = new MemoryByteCode(name);
          xcl.addClass(name, mbc);
          return mbc;
     public Iterable<JavaFileObject> list(JavaFileManager.Location loc, String pkg, Set kinds, boolean recurse) throws IOException {
          System.out.println("list ");
        List<JavaFileObject> result = new ArrayList<JavaFileObject>();
        for (JavaFileObject f : super.list(loc, pkg, kinds, recurse)) {
             System.out.println(f);
            result.add(f);
          return result;
}I run the application and the result shows that it didn't load the jar file into the memory as expected. From the output (below) I got, it doesn't seem to invoke the method list(...) in the class SpecialJavaFileManager.
SpecialJavaFileManager
1. ERROR in \MyServlet.java (at line 1)
     import javax.servlet.http.*;
            ^^^^^^^^^^^^^
The import javax.servlet cannot be resolved
2. ERROR in \MyServlet.java (at line 3)
     class MyServlet extends HttpServlet {
                             ^^^^^^^^^^^
HttpServlet cannot be resolved to a typeDoes somebody know what I probably have missed or done wrong in the codes?
Thanks.
Jonathan

Hi jschell,
I read the thread referred to by the link you gave and tried to add the path using the setLocation method:
JavaCompiler javac = new EclipseCompiler();
StandardJavaFileManager sjfm = javac.getStandardFileManager(null, null, null);
SpecialClassLoader scl = new SpecialClassLoader();
List<File> path = Arrays.asList(new File("C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\lib\\servlet-api.jar"));
sjfm.setLocation(StandardLocation.CLASS_PATH, path);
SpecialJavaFileManager fileManager = new SpecialJavaFileManager(sjfm, scl);After I run the file with the change, I still didn't get the compiler to read the jar the file.
Anyone knows how to solve this issue?
Thank you.
Jonathan

Similar Messages

  • Downloading JAR for temporary in-memory use or saved to local system?

    Hi all,
    I would like to be able to download and create a .jar file in memory, without writing it to disk, as an "option". My app should allow the user to reference an http://file.jar that gets "created" in memory on the client for temporary use, or they can optionally specify to download it and save it as a .jar file. I can't seem to find much info on either.
    For the first case, basically, each time the app runs it should get the .jar file from the location specified, but without actually creating it on disk. Is it possible to download the binary of a .jar file from a web server and create it in memory so that it can be used? Or does it have to be stored on the local file system? If so, then I suppose I could use a "temporary" on disk .jar file, then delete it.
    For the latter, how is a .jar file downloaded and saved to the local system?
    Thanks.

    I don't fully understand your question, but I think
    you want to use JarInputStream.
    -Ron

  • Which jar to use in order to write add-ons for IE

    Hi,
    I don't know whether I am asking the correct question but I want to know can I use any jar in order to create add-ons for Internet explorer and, if any, which one?
    thanks

    Hi Akshay,
    I have used the FM "ISU_DB_EANL_UPDATE" in my project.
    CONSTANTS lc_modify  TYPE c  VALUE 'U'.
      CALL FUNCTION 'ISU_DB_EANL_UPDATE'
        EXPORTING
          x_eanl          = xw_eanl
          x_eanl_old      = xw_eanl
          x_upd_mode      = lc_modify
        TABLES
          xt_eanlh_update = xt_eanlh_mod
          xt_eanlh_old    = xt_eanlh_old.
    where eanl is the entry in EANL table.
    OLD_EANLH contains the old entry line item of the Rate Category table and NEW_EANLH contains the new line item to be added. This is the crude way of doing this. But I didnt find any other FM useful.
    But this works.
    Hope this also resolves your query.
    Regards,
    Manish
    Edited by: Manish  Bisht on Jun 29, 2009 3:43 PM

  • Compile Add-On for SBO 2005 and 2007

    Hi All,
    I am looking for a document that I downloaded a while ago on steps how to compile add-ons for SBO version 2005 and 2007 on the same machine. I don't want to run both versions (I can be running either) just want to be able to compile add-ons on both version 2005 and version 2007 on my local machine. I also don't want to use virtual machine or something like that.
    Thanks for the help,
    Adele

    Hi Adele,
    usually it is enough to change the .dll reference in your code and recompile it.
    you can also decide which diapi connection you use
    when creating the company object
    //The object OComp is defined as company object of the selected version
    Dim OComp As SAPbobsCOM.Company
    Set OComp = New SAPbobsCOM.Company
    or
    //The object OComp is defined as company object of version 2005
    Dim OComp As SAPbobsCOM.Company
    Set OComp = CreateObject("SAPbobsCOM.Company.6.8")
    // for 2007 it should be
    Dim OComp As SAPbobsCOM.Company
    Set OComp = CreateObject("SAPbobsCOM.Company.8")

  • Include jars for compiling and exclude jars for war

    Hello,
    In the context of using ant to create a war, I have some doubts:
    Actually to compile my web application codes, I put in classpath the following two jars as:
           <pathelement location="${lib.dir}/${servlet-api.jar}"/>
           <pathelement location="${lib.dir}/${jsp-api.jar}"/>   without these two jars I would get compiling errors.
    To create a war, I have to exclude these two jars:
       <lib dir="${webapp.dir}/WEB-INF/lib">
                 <exclude name="servlet-api.jar"/>   
                 <exclude name="jsp-api.jar"/> 
               </lib>If I kept these two jars in the war, JBOSS application server would complain of duplicate classes.
    My approach works. But my question is:
    Is it the best practice to include jars for compiling codes and exclude jars if the application servers already have them?
    Best regards,
    Pengyou

    Yes. That is the best practice.
    In fact its the only practice to do it properly.
    You are compiling against Interface only. Your code will work as long as that interface is implemented by the server, even if it does different things under the hood. This is what lets your web application work on whatever server you deploy it on - Jboss, Tomcat, Weblogic - it shouldn't matter as they all implement the same basic interfaces.
    You could also expand that list to include common APIs which you know are available on your server if you don't want to bundle them with every web application.
    JSTL jars are one potential example.

  • Can you add a SD card for extra memory?

    My question is super simple.
    I use AT&T, if that makes a difference. I've heard mixed answers from people, so I'm looking for someone who really knows what they are talking about.

    No, you cannot use an SD card for extra memory. Access the iPhone users manual and you will see there is no SD slot.

  • Add jar files and use those classes at the runtime

    Hi All,
    I need to add some jar files at the runtime depends on which the user selects where the jar file is located and i need to import those classes in other class for some functionalities . I could add jar files by using the URLClassLoader and Class.forName("myjar.myclassname") is also succeeded and i have no clue how to use those classes with in the jar file as i couldn't import those classes also in the source because the jar files are being added at the runtime(This leads to class not found exception at the compile time).
    I had found a complicated way of using those classes after being added at the run time as below.
       Class clazz = Class.forName(myClass);
                final Method method = clazz.getDeclaredMethod(requiredMethod, new Class[]{URL.class});
                final Object returned = method.invoke(clazz.newInstance(), new Object[]{request}); but, its really pain to use in this way in all the places.
    Does any of you have simpler suggestions on how to achieve this?
    Thanks,
    Venky.

    Thanks jschell. Yes, you are right. I had found that using reflection API is the only way to load classes at the run time. But according to our application using reflection makes the application little complex, so while start of the application or during other modifications, i am overwriting my jar file to the latest one using FileChannel class as below
          FileChannel ic = new FileInputStream("new.jar").getChannel();
          FileChannel oc = new FileOutputStream("old.jar").getChannel();
          ic.transferTo(0, ic.size(), oc);
          ic.close();
          oc.close();After this code is executed, our application totally uses the new jar file.It is little fast than using reflection. Is this a good idea?

  • Including External JARs for Java Application in OC4J

    Hi Experts,
    Here is my requirement.
    I have developed my Java application using Tomcat Server & Eclipse. In my application I have used some External JARs & imported the classes in my JSP.
    Now that I'm using OC4J Server instead of Tomcat I'v no clue as to where I have copy these External JARs for my application to work.
    I have installed OBIEE-Client which includes OC4J server. The path where I have placed my application is as below
    *"C:\OracleBI\oc4j_bi\j2ee\home\default-web-app"*
    If I run my application the server does not import the classes in the JSP which we include using Import statement using JSP tags (*ex* - <%@ page import = "org.apache.commons.fileupload.*"%>).
    This is the location which I found, where I need to put my Java-J2EE application. This OC4J_BI comes with OBIEE.
    Kindly help me out on where to place these External JARs exact location in OC4J.
    Also let me know if I have to alter any configuration/xml file (if so pls specify the file name & its location).
    Thanks in advance,
    Venky

    You can either include the external libraries in the application, by placing them into WEB-INF/lib, or you can import them into the server as "shared libraries", normally you'd use the "enterprise manager" application to do this. Having loaded a shared library you then add it to the classpath when you're deploying the application.

  • Error while Installing the Java Add-In for an Existing ABAP System

    Hi all,
    I need help, i am Installing the Java Add-In for an Existing ABAP System
    SAPInst stops on the first installation step: "Central Services Instance (SCS) Java Add-In", the step is "Install common system files" on the following sub-steps:
    These are the last few lines on the sapinst.log.
    INFO 2009-05-21 12:35:12
    Execute step createAccounts of component |NW_Addin_SCS|ind|ind|ind|ind|0|0|NW_Users_Create_Do|ind|ind|ind|ind|3|0.
    INFO 2009-05-21 12:35:18
    Execute step setUserEnvironment of component |NW_Addin_SCS|ind|ind|ind|ind|0|0|NW_Users_Create_Do|ind|ind|ind|ind|3|0.
    INFO 2009-05-21 12:35:19
    Execute step InstallJDBCDriver of component |NW_Addin_SCS|ind|ind|ind|ind|0|0|NW_JDBCDriver_DB4|ind|ind|ind|ind|4|0.
    INFO 2009-05-21 12:35:19
    Creating directory V:\sapmnt\BIQ\jdbc.
    INFO 2009-05-21 12:35:19
    Creating directory V:\sapmnt\BIQ\jdbc\tbx.
    INFO 2009-05-21 12:35:21
    Copied file 'V:/QIBM/ProdData/HTTP/Public/jt400/lib/jt400.jar' to 'V:/sapmnt/BIQ/jdbc/tbx/jt400.jar'.
    INFO 2009-05-21 12:35:22
    Execute step updateNtPatchDlls of component |NW_Addin_SCS|ind|ind|ind|ind|0|0|NW_System|ind|ind|ind|ind|5|0.
    INFO 2009-05-21 12:35:23
    Execute step sCreateSystemOS4 of component |NW_Addin_SCS|ind|ind|ind|ind|0|0|NW_System|ind|ind|ind|ind|5|0.
    ERROR 2009-05-21 12:35:42
    MOS-02001  Call of command "CRTR3SYS SID(BIQ) GLOBALHOST(*LOCAL)" failed. Exception is "CPF0006".
    ERROR 2009-05-21 12:35:42
    MOS-02001  Call of command "CRTR3SYS SID(BIQ) GLOBALHOST(*LOCAL)" failed. Exception is "CPF0006".
    ERROR 2009-05-21 12:35:42
    FCO-00011  The step sCreateSystemOS4 with step key |NW_Addin_SCS|ind|ind|ind|ind|0|0|NW_System|ind|ind|ind|ind|5|0|sCreateSystemOS4 was executed with status ERROR .
    Thanks in advance for any help.
    Kiran Chebrolu

    Hi,
    Hope this note would solve your issue, please read carefully and validate with your issue
    Note 1032019 - Java Add-In: Error when you create the SCS instance
    below notes give your suffice information.
    Note 883948 - NW 7.00(2004s): Inst.Add.Java Usage Types/Software Units
    Note 1268493 - NW 7.01/BS 7: Inst.Add.Java Usage Types/Software Units
    Note 1025789 - RUNR3CMD generates CPF0006
    regards
    nag

  • Where is the jar for me to import?

    import javax.servlet.http.*; <--- showing error
    import kr.pe.okjsp.util.*;
    import com.oreilly.servlet.MultipartRequest;
    public class WriteServlet extends HttpServlet {  <--- showing error
    long long time ago, there was
    server.jar
    but in java 5.0, where is the jar for me to import?
    It would be really appreciated. Do I have to download j2ee for this?
    My memory is fuzzy...
    Thanks -

    Yes, it is part of EE not SE. Or you can get it/them from your application server's lib dir (which may or may not be a better choice).

  • How to add .jar files in my project

    Hi all,
    i am designing a application where i want to translate some words of my web page to different language
    say, i want "search" word to be translated to french language
    i have got some .jar files google-api-translate-java-0.4.jar to do this work...
    can anyone tell in which folder to put .jar files ,so that it works in my project..
    i am using Eclipse SDK 3.3
    Thanks

    how to add .jar files in my project In your eclipse goto,
    Project --> Properties --> Java Buil Path --> Add External Jar
    By that u can select your JAR and click OK..........

  • WAS JAVA add-in for ABAP install error on AIX Oracle

    Hi All
    I am currently trying to install a 640 WAS JAVA add-in for ABAP on AIX 5.2 running oracle 9.2.0.6 for SAP 4.7 SR1.
    I have successfully installed the ABAP stack, however, when I try to install the JAVA add-in, I get an error on step "Start SAP J2EE engine". The error is
    INFO       2006-07-07 04:29:04
               CJSlibModule::writeInfo_impl()
    Output of /usr/sap/BWP/DVEBMGS00/j2ee/os_libs/jcmon 'pf=/sapmnt/BWP/profile/BWP_DVEBMGS00_rhubwp01' is written to the logfile jcmon.log.
    INFO       2006-07-07 04:29:04
               CJSlibModule::writeInfo_impl()
    Execution of the command "/usr/sap/BWP/DVEBMGS00/j2ee/os_libs/jcmon 'pf=/sapmnt/BWP/profile/BWP_DVEBMGS00_rhubwp01'" finished with return code 0. Output: snipped
    INFO       2006-07-07 04:29:04
               CJSlibModule::writeInfo_impl()
    J2EE Engine DVEBMGS00 of SAP system BWP did not come up after 827 seconds: waiting for another 20 seconds.
    ERROR      2006-07-07 04:29:04
               CJSlibModule::writeError_impl()
    CJS-20058  J2EE Engine DVEBMGS00 of SAP system BWP did not reach state "Starting Applications" after 827 seconds: giving up.
    I am new to JAVA, and I found some OSS notes (668606, 545422, and 943498) that might help, but they may as well be written in German for all I can make out what the notes are trying to say.
    Any help would be appreciated.
    Thanks
    Sam

    Oooops, I forgot to paste the error messages
    dev_jcmon
    [Thr  1] *** ERROR => Can't attach to administration shared memory (rc=3) [jcmonxx_mt.c 219]
    dev_jcontrol
    [Thr  1] *** ERROR => invalid return code of process [bootstrap] (exitcode=-1) [jstartxx_mt. 1433]
    [Thr  1] JControlExecuteBootstrap: error executing bootstrap node [bootstrap] (rc=-1)
    [Thr  1] JControlCloseProgram: started (exitcode = -1)
    [Thr  1] JControlCloseProgram: good bye... (exitcode=-1)
    dev_bootstrap
    Signal 6 encountered.
    => 64 bit R/3 Kernel
    => 64 bit AIX Kernel
    => Heap limit      = unlimited
    => Stack limit     = 4294967296
    => Core limit      = 1073741312
    => File size limit = 4294965248
    => Heap address  = 0x0x1111d9fe0
    => Stack address = 0x1111b7a80
    => Stack low     =  0x1111b5180
    => Stack high    =  0xffffffffffff2b0
    => Stack Trace:
            pthread_kill() at 0x900000000382c08
            praise() at 0x90000000038261c
            raise() at 0x900000000045890
            abort() at 0x900000000052dc8
            GetPropertiesMD() at 0x900000010639774
            ciCreateJVM() at 0x9000000106d19f4
            JNI_CreateJavaVM() at 0x90000001066529c
            Unknown at 0x90000001062a810
            JHVM_LoadJavaVM() at 0x1000918d4
            JLaunchIStartFunc() at 0x10008bb14
            pthreadbody() at 0x9000000003734ec
    !!! Invalid stack address encountered: 0x0
    !!! Stack corrupted.
    dev_disp
    J2EE server info
      start = TRUE
      state = STARTED
      pid = 5926962
      argv[0] = /usr/sap/BWD/DVEBMGS84/j2ee/os_libs/jcontrol
      argv[1] = jcontrol
      argv[2] = pf=/usr/sap/BWD/SYS/profile/BWD_DVEBMGS84_mantas
      argv[3] = -DSAPSTART=1
      argv[4] = -DCONNECT_PORT=60977
      argv[5] = -DLISTEN_PORT=60978
      argv[6] = -DSAPSYSTEM=84
      argv[7] = -DSAPSYSTEMNAME=BWD
      argv[8] = -DSAPMYNAME=mantas_BWD_84
      argv[9] = -DSAPPROFILE=/usr/sap/BWD/SYS/profile/BWD_DVEBMGS84_mantas
      argv[10] = -DFRFC_FALLBACK=ON
      argv[11] = -DFRFC_FALLBACK_HOST=localhost
      start_lazy = 0
      start_control = SAP J2EE startup framework
    DpJ2eeStart: j2ee state = STARTED
    DpJ2eeLogin: j2ee state = CONNECTED
    DpJ2eeMsgProcess: j2ee state = CONNECTED (NIECONN_BROKEN)
    DpIJ2eeShutdown: send SIGINT to SAP J2EE startup framework (pid=5926962)
    DpIJ2eeShutdown: j2ee state = SHUTDOWN
    DpEnvCheckJ2ee: switch off j2ee start flag
    DpHdlDeadWp: restart wp (pid=5791744) automatically
    std_bootstrap.out
    JVMCI200 - ERROR: User register saving is not enabled, Garbage Collection could be incorrect.
    JVMCI200 - ERROR: because of this the JVM library is explicitly aborting the process
    JVMCI200 - ERROR: You must either rebuild the executable using "-bM:UR"
    JVMCI200 - ERROR: or run with "export LDR_CNTRL=U
    Thanks
    Sam

  • How can I add jar files into the namespace in code?

    My friends:
    I need to add jar files into my namespace dynamicly in my code.But the jar files might be repeated, I am not sure.so, i wonder how can I add them into my namespace, ignoring the repeated files?
    This is my code:
    URL[] urlArrayA = new URL[5];
    urlArray[0] = sample1;
    urlArray[1] = sample2;
    URL[] urlArrayB = new URL[5];
    urlArrayB[0] = sample3;
    urlArrayB[1] = sample4;
    URLClassLoader urlClassLoaderA = URLClassLoader.newInstance(urlArrayA);
    URLClassLoader urlClassLoaderB = URLClassLoader.newInstance(urlArrayB);
    how can i visit classes in urlClassLoaderA from classes in urlClassLoaderB?

    could anyone please answer the question for me ? thank you...

  • How to add JAR files in JDeveloper 10.1.2

    Hi,
    We have developed a J2EE project using JDeveloper. Now, i have to add Upload CV functionality to the application. I want to use the classes provided by org.apache.commons.fileupload which is there in the commons-fileupload-1.2.2.jar file provided by them. My problem is i am unable to add this JAR file to my project. When i try to add this JAR file using the Project Properties of my project. Its asking me to browse the path of the J2SE Executable or EDIT the Class Path or Source Path or Doc Path. There is not option to add JAR files. If the JAR file is not added, its showing the errors:
    imported class 'org.apache.commons.fileupload.disk.DiskFileItemFactory' not found exception..
    Please let me know how i could associate JAR files to my project so that the upload files functionality is implemented. Will be desperately waiting for any assistance....
    Regards,
    Najmuddin

    Thanks John, that was helpful. After i added the JAR file, its showing me the following error:
    Error(479,16): class FileUploadException not found in class htdocs.recruitment._regMain.CommonsFileUploadServlet
    Is there any specific location where i need to keep my JAR file or i can browse it from anywhere?
    Regards,
    Najmuddin

  • Is there a way to add jar file in my program

    sorry to botter you, but i really need help for this, i really dont know how to do it. i have my prog taht i want to put in jar file, that cause no problem, but my program isnt fully functionnal because he use a jar file (my driver to acces my database) taht i had mount in forte. but i cant put in in my class file, because i want my jar to be able to run everuwhere on any computer taht have the jre installed. so in resume, i want to add jar file in my program... can i have to add it in my jar file, or decomrpesse it and put the folder like org.postgre.mfileshere... ????? i really dont know
    thx to help me

    ok If I understood, you need to add a third part Jar
    file to your own Jar File App so...
    Yes, you can decompress it in a directory tree and
    merge it with your application (i.e) if you have a jar
    file like this:
    br.com.yourApp.util
    and a third part jar file like this:
    br.com.thirdPart.tools
    br.com.thirdPart.util
    you will have these directory trees:
    br/com/yourApp/util/
    br/com/thirdPart/tools/
    br/com/thirdPart/util/
    then you can marge it in a unique tree:
    br/com/yourApp/util/
    ....../thirdPart/tools/
    ................/util/
    then you can make a new jar file with it...
    .....OR YOU CAN ADD THE PATH where your JDBCDrive is
    placed to the classpath of your application just using
    the -classpath option execution string of you
    application, like this:
    C:\jreHome\bin\java.exe -jar -classpath
    .;C:\someDir\thirdPart.jar yourApp.jar
    That's the better way to do it and then everything
    will work! :-)
    []'s Igor
    Brazil * * * * *k thx, ill give a try, and give you result later. but can you answer me another question, why when i double click on any jar file executable, sometimes javawa start but do nothing, sometimes they start and said no main class find, sometimes dotn start anymore, and sometimes work perfectly...?? is the jdk taht is not good? i use the last one
    or problem with my instalation, or the prog i try to run?
    thx

Maybe you are looking for