Using a CheckBox 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.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 Checkbox 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.CHECK);
      button1.setText("orange");
      button1.addSelectionListener(selectionListener);
      Button button2 = new Button(buttonGroup, SWT.CHECK);
      button2.setText("pear");
      button2.addSelectionListener(selectionListener);
      Button button3 = new Button(buttonGroup, SWT.CHECK);
      button3.setText("apple");
      button3.addSelectionListener(selectionListener);
      
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      display.dispose();
   }
}

Creating an SWT FileDialog

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.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
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 FileDialog 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 directoryDialogButton = new Button(buttonGroup, SWT.PUSH);
      directoryDialogButton.setText("FileDialog");
      Label label1 = new Label(buttonGroup, SWT.NONE);
      label1.setText("File selected:");
      final Label label2 = new Label(buttonGroup, SWT.NONE);      
      label2.setText("");
 
      final String [] filterNames = { "All Files", "JPG Files", "GIF Files" };
      final String [] filterExtensions = { "*.*", "*.jpg", "*.gif" };
 
      SelectionListener selectionListener = new SelectionAdapter () {
         public void widgetSelected(SelectionEvent event) {
            FileDialog dialog = new FileDialog(shell, SWT.MODELESS);
            dialog.setFileName ("esuslogo.gif");
            dialog.setFilterNames (filterNames);
            dialog.setFilterExtensions (filterExtensions);
            dialog.setText("Select Image File");
            String result = dialog.open();
            label2.setText("" + result);
            buttonGroup.layout();
         };
      };   
        
      directoryDialogButton.addSelectionListener(selectionListener);
       
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      if (color != null && !color.isDisposed()) {
         color.dispose();
      }
      display.dispose();
   }
}

Creating an SWT Text(Area)

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.Shell;
import org.eclipse.swt.widgets.Text;
 
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 Text Demonstration");
      shell.setLayout(new GridLayout());
 
      shell.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
 
      Text text = new Text(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.WRAP);
      text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
       
      text.setText("Did you know..." +
                   "nn" +
                   "It is impossible to lick your elbow." +
                   "nnnnnnnnnnnnnnn" +
                   "Over 75% of people who read thisn" +
                   "will try to lick their elbow.");
       
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
       
      display.dispose();
   }
}

Catching a specific SIGNAL/Interrupt in Java

You can use the undocumented class sun.misc.Signal. But beware of using the Sun packages.

This program allows you to catch any of the following signals:

   Windows:
      	ABRT	SIGABRT
	FPE 	SIGFPE
    	SEGV	SIGSEGV
	INT	SIGINT
	TERM	SIGTERM
	ILL	SIGILL


   Solaris/Linux:
	HUP	SIGHUP
	INT	SIGINT
	QUIT	SIGQUIT
	ILL	SIGILL
	TRAP	SIGTRAP
	ABRT	SIGABRT
	IOT	SIGIOT (*)
	EMT	SIGEMT (*)
	FPE	SIGFPE
	KILL	SIGKILL
	BUS	SIGBUS
	SEGV	SIGSEGV
	SYS	SIGSYS
	PIPE	SIGPIPE
	ALRM	SIGALRM
	TERM	SIGTERM
	STKFLT	SIGSTKFLT
	USR1	SIGUSR1
	USR2	SIGUSR2
	CHLD	SIGCHLD
	PWR	SIGPWR
	WINCH	SIGWINCH
	URG	SIGURG
	POLL	SIGPOLL
	IO	SIGIO
	STOP	SIGSTOP
	TSTP	SIGTSTP
	CONT	SIGCONT
	TTIN	SIGTTIN
	TTOU	SIGTTOU
	VTALRM	SIGVTALRM
	PROF	SIGPROF
	XCPU	SIGXCPU
	XFSZ	SIGXFSZ
	UNUSED	SIGUNUSED
	SWI	SIGSWI

The example program (Linux/Solaris) demonstrates to catch and perform a System.exit only with a SIGTERM. A SIGHUP will not cause the program to exit.

Main.java:

import sun.misc.Signal;
import sun.misc.SignalHandler;
import java.lang.reflect.*;
 
public class Main
{
   public static void main(String []args) {
      DebugSignalHandler.listenTo("HUP");
      DebugSignalHandler.listenTo("INT");
      DebugSignalHandler.listenTo("KILL");
      DebugSignalHandler.listenTo("TERM");
 
      while (true) {
         try {
            Thread.sleep(1000);
         }
         catch(InterruptedException e) {
         }
      }
   }
}
 
class DebugSignalHandler implements SignalHandler
{
   public static void listenTo(String name) {
      Signal signal = new Signal(name);
      Signal.handle(signal, new DebugSignalHandler());
   }

   public void handle(Signal signal) {
      System.out.println("Signal: " + signal);
      if (signal.toString().trim().equals("SIGTERM")) {
         System.out.println("SIGTERM raised, terminating...");
         System.exit(1);
      }
   }
}

Dynamically add JARs from an application’s lib directory

This example assumes you have the JDBC mm.mysql driver residing in an ext subdirectory.

Main.java:

import java.util.*;
import java.net.*;
import java.io.*;
import java.sql.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      ClassLoader cl = loadExt();
      if (cl != null) {
         cl.loadClass("org.gjt.mm.mysql.Driver").newInstance();
         System.out.println("mysql driver successfully loaded!");
         Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/esus", "USER", "PASS");
 
         //. . .
      }
   }
 
   public static URLClassLoader loadExt() {
      try {
         Vector urls = new Vector();
         File file = new File("ext");
         String[] list = file.list();
         for (int i=0; i<list.length; i++) {
            if (list[i].endsWith(".jar")) {
               urls.add(new URL("file:" + file.getName() + "/" + list[i]));
            }
         }
         return new URLClassLoader((URL[]) urls.toArray( new URL[] { } ));
      } catch ( java.net.MalformedURLException me ) { 
         me.printStackTrace();
      }
 
      return null;
   }
}

Changing the color of one JTable cell

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      super("TableModel Demonstration");
  
      // create our own custom TableModel
      WineTableModel wineModel = new WineTableModel();
      JTable table = new JTable(wineModel);
 
      // since we're using values of floats and boolean here, we need
      // to set the cell renderer for every column. 
      for (int i =0; i<wineModel.getColumnCount();i++) {
         table.setDefaultRenderer(table.getColumnClass(i), new WineCellRenderer());
      }
       
      // add rows to our TableModel, each row is represented as a Wine object
      wineModel.addWine(new Wine("Chateau Meyney, St. Estephe", "1994", 18.75f, true));
      wineModel.addWine(new Wine("Chateau Montrose, St. Estephe", "1975", 54.25f, true));
      wineModel.addWine(new Wine("Chateau Gloria, St. Julien", "1993", 22.99f, false));
      wineModel.addWine(new Wine("Chateau Beychevelle, St. Julien", "1970", 61.63f, false));
      wineModel.addWine(new Wine("Chateau La Tour de Mons, Margeaux", "1975", 57.03f, true));
      wineModel.addWine(new Wine("Chateau Brane-Cantenac, Margeaux", "1978", 49.92f, false));
 
      // create the scroll pane and add the table to it. 
      JScrollPane scrollPane = new JScrollPane(table);
 
      // add the scroll pane to this window.
      getContentPane().add(scrollPane, BorderLayout.CENTER);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}
 
// a simple object that holds data about a particular wine
class Wine {
   private String  name;
   private String  vintage;
   private float   price;
   private boolean inStock;
 
   public Wine(String name, String vintage, float price, boolean inStock) {
      this.name = name;
      this.vintage = vintage;
      this.price = price;
      this.inStock = inStock;
   }
 
   public String getName()     { return name; }
   public String getVintage()  { return vintage; }
   public float  getPrice()    { return price; } 
   public boolean getInStock() { return inStock; }
 
   public String toString() { 
      return "[" + name + ", " + vintage + ", " + price + ", " + inStock + "]"; }
}
 
class WineTableModel extends AbstractTableModel {
   // holds the strings to be displayed in the column headers of our table
   final String[] columnNames = {"Name", "Vintage", "Price", "In stock?"};
 
   // holds the data types for all our columns
   final Class[] columnClasses = {String.class, String.class, Float.class, Boolean.class};
 
   // holds our data
   final Vector data = new Vector();
  
   // adds a row
   public void addWine(Wine w) {
      data.addElement(w);
      fireTableRowsInserted(data.size()-1, data.size()-1);
   }
 
   public int getColumnCount() {
      return columnNames.length;
   }
         
   public int getRowCount() {
      return data.size();
   }
 
   public String getColumnName(int col) {
      return columnNames[col];
   }
 
   public Class getColumnClass(int c) {
      return columnClasses1;
   }
 
   public Object getValueAt(int row, int col) {
      Wine wine = (Wine) data.elementAt(row);
      if (col == 0)      return wine.getName();
      else if (col == 1) return wine.getVintage();
      else if (col == 2) return new Float(wine.getPrice());
      else if (col == 3) return new Boolean(wine.getInStock());
      else return null;
   }
 
   public Object getValueAtRow(int row) {
      Wine wine = (Wine) data.elementAt(row);
      return wine;
   }
 
   public boolean isCellEditable(int row, int col) {
      return false;
   }
}
 
class WineCellRenderer extends DefaultTableCellRenderer {
   public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected,
            boolean hasFocus, int row, int column)
   {
      WineTableModel wtm = (WineTableModel) table.getModel();
      Wine wine = (Wine) wtm.getValueAtRow(row);
 
      if (column == 3 && wine.getInStock() == false) {
         setBackground(Color.red);
      }
      else {
         setBackground(Color.white);
      }
 
      return super.getTableCellRendererComponent(table, value, isSelected, 
                                                 hasFocus, row, column);
   }
}

Setting the a connect timeout on an URLConnection

JDK1.5 allows you to set connect and read timeouts on URLConnection (HttpURLConnection, etc.).

Here is an example:

Main.java:

import java.net.*;

public class Main
{
   public static void main(String []args) throws Exception {
      if (args.length != 1) {
         System.err.println("Usage: java Main <URL>");
         System.exit(0);
      }
          
      URL url = new URL(args[0]);
      URLConnection connection = url.openConnection();
 
      connection.setConnectTimeout(5000);
      connection.connect();
   }
}

Publishing a Websphere MQ ConnectionFactory in an LDAP

The following working code sample allows you to create a QueueConnectionFactory (MQQueueConnectionFactory) and register it as an administered object in an LDAP tree.

I used iPlanet Directory Server 5.0 to test it out.

RegisterWebsphereMQ.java:

import  com.ibm.mq.jms.MQQueueConnectionFactory;
import  javax.naming.*;
import  javax.jms.*;
 
import  java.util.*;
 
public class RegisterWebsphereMQ
{
   public static void main(String args[])
   {
      if (args.length != 5) {
         System.err.println("Usage: RegisterWebsphereMQ LDAP-url base queue-manager username password");
         System.err.println("  eg.:      ldapurl        ldap://127.0.0.1:389");
         System.err.println("            providername   ou=dev,ou=test,o=esus.com");
         System.err.println("            queue-manager  name of the queue manager, eg. MQS1");
         System.err.println("            username       uid=user,ou=People,o=esus.com");
         System.err.println("            password       pw");
         System.exit(1);
      }
      String ldapurl=args[0];
      String base=args[1];
      String queuemgr=args[2];
      String username=args[3];
      String password=args[4];
 
      try {
         Context context = getInitialContext(ldapurl, username, password);
 
         createLDAPObject(context, base, "QueueConnectionFactory");
         createQueueConnectionFactory(context, base, queuemgr);
 
         System.out.println("Registration successful");
      } catch(Exception e) {
         System.out.println("Registration failed: " + e);
         e.printStackTrace();
      }
   }
 
   public static Context getInitialContext(String ldapurl, String username, String password)
                            throws NamingException
   {
      Properties env=System.getProperties();
      env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      env.put(Context.PROVIDER_URL, ldapurl);
      env.put(Context.SECURITY_PRINCIPAL, username);
      env.put(Context.SECURITY_CREDENTIALS, password);
 
      // Retrieve the initial context
      return new InitialContext(env);
   }
 
   public static void createLDAPObject(Context context, String base, String ouName)
                        throws NamingException
   {
      try {
         context.bind("ou=" + ouName + "," + base, new LDAPObject(ouName));
         System.out.println("Created OU [" + ouName + "]");
      }
      catch(NameAlreadyBoundException e) {
         System.out.println("Name " + ouName + " is already bound under " + base);
      }
   }
 
   public static void createQueueConnectionFactory(Context context, String base, String queuemgr)
                         throws NamingException, JMSException
   {
      QueueConnectionFactory qcf = new MQQueueConnectionFactory();
      ((MQQueueConnectionFactory) qcf).setQueueManager(queuemgr);
 
      // Bind the connection factory into the JNDI repository
      context.rebind("cn=queuefactory,ou=QueueConnectionFactory,"+base, qcf);
   }   
}

LDAPObject.java:

import javax.naming.*;
import javax.naming.directory.*;
import java.util.*;
 
class LDAPObject implements DirContext {
   Attributes attributes;
   String name;
    
   public LDAPObject(String name) {
      this.name = name;
 
      attributes = new BasicAttributes(true);
      // case ignore
      Attribute oc = new BasicAttribute("objectclass");
      oc.add("organizationalunit");
      oc.add("top");
 
      attributes.put(oc);
   }
 
   public Attributes getAttributes(String name) throws NamingException {
      if (!name.equals("")) {
         throw new NameNotFoundException();
      }
      return (Attributes) attributes.clone();
   }
 
   public Attributes getAttributes(Name name) throws NamingException {
      return getAttributes(name.toString());
   }
 
   public Attributes getAttributes(String name, String[] ids)
          throws NamingException {
      if (!name.equals("")) {
         throw new NameNotFoundException();
      }
 
      Attributes answer = new BasicAttributes(true);
      Attribute target;
      for (int i = 0; i < ids.length; i++) {
         target = attributes.get(ids[i]);
         if (target != null) {
            answer.put(target);
         }
      }
      return answer;
   }
 
   public Attributes getAttributes(Name name, String[] ids)
          throws NamingException {
      return getAttributes(name.toString(), ids);
   }
 
   public String toString() {
      return name;
   }
 
   public Object lookup(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Object lookup(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void bind(Name name, Object obj) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void bind(String name, Object obj) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void rebind(Name name, Object obj) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void rebind(String name, Object obj) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void unbind(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void unbind(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void rename(Name oldName, Name newName) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void rename(String oldName, String newName) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration list(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration list(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration listBindings(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration listBindings(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void destroySubcontext(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void destroySubcontext(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Context createSubcontext(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Context createSubcontext(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Object lookupLink(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Object lookupLink(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NameParser getNameParser(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NameParser getNameParser(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public String composeName(String name, String prefix)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Name composeName(Name name, Name prefix)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Object addToEnvironment(String propName, Object propVal)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Object removeFromEnvironment(String propName)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Hashtable getEnvironment() throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void close() throws NamingException {
      throw new OperationNotSupportedException();
   }
 
// -- DirContext
   public void modifyAttributes(Name name, int mod_op, Attributes attrs)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void modifyAttributes(String name, int mod_op, Attributes attrs)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void modifyAttributes(Name name, ModificationItem[] mods)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void modifyAttributes(String name, ModificationItem[] mods)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void bind(Name name, Object obj, Attributes attrs)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void bind(String name, Object obj, Attributes attrs)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void rebind(Name name, Object obj, Attributes attrs)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void rebind(String name, Object obj, Attributes attrs)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public DirContext createSubcontext(Name name, Attributes attrs)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public DirContext createSubcontext(String name, Attributes attrs)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public DirContext getSchema(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public DirContext getSchema(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public DirContext getSchemaClassDefinition(Name name)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public DirContext getSchemaClassDefinition(String name)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration search(Name name,
         Attributes matchingAttributes,
         String[] attributesToReturn)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration search(String name,
         Attributes matchingAttributes,
         String[] attributesToReturn)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration search(Name name,
         Attributes matchingAttributes)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration search(String name,
         Attributes matchingAttributes)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration search(Name name,
         String filter,
         SearchControls cons)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration search(String name,
         String filter,
         SearchControls cons)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration search(Name name,
         String filterExpr,
         Object[] filterArgs,
         SearchControls cons)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration search(String name,
         String filterExpr,
         Object[] filterArgs,
         SearchControls cons)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public String getNameInNamespace() throws NamingException {
      throw new OperationNotSupportedException();
   }
}

Sample run:

C:myldap>java RegisterWebsphereMQ ldap://localhost:2000 ou=dev,ou=epais,o=philips.com MQS1 uid=user,ou=People,o=esus.com pw
Created OU [QueueConnectionFactory]
Registration successful

Error message “Bad Magic Number”

Each class file starts with special 4 bytes equal to the hexadecimal value of 0xCAFEBABE – this number identifies the class file format and is humorously named “Magic Number”. When you get an error from the JVM saying “Bad Magic Number”, it simply means the class file it is trying to load is corrupt.

The solution is usually to recompile all your classes.

Drawing a rotated image

Work directly on the class Graphics2D or use the class AffineTransform that allows you to create your own transformation matrixes.

Directly on Graphics2D

Main.java:

import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private Image image;
   private boolean firstTime = true;
   private int degrees = 0;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      image = Toolkit.getDefaultToolkit().getImage("c:\djkrush.jpg");
      waitForImage(image);
 
      getContentPane().setLayout(new BorderLayout());
      JButton button = new JButton("rotate by 10 degrees");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            degrees += 10;
            repaint();
         }
      });
 
      getContentPane().add(BorderLayout.SOUTH, button);
   }
 
   public void paint(Graphics g) {
      super.paint(g);
 
      Graphics2D g2d = (Graphics2D) g;
 
      double radians = degrees * (Math.PI / 180);
      g2d.translate(getSize().width/2, getSize().height/2);
      g2d.rotate(radians); 
      g2d.drawImage(image, 0, 0, this);
   }
 
   public void waitForImage(Image image) {
      MediaTracker mt = new MediaTracker(this);
 
      int id = 0;
      mt.addImage(image, id);
 
      try {
         mt.waitForID(id);
      }
      catch(InterruptedException e) {
         System.out.println("Image loading interrupted : " + e);
      }
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Using AffineTransform

Main.java:

import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private Image image;
   private boolean firstTime = true;
   private int degrees = 0;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      image = Toolkit.getDefaultToolkit().getImage("c:\djkrush.jpg");
      waitForImage(image);
 
      getContentPane().setLayout(new BorderLayout());
      JButton button = new JButton("rotate by 10 degrees");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            degrees += 10;
            repaint();
         }
      });
 
      getContentPane().add(BorderLayout.SOUTH, button);
   }
 
   public void paint(Graphics g) {
      super.paint(g);
 
      if (degrees == 0) {
         g.drawImage(image, getSize().width/2, getSize().height/2, this);
      }
      else {  
         Graphics2D g2d = (Graphics2D) g;
 
         double radians = degrees * (Math.PI / 180);
         AffineTransform at = new AffineTransform();
         at.translate(getSize().width/2, getSize().height/2);
         at.rotate(radians);
         g2d.drawImage(image, at, this);
      }
   }
 
   public void waitForImage(Image image) {
      MediaTracker mt = new MediaTracker(this);
 
      int id = 0;
      mt.addImage(image, id);
 
      try {
         mt.waitForID(id);
      }
      catch(InterruptedException e) {
         System.out.println("Image loading interrupted : " + e);
      }
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

image used: