Tech all over the world
Saturday, May 13, 2006
  Core Java Technologies Tech Tips, May 13, 2006 (Programmatic Access to Network Parameters, Dialog Modality)
You are receiving this e-mail because you elected to receive e-mail from Sun Microsystems, Inc. To update your communications preferences, please see the link at the bottom of this message. We respect your privacy and post our privacy policy prominently on our Web site http://sun.com/privacy/

Please do not reply to the mailed version of the newsletter, this alias is not monitored. Feedback options are listed in the footer for both content and delivery issues.
  Welcome to the Core Java Technologies Tech Tips.
Core Java Technologies
TECHNICAL TIPS
May 13, 2006
View this issue as simple text
In This Issue
 
Welcome to the Core Java Technologies Tech Tips for May 13, 2006. Here you'll get tips on using core Java technologies and APIs, such as those in Java Platform, Standard Edition (Java SE).

This issue covers:

» Programmatic Access to Network Parameters
» Dialog Modality

These tips were developed using a snapshot release of Java Platform, Standard Edition (Java SE 6.0), code name Mustang. You can download a snapshot release of Mustang at https://mustang.dev.java.net/.

This issue of the Core Java Technologies Tech Tips is written by John Zukowski, president of JZ Ventures, Inc. (http://www.jzventures.com).

See the Subscribe/Unsubscribe note at the end of this newsletter to subscribe to Tech Tips that focus on technologies and products in other Java platforms.

PROGRAMMATIC ACCESS TO NETWORK PARAMETERS
 

Java SE 6.0, code name Mustang, is fast approaching its Beta 2 early access release. One of the added features in Java SE 6 gives you access to more information than you could access before about network interfaces. It isn't uncommon to have systems running with multiple active network connections, such as wired, 802.11 a/b/g wireless, and bluetooth. Previous J2SE releases had limited support for access and discovery of information related to multiple connections. Java SE 6 expands this capability.

Introduced in J2SE 1.4, the NetworkInterface class offers access to some information about network interfaces. You could use the getNetworkInterfaces() method in NetworkInterface for information about the set of installed networks, or lookup a specific network with the getByName() or getByInetAddress() methods. You could then display information about the network interface, such as its name or its InetAddress. To see the kind of information you could access using NetworkInterface, run the following program, ListNets, in J2SE 5.0:
    import java.io.*;    import java.net.*;    import java.util.*;     public class ListNets {         public static void main(String args[])          throws SocketException {        Enumeration<NetworkInterface> nets =          NetworkInterface.getNetworkInterfaces();        for (NetworkInterface netint : Collections.list(nets)) {          displayInterfaceInformation(netint);        }      }       private static void displayInterfaceInformation(          NetworkInterface netint) throws SocketException {        System.out.printf(            "Display name: %s%n", netint.getDisplayName());        System.out.printf("Name: %s%n", netint.getName());        Enumeration<InetAddress> inetAddresses =             netint.getInetAddresses();        for (InetAddress inetAddress : Collections.list(            inetAddresses)) {        System.out.printf("InetAddress: %s%n", inetAddress);        }       System.out.printf("%n");      }    }   
If you run the ListNets program on a typical Microsoft Windows machine, your output should look something like the following -- the display names and addresses might be different based on your current hardware and setup:
    Display name: MS TCP Loopback interface    Name: lo    InetAddress: /127.0.0.1     Display name: Intel(R) PRO/100 VE Network Connection -    Packet Scheduler Miniport    Name: eth0     Display name: RCA USB Cable Modem - Packet Scheduler Miniport    Name: eth1    InetAddress: /11.22.33.44 
Linux machines would have similar output for names, but have different display names and possibly different addresses.

With methods such as isMCGlobal() and isMCSiteLocal(), the information you can get about each InetAddress is more related to multicasting and its address type then about the network interface itself. That network interface-related information is now available with the NetworkInterface class in Java SE 6.0.

Network interfaces can be hierarchically organized. The NetworkInterface class in Java SE 6.0 includes two methods, getParent() and getSubInterfaces(), that are pertinent to a network interface hierarchy. The getParent() method returns the parent NetworkInterface of an interface. In other words, if something is a subinterface, getParent() returns a non-null value. The getSubInterfaces() method returns all the subinterfaces of a network interface.

You can discover if a network interface is "up" (that is, running) with the isUp() method. There are also methods that tell you the type of the network interface: isLoopback() tells you if the network interface is a loopback interface, isPointToPoint() tells you if it's a point-to-point interface, and isVirtual() tells you if its a virtual interface.

Beyond basic status information, you can access other network parameters about a network interface such as its physical hardware address (as an array of bytes) and the Maximum Transmission Unit (MTU) (largest packet size).

The last item of information available for each NetworkInterface is a List of a new interface called InterfaceAddress. This gives you the InetAddress for this address, its broadcast address, and its subnet mask.

Here is an updated version of the ListNets program that uses the NetworkInterface enhancements:
    import java.io.*;    import java.net.*;    import java.util.*;        public class ListNets {      private static final Console console = System.console();          public static void main(String args[]) throws           SocketException {        Enumeration<NetworkInterface> nets =          NetworkInterface.getNetworkInterfaces();        for (NetworkInterface netint : Collections.list(nets)) {          displayInterfaceInformation(netint);        }      }          private static void displayInterfaceInformation(          NetworkInterface netint) throws SocketException {        console.printf("Display name: %s%n",             netint.getDisplayName());        console.printf("Name: %s%n", netint.getName());        Enumeration<InetAddress> inetAddresses =             netint.getInetAddresses();        for (InetAddress inetAddress : Collections.list(            inetAddresses)) {          console.printf("InetAddress: %s%n", inetAddress);        }            console.printf("Parent: %s%n", netint.getParent());        console.printf("Up? %s%n", netint.isUp());        console.printf("Loopback? %s%n", netint.isLoopback());        console.printf(            "PointToPoint? %s%n", netint.isPointToPoint());        console.printf(            "Supports multicast? %s%n", netint.isVirtual());        console.printf("Virtual? %s%n", netint.isVirtual());        console.printf("Hardware address: %s%n",          Arrays.toString(netint.getHardwareAddress()));        console.printf("MTU: %s%n", netint.getMTU());            List<InterfaceAddress> interfaceAddresses =             netint.getInterfaceAddresses();        for (InterfaceAddress addr : interfaceAddresses) {          console.printf(              "InterfaceAddress: %s%n", addr.getAddress());        }        console.printf("%n");        Enumeration<NetworkInterface> subInterfaces =             netint.getSubInterfaces();        for (NetworkInterface networkInterface : Collections.list(            subInterfaces)) {          console.printf("%nSubInterface%n");          displayInterfaceInformation(networkInterface);        }        console.printf("%n");      }    }  
Run the updated ListNets in Java SE 6.0. Again, the output depends on your system configuration. Note that some information might not be accessible for security reasons.
    > java ListNets       Display name: MS TCP Loopback interface    Name: lo    InetAddress: /127.0.0.1    Parent: null    Up? true    Loopback? true    PointToPoint? false    Supports multicast? false    Virtual? false    Hardware address: null    MTU: 1520    InterfaceAddress: /127.0.0.1    Broadcast Address: /127.255.255.255    Network Prefix Length: 8     Display name: Intel(R) PRO/100 VE Network Connection -    Packet Scheduler Miniport    Name: eth0    Parent: null    Up? false    Loopback? false    PointToPoint? false    Supports multicast? false    Virtual? false    Hardware address: [0, 1, 2, 3, 4, 5]    MTU: 1500        Display name: RCA USB Cable Modem - Packet Scheduler Miniport    Name: eth1    InetAddress: /11.22.33.44    Parent: null    Up? true    Loopback? false    PointToPoint? false    Supports multicast? false    Virtual? false    Hardware address: [0, 2, 3, 4, 5, 6]    MTU: 1500    InterfaceAddress: /11.22.33.44    Broadcast Address: /11.22.33.255    Network Prefix Length: 22 
The output shows that the network connection eth1 is up, and connected to the Internet with IP address 11.22.33.44. It also shows that network connection eth0 is down. The loopback interface is up (and should always be up).

Compare the results of the program to what you get from something like the ipconfig command (with the /all option). You'll see very similar results.

For more information about network programming with the Java platform, see the Custom Networking trail in the The Java Tutorial.

Back to Top

DIALOG MODALITY
 

Top-level popup windows in "Java-speak" are called dialog boxes (or simply "dialogs"). They are typically used to interact with a user -- either to display a message or to accept user input. Before Java SE 6, dialog boxes were modeless by default, with an option to be modal. When a dialog box is modal, other windows in the application are blocked from accepting input, unless they have the dialog box as their owner. After a user reacts accordingly to a dialog box, that is, by entering input or just closing the dialog, the other windows of the application become accessible again.

Java SE 6 gives you more options regarding dialog modality. No longer are you limited in scope to one level of modality: on or off. Now you have four distinct settings defined by the new Dialog.ModalityType enumeration:
  • MODELESS
  • APPLICATION_MODAL
  • DOCUMENT_MODAL
  • TOOLKIT_MODAL
First let's look at MODELESS and APPLICATION_MODAL. A MODELESS setting means a modeless dialog box. As before, a modeless dialog box does not block input to any other window of the application. Another modal dialog box could block input to it, but a modeless one has no effect on another. If you call the setModal() method of the Dialog class with a value of false, it sets the Dialog.ModalityType to MODELESS.

The APPLICATION_MODAL setting means a modal dialog box. As before, all windows of the application that do not have the modal dialog box in their owner hierarchy are blocked from getting focus. This means that new windows can be created from the modal dialog and will accept input. However, new windows created from other pre-existing windows cannot. If you call the setModal() method of Dialog with a value of true, it sets the modality of the Dialog to DEFAULT_MODALITY_TYPE, which equates to APPLICATION_MODAL. This keeps legacy code valid, though new code should use the new setModalityType() method.

At this point you might ask what if you don't explicitly specify a modality? The answer is that the initial modality is modeless. Also, if you specify a boolean modality, it produces the same settings as calling setModal() with that boolean value. The last option is explicitly setting the modality, which has the obvious effect.

DOCUMENT_MODAL and TOOLKIT_MODAL are where things get interesting. DOCUMENT_MODAL allows you to have different sets of windows that are modal. For instance, you can have a modal application window that displays a help window. Provided that it has a top-level window that is not part of the main application hierarchy, the help window can be modal. In addition, the help window can create other modal windows that have a modality separate from the main window and separate from any modal dialogs that the help window creates. Having a modal application that displays a modal help window is a common need when utilizing the JavaHelp library. It's typical that users want to be able to interact with help, even when the current window is modal. This need wasn't adequately met prior to support for DOCUMENT_MODAL because the main application window and help window had different owner hierarchies.

Think of TOOLKIT_MODAL as APPLICATION_MODAL, where the application is the browser. (In this paragraph what's said about applets also applies to applications started through Java WebStart technology.) This setting allows one applet in a browser to be modal, blocking other applets from accepting input. That's because all the applets are loaded with the same Toolkit. Your applet must have AWTPermission.toolkitModality enabled for TOOLKIT_MODAL to work.

In addition to setting the modality type of a window, you can set the modal exclusion type by calling the setModalExclusionType() method of Window. This allows you to exclude certain windows from behaving according to the pertinent modality type. The setModalExclusionType() method accepts one of three values from the Dialog.ModalExclusionType enumeration:

  • NO_EXCLUDE
  • APPLICATION_EXCLUDE
  • TOOLKIT_EXCLUDE
The NO_EXCLUDE option means no modal exclusion. The window behaves according to its current modality type. The other two settings allow you to use a modality type, but also allow specific windows to accept input focus. The APPLICATION_EXCLUDE setting specifies that at the application level, the window will not behave according to its modality. TOOLKIT_EXCLUDE specifies that at both the application and Toolkit level, the window will not behave according to its modality. There is no way to have a window exclude behavior at the Toolkit level, but not at the application level.

Before using either the modality types or the exclusion option, you can ask the Toolkit if either is supported. To discover if a particular modality is supported, use the boolean isModalityTypeSupported(Dialog.ModalityType modalityType) method. To discover if an exclusion type is supported, use the boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType modalExclusionType) method.

Here's a program, DualModal, that displays two frames that use the DOCUMENT_MODAL setting. Each frame has a button that creates a document modal option pane, accepting input. The label of the selected button changes to the text that was entered when the option pane closes.

    import javax.swing.*;    import java.awt.*;    import java.awt.event.*;     public class DualModal {      public static void main(String args[]) {        Runnable runner = new Runnable() {          public void run() {            JFrame frame1 = new JFrame("Left");            JFrame frame2 = new JFrame("Right");            frame1.setDefaultCloseOperation(               JFrame.EXIT_ON_CLOSE);            frame2.setDefaultCloseOperation(               JFrame.EXIT_ON_CLOSE);            JButton button1 = new JButton("Left");            JButton button2 = new JButton("Right");            frame1.add(button1, BorderLayout.CENTER);            frame2.add(button2, BorderLayout.CENTER);            ActionListener listener = new ActionListener() {              public void actionPerformed(ActionEvent e) {                JButton source = (JButton)e.getSource();                String text = getNewText(source);                if (!JOptionPane.UNINITIALIZED_VALUE.equals(text)                    && text.trim().length() > 0) {                  source.setText(text);                }              }            };            button1.addActionListener(listener);            button2.addActionListener(listener);            frame1.setBounds(100, 100, 200, 200);            frame1.setVisible(true);            frame2.setBounds(400, 100, 200, 200);            frame2.setVisible(true);          }        };        EventQueue.invokeLater(runner);      }         private static String getNewText(Component parent) {           JOptionPane pane = new JOptionPane(             "New label", JOptionPane.QUESTION_MESSAGE          );         pane.setWantsInput(true);         JDialog dialog = pane.createDialog(parent, "Enter Text");         // Uncomment line and comment out next          //  to see application modal         // dialog.setModalityType(         //   Dialog.ModalityType.APPLICATION_MODAL);         dialog.setModalityType(            Dialog.ModalityType.DOCUMENT_MODAL);         dialog.setVisible(true);         return (String)pane.getInputValue();      }    } 
Notice how you can interact with the top-level dialog, but not the frame under either of them when the dialog is shown.

Here is what the initial pair of frames look like:

dialogmod1 Window

And here are the two frames with their respective option panes:

dialogmod2 Window

You might think that changing the setModalityType() line to use APPLICATION_MODAL would allow you to interact with both option frames simultaneously. It won't. You need to finish using one option frame before you can bring up the other.

Two points worth mentioning here. Changing the modality of an already displayed window has no effect. You must hide the dialog box and make it visible again for the new modality setting to take effect.

Also, prior to Java SE 6, any AWT Window or subclass could use the setAlwaysOnTop() method of Window to request that it is always displayed on top. This is not the same as modal and does not prevent other windows from getting input focus.

For more information on dialog modality, see the article The New Modality API in Mustang.

Back to Top

Rate and Review
Tell us what you think of the content of this page.
Excellent   Good   Fair   Poor  
Comments:
If you would like a reply to your comment, please submit your email address:
Note: We may not respond to all submitted comments.
Comments? Send your feedback on the Tech Tips: http://developers.sun.com/contact/feedback.jsp?category=newslet

If you have your own Tech Tip that you would like to share with others, you're encouraged to post it in an appropriate Sun Developer Network forum.

Subscribe to the following newsletters for the latest information about technologies and products in other Java platforms:
  • Enterprise Java Technologies Tech Tips. Get tips on using enterprise Java technologies and APIs, such as those in the Java 2 Platform, Enterprise Edition (J2EE).
  • Wireless Developer Tech Tips. Get tips on using wireless Java technologies and APIs, such as those in the Java 2 Platform, Micro Edition (J2ME).
You can subscribe to these and other Java technology developer newsletters or manage your current newsletter subscriptions on the Sun Developer Network Subscriptions page

ARCHIVES: You'll find the Core Java Technologies Tech Tips archives at:
http://java.sun.com/developer/JDCTechTips/index.html

IMPORTANT: Please read our Terms of Use, Privacy, and Licensing policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/
http://developer.java.sun.com/berkeley_license.html

© 2006 Sun Microsystems, Inc. All Rights Reserved. For information on Sun's trademarks see: http://sun.com/suntrademarks
Java, J2EE, J2SE, J2ME, and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.

Sun Microsystems, Inc. 10 Network Circle, MPK10-209 Menlo Park, CA 94025 US



Please unsubscribe me from this newsletter.


 
Comments: Post a Comment



<< Home
News, Articles, events from all over the world

My Photo
Name:
Location: India

Born on shraavana shudha chauthi of dundubhi naama samvaswara, Im kiran alias kini alias kiri bought up by loving parents. Being from agricultural family I have learnt plowing, carting but never learnt climbing trees. Now away from home I have lost touch with the agricultural skills.

ARCHIVES
January 2006 / February 2006 / March 2006 / April 2006 / May 2006 / June 2006 / July 2006 / August 2006 / September 2006 / October 2006 / November 2006 / December 2006 / April 2007 / May 2007 / June 2007 / July 2007 / August 2007 / September 2007 / October 2007 / November 2007 / December 2007 / January 2008 / February 2008 / March 2008 / April 2008 / May 2008 / June 2008 / July 2008 / August 2008 / September 2008 / October 2008 / November 2008 / December 2008 / January 2009 / February 2009 / March 2009 / April 2009 /


Powered by Blogger