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

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.

Inverting an image

To invert an image, you can use the class LookupOp. This class works with one or more tables that will be applied to the color values of the pixels. To invert an RGB image, every R, G, and B value are subtracted from 256. The lookup table reflects these changes.

The following example shows the original image and an image that has been inverted.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private boolean firstTime = true;
   private BufferedImage sourceBi;
   private BufferedImage destBi;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      }); 
   } 
 
   public void paint(Graphics graphics) {
      Graphics2D g2d = (Graphics2D) graphics;
  
      if (firstTime) {
         Image img = new javax.swing.ImageIcon("meatballs.jpg").getImage(); 
         sourceBi = toBufferedImage(img);
         destBi = new BufferedImage(sourceBi.getWidth(), sourceBi.getHeight(), 
                                    BufferedImage.TYPE_INT_RGB);
         setSize(sourceBi.getWidth(), sourceBi.getHeight()*2);
 
         byte[] intensity = new byte[256];
         for(int i=0; i<256; i++) {
            intensity[i] = (byte) (256 - i);
         }
  
         ByteLookupTable blt = new ByteLookupTable(0, intensity);
         LookupOp op = new LookupOp(blt, null);
         destBi = op.filter(sourceBi, null);
 
         firstTime = false;
      }
 
      g2d.drawImage(sourceBi, 0, 0, this);
      g2d.drawImage(destBi, 0, sourceBi.getHeight(), this);
   }
 
   public static BufferedImage toBufferedImage(Image image) {
      BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), 
                                           BufferedImage.TYPE_INT_RGB); 
 
      // copy the original image
      Graphics g = bi.createGraphics();
    
      g.drawImage(image, 0, 0, null);
      g.dispose();
 
      return bi;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
      main.setSize(300, 150);
   }
}

Image used:

To learn more about image processing,
check out this expensive but excellent book:

Serializing an array in Java

Main.java:

import java.io.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      String stringArray[] = { "this", "is", "a", "test" };
 
      ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test.ser"));
      oos.writeObject(stringArray);
      oos.close();
 
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.ser"));
      String stringArray2[] = (String[]) ois.readObject();           
      ois.close();
   
      for (int i=0; i<stringArray2.length; i++) {
         System.out.println(stringArray2[i]);
      }
   }
}

Reading data from a text file in Java

If you are reading a text file, you can use the FileReader class in the java.io package. Here’s an example:

import java.io.*;
 
public class Main {
   public static void main(String []args) {
      if (args.length != 1) {
         System.out.println("Usage: java Main <textfile>");
         System.exit(1);
      }
  
      try {
         String line;
         BufferedReader br = new BufferedReader(new FileReader(args[0]));
         while ((line = br.readLine()) != null) {
            System.out.println(line);
         }
      }
      catch (IOException e) {
         System.out.println(e);
      }
   }
}

You will probably still see code around that uses the method readLine of the DataInputStream class. Sun has deprecated this method because it does not properly convert bytes (1 byte) to characters (2 bytes). Here’s the code if you’re still using 1.0.2:

import java.io.*;
 
public class Main {
   public static void main(String []args) {
      if (args.length != 1) {
         System.out.println("Usage: java Main <textfile>");
         System.exit(1);
      }
  
      try {
         String line;
         DataInputStream dis = new DataInputStream(new FileInputStream(args[0]));
         while ((line = dis.readLine()) != null) {
            System.out.println(line);
         }
      }
      catch (IOException e) {
         System.out.println(e);
      }
   }
}

Determining if a pathname is absolute

A pathname is absolute if it starts with the root.

Main.java: (on a Windows system):

import java.io.*;
 
public class Main {
   public static void main(String args[]) {
      checkAbsolute("autoexec.bat");
      checkAbsolute("c:\windows\system32\.\cloud.gif");
      checkAbsolute("//windows\..\autoexec.bat");
      checkAbsolute("\windows\..\autoexec.bat");
      checkAbsolute("windows\system32");
   }
 
   public static void checkAbsolute(String s) {
      System.out.print(new File(s).isAbsolute() ? "absolute" : "not absolute");
      System.out.println("t" + s);
   }
}

outputs:

not absolute	autoexec.bat
absolute	c:windowssystem32.cloud.gif
absolute	//windows..autoexec.bat
not absolute	windows..autoexec.bat
not absolute	windowssystem32

Catching events while an image is being written out using ImageIO

Register an IIOWriteProgressListener with your ImageWriter.

   IIOWriteProgressListener listener = new MyWriteProgressListener();
   writer.addIIOWriteProgressListener(listener);

This example reads a JPG and creates a new one, vertically subsampled.

Main.java:

import javax.imageio.metadata.*; 
import javax.imageio.stream.*;
import javax.imageio.event.*;
import javax.imageio.*;
 
import java.awt.image.*; 
import java.util.*;
import java.io.*;
  
public class Main 
{ 
   public static void main(String []args) throws Exception {
      if (args.length != 1 || !args[0].endsWith(".jpg")) {
         System.out.println("Usage: java Main image.jpg");
         System.exit(1);
      }
 
      Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
      ImageReader reader = (ImageReader) readers.next();
 
      Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
      ImageWriter writer = (ImageWriter) writers.next();
 
      ImageInputStream iis = ImageIO.createImageInputStream(new File(args[0]));
      reader.setInput(iis, true);
      BufferedImage bi = reader.read(0);
 
      IIOWriteProgressListener listener = new MyWriteProgressListener();
      writer.addIIOWriteProgressListener(listener);
 
      String jpgFile = args[0].substring(0, args[0].length()-4) + "_new.jpg";
      ImageOutputStream ios = ImageIO.createImageOutputStream(new File(jpgFile));
      ImageWriteParam param = writer.getDefaultWriteParam();
 
      IIOImage iioImage = new IIOImage(bi, null, null);
      param.setSourceSubsampling(1, 4, 0, 0);
      writer.setOutput(ios);
      writer.write(null, iioImage, param);
   }
 
   static class MyWriteProgressListener implements IIOWriteProgressListener {
        float last = 0;
 
	public MyWriteProgressListener() {}

        public void imageStarted(ImageWriter dest, int imageIndex)  { 
           System.out.println("0% -----------------------------------> 100%n");
        }
 
        public void imageProgress(ImageWriter dest, final float percentageDone) {
           int n = (int) (percentageDone-last);
           for (int i=0; i<n/2; i++) {
              System.out.print("*");
           }
           last = percentageDone;
        }
 
        public void imageComplete(ImageWriter dest) { 
           System.out.println();
        }
 
        public void writeAborted(ImageWriter dest)                  { }
        public void sequenceComplete(ImageWriter dest)              { }
        public void sequenceStarted(ImageWriter dest, int minIndex) { }
        public void thumbnailComplete(ImageWriter dest)             { }
        public void thumbnailProgress(ImageWriter dest, float percentageDone) { }
        public void thumbnailStarted(ImageWriter dest, int imageIndex, int thumbnailIndex) { }
   }
}

Dynamically loading and creating a class from a JAR

For this example, let’s create a JAR file called testjar.jar containing only one class in a package esus.testpackage. Create a directory structure:

   esus
     |
     +--- testpackage
               |
               +-------- TestClass.java

TestClass.java:

package esus.testpackage;
 
public class TestClass
{
   public void testMethod() {
      System.out.println("testMethod() called!");
   }
}

Compile and create a JAR file:

   javac esustestpackageTestClass.java
   jar cvf testjar.jar esus

Let’s not add this JAR file to the classpath, but dynamically use it to load a class and execute a method on it. For this purpose, use the URLClassLoader which takes a set of URLs pointing to JARs or directories.

Main.java:

import java.lang.reflect.*;
import java.net.*;
  
public class Main {
   public static void main(String[] args) {
      try {
         URL []urls = new URL[] { new URL("file:testjar.jar") };
 
         ClassLoader cl = URLClassLoader.newInstance(urls);
 
         // load class 
         Class c = cl.loadClass("esus.testpackage.TestClass");
 
         // create instance of class esus.testpackage.TestClass
         Object o = c.newInstance();
 
         // execute method testMethod
         Method m = o.getClass().getMethod("testMethod", new Class[] { });
         m.invoke(o, new Object[] { });
      }
      catch(Exception e) {
         System.out.println(e);
      }
   }
}

outputs:

testMethod() called!

Comparing two arrays

If you want to compare if two arrays point to the same memory, you can simply compare its references:

import java.util.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      int arr[] = { 10, 8, 6, 4, 2, 11, 3, 5, 7, 9 };
 
      int arr2[] = arr;
 
      if (arr == arr2) {
         System.out.println("Arrays are equal"); 
      } 
      else {
         System.out.println("Arrays are not equal"); 
      }
   }
}

If you want to compare each and one of the values of the array’s elements are equal, you can use the handy method equals in the Arrays class. Here’s an example:

import java.util.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      int arr[] = { 10, 8, 6, 4, 2, 11, 3, 5, 7, 9 }; 
      int arr2[] = { 10, 3, 6, 4, 2, 11, 3, 5, 7, 9 };
 
      if (Arrays.equals(arr, arr2)) {
         System.out.println("Arrays are equal");
      }
      else {
         System.out.println("Arrays are not equal");
      }
   }
}