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

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

Creating multi-dimensional arrays

Examine the following double array:

      double ar[][] = 
        { { 20.0 },
          { 20.0, 19 },
          { 20.0, 19.0, 18.0 },
          { 20.0, 19.0, 18.0, 17.0 },
          { 20.0, 19.0, 18.0, 17.0, 16.0 } };

You can achieve the same setup dynamically by looping through the row indices and dynamically creating a array with variable length:

public class Main {
   public static void main(String []args) {
      double ar[][] = null;
 
      ar = new double[5][];
      for (int i=0; i<ar.length; i++) {
         ar[i] = new double[i+1];
         for (int j=0; j<i+1; j++) {
            ar[i][j] = (double) 20 - j;
         }
      }
 
      for (int i=0; i<ar.length; i++) {
         for (int j=0; j<ar[i].length; j++) {
            System.out.print(ar[i][j] + " ");
         }
         System.out.println();
      }
   }
}

Filling in new trace information in the stack trace of an Exception

The stack trace is useful to determine where the exception was thrown. There may be times where you need to rethrow an exception and find out where it was rethrown. You can use the method fillInStackTrace for that.

Main.java:

public class Main {
   public static void main(String args[]) {
      try {
         methodWithException1();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
 
   public static void methodWithException1() throws Exception {
      try {
         methodWithException2();
      }
      catch(Exception e) {
         throw (Exception) e.fillInStackTrace();
//         throw e;
      }
   }
 
   public static void methodWithException2() throws Exception {
      throw new Exception("some extra info");
   }
}

outputs:

java.lang.Exception: some extra info
        at Main.methodWithException1(Main.java:16)
        at Main.main(Main.java:4)

If you would have written throw e instead of throw (Exception e.fillInStackTrace, the output would have been:

java.lang.Exception: some extra info
        at Main.methodWithException2(Main.java:22)
        at Main.methodWithException1(Main.java:13)
        at Main.main(Main.java:4)