Listing all the default values of the look and feel

UIDefaults is a class derived from Hashtable that contains a map of the default values
for the installed UI look and feel (LAF). The following program produces a sorted list:

Main.java:

import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main {
   public static void main(String[] args) {
      UIDefaults defaults = UIManager.getDefaults();
 
      String[] ar = new String[defaults.size()];
      int count=0;
      Enumeration enum = defaults.keys();
      while (enum.hasMoreElements()) { 
         ar[count++] = (String) enum.nextElement();
      }
 
      // sort values
      Arrays.sort(ar);
 
      // print out
      for (int i=0; i<ar.length; i++) {
         System.out.println(ar[i]);
      } 
 
      // exit program (AWT event thread running)
      System.exit(1);
   }
}

outputs:

Button.background
Button.border
Button.disabledText
Button.focus
Button.font
Button.foreground
Button.margin
Button.select
Button.textIconGap
Button.textShiftOffset
ButtonUI
CheckBox.background
CheckBox.border
CheckBox.disabledText
CheckBox.focus
CheckBox.font
CheckBox.foreground
CheckBox.icon
CheckBox.margin
CheckBox.textIconGap
CheckBox.textShiftOffset
CheckBoxMenuItem.acceleratorFont
CheckBoxMenuItem.acceleratorForeground
CheckBoxMenuItem.acceleratorSelectionForeground
CheckBoxMenuItem.arrowIcon
CheckBoxMenuItem.background
CheckBoxMenuItem.border
CheckBoxMenuItem.borderPainted
CheckBoxMenuItem.checkIcon
CheckBoxMenuItem.disabledForeground
CheckBoxMenuItem.font
CheckBoxMenuItem.foreground
CheckBoxMenuItem.margin
CheckBoxMenuItem.selectionBackground
CheckBoxMenuItem.selectionForeground
CheckBoxMenuItemUI
CheckBoxUI
Checkbox.select
ColorChooser.background
ColorChooser.cancelText
ColorChooser.font
ColorChooser.foreground
ColorChooser.hsbBlueText
ColorChooser.hsbBrightnessText
ColorChooser.hsbGreenText
ColorChooser.hsbHueText
ColorChooser.hsbNameText
ColorChooser.hsbRedText
ColorChooser.hsbSaturationText
ColorChooser.okText
ColorChooser.previewText
ColorChooser.resetText
ColorChooser.rgbBlueMnemonic
ColorChooser.rgbBlueText
ColorChooser.rgbGreenMnemonic
ColorChooser.rgbGreenText
ColorChooser.rgbNameText
ColorChooser.rgbRedMnemonic
ColorChooser.rgbRedText
ColorChooser.swatchesDefaultRecentColor
ColorChooser.swatchesNameText
ColorChooser.swatchesRecentSwatchSize
ColorChooser.swatchesRecentText
ColorChooser.swatchesSwatchSize
ColorChooserUI
ComboBox.background
ComboBox.disabledBackground
ComboBox.disabledForeground
ComboBox.font
ComboBox.foreground
ComboBox.listBackground
ComboBox.listForeground
ComboBox.selectionBackground
ComboBox.selectionForeground
ComboBoxUI
Desktop.background
DesktopIcon.background
DesktopIcon.border
DesktopIcon.font
DesktopIcon.foreground
DesktopIconUI
DesktopPaneUI
EditorPane.background
EditorPane.border
EditorPane.caretBlinkRate
EditorPane.caretForeground
EditorPane.font
EditorPane.foreground
EditorPane.inactiveForeground
EditorPane.keyBindings
EditorPane.margin
EditorPane.selectionBackground
EditorPane.selectionForeground
EditorPaneUI
FileChooser.acceptAllFileFilterText
FileChooser.cancelButtonMnemonic
FileChooser.cancelButtonText
FileChooser.cancelButtonToolTipText
FileChooser.detailsViewButtonAccessibleName
FileChooser.detailsViewButtonToolTipText
FileChooser.detailsViewIcon
FileChooser.directoryDescriptionText
FileChooser.fileDescriptionText
FileChooser.fileNameLabelMnemonic
FileChooser.fileNameLabelText
FileChooser.filesOfTypeLabelMnemonic
FileChooser.filesOfTypeLabelText
FileChooser.helpButtonMnemonic
FileChooser.helpButtonText
FileChooser.helpButtonToolTipText
FileChooser.homeFolderAccessibleName
FileChooser.homeFolderIcon
FileChooser.homeFolderToolTipText
FileChooser.listViewButtonAccessibleName
FileChooser.listViewButtonToolTipText
FileChooser.listViewIcon
FileChooser.lookInLabelMnemonic
FileChooser.lookInLabelText
FileChooser.newFolderAccessibleNam
FileChooser.newFolderErrorSeparator
FileChooser.newFolderErrorText
FileChooser.newFolderIcon
FileChooser.newFolderToolTipText
FileChooser.openButtonMnemonic
FileChooser.openButtonText
FileChooser.openButtonToolTipText
FileChooser.saveButtonMnemonic
FileChooser.saveButtonText
FileChooser.saveButtonToolTipText
FileChooser.upFolderAccessibleName
FileChooser.upFolderIcon
FileChooser.upFolderToolTipText
FileChooser.updateButtonMnemonic
FileChooser.updateButtonText
FileChooser.updateButtonToolTipText
FileChooserUI
FileView.computerIcon
FileView.directoryIcon
FileView.fileIcon
FileView.floppyDriveIcon
FileView.hardDriveIcon
FocusManagerClassName
InternalFrame.activeTitleBackground
InternalFrame.activeTitleForeground
InternalFrame.border
InternalFrame.closeIcon
InternalFrame.font
InternalFrame.icon
InternalFrame.iconifyIcon
InternalFrame.iconizeIcon
InternalFrame.inactiveTitleBackground
InternalFrame.inactiveTitleForeground
InternalFrame.maximizeIcon
InternalFrame.minimizeIcon
InternalFrame.paletteBorder
InternalFrame.paletteCloseIcon
InternalFrame.paletteTitleHeight
InternalFrame.titleFont
InternalFrameUI
Label.background
Label.disabledForeground
Label.disabledShadow
Label.font
Label.foreground
LabelUI
List.background
List.cellRenderer
List.focusCellHighlightBorder
List.font
List.foreground
List.selectionBackground
List.selectionForeground
ListUI
Menu.acceleratorFont
Menu.acceleratorForeground
Menu.acceleratorSelectionForeground
Menu.arrowIcon
Menu.background
Menu.border
Menu.borderPainted
Menu.checkIcon
Menu.consumesTabs
Menu.disabledForeground
Menu.font
Menu.foreground
Menu.margin
Menu.selectionBackground
Menu.selectionForeground
MenuBar.background
MenuBar.border
MenuBar.font
MenuBar.foreground
MenuBarUI
MenuItem.acceleratorDelimiter
MenuItem.acceleratorFont
MenuItem.acceleratorForeground
MenuItem.acceleratorSelectionForeground
MenuItem.arrowIcon
MenuItem.background
MenuItem.border
MenuItem.borderPainted
MenuItem.checkIcon
MenuItem.disabledForeground
MenuItem.font
MenuItem.foreground
MenuItem.margin
MenuItem.selectionBackground
MenuItem.selectionForeground
MenuItemUI
MenuUI
OptionPane.background
OptionPane.border
OptionPane.buttonAreaBorder
OptionPane.cancelButtonText
OptionPane.errorIcon
OptionPane.font
OptionPane.foreground
OptionPane.informationIcon
OptionPane.messageAreaBorder
OptionPane.messageForeground
OptionPane.minimumSize
OptionPane.noButtonText
OptionPane.okButtonText
OptionPane.questionIcon
OptionPane.warningIcon
OptionPane.yesButtonText
OptionPaneUI
Panel.background
Panel.font
Panel.foreground
PanelUI
PasswordField.background
PasswordField.border
PasswordField.caretBlinkRate
PasswordField.caretForeground
PasswordField.font
PasswordField.foreground
PasswordField.inactiveForeground
PasswordField.keyBindings
PasswordField.margin
PasswordField.selectionBackground
PasswordField.selectionForeground
PasswordFieldUI
PopupMenu.background
PopupMenu.border
PopupMenu.font
PopupMenu.foreground
PopupMenuSeparatorUI
PopupMenuUI
ProgressBar.background
ProgressBar.backgroundHighlight
ProgressBar.border
ProgressBar.cellLength
ProgressBar.cellSpacing
ProgressBar.font
ProgressBar.foreground
ProgressBar.foregroundHighlight
ProgressBar.selectionBackground
ProgressBar.selectionForeground
ProgressBarUI
RadioButton.background
RadioButton.border
RadioButton.disabledText
RadioButton.focus
RadioButton.font
RadioButton.foreground
RadioButton.icon
RadioButton.margin
RadioButton.select
RadioButton.textIconGap
RadioButton.textShiftOffset
RadioButtonMenuItem.acceleratorFont
RadioButtonMenuItem.acceleratorForeground
RadioButtonMenuItem.acceleratorSelectionForeground
RadioButtonMenuItem.arrowIcon
RadioButtonMenuItem.background
RadioButtonMenuItem.border
RadioButtonMenuItem.borderPainted
RadioButtonMenuItem.checkIcon
RadioButtonMenuItem.disabledForeground
RadioButtonMenuItem.font
RadioButtonMenuItem.foreground
RadioButtonMenuItem.margin
RadioButtonMenuItem.selectionBackground
RadioButtonMenuItem.selectionForeground
RadioButtonMenuItemUI
RadioButtonUI
ScrollBar.background
ScrollBar.darkShadow
ScrollBar.foreground
ScrollBar.highlight
ScrollBar.maximumThumbSize
ScrollBar.minimumThumbSize
ScrollBar.shadow
ScrollBar.thumb
ScrollBar.thumbDarkShadow
ScrollBar.thumbHighlight
ScrollBar.thumbLightShadow
ScrollBar.thumbShadow
ScrollBar.track
ScrollBar.trackHighlight
ScrollBar.width
ScrollBarUI
ScrollPane.background
ScrollPane.border
ScrollPane.font
ScrollPane.foreground
ScrollPaneUI
Separator.background
Separator.foreground
Separator.highlight
Separator.shadow
SeparatorUI
Slider.background
Slider.focus
Slider.focusInsets
Slider.foreground
Slider.highlight
Slider.horizontalThumbIcon
Slider.majorTickLength
Slider.shadow
Slider.trackWidth
Slider.verticalThumbIcon
SliderUI
SplitPane.background
SplitPane.border
SplitPane.dividerSize
SplitPane.highlight
SplitPane.shadow
SplitPaneUI
StandardDialogUI
TabbedPane.background
TabbedPane.contentBorderInsets
TabbedPane.darkShadow
TabbedPane.focus
TabbedPane.font
TabbedPane.foreground
TabbedPane.highlight
TabbedPane.lightHighlight
TabbedPane.selectHighlight
TabbedPane.selected
TabbedPane.selectedTabPadInsets
TabbedPane.shadow
TabbedPane.tabAreaBackground
TabbedPane.tabAreaInsets
TabbedPane.tabInsets
TabbedPane.tabRunOverlay
TabbedPane.textIconGap
TabbedPaneUI
Table.background
Table.focusCellBackground
Table.focusCellForeground
Table.focusCellHighlightBorder
Table.font
Table.foreground
Table.gridColor
Table.scrollPaneBorder
Table.selectionBackground
Table.selectionForeground
TableHeader.background
TableHeader.cellBorder
TableHeader.font
TableHeader.foreground
TableHeaderUI
TableUI
TextArea.background
TextArea.border
TextArea.caretBlinkRate
TextArea.caretForeground
TextArea.font
TextArea.foreground
TextArea.inactiveForeground
TextArea.keyBindings
TextArea.margin
TextArea.selectionBackground
TextArea.selectionForeground
TextAreaUI
TextField.background
TextField.border
TextField.caretBlinkRate
TextField.caretForeground
TextField.font
TextField.foreground
TextField.inactiveForeground
TextField.keyBindings
TextField.margin
TextField.selectionBackground
TextField.selectionForeground
TextFieldUI
TextPane.background
TextPane.border
TextPane.caretBlinkRate
TextPane.caretForeground
TextPane.font
TextPane.foreground
TextPane.inactiveForeground
TextPane.keyBindings
TextPane.margin
TextPane.selectionBackground
TextPane.selectionForeground
TextPaneUI
TitledBorder.border
TitledBorder.font
TitledBorder.titleColor
ToggleButton.background
ToggleButton.border
ToggleButton.disabledBackground
ToggleButton.disabledSelectedBackground
ToggleButton.disabledSelectedText
ToggleButton.disabledText
ToggleButton.focus
ToggleButton.font
ToggleButton.foreground
ToggleButton.margin
ToggleButton.select
ToggleButton.text
ToggleButton.textIconGap
ToggleButton.textShiftOffset
ToggleButtonUI
ToolBar.background
ToolBar.border
ToolBar.dockingBackground
ToolBar.dockingForeground
ToolBar.floatingBackground
ToolBar.floatingForeground
ToolBar.font
ToolBar.foreground
ToolBar.separatorSize
ToolBarSeparatorUI
ToolBarUI
ToolTip.background
ToolTip.border
ToolTip.font
ToolTip.foreground
ToolTipUI
Tree.background
Tree.changeSelectionWithFocus
Tree.closedIcon
Tree.collapsedIcon
Tree.drawsFocusBorderAroundIcon
Tree.editorBorder
Tree.expandedIcon
Tree.font
Tree.foreground
Tree.hash
Tree.leafIcon
Tree.leftChildIndent
Tree.line
Tree.openIcon
Tree.rightChildIndent
Tree.rowHeight
Tree.scrollsOnExpand
Tree.selectionBackground
Tree.selectionBorderColor
Tree.selectionForeground
Tree.textBackground
Tree.textForeground
TreeUI
Viewport.background
Viewport.font
Viewport.foreground
ViewportUI
activeCaption
activeCaptionBorder
activeCaptionText
control
controlDkShadow
controlHighlight
controlLtHighlight
controlShadow
controlText
desktop
inactiveCaption
inactiveCaptionBorder
inactiveCaptionText
info
infoText
menu
menuText
scrollbar
text
textHighlight
textHighlightText
textInactiveText
textText
window
windowBorder
windowText

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();
   }
}