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

Saving a property list to disk

Use the store method. Check out the following example that stores the system properties to a specified file.

Main.java:

import java.util.*;
import java.io.*;
 
public class Main {   
   public static void main(String[] args) throws Exception {
      if (args.length != 1) {
         System.out.println("Usage: java Main <filename>");
         System.exit(1);
      }
 
      BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(args[0]));
      Properties p = System.getProperties();
      p.store(bos, "Our stored System properties");     
   }
}

stores in a specified file:

#Our stored System properties
#Wed Jun 27 17:21:15 CEST 2001
java.specification.name=Java Platform API Specification
awt.toolkit=sun.awt.windows.WToolkit
java.version=1.2.2
java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironment
user.timezone=Europe/Paris
java.specification.version=1.2
java.vm.vendor=Sun Microsystems Inc.
java.vm.specification.version=1.0
user.home=C:\WINDOWS
os.arch=x86
java.awt.fonts=
java.vendor.url=http://java.sun.com/
file.encoding.pkg=sun.io
user.region=US
java.home=C:\JDK1.2.2\JRE
java.class.path=c:\jdk1.2.2\jre\lib\rt.jar;C:\PRO
GRA~1\JMF2.1\LIB\SOUND.JAR;C:\PROGRA~1\JMF2.1\LIB\
JMF.JAR;c:\jakarta-log4j-1.0.4\log4j-core.jar;
line.separator=rn
java.ext.dirs=C:\JDK1.2.2\JRE\lib\ext
java.io.tmpdir=c:\windows\TEMP\
os.name=Windows 95
java.vendor=Sun Microsystems Inc.
java.awt.printerjob=sun.awt.windows.WPrinterJob
java.library.path=C:\JDK1.2.2\BIN;.;C:\WINDOWS\SYSTEM;C:\WINDOWS;C:\JIKES\BIN
;C:\ANT\BIN\;C:\JDK1.2.2\BIN;C:\WINDOWS;C:\WIN
DOWS;C:\WINDOWS\COMMAND;;C:\WN16\BIN;C:\PROGRA~1
NETWOR~1\PGP;C:\VIM\VIM55
java.vm.specification.vendor=Sun Microsystems Inc.
sun.io.unicode.encoding=UnicodeLittle
file.encoding=Cp1252
java.specification.vendor=Sun Microsystems Inc.
user.name=esus
user.language=en
java.vendor.url.bug=http://java.sun.com/cgi-bin/bugreport.cgi
java.vm.name=Classic VM
java.vm.specification.name=Java Virtual Machine Specification
java.class.version=46.0
sun.boot.library.path=C:\JDK1.2.2\JRE\bin
os.version=4.10
java.vm.info=build JDK-1.2.2_005, native threads, symcjit
java.vm.version=1.2.2
java.compiler=symcjit
path.separator=;
user.dir=C:\
file.separator=\
sun.boot.class.path=C:\JDK1.2.2\JRE\lib\rt.jar;C:\
JDK1.2.2\JRE\lib\i18n.jar;C:\JDK1.2.2\JRE\classes

Scheduling a task at a specific time of day, every day in Java

This example will run the thread PrintTask every day at 04h28m30s (just because I wrote this example at that time :).

Main.java:

import java.util.*;
  
public class Scheduler
{
   public static void main(String []args) {
      Timer timer = new Timer();
 
      Calendar calendar = Calendar.getInstance();
      calendar.set(Calendar.HOUR_OF_DAY, 4);
      calendar.set(Calendar.MINUTE, 28);
      calendar.set(Calendar.SECOND, 30);
      Date time = calendar.getTime();
 
      timer.schedule(new PrintTask(),
                     time);     
   }
 
   static class PrintTask extends TimerTask {
      public void run() {
         System.out.println("Task executed");
      }
   }
} 

Rendering HTML documents in Java

JEditorPane is able to display and edit different kinds of content. By default,
text/plain, text/html and text/rtf are recognized and passed on to the
EditorKit that is designed to handle it: DefaultEditorKit, HTMLEditorKit and
RTFEditorKit
. In the following example, a URL can be given in a JTextField.
Clicking GO will invoke the setPage method on the JEditorPane that will load
the page into a default document and set the content type. Using the
mime type of the page, the pane will automatically detect the correct EditorPane to
use.
Try: http://www.yahoo.com and http://www.esus.com/richtext.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.yahoo.com");
      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);
   }
}

Iconifying or deiconinfying a JFrame

Use setState(Frame.ICONIFIED) and setState(Frame.NORMAL).

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame implements ActionListener
{
   public Main()
   {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      JButton iconButton = new JButton("Iconify this Frame");
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      getContentPane().add(iconButton);
      iconButton.addActionListener(this);
   }
 
   public void actionPerformed(ActionEvent ae) {     
      this.setState(Frame.ICONIFIED);  
   }
 
   public static void main(String args[])
   {
      Main main = new Main();
      main.setSize(300, 150);
      main.setVisible(true);
   }
}

Scrolling a JScrollPane to the top programmatically

Call the method scrollRectToVisible of the component that is added to the JScrollPane container as shown in following example:

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() throws Exception {
      getContentPane().setLayout(new BorderLayout());
 
      final JPanel panel = createPanel(); 
      final JScrollPane scrollpane = new JScrollPane(panel);
 
      JButton button = new JButton("Scroll to top!");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            panel.scrollRectToVisible(
              new Rectangle(0, 0, 1, 1));
         }
      });
 
      getContentPane().add(BorderLayout.NORTH, button);
      getContentPane().add(BorderLayout.CENTER, scrollpane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static JPanel createPanel() throws Exception {
      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(50, 20, 10, 10));
 
      for (int i=0; i<50; i++) {
         for (int j=0; j<20; j++) {
            JLabel label = new JLabel("label " + i + ", " + j);
            panel.add(label);    
         }
      }
 
      return panel;
   }
 
   public static void main(String [] args) throws Exception  {
      Main main = new Main();
      main.setSize(600, 600);
      main.setVisible(true);
   } 
} 

Make the tab-text of a JTabbedPane appear bold

You can HTML tags when naming your tabs, as shown in following example.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame implements ActionListener {
   JTabbedPane tabbedPane;
   int ntabs = 0;
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      tabbedPane = new JTabbedPane();
      createTab();
 
      getContentPane().add(BorderLayout.CENTER, tabbedPane);
      setJMenuBar(createMenuBar());
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   
      setTitle("JTabbedPane Bold Demonstration");
      setSize(new Dimension(400, 400));
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
 
      JMenu menu1 = new JMenu("JTabbedPane");
      JMenuItem menuItem1 = new JMenuItem("Create new tab");
      menuItem1.addActionListener(this);
      menu1.add(menuItem1);
      menuBar.add(menu1);
 
      return menuBar;
   }
  
   public void actionPerformed(ActionEvent e) {
      if (e.getActionCommand().equals("Create new tab")) {
         createTab();
      }
   }
 
   protected void createTab() {
      ntabs++;
      if (ntabs % 2 == 0) {
         tabbedPane.addTab("<html><i>Tab #" + ntabs + "</i></html>", 
                             new JLabel("Tab #" + ntabs));
      }
      else {
         tabbedPane.addTab("<html><b>Tab #" + ntabs + "</b></html>", 
                             new JLabel("Tab #" + ntabs));
      }
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Adding a background image to a JToolBar

Override the JToolBar’s method paintComponent, draw the image using g.drawImage and call the superclass’ paintComponent. This is similar to the JPanel implementation.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
 
   public static void main(String []args) {
      Main main = new Main();
      main.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent ev) {
            System.exit(0);
         }
      });
 
      main.pack();
      main.show(); 
   }
 
   private ImageIcon ii = new ImageIcon("mong.jpg");
 
   public Main() {
      super("ToolBar Background Image");
 
      getContentPane().setLayout(new BorderLayout());
 
      //
      // could also use an anonymous class...e.g.,
      // JToolBar toolbar = new JToolBar() {
      //     public void paintComponent(Graphics g) {
      //         ... see Class below...
      //     }
      // };
      //
      JToolBar toolbar = new ToolBarWithBgImage("My Toolbar", JToolBar.HORIZONTAL, ii);
      getContentPane().add(toolbar, BorderLayout.NORTH);
 
      toolbar.add(new JButton("Item 1"));
      toolbar.add(new JButton("Item 2"));
      toolbar.addSeparator();
      toolbar.add(new JButton("Item 3"));  
   }
 
   /**
    * This implementation stretches the image to fit the panel.
    * Could modify this to "tile" the image, center the image, etc.
    */
   class ToolBarWithBgImage extends JToolBar {
 
      private ImageIcon bgImage;
 
      ToolBarWithBgImage(String name, int orientation, ImageIcon ii) {
         super(name, orientation);
         this.bgImage = ii;
         setOpaque(true);
      }
 
      public void paintComponent(Graphics g) {
         super.paintComponent(g);
         if (bgImage != null) {
            Dimension size = this.getSize();
            g.drawImage(bgImage.getImage(), 0,0, size.width, size.height, this);
         }
      }
   }
}

Capturing an event when a JInternalFrame is selected

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.util.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame {
   JDesktopPane desktop;
   int nframes = 0;
  
   public Main() {
      desktop = new JDesktopPane(); 
      setContentPane(desktop);
      setJMenuBar(createMenuBar());
      createInternalFrame(); 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
 
      JMenu createMenu = new JMenu("Create");
      createMenu.setMnemonic(KeyEvent.VK_C);
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            createInternalFrame();
         }
      }); 
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      createMenu.add(newMenuItem);
      menuBar.add(createMenu);
 
      return menuBar;
   }
 
   protected void createInternalFrame() {
      nframes++;
      String title = "JInternalFrame #" + nframes;
      MyJInternalFrame frame = new MyJInternalFrame(title,
         true,    // resizable
         true,    // closable
         true,    // maximizable
         true);   // iconifiable
      frame.setVisible(true); 
 
      desktop.add(frame);
      frame.setSize(200, 200);
      frame.setLocation(30*nframes, 30*nframes);
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(500, 300);
      main.setVisible(true);
   }
} 
 
class MyJInternalFrame extends JInternalFrame 
                       implements VetoableChangeListener { 
   public MyJInternalFrame(String title, boolean resizable, 
                           boolean closable, boolean maximizable, 
                           boolean iconifiable) { 
      super(title, resizable, closable, maximizable, iconifiable); 
      addVetoableChangeListener(this); 
   } 
 
   public void vetoableChange(PropertyChangeEvent pce) 
                                 throws PropertyVetoException { 
      if (pce.getPropertyName().equals(IS_SELECTED_PROPERTY)) { 
         boolean selected = ((Boolean) pce.getNewValue()).booleanValue(); 
         if (selected) { 
            System.out.println(getTitle() + " is selected!");
         } 
      } 
   }
}