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 textured round filled rectangle in Swing

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private BufferedImage image; 
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      image = toBufferedImage(new javax.swing.ImageIcon("c:\djkrush.jpg").getImage());
   }
 
   public void paint(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
 
      Rectangle2D tr = new Rectangle2D.Double(0, 0, image.getWidth(), image.getHeight());
      TexturePaint tp = new TexturePaint(image, tr);
 
      // draw texture filled ellipse, but with antialiasing
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                           RenderingHints.VALUE_ANTIALIAS_ON);
      BasicStroke bs = new BasicStroke(5, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                           10, null, 0);
      g2d.setStroke(bs);
      g2d.setPaint(tp);
      g2d.drawRoundRect(10, 40, 150, 150, 50, 30);
   }
 
   public 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.setSize(170, 210);
      main.setVisible(true);
   }
}

Image used:

Creating an OutputStream that manipulates the data written to it

Create a class that extends from FilterOutputStream and override the method write in which you convert the original value to a new value.

Following example introduces the ChangeCaseOutputStream which will convert any character to uppercase or lowercase depending on how you instantiated the class.

Main.java:

import java.io.*;
 
public class Main {
   public static void main(String args[]) {
      try {
         FileOutputStream fos = new FileOutputStream("test.out");
         ChangeCaseOutputStream ccos = new ChangeCaseOutputStream(
                                        ChangeCaseOutputStream.UPPERCASE, fos);
         ccos.write("hello, world!".getBytes());
         ccos.flush();
         ccos.close();
      }
      catch(FileNotFoundException e) {
         System.out.println(e);
      }
      catch(IOException e) {
         System.out.println(e);
      }
   }
}
 
class ChangeCaseOutputStream extends FilterOutputStream {
   public static final int LOWERCASE = 1;
   public static final int UPPERCASE = 2;
 
   private int conversionType;
 
   public ChangeCaseOutputStream(int conversionType, OutputStream in) {
      super(in);
 
      this.conversionType = conversionType;
   }
 
   public void write(int b) throws IOException {
      if (conversionType == LOWERCASE) {
         out.write((int) Character.toLowerCase((char) b));
      }
      else if (conversionType == UPPERCASE) {
         out.write((int) Character.toUpperCase((char) b));
      }
   }
}

Converting a String to a Reader

Java provides a StringReader class expressly for this purpose. java.io.StringReader has a constructor that takes a String argument.

import java.io.StringReader;
...
String myString = 'Testing 1 2 3...';
StringReader myStringReader = new StringReader(myString);
 
// Then, use standard Reader-reading techniques
// to access the Reader
int len = -1; // Number of chars read
char [] buf = new char[256]; // Characters read from Reader
try { 
   while ((len = myStringReader.read(buf, 0, 256)) != -1) {
      System.out.println('Next chunk from Reader is ' + (new String(buf, 0, len)));
   }
} catch (IOException ioe) {
   System.err.println("Error reading from Reader :" + e.getMessage());
}

Copying a file in Java

Use FileInputStream and FileOutputStream, these classes treat files as byte streams as opposed to FileReader and FileWriter that treat files as character streams.
To copy a file, open the source file with FileInputStream and call the read() method until end-of-file, occurs when read() return -1. In the meantime, use the write method to write that byte to the newly created file.
You can make this process much more performant by using BufferedInput and BufferedOutput Streams.

import java.io.*;
 
public class copy
{
   public static void main(String []args) {
      if (args.length != 2) {
         System.out.println("Required parameter missing");
         System.exit(1);
      }
 
      try {
         FileInputStream fis = new FileInputStream(args[0]);
         FileOutputStream fos = new FileOutputStream(args[1]);
 
         int b;
         while ((b = fis.read()) != -1) fos.write(b);
 
         fos.close();
         fis.close();
      }
      catch(Exception e) {
         System.out.println(e);
      }
   }
}

Moving the mouse cursor programatically

From JDK1.3, you can use the robot class, very useful for testing purposes.
Following example shows you how to take a desktop screenshot (0,0) –> (200,200)
as well as manipulating the mouse cursor. The cursor will traverse diagonally
from the top left corner to the bottom right.

import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() throws Exception {
      Robot robot = new Robot();
      BufferedImage image = robot.createScreenCapture(new Rectangle(0, 0, 200, 200));
      getContentPane().add(new JLabel(new ImageIcon(image)));
      //setSize(200, 200);
      pack();
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public void animateMouse() throws Exception {
      Robot robot = new Robot();
 
      double w = getSize().getWidth();
      double h = getSize().getHeight();
 
      double x1=0, y1=0;
      double dx = w/h;
      double dy = h/w;
      if (dx > dy) dx = 1; else dy = 1;
      do {
         robot.mouseMove((int) x1, (int) y1);
         x1 += dx;
         y1 += dy;
 
         try { Thread.sleep(10); } catch(InterruptedException e) { }
      } while (x1 < w || y1 < h);
   }
 
   public static void main(String args[]) throws Exception {
      Main main = new Main();
      main.show();
      main.animateMouse();
   }
}

Checking if another instance of the same program is already running

The best way in my opinion is to use ServerSockets. A ServerSocket can only be opened once. So if the application is already running, the creation of the same ServerSocket will fail. This is how you know the app is already running. Sockets are the best approach because the ports get closed by the JVM upon shut down, locking files used for behavior might not work under all circumstances.
Here is a sample:

public class MainApp
{
  private static ServerSocket applLockSocket;
 
  public MainApp()
  {
    // Do something...
 
  } 
 
  private static boolean isApplRunning()
  {
    try	
    {
       // Open a ServerSocket on an app specific port
       applLockSocket = new ServerSocket(2345);  
    } 
    catch (java.net.BindException e)
    {
       //There is already an application running!
       return true;
    }
    catch (IOException e)
    {
      // This was not expected...
    }
    return false;
  } 
 
  public static void main(String[] args)
  {
    try
    {
      if (isApplRunning())
      {
        // Since we only allow this application to be 
        // started once, we need to show the user, that
        // this app is already running...		   
        JOptionPane.showMessageDialog(null
          ,"This app is already running!"
          ,"Info:"
          ,JOptionPane.INFORMATION_MESSAGE);
	System.exit(0);
      } 
 
      // Start the application...
      new MainApp();
    } 
    catch (Exception e)
    {
      JOptionPane.showMessageDialog(null
        ,e.toString()
        ,"Error:"
	,JOptionPane.ERROR_MESSAGE);
    } 
  }
} 

Converting a String to a double

Use the wrapper class for double: Double

Main.java:

public class Main {
   public static void main(String args[]) {
      Double d1 = new Double("23456.78901");
 
      double d2 = d1.doubleValue();
 
      System.out.println(d2);
   }
}

Difference between the >> and >>> operators

a >> b will shift the number a by b bits to the right in an unsigned manner. It will always add a zero to the left side to fill up the spot that frees up.

a >>> b will shift the number a by b bits to the right in a signed manner. It will add a zero to the left side if a is positive, but add a one if a is negative as to keep it negative.

Right shifting by one will divide the number by two.
Check out the output of following example program to get the hang of it:

public class Main {
   public static void main(String []args) {
      unsignedShift(123);
      unsignedShift(-123);
 
      signedShift(123);
      signedShift(-123); 
   }
 
   public static void unsignedShift(int n) {
      System.out.println("Unsigned right shift of " + n);
      System.out.println("  before: " + Integer.toBinaryString(n));
      System.out.println("  after:  " + Integer.toBinaryString(n >>> 1));
   }
 
   public static void signedShift(int n) {
      System.out.println("Signed right shift of " + n);
      System.out.println("  before: " + Integer.toBinaryString(n));
      System.out.println("  after:  " + Integer.toBinaryString(n >> 1));
   }
} 

outputs: (modified for readability reasons)

Unsigned right shift of 123
  before: 00000000 00000000 00000000 01111011
  after:  00000000 00000000 00000000 00111101  <-- added zero to the front
Unsigned right shift of -123
  before: 11111111 11111111 11111111 10000101
  after:  01111111 11111111 11111111 11000010  <-- added zero to the front making
                                                   the number positive!
Signed right shift of 123
  before: 00000000 00000000 00000000 01111011
  after:  00000000 00000000 00000000 00111101  <-- added zero to the front 
                                                   because 123 is positive
Signed right shift of -123
  before: 11111111 11111111 11111111 10000101
  after:  11111111 11111111 11111111 11000010  <-- added one to the front keeping
                                                   the result negative