Desktop sharing using ssh tunnel

Share desktop of A to B with C as the hop. You’ll need access to your own server (C).

Execute on A: (assuming 192.168.1.100 is the ip of machine A)

% ssh -R 3390:192.168.1.100:3389 -l username myserver.com
log in and execute
ping 8.8.8.8 -i 5
to prevent the connection from timing out

Execute on B

% ssh -l username myserver.com -L 3391:localhost:3390

This means that you will be able to connect at localhost:3391 from your home computer and everything will be forwarded to myserver.com:3390.

Point your remote desktop connection to localhost:3391

cropped-DSC_0066-1024x477

Hibernate 4 Integrator pattern and Spring’s DI

Enabling @Autowired in Hibernate entities.

Create an EventListener that kicks in after a Hibernate LOAD event.  Using AutowireCapableBeanFactory to wire @Autowire’d dependencies.

package be.esus.core.infrastructure.hibernate;

import be.core.architecture.common.locator.SpringLocator;
import org.hibernate.event.spi.PostLoadEvent;
import org.hibernate.event.spi.PostLoadEventListener;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;

// https://jira.spring.io/browse/SPR-9187
public class MyPostLoadEventListener implements PostLoadEventListener {
   @Override
   public void onPostLoad(PostLoadEvent postLoadEvent) {
      Object entity = postLoadEvent.getEntity();

      AutowireCapableBeanFactory spring = SpringLocator.getApplicationContext().getAutowireCapableBeanFactory();
      spring.autowireBean(entity);
   }
}

(SpringLocator is a simple custom class that is ApplicationContextAware in order to have static access to the ApplicationContext)

Register your new listener in Hibernate’s EventListenerRegistry.

package be.esus.core.infrastructure.hibernate;

import org.hibernate.cfg.Configuration;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.integrator.spi.Integrator;
import org.hibernate.metamodel.source.MetadataImplementor;
import org.hibernate.service.spi.SessionFactoryServiceRegistry;
import org.springframework.stereotype.Component;

@Component
public class MyEventListenerIntegrator implements Integrator {

   @Override
   public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory,
                         SessionFactoryServiceRegistry serviceRegistry) {
      EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class );

      eventListenerRegistry.appendListeners(EventType.POST_LOAD, new MyPostLoadEventListener());
   }

   @Override
   public void integrate(MetadataImplementor metadataImplementor,
                         SessionFactoryImplementor sessionFactoryImplementor,
                         SessionFactoryServiceRegistry sessionFactoryServiceRegistry) {

   }

   @Override
   public void disintegrate(SessionFactoryImplementor sessionFactoryImplementor,
                            SessionFactoryServiceRegistry sessionFactoryServiceRegistry) {

   }
}

To register your SPI (see service loader), create
a (text) file called org.hibernate.integrator.spi.Integrator in META-INF/services/ and put the FQCN of your integrator in it:

be.esus.core.infrastructure.hibernate.MyEventListenerIntegrator

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

Combining multiple InputStreams

You can combine two or more inputstreams with the class SequenceInputStream. It allows
you to put them next to each other, in sequence:

           SequenceInputStream
           +-----------------------+
           |  +-----+-----+-----+  |
 read() <--+  | IS1 | IS2 | IS3 |  |
           |  +-----+-----+-----+  |
           +-----------------------+

There are two ways to construct a SequenceInputStream through its two constructors. You could either pass an enumeration of all your inputstreams, or you can pass in two inputstreams.
The following example allows you to specify two filenames which will be printed out on the console.

Main.java:

import java.util.*;
import java.io.*;
  
public class Main {   
   public static void main(String[] args) throws Exception {
      if (args.length != 2) {
         System.out.println("Usage: java Main <filename1> <filename2>");
         System.exit(1);
      }
 
      FileInputStream fis1 = new FileInputStream(args[0]);
      FileInputStream fis2 = new FileInputStream(args[1]);
 
      SequenceInputStream sis = new SequenceInputStream(fis1, fis2);
      int k;
      while ((k = sis.read()) > -1) {
         System.out.print((char) k);
      }
   }
}

(try it out with two small textfiles :)

Converting a character array to a Reader

Use the class CharArrayReader. Once you have wrapped it into a reader, you can use other readers to access the data, as shown in following example.

Main.java:

import java.io.*;
 
public class Main {
   public static void main(String args[]) {
      char array[] = { 'h', 'e', 'l', 'l', 'o', ',', 'n', 
                       'w', 'o', 'r', 'l', 'd', '!' };
      CharArrayReader car = new CharArrayReader(array);
 
      BufferedReader br = new BufferedReader(car);
      String line;
      while ((line = br.readLine()) != null) {
         System.out.println(line);
      }
   }
}

outputs:

hello,
world!

Listing the contents of a directory in Java

Use the File class. Here’s an example:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      if (args.length != 1) {
         System.err.println("Usage: java Main <path>");
         System.exit(1);
      }
 
      File []files = new File(args[0]).listFiles();
 
      for (int i=0; i<files.length; i++) {
         // Checks whether this it's a directory
         if (files[i].isDirectory()) 
            System.out.println("Directoryt" + files[i].getName());
         else
            System.out.println("Filett" + files[i].getName());
      }
   }
}

If you want to enable wildcards, you can do all the customization yourself using
FilenameFilter. The following example shows you how to list the .java files in
the directory specified at command line:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      if (args.length != 1) {
         System.err.println("Usage: java Main <path>");
         System.exit(1);
      }
 
      File path = new File(args[0]);
      File []files = path.listFiles(
               new FilenameFilter() {
                  public boolean accept(File f, String name) {
                     return name.toLowerCase().endsWith(".java");
                  }
               });
 
      for (int i=0; i<files.length; i++) {
         if (files[i].isDirectory()) 
            System.out.println("Directoryt" + files[i].getName());
         else
            System.out.println("Filett" + files[i].getName());
      }
   }
}

Differentiating between left, middle, right mouse click

Here’s some sample code.

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) { 
            System.exit(1);
         }
      });
 
      getContentPane().addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent me) {
            if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
               System.out.print("Left");
            }
            else if ((me.getModifiers() & InputEvent.BUTTON2_MASK) != 0) {
               System.out.print("Middle");
            }
            else if ((me.getModifiers() & InputEvent.BUTTON3_MASK) != 0) {
               System.out.print("Right");
            }
            System.out.println(" mouse button was clicked!");
         }
      });
   }
  
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}

Trapping CTRL-C in a Java app

The method addShutdownHook() of the java.lang.Runtime class provides a way of trapping a shutdown of the virtual machine. Please not that this method was added since java version 1.3.

The method expects one argument and that is a Thread object. This thread will be started when the virtual machine terminates. The only way this code will not be executed is when you use the method Runtime.halt().
After you have added a Shutdown hook, it is also possible to remove it with the equivalent method removeShutdownHook(). Its parameter should be the same as the one passed in addShutdownHook.

The following code illustrates an example that makes use of the addShutdownHook method.

Main.java:

// The Shutdown class is a sample class to illustrate the
// use of the addShutdownHook method
class Shutdown {
  private Thread thread = null;
 
  public Shutdown() {
    thread = new Thread("Sample thread") {
      public void run() {
        while (true) {
          System.out.println("[Sample thread] Sample thread speaking...");
          try {
            Thread.currentThread().sleep(1000);
          } catch (InterruptedException ie) {
            break;
          }
        }
        System.out.println("[Sample thread] Stopped");
      }
    };
    thread.start();
  }

  public void stopThread() {
    thread.interrupt();
  }
}
 
 
// The ShutdownThread is the thread we pass to the
// addShutdownHook method
class ShutdownThread extends Thread {
  private Shutdown shutdown = null;
 
  public ShutdownThread(Shutdown shutdown) {
    super();
    this.shutdown = shutdown;
  }
  
  public void run() {
    System.out.println("[Shutdown thread] Shutting down");
    shutdown.stopThread();
    System.out.println("[Shutdown thread] Shutdown complete");
  }
}
 
 
// And finally a Main class which tests the two classes
// We let the sample thread run for 10 seconds and then
// force a Shutdown with System.exit(0). You may stop the
// program early by pressing CTRL-C.
public class Main {
  public static void main(String [] args) {
    Shutdown shutdown = new Shutdown();
    try {
      Runtime.getRuntime().addShutdownHook(new ShutdownThread(shutdown));
      System.out.println("[Main thread] Shutdown hook added");
    } catch (Throwable t) {
      // we get here when the program is run with java
      // version 1.2.2 or older
      System.out.println("[Main thread] Could not add Shutdown hook");
    }
 
    try {
      Thread.currentThread().sleep(10000);
    } catch (InterruptedException ie) {
    }
    System.exit(0);
  }
}

Converting a boolean to an int

Assuming true maps to 1, false to 0.

Main.java:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      System.out.println(boolean2Int(true));
      System.out.println(boolean2Int(false));
   } 
 
   public static int boolean2Int(boolean b) {
      return b ? 1 : 0;
   }
}

Determining the component type of an array

Very simple – first obtain the Class object representing the type of the array itself:

  Integer [] arr = new Integer[5];
  Class arrType = arr.getClass();

And then obtain its type using the Class.getComponentType() method:

  Class componentType = arrType.getComponentType();
  System.out.println(componentType.getName());

The above code should print “java.lang.Integer”.