Solved

Problems with Applet/Servlet communication with serialization

Posted on 2003-12-05
9
3,095 Views
Last Modified: 2013-11-24
Hi,

I have a test JApplet with a tread running. Every X seconds, the tread sends a serialized Vector to the servlet as a http request and receives a serialized Vector as a http response. I have two questions:

1)  In my applet, I have a Thread with the inner class UpdateHandler as its runnable target. In UpdateHandler, the above mentioned applet-servlet communication takes place.
When running my applet, I got an exception: java.io.NotSerializedException for UpdateHandler, and when I let UpdateHanler implement Serializable, that error seemed to be fixed. Then I got the same error for the Tread _updateThread. I created an inner class UpdateTread which extends Thread and implements Serializable. Now both errors were gone. Seems strange to me that the objects containing the code for sending an object to/from the servlet, also need to be Serializable, not only the passed Vector. Why is it so?

2)  When the NotSerializedExceptions are gone, I get another error when trying to read the response from servlet, when instantiating new ObjectInputStream(servletConnection.getInputStream())   - see posted code. The exception is:

java.io.FileNotFoundException: http://hostIP:portNo./emilion/servlet/result/TestServlet
      at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:707)
      at sun.plugin.net.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:384)
      at result.TestApplet$UpdateHandler._requestResultsFromServlet(TestApplet.java:158)
      at result.TestApplet$UpdateHandler._requestResults(TestApplet.java:117)
      at result.TestApplet$UpdateHandler.run(TestApplet.java:99)
      at java.lang.Thread.run(Thread.java:536)


Any ideas what causes the error? Help greatly appreciated!



package result;

import java.awt.*;
import java.util.*;
import java.net.URL;
import java.net.URLConnection;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import javax.swing.*;

public class TestApplet extends JApplet implements {

  private UpdateHandler _updateHandler;
  private Thread _updateThread;
  private URL _resultServlet;

  public void init() {
    super.init();

    try {
      String servletPath = "/emilion/servlet/result/TestServlet";
      _resultServlet = new URL("http", getCodeBase().getHost(), getCodeBase().getPort(), servletPath);
    } catch(Exception x) {
      x.printStackTrace();
    }

    // Set up the GUI  
    QCPanel bigViewPanel = new QCPanel();
    QCLabel label = new QCLabel("TEST TEST");
    bigViewPanel.add(label);
    getContentPane().add(bigViewPanel, BorderLayout.CENTER);

    // Updating thread
    _updateHandler = new UpdateHandler();
    _updateThread = new UpdateTread(_updateHandler);
    _updateThread.start();
  }

  private class UpdateTread extends Thread implements Serializable {
    public UpdateTread(UpdateHandler updateHandler) {
      super(updateHandler);
    }
  }

  private class UpdateHandler implements Runnable, Serializable {
    public final static int UPDATE_INTERVAL = 10;

    public UpdateHandler() {
    }

    public void run() {
      try {
          _requestFromServlet();
          // Update GUI with responded data from servlet
          //…..
      } catch (InterruptedException ie) {
      }
    }

    private synchronized void _ requestFromServlet () throws InterruptedException {
      while(true) {
         _request();    
        wait(UPDATE_INTERVAL*1000);
      }
    }

    public Vector _request() {
      ObjectOutputStream outputToServlet;
      ObjectInputStream inputFromServlet;

      Vector testVector = new Vector();
      testVector.add("AAA");
      testVector.add("BBB");
      testVector.add("CCC");

      try {
        // Set up servlet connection
        URLConnection servletConnection = _resultServlet.openConnection();
        servletConnection.setDoInput(true);
        servletConnection.setDoOutput(true);
        servletConnection.setUseCaches(false);
        servletConnection.setDefaultUseCaches(false);
        servletConnection.setRequestProperty("Content-Type", "application/octet-stream");

        // REQUEST
        // Send testVector to servlet
        outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());
        outputToServlet.writeObject(testVector);
        outputToServlet.flush();
        outputToServlet.close();

        // RESPONSE
        // Read the response from the servlet. The servlet will return a sericalized Vector containing
        // Objects (just for testing)
        inputFromServlet = new ObjectInputStream(servletConnection.getInputStream()); //THIS IS WHERE THE EXCEPTION OCCURS
        Vector vectorFromServlet = (Vector)inputFromServlet.readObject();
        inputFromServlet.close();

        return vectorFromServlet;

      } catch(Exception x) {
        x.printStackTrace();
        return null;
      }
    }

  }
 
}




package result;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;

public class TestServlet extends HttpServlet {

  private Vector _viewModels;
  private Vector _viewsFromApplet;

  public void init() {
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {

    ObjectInputStream inputFromApplet = null;
    _viewsFromApplet = null;

    try {
      // Get an input stream from the applet
      inputFromApplet = new ObjectInputStream(request.getInputStream());
      _viewsFromApplet = (Vector)inputFromApplet.readObject();
      inputFromApplet.close();
    } catch(Exception x) {
      x.printStackTrace();
    }

    //Respond to applet
    try {
      _respondResultsToApplet(response, _getObjectVector());
    } catch(Exception x) {
      x.printStackTrace();
    }
  }

  public void doGet(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, IOException {
    doPost(req, resp);
  }

  private void _respondResultsToApplet(HttpServletResponse response, Vector objects) throws Exception {

    if (objects != null) {
      ObjectOutputStream outputToApplet = new ObjectOutputStream(response.getOutputStream());

      outputToApplet.writeObject(objects);
      outputToApplet.flush();
      outputToApplet.close();

    } else {

    }
  }

  private Vector _getObjectVector() {
    // Handle input data from applet
    ///...
    // Objects to be passed back to applet
    Vector v = new Vector();
    v.add(new Object());
    v.add(new Object());
    return v;

  }
}
0
Comment
Question by:MarteJ
  • 4
  • 3
  • 2
9 Comments
 

Author Comment

by:MarteJ
ID: 9881723
Note: replace QCPanel and QCLabel with JPanel and JLabel....:-)
0
 
LVL 35

Expert Comment

by:girionis
ID: 9881762
> Seems strange to me that the objects
>containing the code for sending an object
>to/from the servlet, also need to be
>Serializable, not only the passed Vector. Why
>is it so?

  This is weird.. You shouldn't serialize the object itself if you do not serialize it, just the object that you send through the ObjectInputStream and ObjectOutStream. Are you sure you are not sending the object itself ( UpdateHandler)?

>The exception is:
>
>java.io.FileNotFoundException: http://hostIP:portNo./emilion/servlet/result/TestServlet
>
> Any ideas what causes the error? Help greatly appreciated!

  Can it be the dot you have after the port number?
0
 
LVL 35

Accepted Solution

by:
girionis earned 500 total points
ID: 9881770
 Ahh... you need to use the package of the servlet also:

>http://hostIP:portNo./emilion/servlet/result/TestServlet

  should be:

http://hostIP:portNo/emilion/servlet/result.TestServlet

  or if you indeed have a folder result - apart from the one in the package

http://hostIP:portNo/emilion/servlet/result/result.TestServlet
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9881821
I can see two possible problems with that url. Try

       String servletPath = "./emilion/servlet/result/TestServlet";
      _resultServlet = new URL(getCodeBase(), servletPath);
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Author Comment

by:MarteJ
ID: 9881837
Thanks for quick respond.

2) I just replaced my host IP adress and port number with "hostIP:portNo.", where the portNo. is a 4 digit number.

1) I removed the implementation of Serializable and the error is not there any more... But I get it in my original applet, not this test applet, but that's another story...

I still get the FileNotFoundException, though.


0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9881854
>>I still get the FileNotFoundException, though.

Including trying my suggestion?
0
 
LVL 35

Expert Comment

by:girionis
ID: 9881926
 Have you also checked about the dot (.) after the port number or is it just a syntax error?
0
 

Author Comment

by:MarteJ
ID: 9881978
CEHJ,
I posted my previous comment before refreshing this page. Now that I have tried your suggestion I get the following error:

Bad URL in getProxySettings: http://<hostIP>:<port>./emilion/servlet/result/TestServlet

when I add the dot at the beginning of the path.
Thanks anyway!

girionis,

The following address worked - thanks!

http://hostIP:portNo/emilion/servlet/result.TestServlet

In my original applet, I still need to figure out the Serialization trouble, I might have to come back to that later...

Thanks to all who take the time to help, I really appreciate it. Hope you approve with how I accept answers, please tell me if I am not follwing the standard.
0
 
LVL 35

Expert Comment

by:girionis
ID: 9882004
>In my original applet, I still need to figure out
>the Serialization trouble, I might have to come
>back to that later...

  You *only* need to serialize the objects you are sending across the wire, nothing else. I would infer from the original error message that you are trying to send an object (maybe accidentally) that is not serializable.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Protect jar file - windows app 2 38
Which is the latest version of Apache Tomcatl 3 50
eclipse java  build path 6 44
reverse digits of a number using for loop 5 36
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This video teaches viewers about errors in exception handling.

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now