List out the elements that belong to a particular XML namespace

For more information about namespaces, check out http://www.jclark.com/xml/xmlns.htm.

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

<? xml version="1.0" encoding="UTF-8"?>
<customers xmlns='http://www.esus.com/custns'>
   <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>
   <destination>
      <address xmlns='http://www.esus.com/destns'>123.321.1.20</address>
   </destination>
</customers>

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();
         dbf.setNamespaceAware(true);
         DocumentBuilder db = dbf.newDocumentBuilder();
         doc = db.parse(new File("customers.xml"));
 
         Element root = doc.getDocumentElement();
         root.normalize();
 
         // display all custns elements
         NodeList nl = doc.getElementsByTagNameNS("http://www.esus.com/custns", "*");
         System.out.println("Elements that belong to http://www.esus.com/custns namespace:");
         printNodeList(nl);
 
         // display all destns elements
         nl = doc.getElementsByTagNameNS("http://www.esus.com/destns", "*");
         System.out.println("Elements that belong to http://www.esus.com/destns namespace:");
         printNodeList(nl);          
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
 
   public static void printNodeList(NodeList nl) {
      for (int i=0; i<nl.getLength(); i++) {
         Node n = nl.item(i);
         System.out.println("t" + n.getNodeName());
         Node tn = n.getFirstChild();
         if (!tn.getNodeValue().trim().equals("")) {   
            System.out.println("tt" + tn.getNodeValue());
         }
         System.out.println();
      }
   }
}

outputs:

Elements that belong to http://www.esus.com/custns namespace:
	customers
 
	customer
 
	name
		Joris Van den Bogaert
 
	address
 
	addressline
		Handelskaai 3
 
	zip
		1000
 
	location
		Brussels
 
	country
		BELGIUM
 
	destination
 
Elements that belong to http://www.esus.com/destns namespace:
	address
		123.321.1.20

Creating a database table using JDBC

Check out the MySQL syntax for CREATE TABLE here.

Here’s an example that creates 4 tables in the database esus. Create your SQL create table query string and call executeUpdate on a Statement.

Main.java:

import java.util.*;
import java.sql.*;
 
public class Main {
   public static void main(String []args) {
      try {
         Database db = new Database("org.gjt.mm.mysql.Driver",
                                    "jdbc:mysql://192.168.0.1/esus",
                                    "joris",
                                    "mypass");
 
         db.createTable("customers", "custid int(10) not null auto_increment, " +
                                     "name varchar(30), " +
                                     "email varchar(50), " + 
                                     "primary key(custid)");
         db.createTable("products", "prodid int(10) not null auto_increment, " +
                                    "description varchar(100), " +
                                    "price float(6, 2), " +
                                    "itemsleft int(10), " +
                                    "primary key(prodid)");
         db.createTable("orders", "orderid int(10) not null auto_increment, " + 
                                  "custid int(10), " +
                                  "timestamp datetime, " +
                                  "status tinyint, " +
                                  "primary key(orderid), " +
                                  "index custid (custid)");
         db.createTable("orderitems", "orderid int(10) not null, " +
                                      "prodid int(10) not null, " + 
                                      "quantity int(5) not null, " +
                                      "price float(10, 2) not null, " + 
                                      "primary key(orderid, prodid)";
         db.createTable("accounts", "accountid int(10) not null auto_increment, " +
                                    "custid int(10), " +
                                    "balance float(10,2), " +
                                    "primary key(accountid)");
      }
      catch(Database.DatabaseException e) {
         e.printStackTrace();
      }
   }
}
 
class Database
{
   Connection connection = null;
  
   public Database(String driver, String url, String user, String pass) 
                      throws DatabaseException 
   {
      try {
         Class.forName(driver).newInstance();
 
         connection = DriverManager.getConnection(url, user, pass);
      }
      catch(Exception e) {
         throw new DatabaseException(e.getMessage());
      }
   }
 
   public void createTable(String table, String columns) throws DatabaseException {
      try {
         Statement stmt = connection.createStatement();
         stmt.executeUpdate("create table " + table + " (" + columns + ")");
         stmt.close();
      }
      catch(SQLException e) {
         throw new DatabaseException(e.getMessage());
      }
   }
 
   public class DatabaseException extends Exception {
      public DatabaseException() {
      }
 
      public DatabaseException(String message) {
         super(message);
      }
   }
}   

Updating a row in the resultset

You can always execute an UPDATE statement with the new changes. JDBC2.0 provides another way. It allows you to make changes to a row from ResultSet and reflect the changes in the database.

before:

+---------+--------+---------------------+--------+
| orderid | custid | timestamp           | status |
+---------+--------+---------------------+--------+
|       1 |      1 | 2001-10-13 17:33:11 |      0 |
|       2 |      1 | 1972-12-12 00:00:00 |      1 |
|       3 |      1 | 1999-02-01 00:00:00 |      2 |
|       4 |      2 | 2001-05-01 00:00:00 |      0 |
+---------+--------+---------------------+--------+

Main.java:

import java.util.*;
import java.text.*;
import java.sql.*;
  
public class Main {
   public static void main(String []args) throws Exception {
      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.TYPE_SCROLL_SENSITIVE,
                                               ResultSet.CONCUR_UPDATABLE);
 
         ResultSet rs = stmt.executeQuery("SELECT * FROM orders WHERE orderid = 1"); 
 
         if (rs.next()) {
            // change the status column
            rs.updateInt("status", 1);
            // store changes in database
            rs.updateRow();
         }
 
         stmt.close();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}

after:

+---------+--------+---------------------+--------+
| orderid | custid | timestamp           | status |
+---------+--------+---------------------+--------+
|       1 |      1 | 2001-10-13 17:33:11 |      1 |
|       2 |      1 | 1972-12-12 00:00:00 |      1 |
|       3 |      1 | 1999-02-01 00:00:00 |      2 |
|       4 |      2 | 2001-05-01 00:00:00 |      0 |
+---------+--------+---------------------+--------+

Creating an email containing attachments using JavaMail

This simple example creates an .eml file (which you can open with eg. Outlook Express) containing the file c:autoexec.bat as an attachment.

Creating an attachment with JavaMail is simple: pass a DataSource instance to the constructor of DataHandler and add it to a MimeBodyPart. Add all the MimeBodyParts to a Multipart instance and initialize the message with it.

Main.java:

import javax.activation.*;
import javax.mail.internet.*;
import javax.mail.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      Message message = new MimeMessage((Session) null);
      message.setFrom(new InternetAddress("source@source.com"));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress("dest@dest.com"));
      message.setSubject("JavaMail attachment test");
 
      // create a multipart instance
      Multipart multipart = new MimeMultipart();
 
      // create the body of the email 
      BodyPart bodyPart = new MimeBodyPart();
      bodyPart.setText("Body of email");      
      multipart.addBodyPart(bodyPart);
 
      // create a file attachment
      bodyPart = new MimeBodyPart();
      DataSource source = new FileDataSource("c:\autoexec.bat");
      bodyPart.setDataHandler(new DataHandler(source));
      // remember the name of the file
      bodyPart.setFileName("autoexec.bat");
      multipart.addBodyPart(bodyPart);
 
      message.setContent(multipart);
 
      // write it to an .eml file [or send it with Transport.send(message) ]
      message.writeTo(new BufferedOutputStream(new FileOutputStream("test.eml")));
   }
}

CharSets available on your machine

Main.java:

import java.nio.charset.*;
import java.util.*;
 
public class Main
{
   public static void main(String []args) {
      SortedMap charsets = Charset.availableCharsets();
 
      Collection c = charsets.values();
      Iterator charsetIterator = c.iterator();
      while (charsetIterator.hasNext()) {
         Charset charset = (Charset) charsetIterator.next();         
         System.out.println(charset + " with aliases:");
 
         Set aliases = charset.aliases();
         Iterator aliasIterator = aliases.iterator();
         while (aliasIterator.hasNext()) {
            String alias = (String) aliasIterator.next();
            System.out.println("t" + alias);
         }
         System.out.println();
      }
   }
}

outputs on my Win2000 machine:

ISO-8859-1 with aliases:
	ISO_8859-1:1987
	ISO8859_1
	8859_1
	iso-ir-100
	cp819
	ISO_8859_1
	ISO8859-1
	latin1
	IBM819
	IBM-819
	l1
	ISO_8859-1
	csISOLatin1
	819

ISO-8859-15 with aliases:
	8859_15
	923
	LATIN9
	ISO_8859-15
	ISO8859_15_FDIS
	cp923
	L9
	LATIN0
	csISOlatin9
	ISO8859-15
	IBM923
	ISO-8859-15
	IBM-923
	csISOlatin0

US-ASCII with aliases:
	us
	ISO_646.irv:1991
	ANSI_X3.4-1968
	iso-ir-6
	646
	ISO646-US
	cp367
	ANSI_X3.4-1986
	csASCII
	ASCII
	iso_646.irv:1983
	IBM367

UTF-16 with aliases:
	UTF_16

UTF-16BE with aliases:
	X-UTF-16BE
	ISO-10646-UCS-2
	UTF_16BE

UTF-16LE with aliases:
	UTF_16LE
	X-UTF-16LE

UTF-8 with aliases:
	UTF8

windows-1252 with aliases:
	cp1252

Controlling what and where Tomcat logs information

Log files are written by the Tomcat valve AccessLogValve. A valve, Tomcat only, is a Java class that preprocesses access requests. You can associate valves in server.xml to the containers engine, host and context.

To change the location of the log files:

Search TOMCAT_HOME/conf/server.xml for “AccessLogValve”. Specify the attribute directory as shown in this example:

   <Valve className="org.apache.catalina.valves.AccessLogValve"
          directory="c:\tomcatlogs"  prefix="localhost_access_log." suffix=".txt"
          pattern="common"/>

This will cause all the access logs of the hosting container to be written to c:\tomcatlogs.

To change the type of information written in the log files:

Possible attributes for the AccessLogValve are the following.

  • directory: the directory to where the log files are written, can be relative to CATALINA_HOME or absolute, default value: logs
  • pattern: specifies what type of infomration a log line should contain. You can combine any of the following patterns:
    %a - Remote IP address 
    %A - Local IP address 
    %b - Bytes sent, excluding HTTP headers, or '-' if zero 
    %B - Bytes sent, excluding HTTP headers 
    %h - Remote host name (or IP address if resolveHosts is false) 
    %H - Request protocol 
    %l - Remote logical username from identd (always returns '-') 
    %m - Request method (GET, POST, etc.) 
    %p - Local port on which this request was received 
    %q - Query string (prepended with a '?' if it exists) 
    %r - First line of the request (method and request URI) 
    %s - HTTP status code of the response 
    %t - Date and time, in Common Log Format 
    %u - Remote user that was authenticated (if any), else '-' 
    %U - Requested URL path 
    %v - Local server name 
    

    Specifying common is the same as specifying %h %l %u %t “%r” %s %b.
    For example:
    With pattern common:

    127.0.0.1 - - [21/Jul/2002:20:16:31 -0800] "GET /index.html HTTP/1.1" 200 6827
    127.0.0.1 - - [21/Jul/2002:20:16:31 -0800] "GET /tomcat.gif HTTP/1.1" 200 1934
    127.0.0.1 - - [21/Jul/2002:20:16:31 -0800] "GET /jakarta-banner.gif HTTP/1.1" 304 -
    127.0.0.1 - - [21/Jul/2002:20:16:32 -0800] "GET /tomcat-power.gif HTTP/1.1" 304 -
    

    With pattern Request from %a: %r:

    Request from 127.0.0.1: GET /index.html HTTP/1.1
    Request from 127.0.0.1: GET /tomcat.gif HTTP/1.1
    Request from 127.0.0.1: GET /jakarta-banner.gif HTTP/1.1
    Request from 127.0.0.1: GET /tomcat-power.gif HTTP/1.1
    
  • prefix: a string that should be added to the start of each log filename, default value: access_log
  • suffix: a string that should be added to the end of each log filename, default value: empty
  • resolveHosts: a boolean value, if set to true, it will look up the corresponding host name for the requesting IP address. Use it only if absolutely necessary, it will slow down Tomcat a lot.

Embedding IE in an SWT application

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.ole.win32.OleAutomation;
import org.eclipse.swt.ole.win32.OleControlSite;
import org.eclipse.swt.ole.win32.OleFrame;
import org.eclipse.swt.ole.win32.Variant;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
 
public class EmbedIE {
   OleAutomation automation = null;
   
   public EmbedIE() {
      Display display = new Display();
      Shell shell = new Shell(display);

      FormLayout layout= new FormLayout();
      shell.setLayout(layout);

      OleFrame frame = new OleFrame(shell, SWT.PUSH);
      FormData formData = new FormData();
      formData.top = new FormAttachment(0, 10);
      formData.left = new FormAttachment(0, 100);
      formData.right = new FormAttachment(100, 0);
      formData.bottom = new FormAttachment(100, -10);
      frame.setLayoutData(formData);
      OleControlSite controlSite = new OleControlSite(frame, SWT.NONE, "Shell.Explorer");
      controlSite.doVerb(OLE.OLEIVERB_SHOW);
      automation = new OleAutomation(controlSite);
      int[] rgdispid = automation.getIDsOfNames(new String[]{"GoHome"});
      int dispIdMember = rgdispid[0];
      automation.invoke(dispIdMember);
      
      Composite composite = new Composite(shell, SWT.NONE);
      GridLayout gridLayout = new GridLayout();
      gridLayout.numColumns = 1;
      composite.setLayout(gridLayout);
      Button site1 = new Button(composite, SWT.NONE);
      site1.setText("IE Home");
      Button site2 = new Button(composite, SWT.NONE);
      site2.setText("Synergetic");
      Button site3 = new Button(composite, SWT.NONE);
      site3.setText("Esus.com");
      
      site1.addListener(SWT.Selection, new Listener() {
         public void handleEvent(Event e) {
            goHome();
         }
      });      
      
      site2.addListener(SWT.Selection, new Listener() {
         public void handleEvent(Event e) {
            goUrl("www.synergetic-solutions.be");
         }
      });
      
      site3.addListener(SWT.Selection, new Listener() {
         public void handleEvent(Event e) {
            goUrl("www.esus.com");
         }
      });
      
      
      shell.open();
      
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      display.dispose();      
   }
   
   public void goHome() {
      int[] rgdispid = automation.getIDsOfNames(new String[]{"GoHome"});
      int dispIdMember = rgdispid[0];
      automation.invoke(dispIdMember);
   }      
   
   public void goUrl(String url) {
      int[] rgdispid = automation.getIDsOfNames(new String[]{"Navigate"});
      int dispIdMember = rgdispid[0];
      Variant[] rgvarg = new Variant[1]; // this is the URL parameter
      rgvarg[0] = new Variant(url);
      Variant pVarResult = automation.invoke(dispIdMember, rgvarg);      
   }
   
   public static void main(String []args) {
      new EmbedIE();
   }
}

Creating an SWT ColorDialog

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.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
 
public class Main { 
   static Display display;
   static Shell shell;
   static Color color;
    
   public static void main(String[] args) {
      display = new Display();
      shell = new Shell(display);
 
      // pos x, pos y, width, height
      shell.setBounds(200, 200, 400, 200);
      shell.setText("SWT ColorDialog Demonstration");
      shell.setLayout(new GridLayout());
 
      Group buttonGroup = new Group(shell, SWT.NONE);
      GridLayout gridLayout = new GridLayout();
      gridLayout.numColumns = 3;
      buttonGroup.setLayout(gridLayout);
      buttonGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
       
      SelectionListener selectionListener = new SelectionAdapter () {
         public void widgetSelected(SelectionEvent event) {
            RGB rgb = openColorDialog(shell);
            if (rgb != null) {
               if (color != null && !color.isDisposed()) {
                  color.dispose();
               }
                
               color = new Color(display, rgb);
               shell.setBackground(color);
            }
         };
      };
 
      final Button colorDialogButton = new Button(buttonGroup, SWT.PUSH);
      colorDialogButton.setText("Open ColorDialog");
      colorDialogButton.addSelectionListener(selectionListener);
       
      shell.open();

      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      if (color != null && !color.isDisposed()) {
         color.dispose();
      }
      display.dispose();
   }
    
   public static RGB openColorDialog(Shell shell) {
      ColorDialog dialog = new ColorDialog (shell ,SWT.MODELESS);
      dialog.setRGB (new RGB (100, 100, 100));
      dialog.setText("Choose a color!");
      RGB result = dialog.open ();
       
      return result;
   }      
}

Creating an SWT table without a header

Main.java:

import org.eclipse.swt.SWT;
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());
  
      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);
      // default no header!  uncomment to get header!
      //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();
  
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      display.dispose();
   }
}

Creating a slider in SWT

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Slider;
 
public class Main {
   public static void main (String [] args) {
      Display display = new Display ();
      Shell shell = new Shell (display);
    
      shell.setBounds(200, 200, 250, 250);   
       
      Slider slider = new Slider (shell, SWT.VERTICAL);
      slider.setBounds (10, 10, 20, 200);
      final StyledText styledText = new StyledText(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.WRAP);
      styledText.setBounds(40, 10, 190, 200);
       
      slider.addListener (SWT.Selection, new Listener () {
         public void handleEvent (Event event) {
            String evt = "SWT.NONE";
            switch (event.detail) {
               case SWT.ARROW_DOWN: 
                  evt = "SWT.ARROW_DOWN";
                  break;
               case SWT.ARROW_UP: 
                  evt = "SWT.ARROW_UP"; 
                  break;
               case SWT.PAGE_DOWN: 
                  evt = "SWT.PAGE_DOWN"; 
                  break;
               case SWT.PAGE_UP: 
                  evt = "SWT.PAGE_UP"; 
                  break;
               case SWT.HOME: 
                  evt = "SWT.HOME"; 
                  break;
               case SWT.END: 
                  evt = "SWT.END"; 
                  break;
               case SWT.DRAG: 
                  evt = "SWT.DRAG"; 
                  break;
            }
            styledText.append(evt + "n");
            int offset = styledText.getOffsetAtLine(styledText.getLineCount()-1);
            styledText.setCaretOffset(offset);
            styledText.showSelection();
         }
      });
 
      shell.open ();
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch ()) display.sleep ();
      }
   }
}