MoonOcean

« Previous page | Main
Thursday Mar 06, 2008

Sun Device Detection Tool is open source.

Sun Device Detection Tool is a device driver detection tool which helps users to determine whether their PCI devices are supported by Solaris OS.

To its history, please refer to

The Path to Sun Device Detection Tool

The first version of Sun Device Detection Tool (1.0) was released on Oct. 26, 2006. This is its web site: http://www.sun.com/bigadmin/hcl/hcts/device_detect.jsp. The latest update of it is 2.0.

The source code of Sun Device Detection Tool 2.0 is finally released. It is available at
http://www.opensolaris.org/os/project/ddtool/ddtool-2.0-src.tar.gz. The web site of the open source project is http://www.opensolaris.org/os/project/ddtool/.

 

Friday Feb 22, 2008

Change properties of Java ToolTip (background, border, etc.)

Sun UIRB commitee requires that ToolTips should have a yellow background color (#fff7c8), with a black or dark grey (#4c4f53) border, and the ToolTip should be showed for 15 seconds. 

To change such properties, there is a very simple way by adding a few lines of code (see below) where the ToolTip is referenced:

-----------------------------

 UIManager.put("ToolTip.background", new ColorUIResource(255, 247, 200)); // The color is #fff7c8.
 Border border = BorderFactory.createLineBorder(new Color(76,79,83)); // The color is #4c4f53.
 UIManager.put("ToolTip.border", border);
 ToolTipManager.sharedInstance().setDismissDelay(15000);// 15 seconds    

 setToolTipText(message); // The message is a String variable containing text to display.

-----------------------------

If more properties of the ToolTip are required to be changed, or the changed ToolTip needs to be referenced multiple times in the program, it is better to create a Look&Feel class as follows:

----------------------------------

/**
* DemoFrame.java
* This test frame is to demonstrate changing of tooltip background
*/

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.plaf.ColorUIResource;
import javax.swing.border.Border;

class ToolTipLookAndFeel extends MetalLookAndFeel
{
    protected void initSystemColorDefaults(UIDefaults table)
    {       
        super.initSystemColorDefaults(table);       
        table.put("info", new ColorUIResource(255, 247, 200));   
    }

    protected void initComponentDefaults(UIDefaults table) {
        super.initComponentDefaults(table);

    Border border = BorderFactory.createLineBorder(new Color(76,79,83));
    table.put("ToolTip.border", border);
    }
}


public class DemoFrame extends JFrame
{
    public DemoFrame()
    {
        super("Demo");

        try {                             
            UIManager.setLookAndFeel(new ToolTipLookAndFeel());
        } catch(Exception ex) {       
            System.err.println("ToolTipLookAndFeel exception!");
            System.err.println(ex.getMessage());
        }

        getContentPane().setLayout(new FlowLayout());

        JButton btn = new JButton("<html>Mouse Over me <br> for ToolTip </html>");               
       
        btn.setToolTipText("<html>I have changed <br> the color of <br> background and border. <br> It works! </html>");

        getContentPane().add(btn);

        JLabel label = new JLabel("What about me");
        label.setToolTipText("Me Too...");

        getContentPane().add(label);
    }

    public static void main(String[] arg)
    {
        DemoFrame m = new DemoFrame();

        m.setVisible(true);
        m.setSize(new Dimension(300, 150));
        m.validate();
    }

----------------------------------

Save the above code into a single java file, compile it, and run the DemoFrame class.

Note: If the following line of

    UIManager.setLookAndFeel(new ToolTipLookAndFeel());

is changed to

    UIManager.setLookAndFeel("ToolTipLookAndFeel");

the code of ToolTipLookAndFeel class must be moved to a separated file instead of being a internal class in the DemoFrame.java file. And the ToolTipLookAndFeel.java must be compiled before DemoFrame.java file.
Otherwise, the ToolTipLookAndFeel class cannot be really reference, the exception will be catched without any error or warning message while compiling. It is a little tricky.





 

Tuesday Dec 04, 2007

Is it a bug of Java Web Start?

I hava a Java application which is deployed by JavaWS. And a shared objected is deployed as a native library of the application. (Following is a piece of the JNLP file.)


<resources>
<j2se version="1.4+" java-vm-args="-client"/>
<jar href="/foo.jar" main="true" download="eager"/>
<nativelib href="/libfoo.jar"/>
</resources>


Theoretically, when the application launches, all jar files have been loaded on users' system. And the application should work, even if the network cable is plugged out.

When I tested the application with JRE 1.4.2 and 1.5, it actually worked after launching without network access.

However, when I tried it with JRE 1.6, the application fails. It seems that the application cannot load the shared object.

I am sure that I run the application with JRE1.4.2, 1.5 and 1.6 on the same machine. Each time before I tested it, the Java cache (/.java directory) is cleaned. So I can say that the shared library did not exist on the box for testing 1.4.2 and 1.5.

Is it a bug of JavaWS?

Wednesday Nov 28, 2007

A simple example of JNI

Java Native Interface (JNI) is a standard programming interface for writing Java native methods and embedding the JVM into native applications. Simply, it is a Java technology with which a Java application can call a method written with such as C, C++ and assembly.

Adopting JNI is very simple. You need two components -- a Java program, and a native library. The native library is written in other languages and compiled on corresonding platforms.

A function defined in the native library should be declared in Java code as a 'native' function. And the native library needs to be load in Java code with the System.loadLibrary method. The natvie function could be referced by other regular functions in the Java code.

Following is an example of the Java Code.

JNIFoo.java
===========

public class JNIFoo {    
    public native String nativeFoo();    

    static {
        System.loadLibrary("foo");
    }        

    public void print () {
    String str = nativeFoo();
    System.out.println(str);
    }
    
    public static void main(String[] args) {
    (new JNIFoo()).print();
    return;
    }
}

# javac JNIFoo.java
# javah -jni JNIFoo

A file named as JNIFoo.h is created by running the above two commands. A function of 'JNIEXPORT jstring JNICALL Java_JNIFoo_nativeFoo  (JNIEnv *, jobject)' is in the JNIFoo.h file. The function must be implemented in a source code file (e.g. a C file), and it is the actually entry to do what the funtion of natvieFoo() in Java code do.


foo.c
======

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <jni.h>
#include "JNIFoo.h"

JNIEXPORT jstring JNICALL Java_JNIFoo_nativeFoo (JNIEnv *env, jobject obj)
{
  int i;
  int ds_ret;

  char* newstring;

  jstring ret = 0;

  newstring = (char*)malloc(30);

  if(newstring == NULL)
  {     
      return ret;
  }

  memset(newstring, 0, 30); 
 
  newstring = "foo: Test program of JNI.\n";
  

  ret = (*env)->NewStringUTF(env, newstring);

  free(newstring);

  return ret;
}

JNI libraries are named with the library name used in the System.loadLibrary method of your Java code with a prefix and a suffix. On different OS, the prefix and suffix might be different.

On Solaris OS, it is prefixed by 'lib' and suffixed with '.so'

# cc -Kpic -G -o libfoo.so -I/usr/java/include -I/usr/java/include/solaris foo.c -z text

On Linux OS, it is prefixed by 'lib' and suffixed with '.so'.

# gcc -shared -fpic -o libfoo.so -I/usr/java/include -I/usr/java/include/linux foo.c

On Windows OS, it is prefixed by nothing and suffixed with '.dll'.
It could be compiled with Visual Studio automatically and create a file named as foo.dll.

On Mac OS, it is prefixed by 'lib' and suffixed with '.jnilib'.

# gcc -dynamiclib -o libfoo.jnilib -I/System/Library/Frameworks/JavaVM.framework/Headers foo.c -framework JavaVM

 

To run the JNI program locally, the following command is fine:

# java -Djava.library.path=<path_of_native_lib> JNIFoo 

Tuesday Nov 27, 2007

Bundle an executive binary program with a Java Web Start application

When an Java application needs to call native program(s) to handle situations, JNI is frequently the preferred technology.

If the Java application is deployed with Java Web Start. The embedded native program could be packaged in a jar file, and the jar is deployed as a native library of the Java application.

Following is a piece of JNLP file. It is obvious that the foo.jar is the Java application, and the libfoo.jar including a native program which normally should be an shared object (e.g. libfoo.so on Unix-like OS or foo.dll on Windows OS).

------------------------------------------

<resources>

    <j2se version="1.4+" java-vm-args="-client"/>

    <jar href="/foo.jar" main="true" download="eager"/>

    <nativelib href="/libfoo.jar"/>

</resources>

------------------------------------------

However, sometimes a shared object doesn't meet our requirement. For example, an executive program is always much smaller rather than a dynamic-link library. Considering to reduce launch time, we prefer to bundle an exe file with our JavaWS application instead of a DLL file.


Technically we can bundle any files that we want in our application JAR. The executive binary program could also be packaged in a JAR file. But the methods in the native program cannot be referenced by the Java application directly. In such scenario, the JNI is inapplicable.


The executive program should be executed on users' system, and interface between it and the Java application is its out put message.


Although, it is possible to reference to the contents of the Java Web Start cache directly. We don't recommend it, since the cache is a private implementation of Java Web Start, and is subjected to change anytime.


The URL returned for calls to ClassLoader.getResource() is now the proper JAR URL of the item on the net. (http://java.sun.com/javase/6/docs/technotes/guides/javaws/enhancements6.html, see bullet item related to "Jar Indexing")


We could to access the EXE in the JAR by using a JarURLConnection to get to the resource. e.g ,

| jar:http://www.foo.com/bar/baz.jar!/foo.exe |


We can then get the InputStream of the binary program, and then copy it to a temp location on disk, and then execute it from there.

If the JAR resource is already cached, the contents of the resource will be returned from the cache directly, so there won't be extra network connections to the JAR itself.

NOTE: This solution is only applicable with JVM 1.6.

Following is an example of such an implementation.

--------------------------------------------------------
File of TestFoo.java

====================

... ...

   private String execute() throw IOException {   

    ... ...

    ClassLoader loader = this.getClass().getClassLoader();

    /* jnitest is an binary program running on Solaris OS.

        It is packaged in a Jar file of libjnitest.jar */

    URL url = loader.getResource("jnitest");                           

    /* Note: the size of the buffer must not less than the size of jnitest */

    byte[] buf = new byte[20000];

    int len = 0;

    JarURLConnection uc = (JarURLConnection)url.openConnection();             

    uc.connect();


    InputStream in = new BufferedInputStream(uc.getInputStream());

    len = in.read(buf);

    in.close();             


    File tmpFile = new File(fileName);           

    FileOutputStream output = new FileOutputStream(tmpFile);

    output.write(buf, 0, len);  

    output.close();                                       

    runCommand("chmod +x " + fileName);

    /* Execute the executive native program, and get its output message */

    String outputMessage = runCommand(fileName);            

    return outputMessage;

    }

    private String runCommand(String command) {

        String[] cmd0 = {"sh", "-c", command};

        try {

                Process ps = Runtime.getRuntime().exec(cmd0);

                String str1 = loadStream(ps.getInputStream());

                return str1;

        } catch (IOException ioe) {

                System.err.println("Error: running command on Solaris OS failed.");
        }

        return null;

    }


    private String loadStream(InputStream input) throws IOException {

        int count;

        int BUFFER = 20;

        byte[] data = new byte[BUFFER];

        input = new BufferedInputStream(input);

        StringBuffer buff = new StringBuffer();

        while ((count = input.read(data, 0, BUFFER)) != -1)

            buff = buff.append(new String(data, 0, count));

        return buff.toString();

    }

... ...


File of testfoo.jnlp

====================

... ...

 <resources>

    <j2se version="1.4+" java-vm-args="-client"/>

    <jar href="/testfoo.jar" main="true" download="eager"/>   

    <nativelib href="/libjnitest.jar"/>

 </resources>

... ...