Applet using  URLConnection.setUseCaches (true) cause OutOfMemoryError

Hi all,
I had this prloblem for a couple of weeks.
We had a applet app that retrieve images and show on applet pages. On the applet page there are some image icon like print, rotation, copy ... on the sidebar, also I have two jar files including those classes and images on sever. When users access the applet page, the applet image (a document) show up immediately, but the button icon loading very slow one by one. From java console I can see one jar file which contain image icons were loaded multiple times and very slow about 8 to 10 minuts, after complete loaded, retrieve others will be fine.
I think the cache set to false cause that.
               urlConnection.setUseCaches (*false*);
               urlConnection.setDefaultUseCaches (*false*);But if I set to true:
               urlConnection.setUseCaches (*true*);
               urlConnection.setDefaultUseCaches (*true*);My understanding is that allow to loading very image into local cache. After user retrieve images (about 30 times, they clicked on a document icon to show the image) for certain times, the browser frozen and java console show a error:
com.ibm.mm.viewer.CMBDocumentEngineException: Java heap space
java.lang.OutOfMemoryError: Java heap space
I tried jre1.4.2, 1.5 and 1.6.0_02/_06/_10, didn't work!
jre1.4.1 was fine but our user will use jre1.5 or higher.
Anybody has a solution?
Many thanks!!!
Jx
Edited by: cooooooooool on Nov 25, 2008 7:19 AM

Ah, turns out I had to read the input too. Though I didn't produce much output myself in the script ;)

Similar Messages

  • If in the URLconnection I setUseCaches(true), I must to wait until...

    Hello, sorry for my english and thanks for all.
    I know how can to use an URLconnection for to get the file size for download and after to get the InputStream read it and to get the progress download.
    If in the URLconnection I setUseCaches(true), I must to wait until the file is all download an after I can read the InputStream.
    If in the URLconnection I setUseCaches(false), I can read the InputStream at the same time that the file is downloading.
    I have two questions:
    - if I setUseCaches(true), why I must to wait until the file is all download an after I can read the InputStream?
    - how can I get the progress download if setUseCaches(true) in the URLconnection?
    very thanks

    This is the code that I've used:
    try{
         URLConnection urlconnection;
         urlconnection = (new URL(getDocumentBase(), "beni0271.jpg")).openConnection()
         urlconnection.setUseCaches(true);
         //If in the URLconnection I setUseCaches(true), I must to wait until the file is all download an after I can read the InputStream.
         //If in the URLconnection I setUseCaches(false), I can read the InputStream at the same time that the file is downloading.
         System.out.println(urlconnection);
         length =     urlconnection.getContentLength();
         inps = urlconnection.getInputStream();
         System.out.println(inps);
    }catch(MalformedURLException e){
         System.out.println(e);
    }catch(IOException e){
         System.out.println(e);
    }

  • 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();
    }

  • Invoking servlet using URLConnection

    hi there,
    i am trying to invoke a servlet from one jboss to another servlet on another jboss,using URLConnection.
    iam getting
    java.lang.IllegalStateException: Already connected
    20:57:48,371 ERROR [STDERR] at java.net.URLConnection.setDoInput(URLConnection.java:709)
    20:57:48,371 ERROR [STDERR] at com.dpsl.dxdam.util.assettransfer.FTPController.run(Unknown Source)
    where as if i run the same code on as standalone application,the servlet on the other jboss gets invoked,below is the code:
    URL url = new URL(strPreingestServletUrl);
    URLConnection connection = url.openConnection();     
    connection.connect();                    
    connection.setDoOutput(true);                         connection.setUseCaches(false);                         connection.connect();
    InputStream is = connection.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(is));
    String response = in.readLine();                    System.out.println(response);
         while(response!=null){
         System.out.println(response);
         response = in.readLine();
    is.close();
    in.close();
    please explain why this happens,does it have anything to do with the policy file of catalina.
    thanks in advancePrasad

    So what's the solution? Maybe if you share it you can spare someone else some heartache. - MOD

  • Html file to run an Applet using swings in 1.4.1 or 1.3.1

    Can anyone send me an html document to launch the applet in a browser. I have very basic html, but I need one that uses the appropriate plug-in and that has parameters such as height, width, etc. My applet uses tabbed panes, dialog boxes and comboboxes. It works well with appletviewer, but does not work in IE or Netscape.
    Thank you for your help
    here is what I am using which does does show anything but a grey screen
    <HTML>
    <HEAD>
    <TITLE>
    CIS 602 Semister Project
    </TITLE>
    </HEAD>
    <BODY>
    <BR>
    <H3>
    <CENTER>
    Swing
    </CENTER>
    </H3>
    <H3>
    <BR><BR>
    <P><H3>
    <CENTER>
    <BR><BR>
    <P><h2>
    Structured Problem Solving Strategy
    </h2>
    <blockquote>
    <!--"CONVERTED_APPLET"-->
    <!-- CONVERTER VERSION 1.1 -->
    <SCRIPT LANGUAGE="JavaScript"><!--
    var info = navigator.userAgent; var ns = false;
    var ie = (info.indexOf("MSIE") > 0 && info.indexOf("Win") > 0 && info.indexOf("Windows 3.1") < 0);
    //--></SCRIPT>
    <COMMENT><SCRIPT LANGUAGE="JavaScript1.1"><!--
    var ns = (navigator.appName.indexOf("Netscape") >= 0 && ((info.indexOf("Win") > 0 && info.indexOf("Win16") < 0 && java.lang.System.getProperty("os.version").indexOf("3.5") < 0) || (info.indexOf("Sun") > 0) || (_info.indexOf("Linux") > 0)));
    //--></SCRIPT></COMMENT>
    <SCRIPT LANGUAGE="JavaScript"><!--
    if (_ie == true) document.writeln('<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" WIDTH = "570" HEIGHT = "500" codebase="http://java.sun.com/products/plugin/1.1.2/jinstall-112-win32.cab#Version=1,1,2,0"><NOEMBED><XMP>');
    else if (_ns == true) document.writeln('<EMBED type="application/x-java-applet;version=1.4.2" java_CODE = "semiclient.class" WIDTH = "570" HEIGHT = "500" pluginspage="http://java.sun.com/products/plugin/1.1.2/plugin-install.html"><NOEMBED><XMP>');
    //--></SCRIPT>
    <APPLET CODE = "semiclient.class" WIDTH = "570" HEIGHT = "500" ></XMP>
    <PARAM NAME = CODE VALUE = "semiclient.class" >
    <PARAM NAME="type" VALUE="application/x-java-applet;version=1.4.2">
    </APPLET>
    </NOEMBED></EMBED></OBJECT>
    <!--
    <APPLET CODE = "semiclient.class" WIDTH = "570" HEIGHT = "500" >
    </APPLET>
    -->
    <!--"END_CONVERTED_APPLET"-->
    </Center>
    <BLOCKQUOTE><PRE>
    </PRE></BLOCKQUOTE>
    </H3>
    <BLOCKQUOTE><PRE>
    </PRE></BLOCKQUOTE>
    </H3>
    </BODY></HTML>

    Try this:
    <HTML>
    <HEAD>
    <TITLE>CIS 602 Semister Project</TITLE>
    </HEAD>
    <BODY>
    <CENTER><H3>Swing</H3></CENTER><CENTER><H2>Structured Problem Solving Strategy</H2></CENTER>
            <OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
                width="750"
                height="575"
                align="baseline"
                codebase="http://java.sun.com/products/plugin/autodl/jinstall-1_4_0-win.cab">
                <PARAM NAME="code"       VALUE="full.qualified.ClassName">
                <PARAM NAME="codebase"   VALUE="path/to/your/class/files/or/archive/">
                <PARAM NAME="archive"    VALUE="nameOfJarWhichContainsClassFiles.jar">
                <PARAM NAME="type"       VALUE="application/x-java-applet;version=1.4">
                <PARAM NAME="scriptable" VALUE="false">
                <COMMENT>
                    <EMBED type="application/x-java-applet;version=1.4"
                        width="750"
                        height="575"
                        align="baseline"
                        code="full.qualified.ClassName"
                        codebase="path/to/your/class/files/or/archive/"
                        archive="nameOfJarWhichContainsClassFiles.jar"
                        pluginspage="http://java.sun.com/products/plugin/1.4/plugin-install.html">
                        <NOEMBED>
                            No Java 2 SDK, Standard Edition v 1.4 support for APPLET!!
                        </noembed>
                    </embed>
                </COMMENT>
            </OBJECT>
    </BODY>
    </HTML>

  • Use apex_application.g_unrecoverable_error := TRUE; and apex_collection.truncate_collection doesn't work

    I'm trying to print pdf using JasperReports Integration. I need to do an INSERT then clean all the page items(including the apex_collection.truncate_collection for truncate the collection)  and print with the Jasper call(all in one button).
    The Insert works, and i can perfectlly print too, but the clean page items and the truncate collection doesn't.
    Please HELP! its really urgent!!
    Thnx.
    Ricardo Capuz

    Hi Nicolette, i'm really new on Apex, sorry for the bad explanation.
    First, thank for your answer, my apex version is 4.2.2.
    I'm sure that the insert works perfect, cause i checked with the database.
    i used apex_application.g_unrecoverable_error := true; because is the code that bring the people of JasperReportsIntegration and I tried to comment it but without it, the print doesn't work.
    My problem is when I use the g_unrecoverable_error the printPDF works perfect but apex does not truncate the collection or clean the fields neither.
    I have an invoicing application, i want to click on "generate invoice" and do the insert, print pdf and refresh the page, so that when the user finish to print the invoice, the invoicing application is clean for make another invoice.
    Here's the code of the print pdf....
    DECLARE
               l_blob        BLOB;
               l_mime_type   VARCHAR2 (100 char);
               l_proc varchar2(100) := 'get report as blob, then show';
               l_additional_parameters varchar2(32767);
    BEGIN
          l_additional_parameters := 'USUARIO_CODIGO=' || apex_util.url_encode(:APP_USER);
          l_additional_parameters := l_additional_parameters||'&PRESUPUESTO_NUMERO='||apex_util.url_encode(:PRESUPUESTO_ID);
          xlog (l_proc, 'url (orig):' || 'http://Servidor-New:8181/JasperReportsIntegration/report');
       -- generate the report and return in BLOB
      xlib_jasperreports.set_report_url ('http://Servidor-New:8181/JasperReportsIntegration/report');
      xlib_jasperreports.get_report(
                                       p_rep_name => '&JASPER_HOME./PRESUPUESTO_CNO',
                                       p_rep_format => 'pdf',
                                       p_data_source => '&JASPER_HOME.',
                                       p_rep_locale => 'es_ES',
                                       p_additional_params => l_additional_parameters,
                                       p_out_blob            => l_blob,
                                       p_out_mime_type       => l_mime_type
       -- set mime header and filename
       OWA_UTIL.mime_header (ccontent_type      => l_mime_type,
                             bclose_header      => TRUE);
       -- send Content-Disposition and suggest a file name for saving
       htp.p('Content-Disposition: attachment; filename="'|| 'Presupuesto.pdf' ||'"');
       -- set content length
       HTP.p ('Content-length: ' || DBMS_LOB.getlength (l_blob));
       OWA_UTIL.http_header_close;
       -- download the file and display in browser
       WPG_DOCLOAD.download_file (l_blob);
       -- release resources
       DBMS_LOB.freetemporary (l_blob);
       -- stop rendering of APEX page
      apex_application.g_unrecoverable_error := TRUE;
    /* apex_application.stop_apex_engine;                               -------I PROVE WITH THIS ONE AND IT DOESN'T WORK
       apex_util.redirect_url (                                      --------IF I SET THE BUFFER RESET TO TRUE, IT CLEAN THE FIELDS BUT DON'T PRINT AND IF I SET TO FALSE IT PRINT BUT DON'T CLEAN THE FIELDS.
    p_url => 'f?p=&APP_ID.:30:' || :SESSION,
                              p_reset_htp_buffer => true ); */
        -- Limpieza de ITEMS collection
    apex_collection.truncate_collection(p_collection_name => 'ITEMS');  -----I TRIED TO PUT THIS PART UPPER THAN THE g_unrecoverable_erro BUT IS THE SAME THING.
    :P30_CI:='';
    :P30_NOMB_AP_PACIENTE:=' ';
    :P30_HISTORIA_PACIENTE:= NULL;
    :P30_RIF_RESP_PAGO:=' ';
    :P30_NOMBRE_RESP_PAGO:=' ';
    EXCEPTION
       WHEN OTHERS
       THEN
          xlog (l_proc, SQLERRM, 'ERROR');
          RAISE;
    END;
    I really aprecciate your help. Thank you Nicolette!!!
    Ricardo Capuz

  • Japanese text display problems in applet using plugin

    Hi,
    We've been beating our heads against the wall on this one for quite some time, so any help would be greatly appreciated.
    Our product uses a third party applet (Kavachart from Visual Engineering) to display graphical statistics from our database. We are currently localizing our product to support english and japanese. With Japanese enabled, all pages use euc-jp encoding. The problem we are running into is in the display of japanese text inside this applet in IE 5 and NS 4.7x when using the java plugin (1.3 or 1.4). If the default jre of the browsers are used, the text in the applet renders fine.
    On a suggestion from the supprot folks at Visual Engineering, I modified our code to set the defaultFont parameter on the applet to "serif, 14, 1". With this set, the text in the applet renders ok in IE, but NS on windows and unix is still broken. Given that we are doing all these tests on machines running a native japanese OS, it's not even clear to me why setting the defaultFont should even be required, but at this point, I'll take anything :-)
    Has anyone else run into this and either solved it or proven that a solution is not feasible? I'm at my wits end here....
    Thanks in advance,
    Mark Evangelisto
    Synchronicity Inc.

    If you are using different java plugin, you need to install the international version of the JRE; otherwise, some characters may not be able to display correctly since some of the properties files are missing.
    As for Visual Engineering's suggestion. I don't know why they tell you to set the default font on the applet because it may cause the browser to use the font specified. Your applet works on IE because it will try to use the best font to match the web page's content. For NS anything less then 6.0 (technology based on Mozilla), they never display web page correctly especially if you did what VE suggest.
    If you are running the applet on the native langauge OS with the international version of the JRE installed, the applet should display correctly without setting the default font. If it is not the native langauge OS, first you need to install the international version of the JRE and have the fonts that are able to display the language the applet use.

  • Java Pug-in 1.4.1_02 not closing sockets using URLConnection

    I am developing an applet that accesses a URL to get data to be displayed on the screen (Apache, mod_plsql). The problem is that when I execute the applet using "appletviewer" in my machine, each URLConnection shares only one socket connection to the WEB server. When the same applet is executed in the browser through the Java Plug-in 1.4.1_02, each URLConnection creates a new socket connection. Is there any bug? Is this a matter of configuration? Browser version? To test the applet I am using Forte for Java 4CE, JDK 1.4.1_02 (the same version as the Plug-in). I have tried many things already without success, there are no error messages in the server nor any exception on the applet. Both my machine and the server are Windows 2000 SP3.

    Have you found a solution to this? I'm having a similar problem with URLConnection always starting a new socket connection when run from within the Java Plug-In.

  • Please give me an exemple of an applet using a swing object.

    Please give me an exemple of an applet using a swing object.thank you.

    My problen is that the swing object do not appear in
    my applet. They appear only if i invoque the repaint
    methode.use JApplet, since awt components are heavyweight, and swing components are lightwieght, then your swing components get over painted with aplets background or something.
    anyhow, in your applet you may create JFrame, that would be swing component and if you set it visible, then it will be even visible.
    they say that mixing swing and awt is not good idea, especially when you don't know what you're doing (which might be true in your case)
    so try to migrate your app from AWT based stuff to SWING based stuff, or write your own AWT components that do the job whih you needed swing component for at the first place.
    but if you need to mix awt and swing, then i thing that you should not paint the fole area of applet in applets paint method -- but here i'm not sure, never mixed 'em.
    so you might try to create an applet which paint() method you leave empty and to which you add some JComponent*.
    and see what happens, maybe this JComponent will be visible.
    * -- JComponent is most likely just gray, you might want to add some subclass of it -- JButton, JTextField, JSomethingElse.

  • Chat Applet using RMI .... trouble running the Applet using the IE browser.

    Hi,
    I'm trying to run a chat application using RMI technology. Actually, this wasn't created from the scratch. I got this one from from the cd that comes with the book I bought and I did some refinements on it to suit what I wanted to:
    These are the components of the chat application:
    1. RApplet.html - invokes the applet
    html>
    <head>
    <title>Sample Applet Using Dialog Box (1.0.2) - example 1</title>
    </head>
    <body>
    <h1>The Sample Applet</h1>
    <applet code="RApplet.class" width=460 height=160>
    </applet>
    </body>
    </html>
    2. RApplet.java - Chat session client applet.
    import java.rmi.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import java.rmi.server.*;
    //import ajp.rmi.*;
    public class RApplet extends Applet implements ActionListener {
    // The buttons
    Button sendButton;
    Button quitButton;
    Button startButton;
    Button clearButton;
    // The Text fields
    TextField nameField;
    TextArea typeArea;
    // The dialog for entering your name
    Dialog nameDialog;
    // The name the server knows us as
    String privateName;
    // The name we want to be known as in the chat session
    String publicName;
    // The remote chats erver
    ChatServer chatServer;
    // The ChatCallback
    ChatCallbackImplementation cCallback;
    // The main Chat window and its panels
    Frame mainFrame;
    Panel center;
    Panel south;
    public void init() {
    // Create class that implements ChatCallback.
    cCallback = new ChatCallbackImplementation();
         // Create the main Chat frame.
         mainFrame = new Frame("Chat Server on : " +
                        getCodeBase().getHost());
         mainFrame.setSize(new Dimension(600, 600));
         cCallback.displayArea = new TextArea();
         cCallback.displayArea.setEditable(false);
         typeArea = new TextArea();
         sendButton = new Button("Send");
         quitButton = new Button("Quit");
         clearButton = new Button("Clear");
         // Add the applet as a listener to the button events.
         clearButton.addActionListener(this);
         sendButton.addActionListener(this);
         quitButton.addActionListener(this);
         center = new Panel();
         center.setLayout(new GridLayout(2, 1));
         center.add(cCallback.displayArea);
         center.add(typeArea);
         south = new Panel();
         south.setLayout(new GridLayout(1, 3));
         south.add(sendButton);
         south.add(quitButton);
         south.add(clearButton);
         mainFrame.add("Center", center);
         mainFrame.add("South", south);
         center.setEnabled(false);
         south.setEnabled(false);
         mainFrame.show();
         // Create the login dialog.
         nameDialog = new Dialog(mainFrame, "Enter Name to Logon: ");
         startButton = new Button("Logon");
         startButton.addActionListener(this);
         nameField = new TextField();
         nameDialog.add("Center", nameField);
         nameDialog.add("South", startButton);
         try {
         // Export ourselves as a ChatCallback to the server.
         UnicastRemoteObject.exportObject(cCallback);
         // Get the remote handle to the server.
         chatServer = (ChatServer)Naming.lookup("//" + "WW7203052W2K" +
                                  "/ChatServer");
         catch(Exception e) {
         e.printStackTrace();
         nameDialog.setSize(new Dimension(200, 200));
         nameDialog.show();
    * Handle the button events.
    public void actionPerformed(ActionEvent e) {
         if (e.getSource().equals(startButton)) {
         try {
              nameDialog.setVisible(false);;
              publicName = nameField.getText();
              privateName = chatServer.register(cCallback, publicName);
              center.setEnabled(true);
              south.setEnabled(true);
              cCallback.displayArea.setText("Connected to chat server as: " +
                             publicName);
              chatServer.sendMessage(privateName, publicName +
                             " just connected to server");
         catch(Exception ex) {
              ex.printStackTrace();
         else if (e.getSource().equals(quitButton)) {
         try {
              cCallback.displayArea.setText("");
              typeArea.setText("");
              center.setEnabled(false);
              south.setEnabled(false);
              chatServer.unregister(privateName);
              nameDialog.show();
         catch(Exception ex) {
              ex.printStackTrace();
         else if (e.getSource().equals(sendButton)) {
         try{
              chatServer.sendMessage(privateName, typeArea.getText());
              typeArea.setText("");
         catch(Exception ex) {
              ex.printStackTrace();
         else if (e.getSource().equals(clearButton)) {
         cCallback.displayArea.setText("");
    public void destroy() {
         try {
         super.destroy();
         mainFrame.setVisible(false);;
         mainFrame.dispose();
         chatServer.unregister(privateName);
         catch(Exception e) {
         e.printStackTrace();
    3. Chatcallback.java - interface used by clients to connect to the server.
    import java.rmi.*;
    public interface ChatCallback extends Remote {
    public void addMessage(String publicName,
                   String message) throws RemoteException;
    4. ChatcallbackImplementation.java - implements Chatcallback interface.
    import java.rmi.*;
    import java.io.*;
    import java.awt.event.*;
    import java.awt.*;
    public class ChatCallbackImplementation implements ChatCallback {
    // The buttons
    // The Text fields
    TextArea displayArea;
    public void addMessage(String publicName,
                   String message) throws RemoteException {
    displayArea.append("\n" + "[" + publicName + "]: " + message);
    5. Chatserver.java - interface for the chat server.
    import java.rmi.*;
    import java.io.*;
    public interface ChatServer extends Remote {
    public String register(ChatCallback object,
                   String publicName) throws RemoteException;
    * Remove the client associated with the specified registration string.
    * @param registeredString the string returned to the client upon registration.
    public void unregister(String registeredString) throws RemoteException;
    * The client is sending new data to the server.
    * @param assignedName the string returned to the client upon registration.
    * @param data the chat data.
    public void sendMessage(String registeredString, String message) throws RemoteException;
    6. ChatServerImplementation.java - implements Chatserver interface.
    import java.rmi.*;
    import java.util.*;
    import java.rmi.server.*;
    import java.io.*;
    * A class that bundles the ChatCallback reference with a public name used
    * by the client.
    class ChatClient {
    private ChatCallback callback;
    private String publicName;
    ChatClient(ChatCallback cbk, String name) {
         callback = cbk;
         publicName = name;
    // returns the name.
    String getName() {
         return publicName;
    // returns a reference to the callback object.
    ChatCallback getCallback() {
         return callback;
    public class ChatServerImplementation extends UnicastRemoteObject
    implements ChatServer {
    // The table of clients connected to the server.
    Hashtable clients;
    // Tne number of current connections to the server.
    private int currentConnections;
    // The maximum number of connections to the server.
    private int maxConnections;
    // The output stream to write messages to.
    PrintWriter writer;
    * Create a ChatServer.
    * @param maxConnections the total number if connections allowed.
    public ChatServerImplementation(int maxConnections) throws RemoteException {
         clients = new Hashtable(maxConnections);
         this.maxConnections = maxConnections;
    * Increment the counter keeping track of the number of connections.
    synchronized boolean incrementConnections() {
         boolean ret = false;
         if (currentConnections < maxConnections) {
         currentConnections++;
         ret = true;
         return ret;
    * Decrement the counter keeping track of the number of connections.
    synchronized void decrementConnections() {
         if (currentConnections > 0) {
         currentConnections--;
    * Register with the ChatServer, with a String that publicly identifies
    * the chat client. A String that acts as a "magic cookie" is returned
    * and is sent by the client on future remote method calls as a way of
    * authenticating the client request.
    * @param object The ChatCallback object to be used for updates.
    * @param publicName The String the object would like to be known as.
    * @return The actual String assigned to the object for removing, etc. or
    * null if the client could not register.
    public synchronized String register(ChatCallback object, String publicString) throws RemoteException {
         String assignedName = null;
         if (incrementConnections()) {
         ChatClient client = new ChatClient(object, publicString);
         assignedName = "" + client.hashCode();
         clients.put(assignedName, client);
         out("Added callback for: " + client.getName());
         return assignedName;
    * Remove the client associated with the specified registration string.
    * @param registeredString the string returned to the client upon registration.
    public synchronized void unregister(String registeredString) throws RemoteException {
         ChatCallback cbk;
         ChatClient sender;
         if (clients.containsKey(registeredString)) {
         ChatClient c = (ChatClient)clients.remove(registeredString);
         decrementConnections();
         out("Removed callback for: " + c.getName());
         for (Enumeration e = clients.elements(); e.hasMoreElements(); ) {
              cbk = ((ChatClient)e.nextElement()).getCallback();
              cbk.addMessage("ChatServer",
                        c.getName() + " has left the building...");
         else {
         out("Illegal attempt at removing callback (" + registeredString + ")");
    * Sets the logging stream.
    * @param out the stream to log messages to.
    protected void setLogStream(Writer out) throws RemoteException {
         writer = new PrintWriter(out);
    * The client is sending new message to the server.
    * @param assignedName the string returned to the client upon registration.
    * @param data the chat data.
    public synchronized void sendMessage(String registeredString, String message) throws RemoteException {
         ChatCallback cbk;
         ChatClient sender;
         try {
         out("Recieved from " + registeredString);
         out("Message: " + message);
         if (clients.containsKey(registeredString)) {
              sender = (ChatClient)clients.get(registeredString);
              for (Enumeration e = clients.elements(); e.hasMoreElements(); ) {
                   cbk = ((ChatClient)e.nextElement()).getCallback();
                   cbk.addMessage(sender.getName(), message);
         else {
              out("Client " + registeredString+ " not registered");
         catch(Exception ex){
         out("Exception thrown in newData: " + ex);
         ex.printStackTrace(writer);
         writer.flush();
    * Write s string to the current logging stream.
    * @param message the string to log.
    protected void out(String message){
         if(writer != null){
         writer.println(message);
         writer.flush();
    * Start up the Chat server.
    public static void main(String args[]) throws Exception {
         try {
         // Create the security manager
         System.setSecurityManager(new RMISecurityManager());
         // Instantiate a server
         ChatServerImplementation c = new ChatServerImplementation(10);
         // Set the output stream of the server to System.out
         c.setLogStream(new OutputStreamWriter(System.out));
         // Bind the server's name in the registry
         Naming.rebind("//" + args[0] + "/ChatServer", c);
         c.out("Bound in registry.");
         catch (Exception e) {
         System.out.println("ChatServerImplementation error:" +
                        e.getMessage());
         e.printStackTrace();
    Using my own machine (connected to a network), I tried to test this one out by setting mine as the server and also the client. I did the following:
    1. Compile the source code.
    2. Use rmic to generate the skeletons and/or stubs from the ChatCallbackImplementation and ChatServerImplementation.
    3. Start the rmiregistry with no CLASSPATH
    4. Start the server successfully.
    5. Start the applet using the AppletViewer command.
    It worked fined.
    The problem is when I ran the applet using the browser, IE explorer, the dialog boxes, frame and buttons did appear. I was able to do the part of logging on. But after that, the applet seemed to have hang. No message appeared that says I'm connected (which appeared using the appletviewer). I clicked the send button. No response.
    I double-checked my classpath. I did have my classpath set correctly. I'm still trying to figure out the problem. Up to now, I don't have any clue what it is.
    I will appreciate much if someone can help me figure what's could have possibly been wrong ....
    Thanks a lot ...

    Hi Domingo,
    I had a similar problem running applet/rmi with IE.
    Looking in IE..view..JavaConsole error messages my applet was unable to find java.rmi.* classes.
    I checked over java classes in msJVM, they're not present.
    ( WinZip C:\WINDOWS\JAVA\Packages\9rl3f9ft.zip and others from msVM installed )
    ( do not contain the java.rmi.* packages )
    I have downloaded and installed the latest msJVM for IE5. ( I think its included in later versions)
    @http://www.objectweb.org/rmijdbc/RJfaq.html I found ref to rmi.zip download to provide
    these classes. I couldn't get the classes from the site but I managed to find a ref to IBM
    site @http://alphaworks.ibm.com/aw.nsf/download/rmi which had similar download.
    The download however didn't solve my problems. I was unable to install rmi.zip with
    RmiPatch.exe install.
    I solved this by extracting the class files from rmi.zip and installing them at C:\WINDOWS\JAVA\trustlib ( msJVM installation trusted classes lib defined in
    registry HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Java VM\TrustedLibsDirectory )
    This solved the problem. My rmi/applet worked.
    Hope this helps you.
    Chris
    ([email protected])

  • Swing Applet using JSObject.getWindow can not use javaFX

    I have a Swing Applet that I will like to extend with some javaFX 2.0.3 abilities.
    The Swing Applet uses the JSObject.getWindow method which is part of plugin.jar.
    When I add javaFX I am not able to compile my application as jfxrt.jar also has a JSObject implementation, but without the getWindow method.
    Is there any way I can extend my existing applet with javaFX?

    The order of dependencies is probably not the issue here but rather that there are two classes with the same fully qualified name which causes problems if the signatures differ

  • Applet using NetBeans 3.6

    I have just started using NetBeans 3.6, and I'm new to applets. I have a sample applet which runs OK with all browsers when I use the .class file already supplied by the creator of the applet.
    However, after compiling within NetBeans 3.6 (J2SE 1.4), it runs only when using the AppletViewer within the NetBeans. It does not execute when I shift the browser to Internet Explorer within NetBeans, or when I try to do it through a HTML file outside NetBeans.
    I noticed that this behaviour starts after creating the .class file with NetBeans. If I create the .class file using the javac compiler in a Solaris computer I have access to, it executes both in the Solaris machine (Netscape browser) and in a PC.
    Does anybody have an idea of what is going on? Thanks.

    In the package (folder) which the applet Java exists there is an HTML of the same name. This is used by the AppletViewer to define parameters and settings for the applet when it's loaded. Try viewing the applet using that HTML page.
    Right mouse click on your applet Java file and make sure your properties in NetBeans for the debug is set to Applet Debugging. By defailt NetBeans will assume a Java file is not an applet and will try to debug it as a java application.
    However, after compiling within NetBeans 3.6 (J2SE
    1.4), it runs only when using the AppletViewer within
    the NetBeans. It does not execute when I shift the
    browser to Internet Explorer within NetBeans, or when
    I try to do it through a HTML file outside NetBeans.You can enable the displaying of the Java console for the Explorer Java plug-in. This will allow you to see any exceptions happening which might be causing your problem. If no exceptions are happening, then it's likely the class path in the packages don't match where your running it from.
    I noticed that this behaviour starts after creating
    the .class file with NetBeans. If I create the .class
    file using the javac compiler in a Solaris computer I
    have access to, it executes both in the Solaris
    machine (Netscape browser) and in a PC.Try building a JAR file, and running your applet from the jar in Explorer. Running from classes can cause problems if the folders they exist in don't map out the same as the packages.

  • Problem in loading an applet using JRE 1.5

    Hi,
    I have an applet which is working fine under JRE 1.4, but the same applet failing to load by using JRE 1.5
    Problem Description:
    1. The images in the applet fails to load using JRE 1.5
    2. The Username and Password text box are also failing to initialize.
    Can anyone help me out in this.
    Is there any code changes required ?

    I wonder if you have the same problem as me... Maybe we can find a solution for us both, no need for me to open a new thread for this topic then...
    I wrote an applet using Swing and compiled it using JavaSDK 1.4.x. I also installed the 1.4.x JRE for both of my test browsers. In Mozilla 1.1 the applet displays properly all the time. In IE6 SP1 it sometimes works as intended but sometimes the applet simply stops working, as per my Java Console somewhere after invoking the "start" method. Parts of the applet simply become gray and when I resize it - I have a JFrame in my applet - the whole JFrame becomes gray and does not respond to input nor it redraws itself. Shutting down IE does not close the JFrame(although the java console reports normal program termination and cleanup) and the only way to close it is through the task manager. I am using Windows 98SE btw.
    Does it sound similiar to your problem? It happens ONLY with IE, not with Mozilla. Anybody has an idea on what it could be? I doubt there's an error in my code...

  • I am in process of unlocking my iphone and need to restore my phone backed it up already but ituenes will not let me restore keeps telling me ituenes can not get on the internet no connection with is not true cause otherwise you would not have gotten this

    I have contacted at&t and they did what was nessary to unlock my phone was told to backup my phone and did that so know I just need to restore my phone with ituens which ituenes will not let me do cause I get message can not connect to cause of no internet connection wich is not true cause other wise you would not have gotten this

    Try restoring the iPhone to factory settings. If you are having difficult restoring, put the iPhone into Recovery Mode and see if that then works:
    http://support.apple.com/kb/ht1808
    If not, or if a restore to factory settings does not fix the problem, then your iPhone may have a hardware problem. You can only get the iPhone serviced by Apple in Canada, so you will have to take the iPhone there or send it to someone you know in Canada who can get the iPhone serviced and send it back to you. The only option for getting service in Pakistan would be to pay some unauthorized repair shop to attempt a repair, after which Apple will no longer provide any service even in Canada.
    Regards.

  • Writing new HTML to a page from an applet using LiveConnect, 1.3.1 Plug-i

    Has anyone been able to successfully replace a page with an applet with the dynamically generated HTML from an applet using LiveConnect and Plugin 1.3.1 in Netscape 6.2 or IE?
    The following works fine without plugin or with 1.4.0 beta3 plugin.
    Here is the code that I use without plugin:
    JSObject windowObject = JSObject.getWindow(this);
    JSObject documentObject = (JSObject) windowObject.getMember("document");
    documentObject.call("close",null);
    documentObject.call("open",null);
    String anArray1[] = {null};
    anArray1[0] ="some HTML here";
    documentObject.call("write", anArray1);
    documentObject.call("close",null);
    Here is the code that I use with 1.4.0 plugin:
    JSObject windowObject = JSObject.getWindow(this);
    JSObject documentObject = (JSObject) windowObject.getMember("document");
    String anArray1[] = {null};
    anArray1[0] ="some HTML here";
    documentObject.call("write", anArray1);
    When I try to use anyone of the above using plugin 1.3.1, the browser either hangs or plugin generates runtime error. What is the correct way of writing to a document object? Or what is the way that works for 1.3.1 plugin?

    Hi,
    I am doing this in my applet to replace the page containing the applet with the new content. I tested that extensively with Netscape 4.7 and IE 5.5+. Definitely works if you are using Java Plug-In 1.3.1_02. Does not work well in Netscape 6.2.
        protected void setPageContent(final String newContent) {
            final JSObject window = JSObject.getWindow(this);
            final JSObject document = (JSObject) window.getMember("document");
            new Thread( new Runnable() {
                            public void run() {
                                document.call("clear", null);
                                document.call("write", new String[]{newContent});
                                try {
                                              document.call("close", null);
                                   } catch (JSException ignored) {
                        } ).start();

Maybe you are looking for

  • How to set up 2 agreements for the same From,To,DocType,Version in B2B11g

    Hi I am having an issue in configuring more than one agreement for the same DocType, Version, From and To partner in Oracle B2B11g. When I click "Valid" button on the second agreement it errors out saying duplicate agreement is found for the same Doc

  • HOW TO VIEW .PDF FILES IN ITOUCH4 .

    I DO NOT HAVE INTERNET CONNECTION . CAN ANYONE HELP ME IN VIEWING .PDF FILES LOCALLY WITHOUT INTERNET CONNECTION.DO ITOUCH4 HAVE BUILT IN FEATURE TO VIEW .PDF FILES.

  • Can I connect the mini to an older G5?

    Can I connect the new iMac Mini to an older Power PC G5 (3.0) and make the mini the dominant hard drive?

  • ORDERS05 enhanced with WEMPF and ABLAD

    Hi I need to enhance ORDERS05 Idoc used for Purchase Orders with Reciepient EKKN -WEMPF and Unloading Point EKKN-ABLAD. In my case Reciepient and Unloading point are both text fields used in PO in order to indicate to suuplier where and to whom goods

  • UME Administration Software Component has no DCs in it?

    Hi, I've successfully imported the "UME ADMINISTRATION 7.00" SC for Netweaver 2004s SP10 patch level 0 (and all buildtime required SCs) in a development track, but the Component Build Service says there is nothing to build. The build compartment for