Solved

How to call a Java applet function (using network/URL object) from a JavaScript for Netscape navigator LEGALLY??

Posted on 1997-08-02
10
271 Views
Last Modified: 2008-03-03
 As title, same thing works for IE3, but it won't be allowed in Netscape Navigator (no matter for verion 3 or 4).
  So, any solution for that??

  Appreciate your time and help
(Please E-mail me if possible)

Ok... here is the example...

//Java code!!
import java.awt.*;
import java.applet.*;
import java.io.*;
import java.net.*;

public class test extends Applet {
      public String getDesc(String itemName)
      {
            if (urlDescFile=="")
                  return "no urlDescFile is dedicated";
            String tmp=new String("");
            try{
                  URL url=new URL(this.getCodeBase().toString()+urlDescFile);
                  URLConnection connection=url.openConnection();

                  PrintStream os=new PrintStream(connection.getOutputStream());
                  os.println("itemName="+URLEncoder.encode(itemName));
                  os.close();

                  DataInputStream is=new DataInputStream(connection.getInputStream());
                  String inputLine=new String("");
                  while ((inputLine=is.readLine())!=null)
                        tmp+=inputLine+"\r\n";
                  is.close();
            } catch (MalformedURLException me)
            {
                  return this.getCodeBase().toString()+urlDescFile+"X MalformedURLException: "+me;
            } catch (IOException ioe)
            {
                  return this.getCodeBase().toString()+urlDescFile+"X IOException: "+ioe;
            }
            return tmp;
      }
}

// try the applet tag and JavaScript in your onClick event for a button in your HTML page
<applet code=test.class name=t1>
...
<input type="button" name="B1"
value="test"
language="JavaScript"
onclick="alert(document.t1.getDesc())">
//That's all
0
Comment
Question by:yangsen
  • 5
  • 5
10 Comments
 
LVL 1

Expert Comment

by:fun
ID: 1268826
I don't understand. please explain and provide an example.
0
 

Author Comment

by:yangsen
ID: 1268827
Edited text of question
0
 
LVL 1

Expert Comment

by:fun
ID: 1268828
Your example was very deficient. The java code wouldn't even compile.  However I have fixed it up and made it work. If you would like to see it, it will cost you 200 points.
0
 

Author Comment

by:yangsen
ID: 1268829
Hmm... in the example, I just put the main part in the  java applet (I don't think I have to put everything, do I?), so it won't work if you don't put something more there... Of course, my original java applet works/compiles fine for IE3...
Ok, I already increased points to 200. If you really fix the problem, the point is yours :) (PS. must work fine for Netscape)

0
 
LVL 1

Expert Comment

by:fun
ID: 1268830
The first thing is that the javascript call to getDesc was to a function with no arguments, but the java method had arguments, so there was a mismatch. Here is the fixed up html file. I do not know what the point of this applet is so you will have to adjust the argument to make sense.

          <html>
<head>
</head>
<body>
<applet code=test.class name=t1>
</applet>
<form>
<input type="button" onclick="alert(document.t1.getDesc('b'))">
</form>
</body>
</html>

The java applet did not define all its variables so the compiler complained. I hade to put in a declaration for the variable urlDescFile. I have no idea where that variable was supposed to come from. This class will never give meaningful results because there is no place to redefine that value and so the null case will always predominate. Since the variable is never set to a value, it would never become an empty string, only a null. Therefore, I changed the value of the conditional to match. I also don't understand the purpose and value of the various input and output streams, although that might be evident if I knew what you were trying to do.
At any rate, if you compile the code below, the html above will access it and run the method getDesc and reply that
'no urlDescFile is dedicated', because it isn't and never will be. Thus the javascript will have accessed the applet and run it.

Before you try to recompile this code, remember to remove any stray line breaks.

               //Java code!!
               import java.awt.*;
               import java.applet.*;
               import java.io.*;
               import java.net.*;

               public class test extends Applet {
//added next line
                String urlDescFile;
               public String getDesc(String itemName)
               {
//changed next line
               if (urlDescFile==(null))
               return "no urlDescFile is dedicated";
               String tmp=new String("");
               try{
               URL url=new URL(this.getCodeBase().toString()+urlDescFile);
               URLConnection connection=url.openConnection();

               PrintStream os=new PrintStream(connection.getOutputStream());
               os.println("itemName="+URLEncoder.encode(itemName));
               os.close();

               DataInputStream is=new
               DataInputStream(connection.getInputStream());
               String inputLine=new String("");
               while ((inputLine=is.readLine())!=null)
               tmp+=inputLine+"\r\n";
               is.close();
               } catch (MalformedURLException me)
               {
               return this.getCodeBase().toString()+urlDescFile+"X MalformedURLException: "+me;
               } catch (IOException ioe)
               {
               return this.getCodeBase().toString()+urlDescFile+"X IOException:"+ioe;
               }
               return tmp;
               }
               }

0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

Author Comment

by:yangsen
ID: 1268831
Sorry, maybe I didn't make it clear enough in my question...
My Java code ,JavaScript, and HTML page works fine in IE3.
But Netscape navigator won't allow me to call the java applet function from javascript because the function uses network objects like URL. (If I call a applet function without using network object, everything goes fine in both IE3 and Netscape)

I appology for my ingorance I didn't make it accurate enough when I gave the example. (like lost the parameter when calling the applet funtion, and made you waste time on that)

P.S. I wrote this java applet because I want to put description from a homepage instantly in an editbox when a user click/change one a listbox. (of course java script doesn't provide such a function/object to handle that)

Anyway, I repost ALL the stuff (java applet and the html page), so you just copy and past... thanks a lot

//------------------Java applet-----------
//please focus on the getDesc(string str) function
import java.awt.*;
import java.applet.*;
import java.io.*;
import java.net.*;

public class jlist extends Applet {

      int m_height=0, m_width=0;
      String urlDescFile=new String();

      public String getDesc(String itemName)
      {
            if (urlDescFile=="")
                  return "no urlDescFile is dedicated";
            String tmp=new String("");
            try{
                  URL url=new URL(this.getCodeBase().toString()+urlDescFile);
                  URLConnection connection=url.openConnection();

                  PrintStream os=new PrintStream(connection.getOutputStream());
                  os.println("itemName="+URLEncoder.encode(itemName));
                  os.close();

                  DataInputStream is=new DataInputStream(connection.getInputStream());
                  String inputLine=new String("");
                  while ((inputLine=is.readLine())!=null)
                        tmp+=inputLine+"\r\n";
                  is.close();
            } catch (MalformedURLException me)
            {
                  return this.getCodeBase().toString()+urlDescFile+"X MalformedURLException: "+me;
            } catch (IOException ioe)
            {
                  return this.getCodeBase().toString()+urlDescFile+"X IOException: "+ioe;
            }
            return tmp;
      }

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

            String param;
            param = getParameter("height");
            if (param != null)
                  m_height = Integer.parseInt(param);
            param = getParameter("width");
            if (param != null)
                  m_width = Integer.parseInt(param);
            param = getParameter("urlDescFile");
            if (param != null)
                  urlDescFile = param;
            param = getParameter("urlAssocFile");
            if (param != null)
                  urlAssocFile = param;

            //{{INIT_CONTROLS
            setLayout(null);
            addNotify();
            resize(m_width,m_height);
            list1 = new java.awt.List(0,false);
            add(list1);
            list1.reshape(0,0,m_width,m_height);
            list1.setBackground(new Color(12632256));
            //}}
      }

      public boolean handleEvent(Event event) {
            return super.handleEvent(event);
      }

      //{{DECLARE_CONTROLS
      java.awt.List list1;
      //}}
}

//-------------------------------------------------------------
// here is the homepage
<html>
<body bgcolor="#FFFFFF">

<form method="POST" name="form1">
    <p>user:</p>
    <p><select name="user" size="1" language="JavaScript"
    onchange="var i=document.form1.user.options.selectedIndex
var s=document.form1.user.options[i].text
document.form1.Description.value=document.jlist1.getDesc(s)">
        <option> user1 </option>
        <option> user2 </option>
        <option> user3 </option>
    </select> </p>
    <p>description:</p>
    <p><textarea name="Description" rows="2" cols="20">
</textarea></p>
</form>

<p><applet code="jlist.class" align="baseline" width="5"
height="5" name="jlist1"><param name="urlFile" value="test.htm"></applet></p>
</body>
</html>

0
 

Author Comment

by:yangsen
ID: 1268832
Please ignore the previous comment (still some error there...)
here is the better one:
--------------------------------------------------------------------
Sorry, maybe I didn't make it clear enough in my question...
My Java code ,JavaScript, and HTML page work fine in IE3.
But Netscape navigator won't allow me to call the java applet function from javascript because the function uses network objects like URL. (If I call a applet function without using network object, everything goes fine in both IE3 and Netscape)

I appology for my ignorance I didn't make it accurate enough when I gave the example. (like lost the parameter when calling the applet funtion, and made you waste time on that)

P.S. I wrote this java applet because I want to put description from a homepage instantly in an editbox when a user click/change one a listbox. (of course java script doesn't provide such a function/object to handle that)

Anyway, I repost ALL the stuff (java applet and the html page), so you just copy and past... thanks a lot

//------------------Java applet-----------
//please focus on the getDesc(string str) function
import java.awt.*;
import java.applet.*;
import java.io.*;
import java.net.*;

public class jlist extends Applet {

      int m_height=0, m_width=0;
      String urlDescFile=new String();

      public String getDesc(String itemName)
      {
            if (urlDescFile=="")
                  return "no urlDescFile is dedicated";
            String tmp=new String("");
            URL url;
            try{
                  url=new URL(this.getCodeBase().toString()+urlDescFile);
                  URLConnection connection=url.openConnection();

                  PrintStream os=new PrintStream(connection.getOutputStream());
                  os.println("itemName="+URLEncoder.encode(itemName));
                  os.close();

                  DataInputStream is=new DataInputStream(connection.getInputStream());
                  String inputLine=new String("");
                  while ((inputLine=is.readLine())!=null)
                        tmp+=inputLine+"\r\n";
                  is.close();
            } catch (MalformedURLException me)
            {
                  return this.getCodeBase().toString()+urlDescFile+"X MalformedURLException: "+me;
            } catch (IOException ioe)
            {
                  return this.getCodeBase().toString()+urlDescFile+"X IOException: "+ioe;
            }
            return tmp;
      }

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

            String param;
            param = getParameter("height");
            if (param != null)
                  m_height = Integer.parseInt(param);
            param = getParameter("width");
            if (param != null)
                  m_width = Integer.parseInt(param);
            param = getParameter("urlDescFile");
            if (param != null)
                  urlDescFile = param;

      }

}

//-------------------------------------------------------------
// here is the homepage
<html>
<body bgcolor="#FFFFFF">

<form method="POST" name="form1">
    <p>user:</p>
    <p><select name="user" size="1" language="JavaScript"
    onchange="var i=document.form1.user.options.selectedIndex
var s=document.form1.user.options[i].text
document.form1.Description.value=document.jlist1.getDesc(s)">
        <option> user1 </option>
        <option> user2 </option>
        <option> user3 </option>
    </select> </p>
    <p>Description:</p>
    <p><textarea name="Description" rows="2" cols="20">
</textarea></p>
</form>

<p><applet code="jlist.class" align="baseline" width="5"
height="5" name="jlist1"><param name="urlDescFile" value="test.htm"></applet></p>
</body>
</html>

0
 
LVL 1

Accepted Solution

by:
fun earned 200 total points
ID: 1268833
This has turned into strictly a java question, but here goes. I compiled your code and ran it in NN3.01 I am afraid that you are out of luck there. It does not support the IO features you want. However, NN4.01 in Communicator runs it the same as IE3.02. There is still a problem in that neither function with the output stream. I really don't understand what you meant for that to do. I removed the three lines

PrintStream os=new PrintStream(connection.getOutputStream());
os.println("itemName="+URLEncoder.encode(itemName));
os.close();

and the program seems to do what you wanted. It takes the code in test.htm and puts it into the text box. If you explain what it is you mean for these lines to do, I might be able to suggest a solution.

When you respond, stop rejecting my answer and just reply with comments until I give up trying to answer your question, or you accept my answer.
0
 

Author Comment

by:yangsen
ID: 1268834
PrintStream os=new PrintStream(connection.getOutputStream());
os.println("itemName="+URLEncoder.encode(itemName));
os.close();

Those lines actually make "data transfer for itemName" look like html POST tag:
<form method="POST">
    <input type="hidden" name="itemName" value="bluh">
</form>

then according to this data value, the "test.htm"(may have some CGI response)  will response a description for this itemName.
After client Java applet get the the description, it just return to JavaScript. The JavaScript then change the value of the textbox into the description.

So the overall purpose for thses homepage is to show users the description in real time whenever they change the item selection, instead of puting all items and description in a homepage at a time (which may take lots of time)

No matter you use those three lines or not, Netscape Navigator won't let go because it's illegal to call a Java applet function (must be using network object like URL or even socket) from JavaScript.

Am I clear? please let me know :)
BTW, did you say it works in NN4.01?
0
 
LVL 1

Expert Comment

by:fun
ID: 1268835
A.  I assume that you are using IE3+ and NN3+. If you are using NN2 then You may be right that it does not allow the applet to be called from javascript. If you are using IE4 then I don't know how that would react.

B.  I find that the code you provided does not run in IE3 either. When I try it, an exception is thrown that says ouptut is not recognized. When I try this in NN4.01 the exact same thing occurs.

C.  I do not believe that the printstream commands you used were capable of simulating a form post. There is no way to initiate an action event. Where did you get the idea that this would be true? When I removed these lines from the applet, both IE3.02 and NN4.01 placed the contents of test.htm into the text area as desired.

D.  It is not illegal to call a java applet method from javascript in NN3.01. What does happen, at least for me is that NN3 does not allow you to get the data through an input stream.


E.  What I suggest you consider is to create another method getVar that allows you to pass the argument selected by the user to the applet and pass the contents of that appropriate file back to the textarea. This may not work in NN3 but will in NN4
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Tag input html 4 37
listing all functions in JavaScript 19 101
populate dynamic drop down from a csv 3 36
Re-position the objects 7 47
Today I would like to talk about localizing (Internationalization) JavaScript applications. Introduction When creating an application that is going to be used by many people around the globe, it is important to remember that not everyone speak…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

708 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

13 Experts available now in Live!

Get 1:1 Help Now