J-Integra® and Applets

Contents

  1. What are applets, and why might you consider using them?
  2. What does J-Integra® offer?
  3. An example
  4. Moving beyond the sandbox
  5. Troubleshooting
  6. A note about firewalls
  7. Native mode
  8. More about Excel Programming

1 What are applets, and why might you consider using them?

Java Applets are Java programs that have been built to execute within a Java Virtual Machine (JVM) which is itself executing within a Web Browser. Web Browsers typically display a Hypertext Markup Language (HTML) document, which consists of plain text, with tags, which "mark up" the text. One of these tags is the APPLET tag, which references a Java Program. When the Web Browser sees this tag, it downloads the Java program from the Web Server, and executes the Applet within the Web Browser.

Applets have had a bad reputation in that there are few applets that really do anything useful -- you can do all kinds of cool things with them, but it is difficult to find good examples of Applets that really add a lot of value to the Web Page.

One kind of Applet that has the potential of adding a lot of value is an Applet which acts as the client part of a Client-Server application. Applets can provide far greater interactivity than HTML pages, and can be far more "intelligent", because it is real software executing within the Web Browser.

J-Integra® offers you a mechanism for Web-Enabling existing applications that expose COM Components. No longer do you have to distributed the client part of your software to hundreds (or thousands) of users, and face the myriad of configuration and installation problems that inevitably occur. Instead, have the user dynamically download the client part of your software, in the form of a Java Applet.

What's more, you don't need to do anything special as regards your server software if it already exposes COM Components, since J-Integra® will seamlessly map between Pure Java, and COM, through its internal use of DCOM.

2 What does J-Integra® offer?

J-Integra® can be used by Java Applets running under version 4.05 (possibly earlier 4.x version) of Netscape Navigator, and version 4.0 of Microsoft Internet Explorer, without requiring that any patches be installed, and without requiring code signing. Of course it is bound by the standard restrictions -- Java Applets can only communicate to the host from which they were downloaded.

3 An example

This example is based on the Excel example. You should work through that example prior to trying to do this example, since this example assumes that the Excel proxy files have already been generated, and that the appropriate directory structure and environment variables are in place.

We also assume that you are running a Web Server, and understand how to configure new logical to physical directory name mappings.

  1. Create a jar file containing all of the Excel proxies using the command jar cvf excel.jar excel/*.class

  2. Copy the jintegra.jar and excelXP.jar files to d:/pure. Copy the correct Excel jar file if your use a different version of Excel.

  3. Create the HTML file which will reference the applet in d:\pure\applet.html with the following content:

    <HTML><HEAD><TITLE>J-Integra® Applet Example</TITLE></HEAD>
    <BODY>
    <applet code=ExcelExampleApplet.class width=500 height=250 archive="jintegra.jar, excelXP.jar">
    </applet>
    </BODY>
    </HTML>

  4. This example is based on Microsoft Excel XP version. If you are using Microsoft Excel 97 or Excel 2000, please note that the APIs of Excel 97, 2000 and XP are different. Create the applet source file in d:\pure\ExcelExampleApplet.java with the following content:

    import java.awt.*;
    import java.awt.event.*;
    import com.linar.jintegra.AuthInfo;
    import java.util.Date;

    public class ExcelExampleApplet extends java.applet.Applet {
      private TextField domainFld = new TextField(10);
      private TextField userFld = new TextField(10);
      private TextField passwordFld = new TextField(10);
      private Button connectBtn = new Button("Connect ... ");
      private TextArea textArea = new TextArea(100, 800);

      public void init() {
        // A Simple GUI to let the user enter Authentication information, connect to the
        // server, and see the results.
        setLayout(new GridLayout(2, 1));
        Panel authPanel = new Panel();
        authPanel.setLayout(new GridLayout(4, 2));
        authPanel.add(new Label("Domain"));
        authPanel.add(domainFld);
        authPanel.add(new Label("User"));
        authPanel.add(userFld);
        authPanel.add(new Label("Password"));
        passwordFld.setEchoChar('*');
        authPanel.add(passwordFld);
        authPanel.add(connectBtn);
        add(authPanel);
        add(textArea);
        connectBtn.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            try {
              connectToExcel();
            } catch(Exception e) {
              e.printStackTrace();
            }
          }
        });
      validate();
      }

      private void connectToExcel() {
        try {
          // Begins tracking of created objects in that thread.
          com.linar.jintegra.Cleaner.trackObjectsInCurrentThread();

          String host = getCodeBase().getHost();
          String domain = domainFld.getText().trim();
          String user = userFld.getText().trim();
          String password = passwordFld.getText();

          if (domain.length() == 0 || user.length() == 0 || password.length() == 0) {
            textArea.setText("Please enter Domain User and Password");
            return;
          }
          AuthInfo.setDefault(domain, user, password);

          // Create an instance of Excel.Application on the remote host
          System.out.println("Connecting to " + host);
          excel.Application app = new excel.Application(host);
          textArea.setText("");
          textArea.append("Created an instance of Excel\n");

          // Use Excel objects to get at a range in the displayed Worksheet
          excel.Workbooks workbooks = app.getWorkbooks();
          excel.Workbook workbook = workbooks.add(null);
          excel.Sheets worksheets = workbook.getWorksheets();
          excel.Worksheet sheet = new excel.Worksheet(worksheets.add(null, null, null, null));
          excel.Range range = sheet.getRange("A1:C3", null);
          app.setVisible(true); // Nice to see what is happening
          textArea.append("Made Excel visible\n");

          // New contents for the range -- notice the standard Java types
          Object[][] newValue = {
            { "defe", new Boolean(false), new Double(98765.0 / 12345.0) },
            { new Date(), new Integer(5454), new Float(22.0 / 7.0) },
            { new Boolean(true), "dffe", new Date() }
          };

          // For Excel 2000, use: range.setValue(newValue);
          // For Excel XP, use:
          range.setValue2(newValue); // Update the spreadsheet

          textArea.append("Updated the range ... sleeping for ten seconds\n");
          Thread.sleep(10000); // Sleep 10 seconds -- maybe you want to change this value

          // Get the new content of the range
          // For Excel 2000, use: Object[][] values = (Object[][])range.getValue();
          // For Excel XP, use:
          Object[][] values = (Object[][])range.getValue2();

          // Print them out. Again, the values are standard Java types
          for(int i = 0; i < values.length; i++) {
            for(int j = 0; j < values[i].length; j++) {
              textArea.append(values[i][j] + "\t");
            }
          }
          textArea.append("\n");
          workbook.close(new Boolean(false), null, null); // False="=" don't prompt to save changes
          app.quit();
          textArea.append("Closed Excel down\n");
        } catch(Exception e) {
          if(e instanceof SecurityException) {
            throw (SecurityException)e;
          }
          e.printStackTrace();
        } finally {
          com.linar.jintegra.Cleaner.releaseAllInCurrentThread();
        }
      }
    }
    กก
  5. Compile the Applet, using the command javac ExcelExampleApplet.java:

  6. Set up a mapping on your Web Server, so that when people enter the URL http://your.host.name/applet2excel/applet.html they go d:\pure\applet.html

  7. Try it out! All being well you should see something like this:


    Now ask someone running a Web Browser on a UNIX box on the other side of the world to access your URL...

Remember, there is no need to install any special software on the machine that is hosting the COM Component (in this case Excel) and running the Web Server, since J-Integra® communicates through the standard DCOM protocol. The HTML file, the Java Applet, and the jintegra.jar and excel.jar files must be on the Web Server, so that they can be served to Web Browsers.

The Web Browser can be running on any platform that supports a standard JVM:

4 Moving beyond the sandbox

The above example starts up Excel on the same machine as the Web Server, because it uses the following code to determine the host on which Excel should be created:

String host = getCodeBase().getHost();

If you want to start Excel on the same machine as the Web Browser, then you could change the above code to:

String host = "localhost";

This code will cause a security exception when running in most Web Browsers because they do not allow connections to any machine other than the Web Server.

The situation as regards Java in Web Browsers has been a bit of a mess until recently, because Netscape and Microsoft supported different versions of Java, they supported different subsets of Java versions, and implemented their own extensions, especially security-related extensions.

Sun has gone a long way towards resolving this mess by providing a "Java plugin" technology, which allows you to use Sun's JVM to run Applets in Netscape Navigator and Internet Explorer, rather than using Netscape's or Microsoft's JVM. The Java Plugin is can be downloaded from Sun's Web Site, and is part of JDK1.2 (and higher).

If you wish to try out this example, download and install the Java Plugin by installing JDK1.2 (or higher), if you haven't already done so.

Modify the Java applet, to specify "localhost" as the host on which Excel should run (as shown above).

In order to make Netscape Navigator or Internet Explorer use the Java Plugin rather than their own JVM, you need to use a different HTML tag, rather than the Applet tag. If using Netscape Navigator, the following tag must be used (see the Java Plugin documentation for information on the appropriate Internet Explorer tag. It is also possible to use combined tags:
<HTML><HEAD><TITLE>J-Integra® Signed Applet Example</TITLE></HEAD>
<EMBED type="application/x-java-applet;version=1.2"
  width="500" height="250"
  align="baseline" code="ExcelExampleApplet.class" archive="jintegra.jar, excelXP.jar"
  pluginspage="http://java.sun.com/products/plugin/1.2/plugin-install.html">
  <NOEMBED>
    No JDK 1.2 support for APPLET!!
  </NOEMBED>
</EMBED>
</BODY>
</HTML>

Finally, edit the local policy file which determines what rights are given to Java software downloaded from various URLs. Do this by running the policytool tool:

Use the File|Open menu command to open the default policy file, which in my case is in:
D:\Program Files\JavaSoft\JRE\1.2\lib\security\java.policy
.

Click on the Add Policy Entry button. Because in my case the Applet is being served from a Web Server called linar1, and a logical subdirectory called excel2applet, I specified http://linar1/applet2excel/* as the CodeBase. You might want to put the J-Integra® runtime into a separate subdirectory and use that as the code base:

Click on the Add Permission button, and select Socket Permission as the permisson, localhost as the target name, and Connect as the permission. This will allow the J-Integra® runtime to connect to the local host. You may also want to add the listen and accept permissions, which will allow J-Integra® to listen for events generated by Excel, and allow callbacks to Java objects from COM objects:

Finally, save the new policy file, recompile the Applet, and accessthe Applet from your browser.

5 Troubleshooting

1. First of all, enable the Applet console to see the message of any runtime error. For example on Windows, go to Start > Settings > Control Panel > Java Plug-in, and select Show console:

2. make sure that these files are in your d:\pure directory:

3. If you receive an Automation Execption with "Access Denied" as the description, then the domain, username and password have been refused by DCOM. Proceed to Configuring DCOM for Remote Access

6 A note about Firewalls

In order to J-Integra® to communicate with a remote COM Component, it must open up a TCP/IP connection to that server. If there is a Firewall between Web Browser and the Web Server, such a connection will be blocked.

The standard mechanism for bypassing this is to tunnel the communications over the protocol that can pass through a Firewall -- the HyperText Transfer Protocol. Microsoft have stated that they will support DCOM over HTTP. As soon as there is a publicly available specification, Intrinsyc will look at adding support for DCOM over HTTP. Alternatively, if there is demand, then we will look into implementing such functionality independently.

More information about firewalls is mentioned in Knowledge Base article 30323.

7 Native mode

If you need to run an Applet in native mode or embedding ActiveX Controls in Applets, see Knowledge Base article 30128 for more information.

8 More about Excel Programming

J-Integra® is a generic bi-directional bridge between any Java objects and any COM components. We do not provide the documentation of the generated Java proxies since the Java proxies are just mapped from the programming API of the COM component. For more information about Microsoft Excel programming, please refer to the Microsoft Excel VBA Language Reference. It's also easier to find a VB example first, and then covert the VB example to Java program using the reference Mapping VB Code to Java Code. We can assist you if you encounter any difficulty when mapping the VB code to Java code.