Using getCodeBase

I need to specify the location on my computer of an image I want to load on a JPanel in an applet. The method
getImage(getCodeBase(), "npsha.jpg");
must be used I believe.
I believe I am having problems with getCodeBaseI() because I am having trouble loading my image.
When I display the string representation of getCoseBase() in a label I get something like: http:/Desktop:8082/classpath
this seems to have nothing to do with the actual location of my program file.
Can someone tell me what is goin' on?

according to w3c specs on applet tag:
This attribute specifies the base URI for the applet. If this attribute is not specified, then it defaults the same base URI as for the current document. Values for this attribute may only refer to subdirectories of the directory containing the current document.
More simply put, codebase refers to the location of your applet, or if not supplied, defaults to the location of the page. Put your resources in this folder or beneath and refer to them relatively. For example, if your applet is in a folder named myapplet, getImage(getCodeBase(),"npsha.jpg") would refer to a file which is a sibling of your class file. If you used "images/npsha.jpg", it would refer to the file in the folder images.

Similar Messages

  • Problem with getCodeBase()

    I have a problem with the deployment of a 'jarred' applet. Here's my directory structure (in a web module);
    applets
    myjar.jar
    data.txt
    webpages
    mypage.jsp
    myjar.jar contains an applet.
    mypage.jsp has an applet tag that includes this line:
    archive="../applets/myjar.jar
    This works fine. The problem comes when the applet tries to download data from data.txt. I'm using getCodeBase(), which should return the URL of the applets directory. But getCodeBase() is returning the URL of the webpages directory. In other words, it's behaving like getDocumentBase()!
    Why is this happening? What's the solution? Any help greatly appreciated!
    miguel

    Very good point Ron. I found it out by myself in the meantime: getCodeBase() uses the CODEBASE attribute in the APPLET tag. This info was hard to find!
    Anyway u get your 5 dukedollars!
    The thing is ... my applet is still not working. When in my IDE (Forte), everything is fine, but online, the class cannot be found. This is not a getCodeBase() problem anymore, but probably a classpath problem. I tried putting the applet jar in WEB-INF/lib/, but it didn't work either.
    Here's my original applet tag:
    <applet align="middle" archive="../livemaps/lm_applet_jet.jar" code="applet.Applet1.class" codebase="../livemaps/" height="50" width="60">
    The dir structure is exactly the same but it won't work online!!! Any suggestions?
    miguel

  • GetCodeBase() stopped working on WWW

    I have a Java program that has a LOAD option so users can load data files. In the load function I have code like this:
    JFileChooser chooser = new JFileChooser();
    URL baseURL = getCodeBase();
    c_strDirectory = baseURL.toString();
    baseDir = new File(c_strDirectory);
    chooser.setCurrentDirectory (baseDir);This works fine on my computer and on the network here at work - the file chooser starts in the subdirectory the Applet is in-, but when I posted the Applet to my web site the chooser comes up in the 'Documents and Settings' subdirectory on my C drive.
    Can anyone give me a clue as to what is wrong? Could it be a security issue with my ISP?

    Since you are using getCodeBase(), I am assume you are writing an applet. Since applets mostly live on web pages, you are trying to get a directory of web pages (let me know if I'm wrong here). Directories on the web do not work like directories on your hard drive. Some Web servers allow you to list an index of web pages (like this http://www.ku.edu/history/ ), but the vast majority either don't allow this, or reroute your request to a specific page ( http://www.something.com/index.html ).

  • File path problem and getCodeBase Usage

    I have a java application and read data from file.
    I create file by File file=new File("F:\MyProgram\.txt');
    if I want to give my file to relative path name, HOw can i give. I can move my program to jar file or exe and move to anywhere.
    How can i give file to move anywhere by only give folder name and don't need to give full path name?
    How can I use getCodeBase to give file path name?

    You need to use resources and the URL class, here's an example:URL resourceLocation = getClass().getResource("/configuration.txt");That will give the location of the configuration file regardless of how you've packaged the software. If you need to read the file from a static context use "ClassName.class" in place of "getClass()".

  • How to retrieve the  drive letter of the current directory with an applet ?

    The subject says it all.
    I have this html file and when launched it should get the current drive's letter.
    This is how it's done in java, but I dunno how to make it in an applet version.
    import java.*;
    import java.io.File;
    public class test {
    public static void main (String args[]) {
    File dir1 = new File (".");
    String drive = new String();
    try {
    drive = dir1.getCanonicalPath ();
    char driveletter = drive.charAt(0);
    System.out.println ("Drive letter : " + driveletter);
    catch(Exception e) {
    e.printStackTrace();
    Thank you very much for any hint or any idea.
    Gihan.

    Found the solution, used getCodeBase.
    Thank you.
    Gihan.

  • Java cgi applet not working

    Hi guys,
    I have an applet that allows a user to "create" a datafile using buttons, to ensure consistency of input. I then want to write this file tto my webserver (it keeps the data for a soccer league, with basic stats). I know that applets can't write in theory, so I have tried to do it using the POST function, to a basic CGI programme. I am getting an error
    HTTP/1.1 502 Gateway Error
    Server: Microsoft-IIS/5.0
    Date: Tue, 15 Apr 2003 18:07:32 GMT
    Connection: close
    Content-Length: 186
    Content-Type: text/html
    <head><title>CGI Application Timeout</title></head><body><h1>CGI Timeout</h1>The specified CGI application exceeded the allowed time for processing. The server has deleted the process.Data file sent to host
    I know this is a java forum, but the CGI is simple
    print "content-type: text/plain\n\n";
    open(OUT,"> /Under14/111111.TST");
    while(<>){
         print OUT $_;
         print $_;
    close(OUT);
    exit 0;I have no idea how to debug this particular error, searching the internet brings out hundreds of similar errors, but little explanation of what is going wrong
    The Java code that kicks this off is
    //============================================================================//     
         public void SendData(String data) throws Exception {
              tArea1.append("\n\n************   Sending Data   ************\n");
              URL url = new URL("http","www.lagfc.co.uk","/cgi-bin/ResUpd.cgi");
              URLConnection ucon = url.openConnection();
              ucon.setDoOutput(true);
              ucon.setDoInput(true);
              ucon.setUseCaches(false);
              ucon.setRequestProperty("Content-type", "text/plain");
              ucon.setRequestProperty("Content-length", 750+"");
              PrintStream out = new PrintStream(ucon.getOutputStream());
              out.print(data);
              out.flush();
              out.close();
              DataInputStream in = new DataInputStream(ucon.getInputStream());
              String s;
              while((s=in.readLine()) !=null){
              tArea1.append(s);
              in.close();
              tArea1.append("\n\nData file sent to host");
       } // end of sendData
    //============================================================================//Help..........................

    Sscotties : I do appreciate your help, and maybe I have got wood for trees syndrome. I have been trying to understand what is going wrong here. I started learning Java 2 weeks ago, it seemed a good idea at the time, and a way to combine helping out my daughters football team, with a desire to understand more.
    I do not have a programming background, and so some of what you have been trying to tell me, will have gone right over my head, and I won't know which bits! I didn't understand the implications of what you were asking me to do last night, but having thought it through with a cooler head, I thank you for the login code. It is a good way to stop unauthorised users screwing up my results file. (at least if they only have my level of knowledge!), and as such I will incorporate it into the finished product.
    My frustration is down to the fact that I really have little understanding of what I am doing at this point, and I have no idea how to tackle the problem. Before I post onto this board, I normally do a Google trawl through many pages of data in an effort to try and find the answers myself, it helps with the general understanding of how things work, and is very satisfying when I can fix the problems. I know for example, that java is not the platform independant language I thought it was two weeks ago. Most of my users use basic IE, and so when I test something out, I have to test it using plain IE, then IE with 1.4.1
    then Netscape. This slows things down tremendously, as things like TextArea attributes work differently between MS and 1.4.1. I can work on a simple problem for hours, to find that its just MS doing there own thing. A great tip I got the other day was to compile using -target 1.1. This has increased my speed of development ten fold (now at 8mph!)
    My apologies for being tetchy, its nothing a few beers and a spell away from the PC won't cure.
    Back to the problem in hand. I made all the changes you suggested. The changes to perl make no difference, the error message is the same. I have left your suggestions to use getCodeBase().getHost() in, as they make the applet more portable, and I thank you for that.
    The DataInputStream is deprecated, but as I am using -target 1.1 will this be a problem (Could be Newbie stupid question time! :-{)) I have used this format in other parts of the code as well. I am also using action rather than ActionEvent to listen for events in the prog. This is the only other deprecated method in the coding.
    I don't know how to set permissions on the server, but will ask the question of my hosting company. I have a pick up and run cgi script that does the guest book, and this worked no problem, writing records to a guestdata file, and a password file, with no further changes needed to the file permissions, but still worth checking.
    I am sending the data, because the data is returned to me, before the error message, although not all the data sent has been returned as part of the error message, are there any restrictions on the size of a String, the file is 9250 bytes long, does it need terminating with an EOF marker of some sort ?
    Any advice will be gratefully accepted
    regards
    KPJ

  • HOW CAN I   WRITE   TEXT IN A     FILE

    HI,
    I have problems with saving files on my hard disk with an JAVA Applet.
    Do you know how to do it in the best way?
    here is the code i'm trying:
    public String getCount()
          int count=456;
          String rec=null;
          DataOutputStream dos = null;
          try
            URL                url;
            URLConnection      urlConn;      
            url = new URL(getCodeBase().toString() + "counter.txt");
            urlConn = url.openConnection();
            urlConn.setDoOutput(true);
            urlConn.setUseCaches(false);
            urlConn.setRequestProperty ("Content-Type", "application/x-www-form-urlencoded");
            rec=""+count;
            dos = new DataOutputStream(urlConn.getOutputStream());
            dos.writeChars(rec);
            dos.flush();
            dos.close();
           catch (MalformedURLException mue) { return mue.toString(); }
           catch (IOException ioe) { return ioe.toString(); }
          return rec;
        }this code is simply saving the value ot count in the file "counter.txt"
    I think the problem comes at the line: dos = new DataOutputStream(urlConn.getOutputStream());
    It doesn't throws exception, it just stopes there and doesn't show any result.
    WHY?
    If you have some ideas ...thanks.
    the class DataInputStream is working perfectly. I'm reading, but saving does not work.

    You're using getCodeBase() to construct the file name, apparently, so I guess you are wanting to write to a file on the server where the applet was loaded from. And it looks like you're trying to do a POST to the URL that you construct, or something like that. But the URL ends in ".txt" so most likely your server isn't exposing that URL to the outside world.
    You're on the right track, but you need to write to a URL that can accept POST requests and knows what to do with them. You can't just write to a file on the server -- if you could do that in your applet then anybody in the world could do it from a simple program, so consider the security implications of that.

  • How  can I  load an  image  in a scene?

    I want to load an image in a scene and I have tried it using the
    steve morris example( HAVI example ) , I am using a STB and when I send my xlet I don�t see this imagen at the tv.
    Source code is available from
    http://www.interactivetvweb.org/resources/code/havi/HaviXlet.zip
    Somebody knows another way to do it ???

    I assume you mean a JLabel as an AWT Label cannot display an Image.
    // POINT THE IMAGE BACK TO THE SERVER FROM WHICH THE APPLET WAS DOWNLOADED
    // BY USING GETCODEBASE(). OMIT THAT AND YOU WILL SEE THAT YOU GET A SECURITY
    // EXCEPTION AS THE APPLET WILL TRY TO LOCTE THE IMAGE ON THE LOCAL MACHINE AND
    // APPLETS BY DEFAULT CANNOT ACCESS RESOURCES ON THE CLIENT
    // assumes .gif file exists in same directory as HTML running the Applet
    Image image = getImage(getCodeBase(), "ImageName.gif");
    ImageIcon icon = new ImageIcon(image);
    JLabel - new JLabel(icon);
    // check out the getScaledInstance() method of Image class to resize your image

  • Applet file writing without permission

    Is it possible for an applet to write a text or html document to be displayed in a browser without needing to grant it permissions?

    I experimented with writing a file and naming the file to the directory that the applet's in using getCodeBase(), but that didn't work. I've been looking into writing directly to a browser, but that's kind of ugly, and it looks like you have to play with system paths and what-not in order to talk to javascript, so I ruled that out. Any help is appreciated.

  • Can I create a socket in a JApplet

    I am writing an applet using JApplet. I am trying to connect to a server using java.net.socket. However, every time i run the applet i get the following security exception.
    java.security.AccessControlException: access denied (java.net.SocketPermission 129.64.167.212:19190 connect,resolve)
    i tried substituting the ip address with localhost but it still didn't work.
    I also used getCodeBase().getHost() but my the serverSocket i am running is not on the same IP address as the applet
    is it possible to create a socket in JApplet?
    I would appreciate your help

    You sure can make a socket. but the code you are using is having one error. The following error comes:
    java.security.AccessControlException: access denied (java.net.SocketPermission 129.64.167.212:19190 connect,resolve)
    you use a lower port no., say 1025
    try out, it might help
    Cheers

  • NullPointer thrown with Applet.getParameter()?

    Alright, I've got this error that's been driving me crazy, and knowing me, it's something small that I'm overlooking, so I'd like to apologize in advance for the fact that this is probably something very basic that I'm neglecting.
    I'm writing an Applet that uses the <PARAM> tag to get some parameters. However, since I put this in, it throws a NullPointerException. Now, here's the thing that's got me really confuzzled: the NullPointer is thrown not in my method, but rather in java.applet.Applet.getParameter().
    The line in my code:
    clientID = getParameter("id");The line in the HTML that specifies this parameter:
    <PARAM NAME=ID VALUE=4>I've tried it with quotation marks around the values in the PARAM tag, I've tried it with an upper-case String passed into getParameter (the API's say that it's case-insensitive, so that shouldn't matter), and I'm just generally confused about what it is that I'm doing wrong that is making getParameter() throw a NullPointerException.
    Anyone know what I'm doing wrong?

    Alright, I've been looking through this, and think I've found the problem: for some reason, my Applet isn't creating an AppletStub.
    According to the source code for Applet (here), when I try to call getParameter, Applet just calles getParameter on its AppletStub. That's the only line in Applet.getParameter(), so it's the only place where a NullPointer would be thrown in Applet.getParameter().
    Now, this also means that I'll run into the same problem if I try to use getCodeBase(), meaning that I can't try to get the URL, which should include the variables. And, since the whole point of what I'm trying to do is to allow variable URL's, I also can't hardcode the URL into my program and try to read the <PARAM> tags with a URLConnection.
    So, it looks like my only hope is to somehow get AppletStub working. Does anyone know anything about AppletStub that might help? Please?

  • Problem Loading an Image with javax Swing from a JApplet

    First of all, i use JCreator as java creater and have the newest version of java sdk version.
    Now i need to load an image from the harddrive on which the JApplet is located. I need to do this from inside the JApplet. I have put my pictures in a map 'images' which is located in the same directory as the classes + htm file. It works from inside JCreator, but as soon as i open the normal htm it just WON'T load that image (grmbl).
    Here is my code for loading the image:
    public BufferedImage loadImage (String filename, int transparency)
         Image image;
         if (app)
              image = Toolkit.getDefaultToolkit().getImage(("./images/"+filename));
         else
              String location = "";
              location = "./images/"+filename;
              image = Toolkit.getDefaultToolkit().getImage(location);
         MediaTracker mediaTracker = new MediaTracker(new Container());
         mediaTracker.addImage(image, 0);
         try
              mediaTracker.waitForID(0);
         catch (Exception e)
    Could anybody help me out here??
    I tried a url already using getCodeBase() or getDocumentBase() but that gives an error because it cannot find those if using a JApplet.

    Why don't you use javax.swing.ImageIcon? If you already have a flag telling if it's an application or applet, use the getDocumentBase() to base the URL in the applet part only.

  • Servlet Access

    Hi,
    I want to access a servlet from an applet. I am using getCodeBase() to get the first part of the URL for the servlet. I am using Apache Tomcat as the servlet container. This uses a different port from the Web server. Is there a way I can detect this port rather than hardcoding it in my servlet URL?
    Am I doing this all wrong? Should the html/applets be served from the same container as the servlets?
    Can someone give me a brief outline of the structure I should be using?
    Thanks in advance
    Slacks

    URL url = xyz; // generate the URL here
    URL tomcatPortUrl = new URL(url.getProtocol(), url.getHost(), 8080, url.getFile()); // where 8080 is the tomcat default port...
    BUT
    normally the webserver will redirect a request to tomcat so you don't have to do this...

  • Inserting a pic to an applet

    Can someone tell me how to insert a pic into an applet?

    Use getCodeBase() method, is a good one and avoids wrong typings. But you must pay special atention to your version of SDK. For example: I spent a lot of time some time ago to find why my applets developed last year refuses to run this year!!! The source code was the same (the same file).
    Eventually I've succeeded to figure out: The same applet code compiled with jdk 1.3.1 for example works fine while fails running as long is compiled using SDK 1.4.1 for example. This is due to the new SDK 1.4.1's approach of security policies regarding reading and writing from an applet. One workaround is to set a .policy file (see java tutorial.
    Hope you'll find this useful

  • Fastest way to load an image into memory

    hi, ive posted before but i was kinda vague and didnt get much of a response so im going into detail this time. im making a java program that is going to contol 2 robots in a soccer competition. ive decided that i want to go all out and use a webcam instead of the usual array of sensors so the first step is to load an image into the memory. (ill work on the webcam once ive got something substanical, lol) since these robots have to be rather small (21cm in diameter) i can only use some pretty crappy processors. the robots are going to be both running gentoo linux on a 600 mhz processor, therefore it is absoleutely vital i have a fast method of loading and analyzing images. i need to be able to both load the image quickly, and more importainly analyze it quickly. ive looked at pixelgrabber which looks good, but ive read several things about javas image handling beging crap. these articles are a few years old, and im therefore wonding if there anything from the JAI that will do this for me. thx in advance.

    well i found out why i was having so much trouble
    installing JAI. im now back on windows and i cant
    stand it, so hopefully the bug will be fixed soon. oIt's not so bad. I mean, that's why we love Java! Once your linux problem is fixed you can just transfer your code there as is.
    well. i like the looks of JAI.create() but im not so
    sure how to use it. at this stage im tying to load an
    image from a file. i no to do this with pixelgrabber
    you use getcodebase(), but i dont know how to do it
    with JAI.create. any advice is appreciated. thx.Here are some example statements for handling a JAI image. There are other ways, I'm sure, but I've no idea which are faster, sorry. But this is quite fast on my machine.
    PlanarImage pi = JAI.create("fileload", imgFilename);
    WritableRaster wr = Raster.createWritableRaster(pi.getSampleModel(), null);
    int width = pi.getWidth(); // in case you need to loop through the image
    int height = pi.getHeight();
    wr = pi.copyData(); // copy data from the planar image to the writable one
    wr.getPixel(w,h,pixel); //  pixel is an int array with three elements.
    int red = pixel[0];     // to find out what's the red component
    int[] otherPixel = {0,0,0}
    wr.setPixel(w,h,otherPixel); // make pixel at location (w,h) black.                And here's a link with sample code using JAI. I've tried several of the programs there and they work.
    https://jaistuff.dev.java.net/

Maybe you are looking for

  • Query on PLD

    Hi Experts, Currently, I'm re designing a PLD for Profit and Loss Statement.  Is it possible to include a query and insert it in the PLD?  and How?

  • Display BLOB to JSP

    HI , currenty i doing a final yr project for JSP . i can save the pic into the database in BLOB but have problem display the BLOB into a JSP page. Not to mention in thumbnail format SQLPicInf="select * from Picture where picName = iii"; //passinParam

  • Guest and all users have invalid password

    Dear all, os oul5x64 ebs 12.1.3 when login from login page no one can connect because somehow guest user password was invalid. using note How To Successfully Change The Guest Password In E-Business Suite 11.5.10 and R12 (Doc ID 443353.1) and was able

  • Best practise: validate/check backups are good

    Hello all Oracle 10g on Linux, Veritas NetBackup for Oracle - Release 6.5 How do you ensure that backups taken with rman are good? Some ideas to discuss: - restore/recover backups to a clone database after backup - using command "validate backupset"

  • Can I download Firefox3.0 on my Windows Mellinium Operating System?

    I use Microsoft Windows Millenium Operating system. I have Mozilla Firefox 2.0.0.20 installed now. I also have Internet Explorer 6.0 with SP1. I have been unable to upgrade both browsers due to my older operating system. I cannot update Flash Player,