Using a DigestOutputStream

With a DigestOutputStream, you can calculate a digest (SHA, MD5) while you are passing data through the stream. The process of calculating the digest can be turned off and on with the method DigestOutputStream.on(boolean).

In the following example, Main.java is read in and written to Main.java.digest. In the process, every other byte is taken into account to update the digest. In the end, the digest is appended to Main.java.digest.

Main.java:

import java.security.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      try {
         FileInputStream fis = new FileInputStream("Main.java");
         FileOutputStream fos = new FileOutputStream("Main.java.digest");
 
         MessageDigest md = MessageDigest.getInstance("SHA");
         DigestOutputStream dos = new DigestOutputStream(fos, md);
 
         int b;
         boolean state = true;
         while ((b = fis.read()) != -1) {
            dos.write(b);
 
            state = !state;
            dos.on(state);
         }
 
         // turn of digest calculation
         // and write digest to end of file
         dos.on(false);
         byte[] buffer = md.digest();
         dos.write(buffer, 0, buffer.length);
         dos.close();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
} 

Changing the traversal keys that control focus

In 1.4, you can use the following method.

Main.java:

import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame
{
   JLabel label = new JLabel("Forward: TAB or alt-f, Backward: SHIFT-TAB or alt-b");
   JButton button = new JButton("Button");
   JTextField textfield1 = new JTextField();
   JTextField textfield2 = new JTextField();
 
   public Main() {
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
      Container contentPane = getContentPane();
      contentPane.setLayout(new BorderLayout());
      JPanel panel = new JPanel(new GridLayout(4, 1, 10, 10));
      panel.add(label);
      panel.add(textfield1);   
      panel.add(textfield2);   
      panel.add(button);
      contentPane.add(BorderLayout.NORTH, panel);
 
      // add "alt f" as an alternative to TAB 
      Set set = contentPane.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
      KeyStroke altf = KeyStroke.getKeyStroke("alt F");
      set = new HashSet(set);
      set.add(altf);
      contentPane.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);
 
      // add "alt b" as an alternative to SHIFT-TAB 
      set = contentPane.getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
      KeyStroke altb = KeyStroke.getKeyStroke("alt B");
      set = new HashSet(set);
      set.add(altb);
      contentPane.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, set);
   } 
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(350, 200);
      main.setVisible(true);
   }
}

Typesafe enum in JDK 1.5

Earlier version of the JDK did not have true enumerated types. Many developers have implemented workarounds for this, a popular one described in Effective Java, item 21. Starting from 1.5, enumerated types have been integrated with the language, allowing developers to write more robust programs without having to write dull boilerplate code, which is automatically generated.

A simple example showing some advantages of the new enum feature:

enum DestinationType
{
   queue,
   topic
}

public class Main
{
   public static void main(String []args) {
      DestinationType dt = DestinationType.queue;

      // Outputting an enumerated type is user-friendly
      System.out.println(dt);   // prints out "queue"
      
      // Switch can be used on an enumerated type, no need to qualify the name of the constant
      switch (dt) {
         case queue:  System.out.println("Using a queue");
                      break;
         case topic:  System.out.println("Using a topic");
                      break;
         default:
      }
   }
}

It is possible to iterate over all declared enum constants:

import java.util.*;

enum DestinationType
{
   queue,
   topic
}

public class Main
{
   public static void main(String []args) {
      printDestinations(DestinationType.values());
      
      // or
      
      for (DestinationType dt : DestinationType.values()) {
         System.out.println(dt);
      }
   }
   
   public static void printDestinations(DestinationType[] list) {
      for (int i=0; i<list.length; i++) {
         System.out.println(list[i]);
      }
   }
}

It is even possible to declare methods on enum constants and attach behavior to the constants.

DestinationType.java:

public abstract enum DestinationType
{
   queue {
      public void print(String queueName) {
         System.out.println("This is queue " + queueName);
      }
   },
   topic {
      public void print(String topicName) {
         System.out.println("This is topic " + topicName);
      }
   };
   
   abstract void print(String name);
}

Main.java:

public class Main
{
   public static void main(String []args) {
      DestinationType dt = DestinationType.queue;

      dt.print("queue1");
   }
}

Decompiling JDK 1.5 classes

jad expects class file versions (major.minor) to be 45.3 or 46.0. Sources compiled with 1.5 have the file version 48.0. The following error message is displayed when trying to decompile a 1.5 .class file:

Parsing RequestForEnhancement.class...The class file version is 48.0, expected 45.3 or 46.0
JavaClassFileParseException: Class file version mismatch

To be able to use JAD, we can simply change the class file version of a 1.5 compiled class into 46. The following small application sets the magic number of a .class file or all classes in a jar file to whatever you desire.

ChangeMagicNumber.java:

import java.io.*;
import java.util.*;
import java.util.jar.*;
import java.util.zip.*;
 
public class ChangeMagicNumber
{
   public static void main(String []args) throws Exception {
      if (args.length != 2) {
         System.out.println("Usage: java ChangeMagicNumber [file.class | file.jar] magicNumber (eg. 46)");
         System.exit(1);
      }
       
      String filename = args[0];
      byte desiredMagicNumber = (byte) Integer.parseInt(args[1]);
      if (filename.toLowerCase().endsWith(".jar")) {
         processJar(filename, desiredMagicNumber);
      }
      else {
         processFile(filename, desiredMagicNumber);
      }
   }
    
   public static void processFile(String filename, byte desiredMagicNumber) throws Exception {
      RandomAccessFile raf = new RandomAccessFile(filename, "rw");
      raf.seek(7);
      byte b = raf.readByte();
      if (b != desiredMagicNumber) {
         raf.seek(7);
         raf.writeByte((byte) desiredMagicNumber);
      }
      raf.close();
   }
    
   public static void processJar(String filename, byte desiredMagicNumber) throws Exception {
      JarFile jf = new JarFile(filename);
      JarOutputStream jos = new JarOutputStream(new FileOutputStream(filename + "." + desiredMagicNumber));
      CRC32 crc = new CRC32();
      Enumeration enum = jf.entries();
      while (enum.hasMoreElements()) {
         ZipEntry entry = (ZipEntry) enum.nextElement();
         BufferedInputStream bis = new BufferedInputStream(jf.getInputStream(entry));
         int length = bis.available();
         byte[] buffer = null;
         if (length > 0) {
            buffer = new byte[length];
            bis.read(buffer, 0, length);
            
            buffer[7] = desiredMagicNumber;
            crc.reset();
            crc.update(buffer, 0, length);
            entry.setCrc(crc.getValue());
         }
         
         String e = entry.toString();
         jos.putNextEntry(entry);
         if (length > 0) {
            jos.write(buffer, 0, length);
         }
      }
      jf.close();
      jos.close();
   }
}

For example:

java ChangeMagicNumber rt.jar 46  

produces rt.jar.46, all classes in JAR file can be decompiled with JAD

Now the decompilation of the following 1.5 enum-example source works fine, after changing its file class version to 46.

Main.java:

enum DestinationType
{
   queue,
   topic
}
 
public class Main
{
   public static void main(String []args) {
      DestinationType dt = DestinationType.queue;

      // Outputting an enumerated type is user-friendly
      System.out.println(dt);   // prints out "queue"
      
      // Switch can be used on an enumerated type, no need to qualify the name of the constant
      switch (dt) {
         case queue:  System.out.println("Using a queue");
                      break;
         case topic:  System.out.println("Using a topic");
                      break;
         default:
      }
   }
}

Execute:

   java ChangeMagicNumber DestinationType.class 46
   jad DestinationType.class

results in:

DestinationType.jad:

// Decompiled by Jad v1.5.6d. Copyright 1997-99 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/SiliconValley/Bridge/8617/jad.html
// Decompiler options: packimports(3) 
// Source File Name:   Main.java
 
native class DestinationType extends Enum
{
    public static final DestinationType[] values()
    {
        return (DestinationType[])_2B_VALUES.clone();
    }
 
    public static DestinationType valueOf(String s)
    {
        DestinationType adestinationtype[] = _2B_VALUES;
        int i = adestinationtype.length;
        for(int j = 0; j < i; j++)
        {
            DestinationType destinationtype = adestinationtype[j];
            if(destinationtype.name().equals(s))
                return destinationtype;
        }
 
        throw new IllegalArgumentException(s);
    }
 
    DestinationType(String s, int i)
    {
        super(s, i);
    }
 
    public volatile int compareTo(Enum enum)
    {
        return super.compareTo((DestinationType)enum);
    }
 
    public static final native DestinationType queue;
    public static final native DestinationType topic;
    private static final DestinationType _2B_VALUES[] = {
        queue, topic
    };
 
    static 
    {
        queue = new DestinationType("queue", 0);
        topic = new DestinationType("topic", 1);
    }
}

Creating image thumbnails

Use the class AffineTransform.

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
 
public class Main extends JFrame {
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
   }
 
   public void createThumbs() {
      setTitle("JPG thumbnail images of " + System.getProperty("user.dir"));
 
      File f[] = new File(".").listFiles();
      for (int i=0; i<f.length; i++) {
         if (f[i].getName().endsWith(".jpg")) {
            ImageIcon imageIcon = new ImageIcon(f[i].getName()); 
            ImageIcon image = getThumb(imageIcon, 50);
            JLabel label = new JLabel(image);
            label.setToolTipText(f[i].getName());
            getContentPane().add(label);
            validate();
         }
      }
   } 
  
   public ImageIcon getThumb(ImageIcon imageIcon, int wh) {
      Image source = imageIcon.getImage();
 
      double scalex = (double) wh / source.getWidth(null);
      double scaley = (double) wh / source.getHeight(null);
 
      BufferedImage dest = new BufferedImage(wh, wh, 
                                    BufferedImage.TYPE_INT_RGB);
 
      AffineTransform ta = new AffineTransform();
      ta.scale(scalex, scaley);
          
      Graphics2D g2d = dest.createGraphics();
      g2d.drawImage(source, ta, null);
      g2d.dispose();
 
      return new ImageIcon(dest); 
    }

   public static void main(String[] args) {
      Main main = new Main();
      main.setSize(500, 150);
      main.setVisible(true);
 
      main.createThumbs();
   } 
}

Converting an OutputStream to a Writer

An OutputStream is byte oriented. A Writer is Character oriented. To hook up an OutputStream to a Writer and have the conversion done automatically for you, use the class OutputStreamWriter.

Main.java:

import java.io.*;
 
public class Main {   
   public static void main(String[] args) throws Exception {
      String s = "ABC";
 
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      OutputStreamWriter osw = new OutputStreamWriter(baos);
      for (int i=0; i<s.length(); i++) {
         osw.write((int) s.charAt(i));
      }
      osw.close();
 
      byte[] b = baos.toByteArray();
      for (int i=0; i<b.length; i++) {
         System.out.println(b[i]);
      }
   }
}

outputs:

65
66
67

Displaying binary, hexadecimal or octal values

Use one of the following static methods to convert integers
into binary, hexadecimal or octal string representations:

Integer.toBinaryString(int)
Integer.toHexString(int)
Integer.toOctalString(int)

For bigger values use:

Long.toBinaryString(int)
Long.toHexString(int)
Long.toOctalString(int)

For arbitrary precision integers use
BigInteger.toString(int radix) with the values 2 (binary),
16 (hexadecimal) and 8 (octal).

Determine if a file is hidden in Java

Whether a file is hidden or not, is filesystem dependent. On Windows, a file is hidden when it has been marked hidden.

Main.java:

import java.io.*;
   
public class Main {
   public static void main(String[] args) {
      System.out.println(new File("Main.java").isHidden());
      System.out.println(new File("c:\io.sys").isHidden());
   }
}

prints out:

true
false

Reading a BufferedImage using the ImageIO API

The new ImageIO API allows you to read and write any type of image files as long
as there is a plug-in written for it. Those plug-ins can be provided by third parties.
The appropriate plug-in is choosen depending on the file suffix, mime type, contents or format name.

The following example uses the built-in JPG plug-in.

Main.java:

import javax.swing.event.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.imageio.*;
import javax.swing.*;
import java.net.*;
import java.awt.*;
import java.io.*;
 
public class Main extends JFrame
{
   BufferedImage background;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      try {
         background = ImageIO.read(new URL(&quot;http://www.esus.com/images/mong.jpg&quot;));
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
 
   public void paint(Graphics g) {
      g.drawImage(background, 0, 0, getWidth(), getHeight(), this);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Who is calling a method

Main.java:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      test();
   }
 
   public static void test() {
      System.out.println("Method that called me: " + FlowInspector.getCallingMethod());
      new Main().new Inner().innerTest();
   }
 
   class Inner {
      public void innerTest() {
         System.out.println("Method that called me: " + FlowInspector.getCallingMethod());
      }
   }
}

FlowInspector.java:

public class FlowInspector
{
   public static String getCallingMethod() {
      try {
         StringWriter sw = new StringWriter();
         (new Exception()).printStackTrace(new PrintWriter(sw));
         StringReader sr = new StringReader(sw.getBuffer().toString());
         BufferedReader br = new BufferedReader(sr);
         br.readLine();
         br.readLine();
         br.readLine(); 
         String line = br.readLine();
         line = line.trim().substring(3);
         line = line.substring(0, line.indexOf('('));
 
         return line;
      } catch (Exception e) {
         e.printStackTrace();
      }
 
      return null;
   }
}

Running Main yields:

Method that called me: Main.main
Method that called me: Main.test