Get list of classes present in an applet's Jar file?

I have an applet for drawing diagrams, which is bundled in a jarfile together with classes for each type of element in the drawing (e.g. a class for drawing 2-input NAND gates, a class for J-K flip-flops, and so on). When I add a new type of drawing element I have to modify the applet to add the new class to the applet's "Insert" menu to allow the element to be inserted. What I want to do is to search the jarfile containing the applet for any classes derived from DrawingElement and add them automatically to the Insert menu when the applet is inited. I presume this would require using getClass().getClassLoader() to get the class loader that read the JAR file, but from there it would seem I need to know the name of the resource to load. Is there a way of browsing the list of resources in the JAR file?

AndrewThompson64 wrote:
That 'modify the applet' is not strictly necessary. The list of menu items and classes might be passed to the applet as applet parameters, or as a property file or XML (or whatever) that defines the available elements.I could do this -- I'm just trying to avoid getting the list out of step with the contents (or if you prefer, I'm just being lazy!).
Is there a way of browsing the list of resources in the JAR file?Yes and no. You might try this general strategy (untested).
1) Gain an URL to a resource in the Jar in which the plug-ins exist.
2) Parse that URL for everything before the '!' symbol to get an URL for the Jar itself.
3) Get an InputStream from the Jar via URL.openStream().
4) Get a ZipInputStream by wrapping the InputStream.
5) Iterate the ZipEntry(s) to identify classes in the correct package, and store them in a collection of some type.
6) Iterate the collection and check each one for extending DrawingElement, using reflection.
I am guessing step 6 will require the applet to be trusted.Sounds plausible, and I'll give it a whirl. However, I hadn't thought about the "trusted" bit of this; maybe I can just create new instances and cast to DrawingElement, ignoring any that throw exceptions. I'll have to give it a go and see what happens.
BTW - once you have the right classes, how do you get the screen name of them? Is the name defined in one of the attributes of a DrawingElement? What prevents name clashes?Plan A: I have a getIdentification() method that returns a string identifying the element, but I have to keep this unique the hard way (by hand).
Plan B: use the class name with some prettification (e.g. have a class _2_input_NAND_gate which gets displayed as "2 input NAND gate") so that the compiler does the work of keeping it unique. Not sure I like this, though.
Many thanks for your help.

Similar Messages

  • How to get list of drives present in local file system?

    Hi all,
    I want to show all drives and their contents using JTree.
    Does anybody know how to get list of drives present in local file system?

    Thank you!
    I have new question.
    I want to disply size and file type. Can you give ur suggestion in order to do that?
    I want to provide following using JTree
    + root <Dir> 50KB
    - file1 <txt> 10KB
    - file2 <bmp> 20KB
    + root2 <Dir> 200KB
    -file1 <jpeg> 50KB
    Is this possible?
    Plz reply..........
    bye

  • Getting list of classes?

    Hello all, I was just wondering if there is any way to get a list of all the known classes in a certain package? I know I can get a list of the packages themselves, but not sure about how to go about getting the actual classes.
    Thanks for the help!
    -Nick

    If you only want to get a classes list from a jar package,read the api specof java.uitil.jar.
    java.uitil.jar privides classes for reading and writing the jar file.
    So I think it can satisify your requirement.

  • How to get list of classes in classpath?

    Hi.
    I need to get list of classes in CLASSPATH which implements the some interface.
    How i can get list of classnames from CLASSPATH ?
    TIA

    What you want to do is not that trivial.Its not trivial, but its not really all that hard either.
    I this thing quite a bit in JUnit tests (e.g, all SomeInterface implementations are expected to be serializable - lets hunt them out and check we can actually serialize them. Turned out to do that I needed a generic yet fairly intellegent object creator / populator: That was significantly less trivial than the other task).

  • Problem loading Applets from Jar files on 64 bit machine

    I am developing an applet (extends Applet but uses swing components) using JDK 1.6 (Though these problems still happen in JDK 1.7) and I am unable to get the applet to load on a 64 bit machine in most cases. The web server(s) are running on localhost and I am connecting on the same machine using a local network ip address (such as 192.168.*.*)
    Below are all of my test results. Can someone provide a suggestion for repairing this? The Windows Server machine is a clients computer I access to it via remote desktop but I can't do much with it though I do have administrator rights. The Windows 7 machine is my development platform so I have been able to do extensive testing on it.
    This problem is presenting in the following environments when trying to load an applet from JAR files in a HTML document using the Applet or Object tag.
    Windows Server 2008 (Intel Chipset)
    Tested Browsers:
    Internet Explorer 9 (32 bit) - Shows it is blocked by default then simply shows an x when loaded from a web page, same result when loading from local drive.
    Windows 7 Home Premium (AMD Chipset)
    Tested Browsers:
    Firefox 6.0.1 (32 bit) - Java logo shows with spinner, after a few minutes there is finally an error that a class in the jar was not found
    Internet Explorer 9 (32 bit) - Java logo shows with spinner, after a few minutes there is finally an error that a class in the jar was not found
    Internet Explorer 9 (64 bit) - Java logo shows with spinner and most of the windows desktop manager freezes, keyboard is the only thing that responds so you can alt-tab to another app to regain control of the desktop.
    Chrome (32 bit) - Java logo shows with spinner, after a few minutes there is finally an error that a class in the jar was not found
    The only way I have been able to get a Java applet to run on a 64 bit machine are the following ways.
    Firefox 9 nightly (64 bit) works perfectly! Go Firefox!
    Internet Explorer 9 (32 bit) loading directly from drive (c:\...)
    Chrome (32 bit) loading directly from drive (c:\...)
    Firefox 6.0.1 (32 bit) loading directly from drive (c:\....)
    Can someone please help! I've been fighting with this bug for over a week and I can't find anything that will solve it, I have noticed that in some cases if my jar has very little code in it than it will run on the server, but the minute I start adding things to it the jar won't load anymore.

    jschell wrote:
    rritoch wrote:
    I am developing an applet (extends Applet but uses swing components) using JDK 1.6 (Though these problems still happen in JDK 1.7) and I am unable to get the applet to load on a 64 bit machine in most cases.
    To clarify...
    1. You have tried it on 32 bit machine? Exactly which OS?I tested this on Windows Vista Business which is in 32 bit mode and the applets run without any problems
    >
    2. Your only 64 bit tests have involved 2008/Win7?
    If so then I would suspect something with windows not java. Probably permissions.
    The web server(s) are running on localhost and I am connecting on the same machine using a local network ip address (such as 192.168.*.*)
    Yes, I haven't tried running the jars on other operating systems.
    >
    I don't understand that. If you are running on localhost then you should connect to localhost. If running on an IP then you should connect to that. Perhaps you meant that you have tested using both of those?I'm testing using the lan ip address but I'm connecting from the same machine. I've tried localhost and that didn't work so I tried lan ip since that will likely have a different java security context than localhost. At first I was blaming the IIS server but I downloaded the jar directly and using HTTP fox was able to verify that the jar is being sent with the correct mime-type and that the server can upload the jar file without a problem. This leaves me to believe the problem is with Java.

  • How do I update a file in an Applet's JAR file from the Applet code

    Here's my problem.
    My applet is using a serializable history data in which I am storing in the applet's JAR file. When I run the applet, I read the file with "getResourceAsStream()" and run my program with that hist data. When my applet is closed, I need to update this file from my Applet's code and I dumfounded about how to do that.
    Is there any way to update a file in the Applet's JAR file through the Java Applet code? (i.e. OutputStream?).
    Would appreciate any advice people have.

    Just place a copy of the file on the local hard disk and update that. When you start the Applet you try to read from the hard disk. If the file exists then no problem otherwise copy it from the jar to the hard disk.

  • How can i get the path to config folder placed inside the jar file?

    Hi i have developed an RCP application using eclipse.
    In my application config directory is there.
    When i export my RCP application as JNLP Project the jar file is created which contains config folder inside it.
    When i download the application using java web start , how can i get the path to config folder placed inside the jar file?
    Will the config folder exists in local cache in my system?
    Help needed.
    -Deepak

    -- This works in CS6:
    tell application "Adobe InDesign CS6"
      set myDocument to active document
      set selectedRectangles to selection of myDocument
      set theGraphicsLink to file path of item link of (graphic 1 of (item 1 of selectedRectangles))
    --> "Macintosh HD:folder/folder/filename.tif"
    end tell

  • Getting list of classes from a jar

    Hi
    I want to retrieve list of class names from a jar. i used URLClassLoader and it retrieves pakcage name but i don't know how to retrieve class names

    I don't know if this is the best way, but I did this once before like this:import java.util.jar.JarEntry;
    import java.util.jar.JarFile;
    // then you can do this
    String path = "path to some JAR file goes here";
    JarFile jar = new JarFile(path);
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements())
       JarEntry entry = entries.nextElement();
       String name = entry.getName();
       if (name.endsWith(".class"))
          // this is a class entry
    }

  • Reading from the Applet's JAR file.

    Is it possible to read a file stored in the jar file that the (unsigned) applet is being executed in? I have a line that goes like (in is just an InputStream):
    in = getClass().getResource( "/exercise.xml" ).openStream();
    and then, in another class, i do (bulider is an instance of javax.xml.parsers.DocumentBuilder, created from the DocumentBuilderFactory class):
    doc = builder.parse( in );
    but this always results in a security exception (works fine from the applet viewer). I tried specifying the full path to the .jar file as the codebase, but got the same results. I have not tested this from an actual web server, i am only opening the .html file directly in IE.
    Due to the nature of the application, it is not possible to host the file seperately on a webserver.
    It seems to me that there is no reason an applet shouldnt be allowed to load a file from the .jar it is executing in, could this simply be a problem of the file being local, and thus linked to from a file:// tag?
    Thanks for any help.
    Thomas Stephens

    Hi Guys
    I have figured out this problem. It's got to do with classloader.
    Applet uses a separate classloader. So using the static getSystemResource(),
    we never get contents from applet jar files. The following will work nicely.
    It is noted that you must loacate the applet classloader as in the first line
    and use the non-static method getResource();
    ObjectInJar obj = new ObjectInJar(); // create an object with a class in the jar file.
    ClassLoader cl = obj.getClass().getClassLoader();
    InputStream stream = cl.getResource("your_filepath_in_jar").openStream();
    Cheers.

  • Class not found error while executing jar file

    I have written a java code in which i am connecting to database....when i run the class file using......java class_filename it works........
    but when i run the jar file using .......java -jar jar_name ...yi gives me the error as 'Class not found'......
    can anybody help me please......
    Thanks and Regards,
    Siddhesh

    that class is part of jar file.....in classpath i have included zip files for jdbc ...to get databse connection.....and the jar being executed ................still it gives the error ClassDefnotfound which i think is due to database connection problem.....the exception is raised while.....
    Class.ForName("Driver_name").newInstance();/ This driver is present in zip files that i have added in classpath....
    above statement doesn,t giv error while i execute the class file............but exception while executing jar file only..
    Thnaks and regards,
    siddhesh

  • Can javascript pass values to applet inside jar file?

    I have an applet that receives the computer name selected via javascript and then resolves the name with the name server and returns any available ip addresses (via a browser). When running this applet unsigned, I can only resolve my own local machine and I get security exception errors(access denied) for any other computer selections (this would be expected).
    I have created a jar file encompassing the class file and java file for this applet signing it with the designated signature. When using the jar file, the applet will start, but no names can be resolved (including the local machine) and there are no errors on the java console...(???)
    HTML code is as follows:
    <html>
    <body>
    <form>
    <fieldset style="width:100%"><legend>  ?</legend>
    <select name="CNList"
    onChange="var f = document.forms[0]
    if (f.CNList.options[f.CNList.selectedIndex].text=="") {
    alert("Please choose a computer name for this test.");
    f.CNList.focus();
    return false;
    }else{
    var cnv = f.CNList.options[f.CNList.selectedIndex].text;
    document.myApplet.newText(cnv);
    return false;"
    >
    <option value="-SELECT COMPUTER NAME-" selected>-SELECT COMPUTER NAME-
    <option value="BELKNAP">BELKNAP
    <option value="DOWNS">DOWNS
    <option value="GSIMS">GSIMS
    <option value="SPOTSYLVANIA">SPOTSYLVANIA
    <option value="CEDAR">CEDAR
    <option value="BELLMEAD">BELLMEAD
    <option value="ASHLAND">ASHLAND
    <option value="COMFORT">COMFORT
    <option value="ROSS">ROSS
    <option value="PUTNAM">PUTNAM
    <option value="CHARITY">CHARITY
    <option value="FRODO">FRODO
    <option value="PLUTO">PLUTO
    <option value="DENTON">DENTON
    <option value="HOOD">HOOD
    <option value="KODIAK">KODIAK
    <option value="SUNDOWN">SUNDOWN
    <option value="FROST">FROST
    <option value="TRINITY">TRINITY
    <option value="LOUDOUN">LOUDOUN
    <option value="MPAPE">MPAPE
    <option value="QUENTIN">QUENTIN
    <option value="DUNDEE">DUNDEE
    <option value="SIGMA">SIGMA
    <option value="PSI">PSI
    <option value="CUBE">CUBE
    <option value="ALOHA">ALOHA
    <option value="OBION">OBION
    </select>
    <br />
    <applet code=NSQuery2.class
            archive="NSQuery2.jar"
            width=400 height=250
         name="myApplet"
         id="myApplet"
         >
         <p>Sorry, you need a Java enabled browser to see the applet's info.</p>
    </applet>
    </form>
    </body>
    </html>JAVA Applet code is as follows:
    /* Gets ComputerName selected, returns IP Address(es)*/
    // Instead of importing just 1 or 2 parts of java.awt and java.applet classes,
    // we have chosen to import everything at once.
    // To do this we use the wildcard operator (*).
    import java.awt.*;
    import java.applet.*;
    import java.io.*;
    import java.lang.String;
    import java.net.InetAddress;
    public class NSQuery2 extends Applet {
    // This declares a string variable named computerName for future use.
    String computerName;
      public void init() {
      // Set background color of our applet to white.
      setBackground(Color.white);
      public void paint(Graphics g) {
        super.paint(g);
        try {
          g.drawString("Computer Name: " + this.computerName, 23, 43);
          String[] ips = new queryhost().getIPAddressArray(this.computerName);
            for (int j=0; j<ips.length; j++) {
          g.drawString("IP Address   : " + ips[j], 23, (12*j)+((j+10)+91));
        } catch (Exception e) {
                g.drawString("Can't detect selected host name.  Check Network settings.", 23, 60);
       public static void main(String[] args) { new NSQuery2(); }
       public static String[] getIPAddressArray(String computerName) {
       //create int which is (sRemoteHost.length() + 1)
       int sRemoteHostchars = computerName.length();
         sRemoteHostchars++;
        //below returns a array of type InetAddress which holds entries such as: hostname1/IPAddress1 etc
       InetAddress[] remoteHostName = null;
       try {
          remoteHostName = InetAddress.getAllByName(computerName); // get IP Address(es)
       catch (Exception e) {
          e.printStackTrace();
        // below creates an array of type string which holds entries such as : IPAddress1 etc
        String[] remoteIP = new String[ remoteHostName.length ] ;
        for (int i=0; i<remoteHostName.length; i++) {
           String iponly = remoteHostName.toString();
    iponly = iponly.substring(sRemoteHostchars);
    remoteIP[i] = iponly;
    return remoteIP;
    public void newText(String s){
    this.computerName = s;
    repaint();
    Anyone have any ideas as to why this can't be performed?
    Thanks in advance,
    Geoff-

    Hey thanks for the response (seems that most responses
    are gender specific around here :) )!No, they are not. Ask a good question (not "do my homework for me") and ask it specifically, and you will get good help whatever your gender. I am a girl; I make no attempt to hide this. I have always gotten good, solid advice from this forum without any reference to my gender, without any ascerbic remarks, without scorn from the respondant.
    You are probably referring to the "girl needs som help" thread or other recent threads from girls (well maybe girls, who knows).
    The content of these posts were:
    1) asking to help with blatant cheating on homework
    2) extremely vague
    3) used the OPs gender as an excuse for 1) and/or 2)
    Using your gender as an excuse for being unable to put code together and requesting help with cheating:
    -implies girls are too stupid to do math, programming, engineering
    -implies that girls who are in these fields are freaks/mutants/other
    -implies that gender is an exucse for laziness
    -implies that girls cannot think logically
    -implies that girls do not have to follow rules of integrity, or that girls have no integrity
    Such posts understandibly raise the ire of women software engineers who have worked hard to get where they are. (And also of male software engineers who can see through the request as a play on a stereotype)
    It is akin to a girl coming to my office hours and saying "I have my mechanics final exam tomorrow, but I didn't study all semester because I'm a girl and math is too haaaaard"
    Honestly, I would try to help the girl as much as I could, not because she's a girl, but because it is part of my duty, my responsibility, to help students.
    But before I could do it, I would have to count to ten a few times to get my temper under control.
    jen

  • URGENT Help for applet with JAR file in Netscape

    I am having Applet with few classes
    Html is in /www directory
    and all class files are in /www/javaclassfiles
    I jared all javaclassfiles with following command
    c:\www\javaclassfiles>jar -cvf sample.jar TaxPaymentAppletForm.class *.class
    where sample.jar is my jar file and TaxPaymentAppletForm.class is the main applet class file.
    THEN I DELETED ALL CLASS FILES & KEPT ONLY SAMPLE.JAR FILE ON SERVER
    My html code is like below:
    <APPLET CODE="TaxPaymentAppletForm" ARCHIVE="sample.jar" CODEBASE="JavaClassFiles" WIDTH=460 HEIGHT=400></APPLET>
    The things are running on IE properly, but not on Netscape. Netscape is giving following error :
    java.io.IOException: <null>
    at netscape.net.URLConnection.connect(Compiled Code)
    at netscape.net.URLConnection.getInputStream(Compiled Code)
    * at netscape.applet.AppletClassLoader.grabArchiveFile(Compiled Code)
    at netscape.applet.AppletClassLoader.openArchive(Compiled Code)
    at netscape.applet.AppletClassLoader.openArchive(Compiled Code)
    at netscape.applet.AppletClassLoader.<init>(Compiled Code)
    at netscape.applet.AppletClassLoader.getClassLoader(Compiled Code)
    at netscape.applet.DerivedAppletFrame$LoadAppletEvent.dispatch(Compiled Code)
    at java.awt.EventDispatchThread$EventPump.dispatchEvents(Compiled Code)
    at java.awt.EventDispatchThread.run(Compiled Code)
    at netscape.applet.DerivedAppletFrame$AppletEventDispatchThread.run(Compiled Code)
    # Unable to load archive http://nearbuy_server:90/iras/JavaClassFiles/sample.jar: java.io.IOException: <null>
    # Applet exception: class TaxPaymentAppletForm could not be loaded
    # Applet exception: class TaxPaymentAppletForm could not be loaded
    # Applet exception: class TaxPaymentAppletForm could not be loaded
    In netscape also it is sometimes running some times not, without any logical reson.
    Any help regarding this is appreciated
    manisha

    Following is the more detailed analysis when applet is running and when not
    On local server, it is running fine on both IE / Netscape
    When I transfered jar file to live server
    On IE it is running for the first time and then onwards not running, If I clear the catch then again applet is running.
    For second time it is giving following error :
    IOException Loading Archive: http://dev1.janusx-collections.com/iras/JavaClassFiles/AppletForm.jar
    java.io.IOException: dev1.janusx-collections.com:80//iras/JavaClassFiles/AppletForm.jar
    at com/ms/net/wininet/http/HttpInputStream.connect
    at com/ms/net/wininet/http/HttpInputStream.<init>
    at com/ms/net/wininet/http/HttpURLConnection.createInputStream
    at com/ms/net/wininet/WininetURLConnection.getInputStream
    at com/ms/vm/loader/JarArchiveSet.loadNextJar
    at com/ms/vm/loader/JarArchiveSet.getResourceBits
    at com/ms/vm/loader/JarArchiveSet.getClassData
    at com/ms/vm/loader/ResourceLoader.getClassData
    at com/ms/vm/loader/URLClassLoader.findClass
    at com/ms/vm/loader/URLClassLoader.loadClass
    at com/ms/vm/loader/URLClassLoader.loadClass
    at com/ms/applet/AppletPanel.processSentEvent
    at com/ms/applet/AppletPanel.processSentEvent
    at com/ms/applet/AppletPanel.run
    at java/lang/Thread.run
    java.lang.ClassNotFoundException: TaxPaymentAppletForm
    at com/ms/vm/loader/URLClassLoader.loadClass
    at com/ms/vm/loader/URLClassLoader.loadClass
    at com/ms/applet/AppletPanel.processSentEvent
    at com/ms/applet/AppletPanel.processSentEvent
    at com/ms/applet/AppletPanel.run
    at java/lang/Thread.run
    ON Netscape it is NOT running at all on from live server and error is as given in above first post.
    manisha

  • Unsupported class version error trying to run jar file on windows machine

    Hi,
    i've written a program that connects to an access database to get its data. Created a jar file with the class files, the access database and other required files.
    works fine on my home windows computer but when i try to run it on another machine i get an error.
    here's what i write on the cmd: java -Xmx128m -jar myFile.jar
    heres the error i get:
    Exception in thread "main" java.lang.UnsupportedClassVersionError: StartUp(Unsupported major.minor version 49.0)
    at java.lang.ClassLoader.defineClass0(Native Method)
    and so on.
    It seems like it might be quite a basic error but i'm lost, can anyone please shed some light and tell me where i'm going wrong?
    cheers in advance

    hey there, in case anyone was going to reply, i've worked it out now. couldn't work out what was wrong at first so just pulled out all my classes and put them into a brand new jar file. now use javaw -jar instead of java and it worked fine! wierd...

  • Unable to load database driver from my applet's jar file

    I'm trying to set up an applet that will talk to a MySQL database. I have no problem connecting to the database as I'm developing the code ("un-jarred"), but when I create a jar file of my code to test through a web browser, I cannot connect to the database due to the usual ClassNotFoundException. I have included mysql-connector-java-3.1.12-bin.jar (the current driver) in the jar, but I don't know if I'm supposed to supply some info through an attribute to the applet tag to let it know that the jar contains the driver it needs or if I have to call the driver differently in my code.
    Any help is appreciated, thanks.

    The simplest approach is always the best. :)Abso-lutely.
    Awesome, that worked perfectly. I Included the extra
    jar file in the applet tag and now my applet makes
    some sweet lovin' to the database.And you have succeeded where thousands have failed. Congratulations.

  • Java 5.0 does not recognize wrapped Class-Path in Manifest.MF of .jar file?

    Java: build 1.5.0_05-b05
    Ant: 1.6.2
    I use Ant <jar> task to create a standalone application in a .jar file. I have a very long "Class-Path" in the Manifest.MF file. The long Class-Path is wrapped at every 70th character by the <jar> task. I cannot run "java -jar <the jar file>", because Java runtime cannot find classes.
    I found the following Q&A from ANT's FAQ page,
    Q: Whenever I use the Ant jar or manifest related tasks, long lines in my manifest are wrapped at 70 characters and the resulting jar does not work in my application server. Why does Ant do this?
    A: Ant implements the Java Jar file specification. Please refer to the notes section where it discusses the maximum allowable length of a line and the concept of continuation characters.
    If a jar file produced by Ant does not work in your appserver, and that failure is due to the wrapped manifest, then you need to consult your appserver provider, as it is a bug in their appserver. Far more likely, however, is a problem in your specification of your classpath. It is not Ant's wrapping of your classpath that is the problem.
    Do not raise a bug about this issue until you have checked to ensure that the problem is not due to your classpath specification.
    Any idea?

    "will be searched ALSO."...
    From: http://java.sun.com/docs/books/tutorial/ext/basics/load.html
    Understanding Extension Class Loading
    The extension framework makes use of the new class-loading mechanism in the JavaTM 1.2 platform. When the runtime environment needs to load a new class for an application, it looks for the class in the following locations, in order:
    1. Bootstrap classes: the runtime classes in rt.jar and internationalization classes in i18n.jar.
    2. Installed extensions: classes in JAR files in the lib/ext directory of the JRE.
    3. The class path: classes, including classes in JAR files, on paths specified by the system property java.class.path. If a JAR file on the class path has a manifest with the Class-Path attribute, JAR files specified by the Class-Path attribute will be searched also.
    [snip]

Maybe you are looking for