What is a Valve?

A Valve is not defined in the Servlet/JSP spec, it is Tomcat specific. From the Tomcat docs:
A Valve element represents a component that will be inserted into the request processing pipeline for the associated Catalina container (Engine, Host, or Context).

For example, with the valve Remove Address Filter, you can decide whether or not to continue processing the request based on a regular expression that takes as input the IP address of the client.

You associate a Valve with a particular container (Engine, Host, or Context) in server.xml.

Check out the Q/A’s on how to use the Valves that come with Tomcat, and how to write your own.

Using an ArrowButton 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.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
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 ToggleButton Demonstration");
      shell.setLayout(new GridLayout());
 
      Group buttonGroup = new Group(shell, SWT.NONE);
      GridLayout gridLayout = new GridLayout();
      gridLayout.numColumns = 4;
      buttonGroup.setLayout(gridLayout);
      buttonGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
 
      SelectionListener selectionListener = new SelectionAdapter () {
         public void widgetSelected(SelectionEvent event) {
            System.out.println("integer value for alignment: " + ((Button) event.widget).getAlignment());
         };
      };
 
      createArrowButton(buttonGroup, SWT.LEFT, selectionListener);
      createArrowButton(buttonGroup, SWT.RIGHT, selectionListener);
      createArrowButton(buttonGroup, SWT.UP, selectionListener);
      createArrowButton(buttonGroup, SWT.DOWN, selectionListener);
      
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      display.dispose();
   }
   
   public static void createArrowButton(Composite parent, int alignment, 
                                          SelectionListener selectionListener) {
      GridData gridData = new GridData();
      gridData.widthHint = 30;
      gridData.heightHint = 30;
      Button button = new Button(parent, SWT.ARROW);
      button.setLayoutData(gridData);
      button.setAlignment(alignment);
      button.addSelectionListener(selectionListener);
   }
}

Using the SWT MessageDialog

SWT.OK


SWT.OK | SWT.CANCEL

SWT.ICON_INFORMATION

SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_QUESTION

SWT.RETRY | SWT.CANCEL | SWT.ICON_ERROR

SWT.RETRY | SWT.ABORT | SWT.IGNORE | SWT.ICON_WARNING

Full working example: Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TreeItem;
 
public class Main {
   public static void main(String[] args) {
      Display display = new Display();
      Shell shell = new Shell(display);
 
      MessageBox dialog = new MessageBox(shell, SWT.OK);
      dialog.setMessage("The 11th of September has learned us...");
      dialog.setText("Information");
      printResult(dialog.open());
       
      dialog = new MessageBox(shell, SWT.OK | SWT.CANCEL);
      dialog.setMessage("that it's not cool to die from hunger.");
      dialog.setText("Information");
      printResult(dialog.open());
 
      dialog = new MessageBox(shell, SWT.ICON_INFORMATION);
      dialog.setMessage("Click CANCEL");
      dialog.setText("Information");
      printResult(dialog.open());
       
      dialog = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_QUESTION);
      dialog.setMessage("Do you really want to format your neighbor's drive?");
      dialog.setText("Question");
      printResult(dialog.open());
 
      dialog = new MessageBox(shell, SWT.RETRY | SWT.CANCEL | SWT.ICON_ERROR);
      dialog.setMessage("You don't have a neighbor.");
      dialog.setText("Error");
      printResult(dialog.open());
       
      dialog = new MessageBox(shell, SWT.RETRY | SWT.ABORT | SWT.IGNORE | SWT.ICON_WARNING);
      dialog.setMessage("Don't you really want to not discontinue the proceeding task?");
      dialog.setText("Warning");
      printResult(dialog.open());
       
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
       
      display.dispose();
   }
    
   public static void printResult(int result) {
      switch (result) {
         case SWT.OK:
            System.out.println("SWT.OK");
            break;
         case SWT.CANCEL:
            System.out.println("SWT.CANCEL");
            break;
         case SWT.YES:
            System.out.println("SWT.YES");
            break;
         case SWT.NO:
            System.out.println("SWT.NO");
            break;
         case SWT.ABORT: 
            System.out.println("SWT.ABORT");
            break;
         case SWT.RETRY:
            System.out.println("SWT.RETRY");
            break;
         case SWT.IGNORE:
            System.out.println("SWT.IGNORE");
            break;
         default:
            System.out.println(result);
            break;     
      } 
   }
}

Creating an SWT Tree with images

Main.java:

import java.io.FileInputStream;
import java.io.IOException;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
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) throws Exception {
      Display display = new Display();
      Shell shell = new Shell(display);
 
      // pos x, pos y, width, height
      shell.setBounds(200, 200, 300, 200);
      shell.setText("SWT Tree Demonstration");
      shell.setLayout(new GridLayout());
 
      Tree tree = new Tree(shell, SWT.BORDER);
       
      TreeItem node1 = new TreeItem (tree, SWT.NULL);
      node1.setText("My Computer");
      node1.setImage(getImage("mycomp.gif"));
       
      TreeItem node2 = new TreeItem(node1, SWT.NULL);
      node2.setText("Audio");
      node2.setImage(getImage("audio.gif"));
 
      TreeItem node3 = new TreeItem(node1, SWT.NULL);
      node3.setText("Control Panel");
      node3.setImage(getImage("controlpanel.gif"));
 
      TreeItem node4 = new TreeItem(node1, SWT.NULL);
      node4.setText("Folder");
      node4.setImage(getImage("folder.gif"));
       
      TreeItem node5 = new TreeItem(node1, SWT.NULL);
      node5.setText("Local Disk (C:)");
      node5.setImage(getImage("localdisk.gif"));
 
      TreeItem node6 = new TreeItem(node1, SWT.NULL);
      node6.setText("doc on '192.168.0.1' (Z:)");
      node6.setImage(getImage("network.gif"));
 
      tree.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
             
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
       
      display.dispose();
   }
    
   public static Image getImage(String location) throws IOException {
      ImageData source = new ImageData(Main.class.getResourceAsStream(location));
      ImageData mask = source.getTransparencyMask();
      return new Image(null, source, mask);   
   }           
}

Images used:





Logging AWT events

You can do so by subclassing EventQueue and adding logging functionality. Then replace the system event queue with that logging queue.

Main.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      getContentPane().add(new JButton("Test button"));
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.setDefaultCloseOperation(EXIT_ON_CLOSE);
      main.setSize(200, 200);
 
      main.getToolkit().getSystemEventQueue().push(new LoggingEventQueue());
 
      main.setVisible(true);
   }
}

LoggingEventQueue.java:

import java.awt.*;
 
public class LoggingEventQueue extends EventQueue
{
   protected void dispatchEvent(AWTEvent event) {
      super.dispatchEvent(event);
      System.out.println(event);
   }
}

Getting context initialization parameters in JSP

Context initialization parameters are parameters defined in the web.xml deployment descriptor and are available to all servlets of your webapplication.

web.xml example:

<?xml version="1.0" encoding="ISO-8859-1"?>
 
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
 
<web-app>
   <context-param>
      <param-name>name1</param-name>
      <param-value>value1</param-value>
   </context-param>
   <context-param>
      <param-name>name2</param-name>
      <param-value>value2</param-value>
   </context-param>
</web-app>

getparams.jsp:

<%
   ServletContext context = config.getServletContext();
   String value1 = context.getInitParameter("name1");
   String value2 = context.getInitParameter("name2");
%>
 
Value of name1: <%=value1%><br>
Value of name2: <%=value2%>

Have two JTrees vertically aligned in a JScrollPane

Main.java:

import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
 
public class Main extends JFrame
{
   public Main() {
      DefaultMutableTreeNode root = createNodes();
      JTree tree1 = new JTree(root);
      JTree tree2 = new JTree(root);
 
      tree1.addTreeSelectionListener(new TreeSelectionListener() {
         public void valueChanged(TreeSelectionEvent e) {         
            TreePath path = e.getPath();
            System.out.println(path.getLastPathComponent());     
         }
      });
 
      tree2.addTreeSelectionListener(new TreeSelectionListener() {
         public void valueChanged(TreeSelectionEvent e) {         
            TreePath path = e.getPath();
            System.out.println(path.getLastPathComponent());     
         }
      });
  
      Box box = Box.createVerticalBox();
      box.add(tree1);
      box.add(tree2);
 
      // bugparade #4833645
      tree1.setMinimumSize(tree1.getPreferredSize());
      tree1.setAlignmentX(0);
      tree2.setMinimumSize(tree2.getPreferredSize());
      tree2.setAlignmentX(0);
 
      getContentPane().setLayout(new BorderLayout());
     
      JScrollPane sp = new JScrollPane(box);
      sp.getViewport().setBackground(Color.white);
 
      getContentPane().add(BorderLayout.NORTH, sp);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
  
   public static DefaultMutableTreeNode createNodes() {
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("Java");
      
      DefaultMutableTreeNode j2se = new DefaultMutableTreeNode("J2SE");
      DefaultMutableTreeNode j2ee = new DefaultMutableTreeNode("J2EE");
      DefaultMutableTreeNode j2me = new DefaultMutableTreeNode("J2ME");
 
      j2se.add(new DefaultMutableTreeNode("http://java.sun.com/j2se/"));
      j2ee.add(new DefaultMutableTreeNode("http://java.sun.com/j2ee/"));
      j2me.add(new DefaultMutableTreeNode("http://java.sun.com/j2me/"));
 
      root.add(j2se);
      root.add(j2ee);
      root.add(j2me);
 
      return root;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Converting a ByteArrayInputStream to a ReadableByteChannel

Main.java:

import java.nio.channels.*;
import java.nio.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      byte[] buffer = "contents of the buffer".getBytes();
      ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
 
      ReadableByteChannel byteChannel = Channels.newChannel(bais);   
      ByteBuffer bb = ByteBuffer.allocate(10);
      
      int n;
      while ((n = byteChannel.read(bb)) > -1) {
         bb.rewind();
         
         for (int i=0; i<n; i++) {
            System.out.print((char) bb.get());
         }
      }
   }
}

Using an ArrayBlockingQueue

This example provides an example of all the significant methods in ArrayBlockingQueue.

Main.java:

import static java.lang.Math.*;
import java.util.concurrent.*;
import java.util.*;
  
public class Main
{
   public static void main(String []args) {
      BlockingQueue<Message> blockingQueue = new ArrayBlockingQueue<Message>(10);
  
      // put 10 elements on the queue
      Random r = new Random();
      for (int i=0; i<10; i++) {
         // abs() can be used without qualification because java.lang.Math is statically imported
         Message<String> m = new Message<String>("Random Message #" + abs(r.nextInt() % 100));
         System.out.println("Adding message '" + m + "'");
         try {
            blockingQueue.put(m);
         }
         catch(InterruptedException e) { } 
      }
       
      // removed 5 first elements and put them into a TreeSet, 
      // notice that the class Message implements Comparable to do so!
      System.out.println("nTreeSet");
      System.out.println("-------");
      TreeSet<Message> treeSet = new TreeSet<Message>();
      blockingQueue.drainTo(treeSet, 5);
      System.out.println(treeSet);
  
      // offer 6 elements to the (tail of the) queue, last element will not be inserted because 
      // queue is full and space does not free up within 5 seconds
      System.out.println("nOffer");
      System.out.println("-----");
      for (int i=0; i<6; i++) {
         Message<String> m = new Message<String>("Message #" + (i+1));
         System.out.println("Offering " + m);
         try {
            blockingQueue.offer(m, 5, TimeUnit.SECONDS);
         }
         catch(InterruptedException e) { }
      }
       
      // iterate over the elements left in the BlockingQueue
      System.out.println("nIterator");
      System.out.println("--------");
      Iterator<Message> iter = blockingQueue.iterator();
      while (iter.hasNext()) {
         System.out.println(iter.next());
      }
       
      System.out.println("nPeek (retrieve but not remove)");
      System.out.println("----");
      System.out.println(blockingQueue.peek());
  
      System.out.println("nPoll (retrieve and remove)");
      System.out.println("----");
      System.out.println("Removing " + blockingQueue.poll());
  
      System.out.println("nSize and Remaining capacity");
      System.out.println("-----------------");
      System.out.println("Size of queue: " + blockingQueue.size());
      System.out.println("Remaining capacity of queue: " + blockingQueue.remainingCapacity());
  
      System.out.println("nConverting to array Message[]");
      System.out.println("-----------------------------");
      Message[] messages = blockingQueue.toArray(new Message[] { });
      for (int i=0; i<messages.length; i++) {
         System.out.println("From array: " + messages[i]);
      }
   }
}
  
class Message<T extends Comparable> implements Comparable<T>
{
   private T contents;
    
   public Message(T contents) {
      this.contents = contents;
   }
    
   public T getContents() {
      return contents;
   }
    
   public String toString() {
      return ""+contents;
   }
    
   public int compareTo(T o) {
      return o.compareTo(contents);
   }   
}

outputs:

Adding message 'Random Message #68'
Adding message 'Random Message #53'
Adding message 'Random Message #27'
Adding message 'Random Message #35'
Adding message 'Random Message #40'
Adding message 'Random Message #14'
Adding message 'Random Message #61'
Adding message 'Random Message #50'
Adding message 'Random Message #81'
Adding message 'Random Message #5'
  
TreeSet
-------
[Random Message #27, Random Message #35, Random Message #40, Random Message #53,
 Random Message #68]
  
Offer
-----
Offering Message #1
Offering Message #2
Offering Message #3
Offering Message #4
Offering Message #5
Offering Message #6
  
Iterator
--------
Random Message #14
Random Message #61
Random Message #50
Random Message #81
Random Message #5
Message #1
Message #2
Message #3
Message #4
Message #5
  
Peek (retrieve but not remove)
----
Random Message #14
  
Poll (retrieve and remove)
----
Removing Random Message #14
  
Size and Remaining capacity
-----------------
Size of queue: 9
Remaining capacity of queue: 1
  
Converting to array Message[]
-----------------------------
From array: Random Message #61
From array: Random Message #50
From array: Random Message #81
From array: Random Message #5
From array: Message #1
From array: Message #2
From array: Message #3
From array: Message #4
From array: Message #5

Using a Japanese font in Swing components

To answer this question, I installed a Japanese font to play around with. It’s called MS Mincho. After installing it, I modified the JDK properties so that it recognizes this font. I assume here that you are using JDK1.2.2. Go to c:\jdk1.2.2\jre\lib and copy font.properties.ja to font.properties (make a backup of the original font.properties first). Then modify this file font.properties and change serif.plain.0 to MS Mincho,ANSI_CHARSET. Also add the entry filename.MS_Mincho=msmincho.ttf.

You can use this test program that allows you to display RTF text, using the RTFEditorKit. Point the URL in the application to http://www.esus.com/docs/Hello.rtf

import javax.swing.text.html.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.awt.*;
import java.io.*;
 
public class Main extends JFrame
{
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
 
   public Main() {
 
      JButton uriButton = new JButton("Go!");
      // needs to be final to allow the inner class to access it!
      final JTextField uriTextField = new JTextField();
      final JEditorPane htmlPane = new JEditorPane();
      uriTextField.setText("http://www.esus.com/docs/Hello.rtf");
      htmlPane.setEditable(false);
 
      uriButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            try {
               htmlPane.setPage(new URL(uriTextField.getText()));
            }
            catch(Exception e) {
               System.out.println(e);
            }
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      JPanel topPanel = new JPanel(new BorderLayout());
      topPanel.add(BorderLayout.CENTER, uriTextField);
      topPanel.add(BorderLayout.EAST, uriButton);
 
      getContentPane().add(BorderLayout.NORTH, topPanel);
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(htmlPane));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      setSize(400, 400);
   }
}

Feel free to post any more sample code or detailed explanation on how to change the font.properties file to add MS Mincho properly.