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 dimensions of a text in Swing

This example shows you how to center a text on the JFrame. It will take into account the specifics of the chosen font. Run it from command line like java Main Helvetica.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   private String fontname;
   private String text = "Easter Island";
 
   public Main(String fontname) {
      this.fontname = fontname;
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
   } 

   public void paint(Graphics g) {
      super.paint(g);
 
      Graphics2D g2d = (Graphics2D) g;
      Font f = new Font(fontname, Font.BOLD, 36);
      FontMetrics fm = getFontMetrics(f);
 
      int swidth = fm.stringWidth(text);
      int sheight = fm.getAscent();
 
      int width = getSize().width;
      int height = getSize().height;
 
      g2d.setColor(Color.gray);
      g2d.drawLine(0, height/2, width, height/2);
      g2d.drawLine(width/2, 0, width/2, height);
 
      g2d.setColor(Color.black);
      g2d.setFont(f);
      g2d.drawString(text, width/2 - swidth/2, height/2 + sheight/2);
   }
  
   public static void main(String []args) {
      if (args.length == 0) {
         System.err.println("Usage: java Main <fontname>");
         System.exit(1);
      }
 
      Main main = new Main(args[0]);
      main.setVisible(true);
      main.setSize(300, 300);
   }
}

Skipping part of an InputStream when reading from it

You can do so using the method skip. You can call this method from any point where you are in the inputstream.

The following program skips half of the file, where the filename is supplied at command line.

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));
 
      int half = (int) file.length() / 2;
      bis.skip(half);
 
      int b;
      while ((b = bis.read()) > 0) {
         System.out.print((char) b);
      } 
   }
}

Writing a file in UTF-8 encoding using a Writer

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

Main.java:

import java.io.*;
 
public class Main {
   public static void main(String args[]) {
      try {
         OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("test.utf"), "UTF8");
         BufferedWriter bw = new BufferedWriter(osw);
         bw.write("hu0000ello");
         bw.close();
      }
      catch(FileNotFoundException e) {
         System.out.println(e);
      }
      catch(IOException e) {
         System.out.println(e);
      }
   }
}

Tell how much free space is on disk in Java

Unfortunately, there is no API or method to find out, not even in JDK 1.3. Check out BUG 4057701 in Sun’s Bug Parade. Until this bug is fixed, you can try out to execute an external command like dir (Windows) or du (unix) and parse the output:

import java.util.*;
import java.text.*;
import java.io.*;
  
public class Main
{
   public static void main(String [] args) throws Exception {
      long fs = getFreeSpace("c:");
 
      System.out.println("Free space: " + fs);
   }
 
   public static long getFreeSpace(String dir) throws Exception {
      String osname = System.getProperty("os.name");
      String command = "";
      if (osname.indexOf("NT") > -1)
         command = "c:\winnt\cmd.com";
      else if (osname.indexOf("Windows") > -1)
         command = "c:\windows\command.com";
 
      Process p = Runtime.getRuntime().exec(command + " /c dir " + dir + " > c:\dir.txt");
      p.waitFor(); 
 
      File f = new File("c:\dir.txt");
      BufferedReader br = new BufferedReader(new FileReader(f));
      String line;
      String totalBytes = "";
      while ((line = br.readLine()) != null) {
         if (line.indexOf("bytes free") > -1) {
            int start = line.indexOf("dir(s)") + 7;
            int end = line.indexOf("bytes free", start);
            totalBytes = line.substring(start, end).trim();
            break;
         }
      }
 
      br.close();
      f.delete();
 
      return NumberFormat.getInstance().parse(totalBytes).longValue(); 
   }
}

This code needs to be adapted to be language and platform independent!

Detecting if the right button was clicked in Swing

To determine whether a right mouse click button was clicked or not, write code in the mouseClicked function of the mouseListener Interface.

   class MyMouseListener extends MouseAdapter
   {
      public void mouseClicked(MouseEvent me)
      {
         if ((me.getModifiers() & InputEvent.BUTTON3_MASK) != 0)
            // right mouse clicked......   
         }
      }
   };
 
   /* getModifiers() gives constant modifier for a particular click();
      BUTTON3_MASK is constant modifier for the right moouse click */

Getting a list of packages that have been loaded

Main.java:

public class Main
{
   public static void main(String []args) {
      Package[] packages = Package.getPackages();
      for (int i=0; i<packages.length; i++) {
         System.out.println(packages[i]);
      }
   }
}

prints out:

package java.util.zip, Java Platform API Specification, version 1.3
package java.security, Java Platform API Specification, version 1.3
package java.io, Java Platform API Specification, version 1.3
package sun.net.www.protocol.file, Java Platform API Specification, version 1.3
package sun.net.www.protocol.jar, Java Platform API Specification, version 1.3
package sun.net.www, Java Platform API Specification, version 1.3
package java.util.jar, Java Platform API Specification, version 1.3
package sun.security.action, Java Platform API Specification, version 1.3
package java.lang, Java Platform API Specification, version 1.3
package sun.io, Java Platform API Specification, version 1.3
package java.util, Java Platform API Specification, version 1.3
package sun.misc, Java Platform API Specification, version 1.3
package java.security.cert, Java Platform API Specification, version 1.3
package java.lang.reflect, Java Platform API Specification, version 1.3
package java.net, Java Platform API Specification, version 1.3
package sun.security.util, Java Platform API Specification, version 1.3
package java.lang.ref, Java Platform API Specification, version 1.3
package sun.security.provider, Java Platform API Specification, version 1.3
package com.sun.rsajca

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

Use the static method parseInt in the Integer primitive wrapper class. You pass in a string containing the digits of the specified radix. If a digit is not in the radix range, you’ll get a NumberFormatException.

Here’s an example:

public class Main
{
   public static void main(String args[]) {      
      // convert from hexadecimal                
      int a = Integer.parseInt("FF1C", 16);
  
      // convert from octal
      int b = Integer.parseInt("107", 8);
 
      // convert from binary
      int c = Integer.parseInt("10010", 2);
 
      System.out.println(a);   // 65308
      System.out.println(b);   // 71
      System.out.println(c);   // 18
   }
}

Randomly shuffling an array

Take two random numbers between 0 and the length of the array (bounds inclusive) and swap the values.

This example shows you a method that can take an array of any type and just swaps references around.

Main.java:

import java.util.*;
import java.io.*;
import java.lang.reflect.*;
 
public class Main
{
   public static void main(String []args) {
      int[] arr = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  
      System.out.print("Before:nt");
      printArray(arr);
 
      shuffleArray(arr); 
 
      System.out.print("After:nt");
      printArray(arr);
   }
  
   public static void printArray(int []arr) { 
      for (int i=0; i<arr.length; i++) {
         System.out.print(arr[i] + " ");
      }
      System.out.println();
   }
 
   public static void shuffleArray(Object arr) {
      Random r = new Random();
      for (int i=0; i<100; i++) {
         int r1 = Math.abs(r.nextInt() % 10);
         int r2 = Math.abs(r.nextInt() % 10);
         Object el0 = Array.get(arr, r1);
         Object el1 = Array.get(arr, r2);
         Array.set(arr, r2, el0);
         Array.set(arr, r1, el1);
      }
   }
}

outputs:

Before:
	0 1 2 3 4 5 6 7 8 9 
After:
	1 4 7 3 5 9 6 2 8 0