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

Drawing a filled oval in Swing

Use the method fillOval.

Main.java:

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);
         }
      });
   }
 
   public void paint(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
  
      g2d.setColor(Color.green);
      g2d.fillOval(10, 40, getSize().width-20, getSize().height-60);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(250, 150);
      main.setVisible(true);
   }
}

Java InputStream mark() and reset()

You can use the method mark to mark a position in the inputstream and the method reset to return to that mark. It allows you to read ahead in the inputstream to determine what to do next. The mark method accepts an limit (integer), which denotes the maximum number of bytes that are to be read ahead. If you read more than this limit, you cannot return to this mark.
Before you can use the mark and reset, you need to test out whether these operations are supported on the inputstream you’re reading off. You can do that with markSupported.

The following program reads in a file once and the second half of the file again using the same inputstream.

Main.java:

import java.io.*;
  
public class Main {
   public static void main(String args[]) throws Exception {
      if (args.length != 1) {
         System.err.println("Usage: java Main <file.txt>");
         System.exit(1);
      }
 
      File file = new File(args[0]);
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
      if (bis.markSupported()) {
         int b, count=0;
         int half = (int) file.length() / 2;
         System.out.println("Complete file:");
         while ((b = bis.read()) > 0) {
            System.out.print((char) b);
            if (++count == half+1) 
               bis.mark(half);
         }
 
         System.out.println("---------------------------");
 
         bis.reset();
 
         System.out.println("Read in second half of file again:");
         while ((b = bis.read()) > 0) {
            System.out.print((char) b);
         }
      }
   }

To read-ahead, you can also use the PushBackInputStream.

Reading a file that is encoded in UTF-8 using a Reader

You can specify the encoding UTF-8 with InputStreamReader. This class will convert the incoming bytes to Unicode.

Main.java:

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

Note: Since UTF-8 is backwards compatible with ASCII, you can test this program with those types of files.

Reading a binary file into a byte array

Use BufferedInputStream as shown in following example.

Main.java:

import java.io.*;
 
public class Main {
   public static void main(String args[]) {
      if (args.length != 1) {
         System.err.println("Usage: java Main <file>");
         System.exit(1);
      }
 
      try {
         File f = new File(args[0]);
         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
         byte[] buffer = new byte[(int) f.length()];
         bis.read(buffer, 0, buffer.length);
         bis.close();
         System.out.println("Read file with " + buffer.length + " bytes.");
      }
      catch(IOException e) {
         System.err.println(e);
      }
   }
}

Detecting a triple-click in Swing

Use the method getClickCount() as shown in following example.

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.getClickCount() == 3) {
               System.out.println("Button was clicked 3 times!");
            }
         }
      });
   }
  
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}

Executing another java app from an already running one

You can either invoke the program entry point (the “main” function) of the other
application:

public class App1 {
   public void main(String args[]) {

      String []args2 = { "firstparam", "secondparam" };

      App2.main(args2);

   }
}

This will run App2 in the currently running JVM. You could also have the
new application running in another instance of a VM:

public class App1 {
   public void main(String []args) {
      
      Runtime.exec("java App2 firstparam secondparam");

   }
}

Converting an integer to a hexadecimal (hex), octal or binary representation

Three useful functions in the Integer class do exactly this. Following program
demonstrates the use. Notice that the method toHexString returns the hexadecimal
representation in lowercase!

public class Main
{
   public static void main(String args[]) {
      int intValue = 65443;
 
      String hexValue = Integer.toHexString(intValue);
      String octValue = Integer.toOctalString(intValue);
      String binValue = Integer.toBinaryString(intValue);
 
      System.out.println(hexValue.toUpperCase());
      System.out.println(octValue);
      System.out.println(binValue);
   }
}

outputs:

FFA3
177643
1111111110100011