Using the RequestDumperValve

This valve will dump all headers/cookies to the log files allowing you to debug. You specify it without any attributes, just the valve classname:

   <Valve className="org.apache.catalina.valves.RequestDumperValve"/>

Disabling an SWT button

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.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, 400, 200);
      shell.setText("SWT Button Enabled/Disabled 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) {
            Button button = ((Button) event.widget);
            System.out.print(button.getText());
            System.out.println(" selected = " + button.getSelection());
         };
      };
      
      Button button1 = new Button(buttonGroup, SWT.PUSH);
      button1.setText("enabled");
      button1.setEnabled(true);
      button1.addSelectionListener(selectionListener);
      
      Button button2 = new Button(buttonGroup, SWT.PUSH);
      button2.setText("disabled");
      button2.setEnabled(false);
      button2.addSelectionListener(selectionListener);
      
      shell.open();

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

Creating a Shell with only the minimize button enabled in SWT

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.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Listener;
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 Shell Demonstration");
      shell.setLayout(new GridLayout());
 
      final Group buttonGroup = new Group(shell, SWT.NONE);
      GridLayout gridLayout = new GridLayout();
      gridLayout.numColumns = 3;
      buttonGroup.setLayout(gridLayout);
      buttonGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
       
      final Button createShellButton = new Button(buttonGroup, SWT.PUSH);
      createShellButton.setText("Open Shell");
 
      SelectionListener selectionListener = new SelectionAdapter () {
         public void widgetSelected(SelectionEvent event) {
            final Shell childShell = new Shell(SWT.BORDER | SWT.MIN);
            Button closeButton = new Button(childShell, SWT.PUSH);
            closeButton.setBounds(10, 10, 100, 30);
            closeButton.setText("Close Shell");
            closeButton.addListener(SWT.Selection, new Listener() {
               public void handleEvent(Event event) {
                  childShell.dispose();
               }
            });
          
            childShell.setSize (300, 100);
            childShell.setText ("Title of Shell");
            childShell.open ();                  
         };
      };
       
      createShellButton.addSelectionListener(selectionListener);
       
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      if (color != null && !color.isDisposed()) {
         color.dispose();
      }
      display.dispose();
   }
}

Having a border around an SWT list

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.List;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

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 List Demonstration");
      shell.setLayout(new GridLayout());

      String []items = {"Belgium", "The Netherlands", "France", "Germany", "Italy",
                        "Luxembourg", "Switzerland", "Austria", "Finland", "Iceland" };
      
      // to have a border around your list, "or" SWT.BORDER
      final List list = new List(shell, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.BORDER);
      list.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
      list.setItems (items);
            
      shell.open();
      
      shell.addShellListener(new ShellAdapter() {
         public void shellClosed(ShellEvent se) {
            int[] indices = list.getSelectionIndices();
            System.out.println("Selected items:");
            for (int i=0; i<indices.length; i++) {
               System.out.println(list.getItem(indices[i]));   
            }
         }
      });      

      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      
      display.dispose();
   }
   
   public static void recurseTree(TreeItem item) {
      System.out.println(item.getText() + "tChecked=" + item.getChecked());
      TreeItem[] treeItems = item.getItems(); 
      for (int i=0; i<treeItems.length; i++) {
         TreeItem treeItem = treeItems[i];
         recurseTree(treeItem);
      }   
   }
}

Modifying the elements in an private array from another class?

An example:

import java.lang.reflect.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      PrivateClass pc = new PrivateClass();
 
      pc.printArray();
 
      Class clazz = pc.getClass();
      Field field = clazz.getDeclaredField("privateArray");
      field.setAccessible(true);
      int []array = (int[]) field.get(pc);
 
      array[0] = 3;
      array[1] = 2;
      array[2] = 1;
 
      pc.printArray();
   }
}
 
class PrivateClass
{
   private int[] privateArray = { 1, 2, 3 };
 
   public void printArray() {
      System.out.print("[ ");
      for (int i=0; i<privateArray.length; i++) {
         System.out.print(privateArray[i] + " ");
      }
      System.out.println("]");
   }
}

outputs:

[ 1 2 3 ]
[ 3 2 1 ]

Receiving messages asynchronously from a JMS queue

I used openjms to develop this example. Check out this Q&A first!

The following example receives a message asynchronously from the testqueue queue. The acknowledgement mode is set to AUTO_ACKNOWLEDGE, which means that the session will automatically acknowledges a client’s receipt of a message. With asynchronous reception, the onMessage method of your implementation of MessageListener is called when there is a message available on the queue.

To receive message synchronously, check this Q&A.

Main.java:

import javax.naming.*;
import java.util.*;
 
import javax.jms.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      Hashtable env = new Hashtable();
      env.put(Context.INITIAL_CONTEXT_FACTORY,"org.exolab.jms.jndi.rmi.RmiJndiInitialContextFactory");
      env.put(Context.PROVIDER_URL, "rmi://localhost:1099/JndiServer");
      Context ctx = new InitialContext(env);
  
      QueueConnectionFactory cnxFactory = (QueueConnectionFactory) ctx.lookup("JmsQueueConnectionFactory");
 
      Connection connection = ((QueueConnectionFactory) cnxFactory).createQueueConnection();
      QueueSession session = ((QueueConnection) connection).createQueueSession(
                                   false, Session.AUTO_ACKNOWLEDGE);
      Queue queue = session.createQueue("testqueue");
      QueueReceiver receiver = session.createReceiver(queue);
  
      MyMessageConsumer consumer = new MyMessageConsumer();
      receiver.setMessageListener(consumer);
 
      connection.start();
   }
}
 
class MyMessageConsumer implements MessageListener
{
   public void onMessage(Message message) {
      System.out.println("Message received: " + message);
   }
}

Pretty-printing an XML in Java

Imagine you want to format the following xml in a human-friendly format: test.xml:

<?xml version="1.0" encoding="UTF-8" ?> 
<message><content>Hello World!</content><destinations><dest>jmsqueue:myjmsqueue</dest>
<dest>file:/home/filequeue</dest><dest>123.30.230.90</dest></destinations></message>

You can do this using the XSLT transformer package. Working code sample: Main.java:

import org.w3c.dom.*;
 
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.*;
   
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("test.xml"));
   
         // use the XSLT transformation package to output the subtree destinations
         Transformer transformer = TransformerFactory.newInstance().newTransformer();
         transformer.setOutputProperty(OutputKeys.METHOD, "xml");
         transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
         transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
          
         StringWriter sw = new StringWriter();
         transformer.transform(new DOMSource(doc), new StreamResult(sw));
          
         System.out.println(sw.toString());
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}

outputs:

<?xml version="1.0" encoding="UTF-8"?>
<message>
  <content>Hello World!</content>
  <destinations>
    <dest>jmsqueue:myjmsqueue</dest>
    <dest>file:/home/filequeue</dest>
    <dest>123.30.230.90</dest>
  </destinations>
</message>

Getting the state of a thread (running, blocked, etc)

This becomes very simple with the new java.lang.management package in JDK 1.5. The following example starts up a Task thread and a Monitor Thread. The Monitor thread prints out the state of the Task thread every half a second. All possible thread states are documented in the API docs.

Main.java:

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMBean;
import java.lang.management.ThreadState;
 
public class Main
{
   public static void main(String []args) {
      final Task t1 = new Task();
       
      t1.setName("Task Thread");
      t1.start();
       
      Thread monitorThread = new Thread() {
         public void run() {
            ThreadMBean mbean = ManagementFactory.getThreadMBean();
            ThreadInfo threadInfo1 = mbean.getThreadInfo(t1.getId());
 
            System.out.println("tMonitoring " + t1.getName() + " for 10 secondsn");
            System.out.println("tcountertstatettTotal CPU Time"); 
            for (int i=0; i<20; i++) {
               threadInfo1 = mbean.getThreadInfo(t1.getId());
               System.out.println("t" + t1.getCounter() + "t" + threadInfo1.getThreadState() + "  t" + 
                                  (mbean.getThreadCpuTime(t1.getId()) / 1000000) + " ms");
               
               try { Thread.sleep(500); } catch(Exception e) { }
            }
             
            t1.terminate();
         }
      };
       
      monitorThread.start();
   }
}
 
class Task extends Thread
{
   long counter = 0;
   private boolean terminated = false;
 
   public void run() {
      while (true) {
         if (terminated) return;
         
         counter++;
         for (int i=0; i<50000000; i++) { }
         try { Thread.sleep(100); } catch(Exception e) { }
      }
   } 
    
   public long getCounter() {
      return counter;
   }
    
   public void terminate() {
      terminated = true;
   }
}

outputs:

        Monitoring Task Thread for 10 seconds
 
        counter state           Total CPU Time
        1       Running         110 ms
        3       Sleeping        360 ms
        5       Sleeping        610 ms
        8       Running         911 ms
        10      Running         1211 ms
        12      Sleeping        1472 ms
        14      Sleeping        1712 ms
        17      Running         2012 ms
        19      Running         2313 ms
        21      Sleeping        2573 ms
        23      Sleeping        2824 ms
        26      Running         3104 ms
        28      Sleeping        3424 ms
        30      Sleeping        3675 ms
        33      Running         3965 ms
        35      Running         4266 ms
        37      Sleeping        4536 ms
        39      Sleeping        4786 ms
        42      Running         5087 ms
        44      Running         5387 ms

Storing properties into an XML file in JDK 1.5

StoreProps.java:

import java.util.*;
import java.io.*;
 
public class StoreProps
{
   public static void main(String []args) {
      Properties props = new Properties();
       
      props.put("path", "c:\program files\app");
      props.put("socketlock", "4550");
       
      System.out.println(props);
       
      try {
         // the second parameter is a single comment you can provide
         props.storeToXML(new FileOutputStream(new File("config.xml")), "Configuration for application");
      }
      catch(IOException e) { 
         e.printStackTrace();
      }
   }
}

Generates the file config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Configuration for application</comment>
<entry key="socketlock">4550</entry>
<entry key="path">c:program filesapp</entry>
</properties>

Getting the FontMetrics of all available fonts on your system?

This code will display some FontMetrics information about the font you select.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      FontRendering fr = new FontRendering();
      getContentPane().add(BorderLayout.CENTER, fr);
      getContentPane().add(BorderLayout.NORTH, new FontRenderingControls(fr));
   } 
 
   public static class FontRenderingControls extends JPanel implements ActionListener {
      FontRendering fr;
 
      public FontRenderingControls(FontRendering fr) {
         this.fr = fr;
 
         Vector v = new Vector();
         GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
         Font f[] = ge.getAllFonts();
         for (int i = 0; i < f.length; i++) {
            if (f[i].canDisplayUpTo(f[i].getName()) > 0) {
               v.addElement(f[i].getName());
            }
         }      
 
         final JComboBox fontCombo = new JComboBox(v);
         add(fontCombo);
         fontCombo.addActionListener(this);
      }
 
      public void actionPerformed(ActionEvent e) {
         JComboBox fontCombo = (JComboBox) e.getSource();
         fr.font = (String) fontCombo.getSelectedItem();
         fr.repaint();
      }
   }
 
   public static class FontRendering extends JPanel {
      public String text = "Easter Island";
      public String font = "Helvetica";
 
      public void paint(Graphics g) {
         Graphics2D g2d = (Graphics2D) g;
 
         Font f = g2d.getFont();
  
         g2d.setFont(new Font(font, Font.BOLD, 36));
         g2d.drawString(text, 10, 40); 
 
         FontMetrics fm = g2d.getFontMetrics();
    
         g2d.setFont(f);
         FontMetrics fm2 = g2d.getFontMetrics();
         g2d.drawString("FontMetrics:", 10, 60);
         g2d.drawString("Ascent: "      + 
                          fm.getAscent(), 50, 60 + fm2.getHeight());
         g2d.drawString("Descent: "     + 
                          fm.getDescent(), 50, 60 + fm2.getHeight() * 2);
         g2d.drawString("Height: "      + 
                          fm.getHeight(), 50, 60 + fm2.getHeight() * 3);
         g2d.drawString("Leading: "     + 
                          fm.getLeading(), 50, 60 + fm2.getHeight() * 4);
         g2d.drawString("MaxAdvance: "  + 
                          fm.getMaxAdvance(), 50, 60 + fm2.getHeight() * 5);
         g2d.drawString("MaxAscent: "   + 
                          fm.getMaxAscent(), 50, 60 + fm2.getHeight() * 6);
         g2d.drawString("MaxDescent: "  + 
                          fm.getMaxDescent(), 50, 60 + fm2.getHeight() * 7);
      }
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
      main.setSize(300, 300);
   }
}