Solved

CodeBase Enabled--still applet hangs!

Posted on 1998-09-01
10
311 Views
Last Modified: 2013-12-29
Hi,
awilkins (EE Expert) provided the following Applet for writing/reading to disk with Java (which I compiled as "cookin.class".  For development purposes I am trying to run it locally without signing it. I followed directions explicitly from Netscape's Alec Plumb for activating codebase principals in NN 4.06, and wrote a simple HTML page to call the applet functions (see "test.htm" below).  When I place the test.htm and cookin.class files in the same directory and load the former into NN 4...

a. Status bar reads "running applet..."
b. the phrase "Setting up..." displays as expected
c. then......nothing.  Status bar reads "document done".

***********************************************
here's the applet: cookin.java (cookin.class)...

import java.applet.Applet;
   import java.io.*;

   public class cookin extends Applet
   {
     String baseDir; // base Directory for all your cookies to be placed in.

     public void init()
     {
       baseDir = "C:\\temp";  // change as desired
     }

     public void writeCookie(String fileName, String value)
     {
       try {
         FileWriter fileWrite = new FileWriter(baseDir + fileName);
         fileWrite.write(value);
       } catch (IOException e) {
         System.out.println("Error writing a cookie");
         System.out.println(e.toString());
       }
     }

     public String readCookie(String fileName)
     {
       try {
         BufferedReader fileRead = new BufferedReader(new FileReader(baseDir + fileName));

         StringBuffer strb = new StringBuffer("");  // creates an initially blank StringBuffer

         while (fileRead.ready())  // while more remains to be read
           strb.append(fileRead.readLine());

         return new String(strb); // converts strb to a String

       } catch (IOException e) {
         System.out.println("Error reading a cookie");
         System.out.println(e.toString());
         return "Error reading a cookie";
       }
     }

     public void deleteCookie(String fileName)
     {
       File f = new File(baseDir + fileName);
       f.delete();
     }
   }
***********************************************
here's test.htm...

<HTML>
<HEAD>
<TITLE>Testing 'cookin' applet</TITLE>
</HEAD>
<BODY>
<applet code="cookin.class" name="cookin" width=300 height=2>
</applet>

<script language = "JavaScript">
   <!--
document.write("Setting up...");
document.cookin.writeCookie("testfile.txt", "It works!");
document.write("File Written...");
var x = document.cookin.readCookie("testfile.txt");
document.write("File Read...");
alert("Recalled value ="+x);

  //  -->
   </script>

</BODY>
</HTML>

CAN ANYONE HELP ME GET THIS FILE READ/WRITE APPLET WORKING??
0
Comment
Question by:boatful
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
10 Comments
 
LVL 2

Accepted Solution

by:
threshold earned 200 total points
ID: 1223229
If you want to use the Capabilities Classes to read/write the local file in unsigned applet, you should
1. enable the codebase principal:
    find the files named pref.js in the c:/.../Nestscape/Users/.../ and add a line below into it.

        user_pref("signed.applets.codebase_principal_support", true);

2. In your applet code, import netscape.security.PrivilegeManager, and write the code below before you read/write the files on local

      try {
         PrivilegeManager.enablePrivilege("UniversalFileAccess"); // high risk!!
         System.out.println("\tSuccess!");
      } catch (netscape.security.ForbiddenTargetException e) {
         System.out.println("\tFailed! Permission to read system properties denied by user.");
      } catch (Exception e) {
         System.out.println("\tFailed! Unknown exception while enabling privilege.");
         e.printStackTrace();
      }

3. then, you can use the FileWriter/FileReader to read/write the file on local

4. If everything you did is right, NS will prompt a security granting window to user while 2. is running.

You can find the package 'netscape.security.*' and documents in

        http://developer.netscape.com/docs/manuals/signedobj/capsapi.html

btw, can you post the error message in Java Console of Netscape?
0
 

Author Comment

by:boatful
ID: 1223230
Hi Threshold,
Thanks for a speedy reply!  Unfortunately I'm just beginning to understand Java, so I'm going to need your help pasting your code correctly into the existing applet (above).  I've tried it myself several different ways, but my java compiler yields 1-2 errors each time.
I also have 3 related follow-up questions:

1.  Is importing netscape.security.PrivilegeManager  necessary even for signed applets, or only when debugging with CodeBase Principals Enabled??

2.  Does filewriter automatically create directories/folders if parts of the path you specify don't already exist??

3.  Is it customary to include the MS-DOS extension when specifying a filename for filewriter??

Thanks very much for helping me through this, thresh!
Tony
VT

PS Here's what I get when debugging via the Java Console:

# Applet debug level set to 9

# stopApplet: contextID=5 appletID=12971104 parentMWContext=12845312

# Stopping applet: cookin, appletID=12971104, contextID=5

# Applet cookin stopped

# startApplet: contextID=5 appletID=12971104 newFrameMWContext=12845312

# Starting applet: cookin, appletID=12971104, contextID=5

# Applet cookin running

# reflectApplet: contextID=5 appletID=12971104

#   reflectApplet: appletID=12971104

#   reusing class loader netscape.applet.AppletClassLoader@800d4b5
#      context = netscape.applet.MozillaAppletContext@800d070
#      codebase = file:/F|/WWW/Beaconess/IE/

#      scriptOrigin = file:///F|/WWW/Beaconess/IE/Cookin2.htm


0
 
LVL 2

Expert Comment

by:threshold
ID: 1223231
1. netscape.security.PrivilegeManager is necessary for signed applets in Netscape 4.0x

2. FileWriter will create a file if it doesn't exist, but not create the directory which the file needs.
    We can use File.mkDir() to create the directory

3. I can't get the point of your question

It seems your Java didn't run...
use more System.out.println(...) in your Java to ensure the methods were invoked.

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:boatful
ID: 1223232
Hi again,
You're a step ahead of me Threshold. You see, I can't seem to consolidate your suggestions into the original applet correctly (thus it won't even compile).  If you'd be willing to piece the two together using the correct order and syntax, that would be great.  I'd be glad to double the points if you can help me get this applet running.  I need it to sidestep the limitations of cookies in JavaScript, so that I can save more that 20 'cookies' per domain, and save datastrings longer that 4 kb.  If you're interested in the application I'm building, you may check it out at http://users.aol.com/beaconess/HEP/.  If I sound ignorant about Java that's quite accurate.  I'm pretty fluent in JavaScript, and I intend only to learn as much Java as is necessary to save long datastrings (and lots of them) in my program.
Question #3 is: do I send as a filename "mystring" or "mystring.txt"?
Thanks...
Tony
0
 

Author Comment

by:boatful
ID: 1223233
Looking good Threshold!
I pieced together the applet so that netscape.security.* imports and when I run it I get the GRANT PRIVILEGES dialog. So far so good!
The Java Console contains 'Success!', so I know the init() object is working (see below). The writeCookie() object seems to hang, however (no file is written and no error messages show up in the Java console). I'll experiment with adding System.out.println(...) statements there.
Stay tuned...

APPLET AS OF 9/7 (HAPPY LABOR DAY)

import java.applet.Applet;
   import java.io.*;
     import netscape.security.*;

   public class cookin3 extends Applet
   {
     String baseDir = "C:\\temp"; // base Directory for all your cookies to be placed in.
     
     public void init()
     {
         try {
            PrivilegeManager.enablePrivilege("UniversalFileAccess"); // high risk!!
            System.out.println("\tSuccess!");
         } catch (netscape.security.ForbiddenTargetException e) {
            System.out.println("\tFailed! Permission to read system properties denied by user.");
         } catch (Exception e) {
            System.out.println("\tFailed! Unknown exception while enabling privilege.");
            e.printStackTrace();
         }

     }

     public void writeCookie(String fileName, String value)
     {
       try {
         FileWriter fileWrite = new FileWriter(baseDir + fileName);
         fileWrite.write(value);
       } catch (IOException e) {
         System.out.println("Error writing a cookie");
         System.out.println(e.toString());
       }
     }

     public String readCookie(String fileName)
     {
       try {
         BufferedReader fileRead = new BufferedReader(new FileReader(baseDir + fileName));

         StringBuffer strb = new StringBuffer("");  // creates an initially blank StringBuffer

         while (fileRead.ready())  // while more remains to be read
           strb.append(fileRead.readLine());

         return new String(strb); // converts strb to a String

       } catch (IOException e) {
         System.out.println("Error reading a cookie");
         System.out.println(e.toString());
         return "Error reading a cookie";
       }
     }

     public void deleteCookie(String fileName)
     {
       File f = new File(baseDir + fileName);
       f.delete();
     }
   }

0
 

Author Comment

by:boatful
ID: 1223234
the latest...
I modified the writeCookie object as follows...

public void writeCookie(String fileName, String value)
{
  try {
    System.out.println("\ttrying to instantiate fileWrite...");
    FileWriter fileWrite = new FileWriter(baseDir + fileName);
    System.out.println("\tfileWrite instantiated!");
    fileWrite.write(value);
    System.out.println("\t"+value+" written to "+baseDir+fileName);
  } catch (IOException e) {
    System.out.println("Error writing a cookie");
    System.out.println(e.toString());
  }
}

but all I ever get in the java console is "trying to instantiate fileWrite...".  I NEED YOUR HELP !!!
Tony
     

0
 

Author Comment

by:boatful
ID: 1223235
OK, Threshold...
I'm closer still.  I got a lesson in inheritance from MSMOLYAK and now the writeCookie method actually creates a blank file in the specified directory, however the method doesn't write the string 'value' to the new file.  Unfortunately, no exception is thrown either.  Can you (or anyone else) diagnose...???
0
 
LVL 2

Expert Comment

by:threshold
ID: 1223236
If you got a blank file, the most possible reason is that you didn't close it.
All File I/O will be cached in memory by OS, we have to use the methods like 'close' or 'flush' to make sure the OS write the data to disk.
0
 
LVL 2

Expert Comment

by:threshold
ID: 1223237
FileWriter fileWrite = new FileWriter(baseDir + fileName);
fileWrite.write(value);
fileWrite.close();  // ------------------------> it's needed!
0
 

Author Comment

by:boatful
ID: 1223238
Thanks kindly for all your support and encouragement.  I now have a single applet capable of file and folder read/write/list/delete (see below).  I want you to have the points, but I have a couple of follow-up questions even so.

First, is it possible to request limited access to I/O functions, e.g. I/O exclusively to a floppy drive??

What do I need to modify for the applet to work in MSIE 4.0??

JavaScript string methods don't work on values returned by the applet unless I use a phrase like:
newstring = unescape(escape(document.cookin.iomanager(3,"","testfile",""))). Is there a more efficient way??

Here's the applet:

import java.applet.Applet;
   import java.io.*;
      import netscape.security.*;

   public class cookie extends Applet
   {
     String baseDir = "C:\\TheraLnk\\program"; // base Directory for all your cookies to be placed in.
     String retval = "dummy";
     public String iomanager(int task, String folderName, String fileName, String val)
     {
      if (task <=5)
     {
          try {
            PrivilegeManager.enablePrivilege("UniversalFileAccess"); // high risk!!
            System.out.println("\tSuccess!");
         } catch (netscape.security.ForbiddenTargetException e) {
            System.out.println("\tFailed! Permission to read system properties denied by user.");
         } catch (Exception e) {
            System.out.println("\tFailed! Unknown exception while enabling privilege.");
            e.printStackTrace();
         }
       retval = new String("init");
      }

      if (task == 1)
      {
      try {
          File td = new File(baseDir+folderName);
          if (td.mkdir())
              System.out.println("\tpowerfolder instantiated!"); //MESSAGE 2
            retval = new String("dir");
      }
      catch (SecurityException e) {
          System.out.println("Error making a folder"); //MESSAGE 4
                  System.out.println(e.toString()); //MESSAGE 5
          retval = new String("dir err");
        }

     }

      if (task == 2)
      {

       try {
      FileWriter powerCookie = new FileWriter(baseDir + folderName + fileName);
      System.out.println("\tpowerCookie instantiated!"); //MESSAGE 2
      powerCookie.write(val);
      powerCookie.close();
      System.out.println("\t"+val+" written to "+baseDir + folderName + fileName); //MESSAGE 3;
      retval = new String("write");
       } catch (IOException e) {
      System.out.println("Error writing a cookie"); //MESSAGE 4
      System.out.println(e.toString()); //MESSAGE 5
      retval = new String("write err");
       }
     }

      if (task == 3)
      {

       try {
      BufferedReader fileRead = new BufferedReader(new FileReader(baseDir + folderName + fileName));
      //the default buffer length crumps after about 2610th character in a string.
      StringBuffer strb = new StringBuffer("");  // creates an initially blank StringBuffer
      while (fileRead.ready())  // while more remains to be read
      strb.append(fileRead.readLine());
      retval = new String(strb); // converts strb to a String

       } catch (IOException e) {
      System.out.println("Error reading a cookie");
      System.out.println(e.toString());
      retval = new String("read err");
       }
     }

      if (task == 4)
      {

       System.out.println("\tDeleting... "+baseDir + folderName + fileName);
       File f = new File(baseDir + folderName + fileName);
       f.delete();
       retval = new String("del");
     }

      if (task == 5)
      {
      try {
                  System.out.println("Starting filelist routine");
          File d = new File(baseDir + folderName);
          String files[] = null;
          files = d.list();
          System.out.println("Success on File.list.  Found " + files.length + " files in " + d.toString());
                  retval = "";
          for (int i = 0; i < files.length; i++) {
            if (i !=0) {
            retval += "*~&!^H@%#$";
            }
            retval += files[i].toString();
                  }
      System.out.println(retval);
              }
      catch (SecurityException e) {
           System.out.println("Caught security exception on File.list");
           retval = "list err";
       }
     }
   return retval;
   }
}

0

Featured Post

[Webinar] Learn How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

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

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…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

717 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