Creating a formatted textfield that only accepts IP addresses

JDK1.4 introduced the JFormattedTextfield with which you can set a mask on a text field.
This example not only shows you how to set the mask (eg. 255.255.xxx.xxx), but also how to use an InputVerifier to check whether the inputted digits lie in the range [0-255].

Main.java:

import javax.swing.JFormattedTextField.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() throws Exception
   {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      MaskFormatter formatter = new MaskFormatter("255.255.###.###");
      formatter.setPlaceholderCharacter('0');
 
      final JFormattedTextField formattedTf = new JFormattedTextField(formatter);
      formattedTf.setInputVerifier(new IPTextFieldVerifier());
 
      final JTextField normalTf = new JTextField(25);
      JButton button = new JButton("Get value");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) { 
            normalTf.setText(""+formattedTf.getValue());
         }
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      getContentPane().add(formattedTf);
      getContentPane().add(button);
      getContentPane().add(normalTf);
 
      formattedTf.setPreferredSize(normalTf.getPreferredSize());
   }
  
   public static void main(String args[]) throws Exception 
   {
      Main main = new Main();
      main.setSize(300, 150);
      main.setVisible(true);
   }
}
 
class IPTextFieldVerifier extends InputVerifier {
   public boolean verify(JComponent input) {
      if (input instanceof JFormattedTextField) {
         JFormattedTextField ftf = (JFormattedTextField)input;
         AbstractFormatter formatter = ftf.getFormatter();
         if (formatter != null) {
            String text = ftf.getText();
            StringTokenizer st = new StringTokenizer(text, ".");
            while (st.hasMoreTokens()) {
               int value = Integer.parseInt((String) st.nextToken());
               if (value < 0 || value > 255) {
                  // to prevent recursive calling of the 
                  // InputVerifier, set it to null and
                  // restore it after the JOptionPane has
                  // been clicked.
                  input.setInputVerifier(null);
                  JOptionPane.showMessageDialog(new Frame(), "Malformed IP Address!", "Error", 
                                                JOptionPane.ERROR_MESSAGE);
                  input.setInputVerifier(this);  
                  return false;
               }
            }
            return true;
         }
      }
      return true;
   }
 
   public boolean shouldYieldFocus(JComponent input) {
      return verify(input);
   }
}

Returning an image stored in mysql with a servlet

To answer this, I created a table images in a test database and stored the esus logo in it.

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

To save an image in this table, use the following code and specify the image at command line. Use a JPG image, as the MIME content type for the servlet we’ll write will be image/jpeg.

Main.java:

import java.util.*;
import java.text.*;
import java.sql.*;
import java.io.*;  
 
public class Main {
   public static void main(String []args) throws Exception {
      try {
         if (args.length != 1) {
            System.out.println("Usage: java Main <img>");
            System.exit(1);
         }
 
         Class.forName("org.gjt.mm.mysql.Driver").newInstance();
         Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/testdb", 
                                                       "",
                                                       "");
 
         File file = new File(args[0]);
         FileInputStream fis=new FileInputStream(file);
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         byte buf[]=new byte[1024];
         int length=-1;
         while((length=fis.read(buf))!=-1) {
            baos.write(buf,0,length);
         }
 
         PreparedStatement insertStmt = conn.prepareStatement(
                                       "INSERT INTO images (name, length, data) " +
                                       "VALUES (?, ?, ?)");
         insertStmt.setString(1, file.getName());
         insertStmt.setInt(2, (int) file.length());
         insertStmt.setBytes(3, baos.toByteArray());
         insertStmt.execute();
 
         fis.close();
         baos.close();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}

The servlet that delivers the image to the browser looks just like any other one, except that the MIME content-type attribute is set to image/jpeg (use image/gif for GIF files). The rest of the code handles the reading of the image from the mysql table given its unique index.

Servlet GetImage.java:

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.sql.*;
import java.io.*;
 
public class GetImage extends HttpServlet {
 
   public void doGet(
       HttpServletRequest request,
       HttpServletResponse response)
         throws ServletException, IOException {
 
     response.setContentType("image/jpeg");
 
     ServletOutputStream sos = response.getOutputStream();
 
     int imageuid = Integer.parseInt(getValues(request, "imageuid"));
     byte[] buf = getImageFromDB(imageuid);
 
     sos.write(buf);
 
     sos.flush();
  }
 
   public byte[] getImageFromDB(int imageuid) {
      byte[] buffer = null;
 
      try {
         Class.forName("org.gjt.mm.mysql.Driver").newInstance();
         Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/testdb", 
                                                       "",
                                                       "");
 
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT name, length, data FROM images " +
                                          "where imageuid = " + imageuid);
      
         if (rs.next()) {
            String name = rs.getString("name");
            int length = rs.getInt("length");
            buffer = rs.getBytes("data");
         }
      }
      catch(Exception e) {
         e.printStackTrace();
      }
 
      return buffer;
   }
 
   public String getValues(HttpServletRequest request, String name) {
      String retVal = "";
 
      String values[] = request.getParameterValues(name);
      if (values == null) {
      }
      else if (values.length == 1) {
         retVal = values[0];
      }
      else {
         for (int i=0; i<values.length; i++) {
            retVal += values[i] + ", ";
         }
      }
 
      return retVal;
   }
}

You can now use the reference to this servlet in an img src HTML tag:

<html>
<body>
<center><img src="http://localhost:8080/servlet/GetImage?imageuid=1"></center>
</body>
</html>

Example of TreeTable

The example program about TreeTable discussed in Sun’s article Creating TreeTables: Part 2 adds unnecessary complexity. The following is a much simpler one and will get you started much quicker.

Prerequisite: Download src.zip from the above url and compile the with both programs presented here.

Main.java:

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat;
 
public class Main extends JFrame {
   protected MyTreeTableModel  model;
   protected JTreeTable        treeTable;
 
   public Main() {
      super("Main");
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      model     = new MyTreeTableModel();
      treeTable = new JTreeTable(model);
 
      getContentPane().add(new JScrollPane(treeTable));
 
      try {
         UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
         SwingUtilities.updateComponentTreeUI(this);
      }
      catch(Exception e) {
         e.printStackTrace();
      }
 
      pack();
      show();
   }
 
   public static void main(String[] args) {
      new Main();
   }
}

MyTreeTableModel.java:

import java.io.IOException;
import java.io.File;
import java.util.Date;
import java.util.Stack;
import javax.swing.SwingUtilities;
import javax.swing.tree.TreePath;
import java.util.*;
 
public class MyTreeTableModel extends AbstractTreeTableModel {
 
   // Names of the columns.
   static protected String[] cNames = {"Column 1", "Column 2", 
                                       "Column 3", "Column 4"};
   // Types of the columns.
   static protected Class[]  cTypes = { TreeTableModel.class, String.class, 
                                        String.class, String.class };
   static Entry rootEntry;  
 
   /******** Entry class represents the parent and leaf nodes **********/
   static class Entry {
      private String name; 
      private boolean isLeaf;
      private Vector children = new Vector();
 
      public Entry(String name, boolean isLeaf) {
         this.name = name;
         this.isLeaf = isLeaf;
      }
 
      public Vector getChildren() {
         return children;
      }
 
      public boolean isLeaf() {
         return isLeaf;
      }
 
      public String getName() {
         return name;
      }
 
      public String toString() {
         return name;
      }
   }
 
   static {
      rootEntry = new Entry("rootentry", false);
      rootEntry.getChildren().addElement(new Entry("test1", true));
      rootEntry.getChildren().addElement(new Entry("test2", true));

      Entry subEntry1 = new Entry("subentry1", false);
      subEntry1.getChildren().addElement(new Entry("test3", true));
      subEntry1.getChildren().addElement(new Entry("test4", true));
      Entry subEntry2 = new Entry("subentry2", false);
      subEntry2.getChildren().addElement(new Entry("test5", true));
      subEntry2.getChildren().addElement(new Entry("test6", true));
      rootEntry.getChildren().addElement(subEntry1);
      rootEntry.getChildren().addElement(subEntry2); 
   }
   /*************************************/
 
   public MyTreeTableModel() { 
      super(rootEntry);
   }
 
   public int getChildCount(Object node) { 
      if (!((Entry) node).isLeaf()) {
         return ((Entry) node).getChildren().size();
      }
      return 0;
   }
 
   public Object getChild(Object node, int i) { 
      return ((Entry) node).getChildren().elementAt(i);
   }
 
   public boolean isLeaf(Object node) {
      return ((Entry) node).isLeaf();
   }
 
   public int getColumnCount() {
      return cNames.length;
   }
 
   public String getColumnName(int column) {
      return cNames[column];
   } 
 
   public Class getColumnClass(int column) {
      return cTypes[column];
   }
 
   public Object getValueAt(Object node, int column) {
      switch(column) {
         case 0:
            return node;
         case 1:
            return "value1";
         case 2:
            return "value2";
         case 3:
            return "value3";
      }
   
      return null; 
   }
}

Sending an email using JavaMail

This example assumes you have JavaMail1.2 installed. It can be downloaded from http://java.sun.com/products/javamail/. Add both mail.jar and activation.jar to your classpath.

Set the property mail.smtp.host with your SMTP host, create a session, tie it to your message and send it with the Transport class. It’s that simple!

SendMessage.java:

import javax.mail.internet.*;
import javax.mail.*;
import java.util.*;
 
public class SendMessage
{
   public static void main(String []args) {
      try {
         String host = "fill in your SMTP host here";
         String from = "FROM email address";
         String to   = "TO email address";
 
         Properties properties = new Properties();
         properties.put("mail.smtp.host", host);
 
         Session session = Session.getDefaultInstance(properties);
 
         MimeMessage message = new MimeMessage(session);
         message.setFrom(new InternetAddress(from));
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
 
         message.setSubject("Hi!");
         message.setText("I send you this file in order to have your advice");
 
         Transport.send(message);
      }
      catch(MessagingException e) {
         e.printStackTrace();
      }
   }
}

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

Capturing an area of the native screen

Use the Robot class, introduced in JDK1.3. The method createScreenCapture creates a BufferedImage containing pixels read from the native screen.

This example reads the top left corner of my Win2000 screen and displays it inside a JFrame.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   BufferedImage background;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      try {
         Robot robot = new Robot();
         background = robot.createScreenCapture(
                         new Rectangle(0, 0, 100, 200)); 
      }
      catch(AWTException e) {
         e.printStackTrace();
      }
   }
 
   public void paint(Graphics g) {      
      if (background != null) {
         g.drawImage(background, 0, 0, getWidth(), getHeight(), this);   
      }
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(100, 200);
      main.setVisible(true);
   }
}

Using a shutdown hook

To gain control over when you application shuts down (eg. to close database connections), you can use the 1.3 method addShutdownHook in the Runtime class and pass it a thread object. The JVM will execute the thread when the application is about the end.

eg.

public class Main
{
   public static void main(String args[]) {

      Runtime.getRuntime().addShutdownHook(new Thread() {
         public void run() {
            System.out.println("Shutting down...");
         }
      });

      System.out.println("press ctrl-c to exit!");
      while (true) ;
   }
}

Difference between <jsp:forward> and response.sendRedirect()

  • With response.sendRedirect(), the browser is asked to go get another page. All HTTP parameters of the original request are lost. The browser’s location bar changes.
  • <jsp:forward> is more efficient. It forwards the request to the specified JSP page on the server side, without asking the browser to generate a new request. You can only forward to resources served by your application server! It also keeps the state.
    The browser’s location bar doesn’t change.

    To test it out, check out
    response.sendRedirect()
    http://www.javaspace.com/docs/DoRedirect.jsp?orderID=100
    <jsp:forward>
    http://www.javaspace.com/docs/DoForward.jsp?orderID=100

    DoRedirect.jsp:

    <%
       response.sendRedirect("/docs/ResultingPage.jsp");
    %>
    

    DoForward.jsp:

    <jsp:forward page="ResultingPage.jsp"/>
    

    ResultingPage.jsp:

    The is the JSP page <i>ResultingPage.jsp</i> the forwarding or redirection.
    <br>
    <br>
    Did the browser's location bar change?
    <br><br>
    The parameter <i>orderID</i> is set to <%=request.getParameter("orderID")%>.