Checking whether an XML node has attributes

Use the method hasAttributes defined in the interface Node, a superinterface of Element.

Main.java:

import org.w3c.dom.*;
  
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
 
import java.io.*;
   
public class Main
{
   public static void main(String []args) {
      Document doc;
  
      try {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         doc = db.parse(new File("customers.xml"));
 
         Element root = doc.getDocumentElement();
         if (root.hasAttributes()) {
            System.out.println(root.getTagName() + " has attributes!");
         }
         else {
            System.out.println(root.getTagName() + " has no attributes!");
         }
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}

customers.xml (!!remove the space between ? and xml):

<? xml version="1.0" encoding="UTF-8"?>
<customers id="1">
   <customer id="C12345" type="prio1">
      <name>Joris Van den Bogaert</name>
      <address>
         <addressline>Handelskaai 3</addressline>
         <zip>1000</zip>
         <location>Brussels</location>
         <country>BELGIUM</country>
      </address>
   </customer>
</customers>

Retrieve a Java object from a file on the local file system using JDNI

You can bind an object into a context, provided your object is a Reference or implements the Referenceable interface. The object is stored in a file called .bindings as a set of properties.

The following example shows how to read the object created in the QA How do I store a Java object in a file on the local file system using JNDI?.

Read.java:

import javax.naming.event.*;
import javax.naming.*;
import java.util.*;
import java.io.*;
  
public class Read
{
   public static void main(String []args) {
      try {
         Properties properties = new Properties();
         properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
         properties.put(Context.PROVIDER_URL, "file:///");
 
         InitialContext ctx = new InitialContext(properties);
 
         Context context = (Context) ctx.lookup("c:\temp\");
 
         Member member = (Member) context.lookup("member.obj");
         System.out.println(member);
 
         ctx.close(); 
      }
      catch(NamingException ne) {
         ne.printStackTrace();
      }
   }
}

prints out:

[Joris Van den Bogaert, joris1@esus.com]

Storing and retrieving a serialized object in a database table

As an example, I created the following table:

mysql> create table objects (objectid int(10) not null auto_increment, 
name varchar(30), data blob, length int(6), primary key(objectid));
Query OK, 0 rows affected (0.12 sec)
 
mysql> desc images;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| objectid | int(10)     |      | PRI | NULL    | auto_increment |
| name     | varchar(30) | YES  |     | NULL    |                |
| length   | int(6)      | YES  |     | NULL    |                |
| data     | blob        | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+

In the following code, a string array is serialized and stored in the objects table.

Main.java:

import java.sql.*;
import java.io.*;  
 
public class Main {
   public static void main(String []args) {
      try {
         Class.forName("org.gjt.mm.mysql.Driver").newInstance();
         Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.0.1/esus", 
                                                       "joris",
                                                       "mypass");
 
         String stringArray[] = { "this", "is", "a", "test" };       
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(baos);
         oos.writeObject(stringArray);
 
         PreparedStatement insertStmt = conn.prepareStatement(
                                       "INSERT INTO objects (name, length, data) " +
                                       "VALUES (?, ?, ?)");
         insertStmt.setString(1, "stringarray");
         byte[] buffer = baos.toByteArray();
         insertStmt.setInt(2, buffer.length);
         insertStmt.setBytes(3, buffer);
         insertStmt.execute();
 
         oos.close();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}

To read it back in:
Main.java:

import java.sql.*;
import java.io.*;  
 
public class Main {
   public static void main(String []args) {
      try {
         Class.forName("org.gjt.mm.mysql.Driver").newInstance();
         Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.0.1/esus", 
                                                       "joris",
                                                       "mypass");
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT name, length, data FROM objects");
      
         if (rs.next()) {
            String name = rs.getString("name");
            int length = rs.getInt("length");
            byte[] buf = rs.getBytes("data");
 
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(buf));
            String[] stringArray = (String[]) ois.readObject();
            ois.close();
 
            for (int i=0; i<stringArray.length; i++) {
               System.out.println(stringArray[i]);
            }
         }
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}

outputs:

this
is
a
test

Writing an Exception stack trace to a String

Main.java:

import java.io.*;

public class Main {
   public static void main(String []args) {
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      Exception e = new Exception();
      e.printStackTrace(pw);
      System.out.println(sw.toString());
   }
}

In NIO, what is the difference between a mandatory lock and an advisory lock?

A lock makes it possible to lock an entire file or a region of a file. Some filesystems implement advisory locking, which means that programs must all work together in order to preserve file integrity. It’s similar to having a synchronized block, which doesn’t really prevent your data from being corrupted, but just prevents threads to acquire the same lock.
If mandatory locking is implemented in a filesystem, a process cannot access a file or a region on a file in a way that would violate the lock.

Configuring Tomcat to use SSL

SSL stands for Secure Socket Layer. It allows the communication between your browser and the webserver to be encrypted. Tomcat is a Servlet/JSP container but is just a simple webserver as well. Typically, the Apache web server is used to serve static pages while the servlet/JSP requests are redirected to the Tomcat container. Then you can simply configure SSL on the Apache Web server level, in which case you would not need to do SSL configuration on Tomcat itself. It is useful however if you are running Tomcat standalone.

1) Install JSSE

If you are not using JDK1.4+, you need to install JSSE separately. I was using JDK1.3.1 to create this example, and to make it easy, I copied to files jcert.jar, jnet.jar, jsse.jar into c:\jdk1.3.1\jre\lib\ext. If you do this, you don’t need to fiddle around with the classpath. You can d/l JSSE here: http://java.sun.com/products/jsse/.

2) Create a keystore file that contains your certificate:

C:\Program Files\Apache Tomcat 4.0>keytool -genkey -alias tomcat -keyalg RSA 
                                           -keystore tomcatkeystore.kst
Enter keystore password:  123456
What is your first and last name?
  [Unknown]:  Joris Van den Bogaert
What is the name of your organizational unit?
  [Unknown]:  Esus
What is the name of your organization?
  [Unknown]:  Esus
What is the name of your City or Locality?
  [Unknown]:  Brussels
What is the name of your State or Province?
  [Unknown]:
What is the two-letter country code for this unit?
  [Unknown]:  BE
Is <CN=Joris Van den Bogaert, OU=Esus, O=Esus, L=Brussels, ST=Unknown, C=BE> correct?
  [no]:  yes
 
Enter key password for <tomcat>
        (RETURN if same as keystore password):  123456

3) Modify TOMCAT-HOME/bin/server.xml

You can just uncomment the SSL connector. Modify it so that it points to the keystore file that you just created:

    <!-- Define an SSL HTTP/1.1 Connector on port 8443 -->
    <Connector className="org.apache.catalina.connector.http.HttpConnector"
               port="8443" minProcessors="5" maxProcessors="75"
               enableLookups="true"
	       acceptCount="10" debug="0" scheme="https" secure="true">
      <Factory className="org.apache.catalina.net.SSLServerSocketFactory"
               clientAuth="false" protocol="TLS"
               keystoreFile="tomcatkeystore.kst" 
               keystorePass="123456"/>
    </Connector>

Note 1: 8443 is the port number that Tomcat will listen to for secure connections. If you want
to use another port number, make sure you also change the redirectPort attribute in the non-SSL connector to point to the port you choose.

Note 2: If you didn’t specify the option -keystore when creating your certificate, the keystore would have been stored in your home directory as .keystore. In that case, you don’t need to specify the keystoreFile nor keystorePass.

4) Restart Tomcat

5) Check it out: https://localhost:8443

Creating a JFace ApplicationWindow with MenuBar

Main.java:

import org.eclipse.jface.dialogs.*;
import org.eclipse.jface.action.*;
import org.eclipse.jface.window.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.*;
 
public class Main extends ApplicationWindow {
   public Main(Shell parent) {
      super(parent);
   }
   
   public static void main(String []args) {
      Display display = new Display();
      Shell shell = new Shell(display);
      
      Main main = new Main(shell);
      main.createComponents();
      main.open();
   }
 
   public void createComponents() {
      setBlockOnOpen(true);
      addMenuBar();
   }
   
   protected MenuManager createMenuManager() {
      MenuManager menuManager = new MenuManager();
      menuManager.add(createFileMenu());
      return menuManager;
   }
   
   protected MenuManager createFileMenu() {
      MenuManager menu = new MenuManager("&File", "Id01");

      menu.add(new Action() {
         public String getText() {
            return "&Open";
         }
         
         public void run() {
            String[] buttons = { IDialogConstants.OK_LABEL,
                                  IDialogConstants.CANCEL_LABEL };
            MessageDialog dialog = new MessageDialog(getShell(), "Title", null, 
                                                     "File/Open selected!", 
                                                     MessageDialog.INFORMATION, buttons, 0);
            dialog.open();   // blocking call
         }
      });

      menu.add(new Action() {
         public String getText() {
            return "E&xit";
         }
         
         public void run() {
            Main.this.getParentShell().close();
         }
      });
       
      return menu;
   }
    
   protected void configureShell(Shell shell) {
      super.configureShell(shell);
      shell.setSize(300, 200);
      shell.setText("Example JFace with MenuBar");
   }  
}

Making an SWT combobox read-only

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;

public class Main {
   public static void main(String[] args) {
      Display display = new Display();
      Shell shell = new Shell(display);

      // pos x, pos y, width, height
      shell.setBounds(200, 200, 300, 200);
      shell.setText("SWT Simple Editable Combobox Demonstration");
      shell.setLayout(new GridLayout());

      String[] comboData = { "one", "two", "three", "four", "five",
                             "six", "seven", "eight", "nine", "ten",
                             "eleven", "twelve", "thirtheen", "fourteen",
                             "fifteen", "sixteen", "seventeen", "eighteen",
                             "nineteen", "twinty" };

      Group comboGroup = new Group(shell, SWT.NULL);
      GridLayout gridLayout = new GridLayout();
      gridLayout.numColumns = 1;
      comboGroup.setLayout(gridLayout);
      comboGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
      comboGroup.setText("Non-Editable Combo");
      
      Combo combo = new Combo(comboGroup, SWT.DROP_DOWN | SWT.READ_ONLY);
      
      SelectionListener selectionListener = new SelectionAdapter () {
         public void widgetSelected(SelectionEvent event) {
            Combo combo = ((Combo) event.widget);
            System.out.print(combo.getText());
            System.out.println(" selected = " + combo.getSelection());
         };
      };
      combo.addSelectionListener(selectionListener);
      combo.setItems(comboData);
      
      shell.open();

      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      display.dispose();
   }
}

Creating a checked SWT Table

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
 
public class Main {
   public static void main(String[] args) {
      Display display = new Display();
      Shell shell = new Shell(display);
 
      // pos x, pos y, width, height
      shell.setBounds(200, 200, 300, 200);
      shell.setText("SWT Table Demonstration");
      shell.setLayout(new GridLayout());
 
      final Table table;
      String[] columnTitles = { "Wine", "Vintage", "Price" };
 
      Object[][] tabledata = {
            { "Chateau Meyney, St. Estephe",       new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe",     new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien",        new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
      };
 
      Group tableGroup = new Group(shell, SWT.NULL);
      GridLayout gridLayout = new GridLayout();
      gridLayout.numColumns = 1;
      tableGroup.setLayout(gridLayout);
      tableGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
      tableGroup.setText("Table");
 
      table = new Table(tableGroup, SWT.FULL_SELECTION | SWT.CHECK);
      table.setHeaderVisible(true);
       
      for (int i=0; i<columnTitles.length; i++) {
         TableColumn tableColumn = new TableColumn(table, SWT.NULL);
         tableColumn.setText(columnTitles[i]);
      }  
       
      for (int i=0; i<tabledata.length; i++) {
         TableItem tableItem = new TableItem(table, SWT.NULL);
         for (int j=0; j<columnTitles.length; j++) {
            tableItem.setText(j, ""+tabledata[i][j]);
         }
      }
 
      for (int i=0; i<columnTitles.length; i++) {
         TableColumn tableColumn = table.getColumn(i);
         tableColumn.pack();
      }      
       
      shell.open();
       
      shell.addShellListener(new ShellAdapter() {
         public void shellClosed(ShellEvent se) {
            for (int i=0; i<table.getItemCount(); i++) {
               TableItem tableItem = table.getItem(i);
               System.out.println(tableItem.getText(0));
               System.out.println("tChecked: " + tableItem.getChecked());
            }                        
         }
      });
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
       
      display.dispose();
      
   }
}

Creating a smooth ProgressBar in SWT

Main.java:

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
 
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
 
public class Main {
   private DownloadThread downloadThread = null;
   private boolean disposed = false;
    
   public Main() {
      final Display display = new Display();
      Shell shell = new Shell(display);
      shell.setText("SWT Smooth ProgressBar Demonstration");

      shell.setLayout(new FormLayout());
      shell.setBounds(200, 200, 700, 200);
       
      Label downloadLabel = new Label(shell, SWT.NONE);
      FormData data0 = new FormData();
      data0.left = new FormAttachment(0, 0);
      //data0.top = new FormAttachment(localLabel, 15);
      //data2.right = new FormAttachment(100, -100);
      downloadLabel.setLayoutData(data0);
      downloadLabel.setText("FTP file: ");
 
      final Text downloadField = new Text(shell, SWT.SINGLE | SWT.BORDER);
      FormData data1 = new FormData();
      data1.left = new FormAttachment(downloadLabel, 15);
      data1.right = new FormAttachment(100, -100);
      downloadField.setLayoutData(data1);
      downloadField.setText("ftp://ftp.mozilla.org/pub/mozilla/moz-sol/1.2a-02-09-25/mozilla-sparc-sun-solaris2.7.tar.gz");
            
      Label localLabel = new Label(shell, SWT.NONE);
      FormData data2 = new FormData();
      data2.left = new FormAttachment(0, 0);
      data2.top = new FormAttachment(localLabel, 15);
      localLabel.setLayoutData(data2);
      localLabel.setText("Save As: ");
      
      final Text localField = new Text(shell, SWT.SINGLE | SWT.BORDER);
      FormData data3 = new FormData();
      data3.left = new FormAttachment(localLabel, 15);
      data3.top = new FormAttachment(downloadField, 5);
      data3.right = new FormAttachment(100, -400);
      localField.setLayoutData(data3);
      localField.setText("c:\temp\tmp.bin");
      
      final Button downloadButton = new Button(shell, SWT.NONE);
      FormData data4 = new FormData();
      data4.left = new FormAttachment(downloadField, 5);
      data4.right = new FormAttachment(100, -5);
      downloadButton.setLayoutData(data4);
      downloadButton.setText("Download");
      
      Label progressLabel = new Label(shell, SWT.NONE);
      progressLabel.setText("Download progress:");
      FormData data5 = new FormData();
      data5.top = new FormAttachment(localField, 15);
      data5.left = new FormAttachment(10, 15);      
      data5.right = new FormAttachment(90, -15);
      progressLabel.setLayoutData(data5);      
             
      final ProgressBar progressBar = new ProgressBar(shell, SWT.SMOOTH);
      FormData data6 = new FormData();
      data6.top = new FormAttachment(localField, 35);
      data6.left = new FormAttachment(10, 15);      
      data6.right = new FormAttachment(90, -15);
      progressBar.setLayoutData(data6);
 
      shell.open();
 
      final DownloadListener downloadListener = new DownloadListener() {
         public void setMinimum(final int min) {
            display.asyncExec(new Runnable() {
               public void run() {
                  if (!disposed) {
                     progressBar.setMinimum(min);
                  }
               }
            });
         }
         
         public void setMaximum(final int max) {
            display.asyncExec(new Runnable() {
               public void run() {
                  if (!disposed) {
                     progressBar.setMaximum(max);
                  }
               }
            });
         }
         
         public void setSelection(final int selection) {
            display.asyncExec(new Runnable() {
               public void run() {
                  if (!disposed) {
                     progressBar.setSelection(selection);
                  }
               }
            });
         }
         
         public void downloadEnded() {
            if (!disposed) {
               display.asyncExec(new Runnable() {
                  public void run() {
                     System.out.println("disposed = " + disposed);
                     if (!disposed) {                  
                        downloadButton.setText("Download");  
                     }
                  }
               });
            }
         }
      };
      
      downloadButton.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(SelectionEvent event) {
            try {
               Button button = (Button) event.getSource();
               if (button.getText().equalsIgnoreCase("download")) {
                  if (downloadField.getText().trim().equals("")) return;
                  
                  File localFile = new File(localField.getText());
                  downloadThread = new DownloadThread(downloadListener, 
                                                      localFile,
                                                      new URL(downloadField.getText()));
                  downloadThread.start();
                  downloadButton.setText("Stop");
               }
               else {
                  downloadThread.terminate();
               }
            }
            catch(MalformedURLException e) {
               e.printStackTrace();
            }
         };
      });
 
      shell.addShellListener(new ShellAdapter() {
         public void shellClosed(ShellEvent se) {
            disposed = true;     
            if (downloadThread != null) {         
               downloadThread.terminate();
            }
         }
      });        
      
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      
      display.dispose();
   }
   
   public static void main(String[] args) {
      new Main();
   }
}
 
interface DownloadListener {
   public void setMinimum(int min);
   public void setMaximum(int max);
   public void setSelection(int selection);
   public void downloadEnded();
}
 
class DownloadThread extends Thread
{
   private int length = 0;
   private URL url = null;
   private File localFile = null;
   private DownloadListener listener = null;
   private boolean terminated = false;
   
   public DownloadThread(DownloadListener listener, File localFile, URL url) {
      this.url = url;
      this.localFile = localFile;
      this.listener = listener;
   }
   
   public void terminate() {
      terminated = true;
   }
   
   public void run() {
      try {
         System.out.println(url);
         URLConnection con = url.openConnection();
         System.out.println("Connecting...");
         con.connect();
         System.out.println("Connected!");
         int length = con.getContentLength();
 
         listener.setMinimum(0);
         listener.setMaximum(length);
          
         int block = 4096;
         int count = 0;
         FileOutputStream fos = new FileOutputStream(localFile);
         InputStream is = con.getInputStream();
         byte[] buff = new byte[block];
         int read = 0;
 
         listener.setSelection(0);
         while((read = is.read(buff, 0, block)) != -1) {
            byte[] bytes;
            if(read != buff.length) {
               bytes = new byte[read];
               System.arraycopy(buff, 0, bytes, 0, read);
            } 
            else {
               bytes = buff;
            }
            fos.write(bytes);
            count += read;
           
            if (terminated) {
               break;
            }
 
            listener.setSelection(count);
         }
         fos.flush();
         fos.close();
         
         listener.downloadEnded();
      } catch(Exception e) {
         System.out.println("Error downloading file " + url);
         e.printStackTrace();
      }
   }
}