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 a ZIP file containing multiple compressed files in Java

A ZipOutputStream is able to create an outputstream containing several data streams converted into the ZIP format. The resulting outputstream is either compressed at a certain level (higher level means better compression) or uncompressed. These are the steps to take to create a ZIP stream:

   1) Create a ZipOutputStream, and pass it an outputstream sink 
      (typically a FileOutputStream)
   2) For every distinct data stream (eg. file in directory), create 
      a ZipEntry that contains information about the data stream (eg.
	compression level, optional comment, ...) and write that ZipEntry
	to the ZipOutputStream with the method <i>putNextEntry</i>.
   3) Read the actual data from the source (eg. file) and write it to the
      ZipOutputStream.
   4) Finalize the entry in the ZipOutputStream by calling <i>closeEntry</i>.
   5) Perform step 2, 3 and 4 until there are no more entries (or files) to zip.

Following example zips up all the .java files in the current directory into javafiles.zip.

Main.java:

import java.util.zip.*;
import java.io.*;
  
public class Main
{
   public static void main(String []args) {
      try {
         File dir = new File(".");
         String []filenames = dir.list();
 
         ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("javafiles.zip"));
         byte[] buffer = new byte[1024];
         int length;
 
         for (int i=0; i<filenames.length; i++) {
            if (filenames[i].endsWith(".java")) {
               FileInputStream fis = new FileInputStream(filenames[i]);
 
               ZipEntry ze = new ZipEntry(filenames[i]);
               zos.putNextEntry(ze);
  
               while ((length = fis.read(buffer)) >= 0) {
                  zos.write(buffer, 0, length);
               }
 
               fis.close();
               zos.closeEntry();
 
               System.out.println(filenames[i] + " " + ze.getCompressedSize()
                                  + "/" + ze.getSize()); 
            }
         }
 
         zos.close();    
      }
      catch(IOException e) {
         System.err.println(e);
      }
   }
}

You can change the compression method with setMethod. ZipOutputStream’s default compression method is DEFLATED which uses java.util.zip.Deflater. The only other method that is currently supported is STORED which doesn’t do any compression. When using this method, however, you must initialize the ZipEntry with a CRC-value and a file size of a datastream before you can write it to the ZipOutputStream otherwise it will throw the following exception:

   java.util.zip.ZipException: STORED entry missing size, compressed size, or crc-32

(the method DEFLATED doesn’t have this requirement). That sucks, cause you will have to process the data stream an extra time (to find out the CRC-value and file size).

Examples of JOptionPane?

   JOptionPane.showMessageDialog(frame, "File successfully imported!");

   JOptionPane.showMessageDialog(frame, "Deprecated version", "Warning", 
                                 JOptionPane.WARNING_MESSAGE);

   JOptionPane.showMessageDialog(frame, "Error importing file!", "Error", 
                                 JOptionPane.ERROR_MESSAGE);

   JOptionPane.showMessageDialog(frame, "File successfully imported!", "Message", 
                                 JOptionPane.PLAIN_MESSAGE);

   JOptionPane.showMessageDialog(frame, "File successfully imported?", "Question",
                                 JOptionPane.QUESTION_MESSAGE);

   ImageIcon icon = new ImageIcon("thumbsup.gif");
   JOptionPane.showMessageDialog(frame, "File successfully imported!", "Hey", 
                                 JOptionPane.INFORMATION_MESSAGE, icon);

   int status = JOptionPane.showOptionDialog(frame, "Are you sure you want to import this file?", 
                                             "Question", JOptionPane.YES_NO_CANCEL_OPTION, 
                                             JOptionPane.QUESTION_MESSAGE, null, null, null);
   System.out.println("Option " + status + " selected!");

   Object[] options = { "Ja", "Nee", "Annuleren", "Test" };
   status = JOptionPane.showOptionDialog(frame, "Ben je zeker dat je dit bestand wilt importeren?",
                                         "vraag", -1, JOptionPane.QUESTION_MESSAGE, null,
                                         options, options[2]);
   System.out.println("Option " + status + " selected!");

   options = new Object[] { "Yes, please", "No, thanks" };
   status = JOptionPane.showOptionDialog(frame, "Error importing, try again?", "Question",
                                         -1, JOptionPane.ERROR_MESSAGE, null,
                                         options, options[0]);
   System.out.println("Option " + status + " selected!");

   String value = JOptionPane.showInputDialog("Please enter your name"); 
   System.out.println("You entered: " + value);

   options = new Object[] { "male", "female" };
   value = (String) JOptionPane.showInputDialog(frame, "Select your sex", "Input", 
                                                JOptionPane.QUESTION_MESSAGE, icon, options, 
                                                options[1]); 
   System.out.println("You entered: " + value);

   JDesktopPane desktop = new JDesktopPane(); 
   frame.setContentPane(desktop);
   frame.setSize(new Dimension(400, 200));
   frame.setLocation(100, 100);
   frame.setVisible(true);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
   status = JOptionPane.showInternalOptionDialog(desktop, "Are you sure you want to import this file?", 
                                                 "Question", JOptionPane.YES_NO_CANCEL_OPTION, 
                                                 JOptionPane.QUESTION_MESSAGE, null, null, null);
   System.out.println("Option " + status + " selected!");

The complete working example: Main.java:

import javax.swing.*;
import java.awt.*;
 
public class Main
{
   public static void main(String []args) {
      JFrame frame = new JFrame();
 
      // #1 
      JOptionPane.showMessageDialog(frame, "File successfully imported!");
 
      // #2
      JOptionPane.showMessageDialog(frame, "Deprecated version", "Warning", 
                                    JOptionPane.WARNING_MESSAGE);
 
      // #3
      JOptionPane.showMessageDialog(frame, "Error importing file!", "Error", 
                                    JOptionPane.ERROR_MESSAGE);
      
      // #4
      JOptionPane.showMessageDialog(frame, "File successfully imported!", "Message", 
                                    JOptionPane.PLAIN_MESSAGE);
 
      // #5
      JOptionPane.showMessageDialog(frame, "File successfully imported?", "Question",
                                    JOptionPane.QUESTION_MESSAGE);
 
      // #6
      ImageIcon icon = new ImageIcon("thumbsup.gif");
      JOptionPane.showMessageDialog(frame, "File successfully imported!", "Hey", 
                                    JOptionPane.INFORMATION_MESSAGE, icon);
 
      // #7
      int status = JOptionPane.showOptionDialog(frame, "Are you sure you want to import this file?", 
                                                "Question", JOptionPane.YES_NO_CANCEL_OPTION, 
                                                JOptionPane.QUESTION_MESSAGE, null, null, null);
      System.out.println("Option " + status + " selected!");
 
      // #8
      Object[] options = { "Ja", "Nee", "Annuleren", "Test" };
      status = JOptionPane.showOptionDialog(frame, "Ben je zeker dat je dit bestand wilt importeren?",
                                            "vraag", -1, JOptionPane.QUESTION_MESSAGE, null,
                                            options, options[2]);
      System.out.println("Option " + status + " selected!");
 
      // #9
      options = new Object[] { "Yes, please", "No, thanks" };
      status = JOptionPane.showOptionDialog(frame, "Error importing, try again?", "Question",
                                            -1, JOptionPane.ERROR_MESSAGE, null,
                                            options, options[0]);
      System.out.println("Option " + status + " selected!");
 
      // #10
      String value = JOptionPane.showInputDialog("Please enter your name"); 
      System.out.println("You entered: " + value);
      
      // #11
      options = new Object[] { "male", "female" };
      value = (String) JOptionPane.showInputDialog(frame, "Select your sex", "Input", 
                                                   JOptionPane.QUESTION_MESSAGE, icon, options, 
                                                   options[1]); 
      System.out.println("You entered: " + value);
 
      // #12
      JDesktopPane desktop = new JDesktopPane(); 
      frame.setContentPane(desktop);
      frame.setSize(new Dimension(400, 200));
      frame.setLocation(100, 100);
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
      status = JOptionPane.showInternalOptionDialog(desktop, "Are you sure you want to import this file?", 
                                                    "Question", JOptionPane.YES_NO_CANCEL_OPTION, 
                                                    JOptionPane.QUESTION_MESSAGE, null, null, null);
      System.out.println("Option " + status + " selected!");
 
      System.exit(1);
   }
}

Setting the decoration style of a JFrame

(JDK1.4+!)

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
class Main extends JFrame {
    public Main() {
        setUndecorated(true);
        getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Decoration example");
        setSize(400, 400);
        Object[] options = { "COLOR_CHOOSER_DIALOG",
                             "ERROR_DIALOG",
                             "FILE_CHOOSER_DIALOG", 
                             "FRAME",
                             "INFORMATION_DIALOG",
                             "NONE",
                             "PLAIN_DIALOG", 
                             "QUESTION_DIALOG",
                             "WARNING_DIALOG" };
        final JComboBox combobox = new JComboBox(options);
        combobox.setSelectedItem("FRAME");
        getContentPane().setLayout(new FlowLayout());
        getContentPane().add(combobox);
 
        combobox.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent ae) {
              String selected = (String) combobox.getSelectedItem();
              if (selected.equals("COLOR_CHOOSER_DIALOG"))
                 setDecorationStyle(JRootPane.COLOR_CHOOSER_DIALOG);
              else if (selected.equals("ERROR_DIALOG"))
                 setDecorationStyle(JRootPane.ERROR_DIALOG);
              else if (selected.equals("FILE_CHOOSER_DIALOG"))
                 setDecorationStyle(JRootPane.FILE_CHOOSER_DIALOG);
              else if (selected.equals("FRAME"))
                 setDecorationStyle(JRootPane.FRAME);
              else if (selected.equals("INFORMATION_DIALOG"))
                 setDecorationStyle(JRootPane.INFORMATION_DIALOG);
              else if (selected.equals("NONE"))
                 setDecorationStyle(JRootPane.NONE);
              else if (selected.equals("PLAIN_DIALOG"))
                 setDecorationStyle(JRootPane.PLAIN_DIALOG);
              else if (selected.equals("QUESTION_DIALOG"))
                 setDecorationStyle(JRootPane.QUESTION_DIALOG);
              else if (selected.equals("WARNING_DIALOG"))
                 setDecorationStyle(JRootPane.WARNING_DIALOG);
           }
        });
    }
 
    public void setDecorationStyle(int decorationStyle) {
       setVisible(false);
       getRootPane().setWindowDecorationStyle(decorationStyle);
       setVisible(true);
    }
 
    public static void main(String[] args) {
        new Main().setVisible(true);
    }
}

Find out what JTabbedPane tab is selected

Note:
1.Each Tab in a Tabbed Pane is a JPanel i.e it has a name
2.The first Tab index is ’0′, 2′nd tab ’1′ and so on.
3.’StateChanged’ event is fired on selection of a tab.

....
....
....
tabbedPane.addChangeListener(changeListener)
....
....
public void stateChanged(changeEvent)
{
   if(e.getSource() == tabbedPane)
   {
      int i = tabbedPane.getSelectedIndex();
      Component c = tabbedPane.getSelectedComponent();
   }
}
....
....

Changing the margins of a JToolBar

Set an empty border on your JToolBar object.

Main.java:

import javax.swing.border.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
  
public class Main extends JFrame {
   public Main() {
      super("JToolBar example");
 
      final JTextArea textArea = new JTextArea(5, 30);
      JToolBar toolBar = new JToolBar();
 
      JButton gifButton = new JButton(new ImageIcon("gifIcon.gif"));
      JButton jpgButton = new JButton(new ImageIcon("jpgIcon.gif"));
      JButton tiffButton = new JButton(new ImageIcon("tiffIcon.gif"));
 
      gifButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("gifButton clicked!n");
         }
      });
 
      jpgButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("jpgButton clicked!n");
         }
      });
        
      tiffButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("tiffButton clicked!n");
         }
      });
 
      toolBar.add(gifButton);
      toolBar.add(jpgButton);
      toolBar.add(tiffButton);
 
      toolBar.setBorder(new EmptyBorder(new Insets(10,10,10,10)));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.NORTH, toolBar);
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(textArea));
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}

images used:


Setting the top-left icon of a JInternalFrame

Use setFrameIcon():

JInternalFrame frame = new JInternalFrame("Test",false,false,false,false);

try {
  URL url = new URL("http://localhost/images/icon.gif");
  ImageIcon icon = new ImageIcon(url);
  frame.setFrameIcon(icon);
} catch (MalformedURLException me) {}

...

Creating a JCheckBoxGroup


JCheckBoxGroup.java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
public class JCheckBoxGroup extends JFrame{
   private ButtonGroup checkBoxGroup;
   private JCheckBox check1, check2, check3;
   private JPanel panel;
 
   public JCheckBoxGroup() {
      super("JCheckBoxGroup Example");
      panel = new JPanel(new GridLayout(3,0));
      check1 = new JCheckBox("1", true);
      check2 = new JCheckBox("2", false);
      check3 = new JCheckBox("3", false);
      checkBoxGroup = new ButtonGroup();
 
      //add CheckBoxes to ButtonGroup
      checkBoxGroup.add(check1);
      checkBoxGroup.add(check2);
      checkBoxGroup.add(check3);
  		
      panel.add(check1);
      panel.add(check2);
      panel.add(check3);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            dispose();
            System.exit(0);
         }
      });
   
      setContentPane(panel);
      setSize(250,150);
      setVisible(true);
   }
 
   public static void main(String args[]) {
      JCheckBoxGroup j = new JCheckBoxGroup();
   }
}

Putting a JButton inside a JComboBox

Here’s an example:

import javax.swing.plaf.basic.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
    
public class Main extends JFrame
{ 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
      
      final JButton buttonOk = new JButton("OK");
      buttonOk.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println(ae.getActionCommand() + " clicked!");
         }
      });
      final JButton buttonCancel = new JButton("Cancel");
      buttonCancel.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println(ae.getActionCommand() + " clicked!");
         }
      });
 
      final JComboBox combobox = 
         new JComboBox(new Object[] {
               "Item 1",
               "Item 2",
               "Item 3",
               buttonOk,
               "Item 4",
               "Item 5",
               buttonCancel
            }
         );
 
      getContentPane().add(combobox);
      combobox.setRenderer(new ButtonComboBoxRenderer());
      combobox.addActionListener(new ButtonComboBoxListener(this, combobox));
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });      
   
      setSize(new Dimension(200, 200));
   } 
 
   public static void main(String[] args) throws Exception {
      Main main = new Main();
      main.setVisible(true);
   }
}
 
class ButtonComboBoxRenderer extends BasicComboBoxRenderer implements ListCellRenderer
{
   public ButtonComboBoxRenderer() {
      super();
   }
   
   public Component getListCellRendererComponent( JList list, 
           Object value, int index, boolean isSelected, boolean cellHasFocus) {
      if (isSelected) {
          setBackground(list.getSelectionBackground());
          setForeground(list.getSelectionForeground());
      }
      else {
          setBackground(list.getBackground());
          setForeground(list.getForeground());
      }
 
      setFont(list.getFont());
      if (value instanceof Icon) {
         setIcon((Icon)value);
      }
      if (value instanceof JButton) {
         return (Component) value;
      }
      else {
         setText((value == null) ? "" : value.toString());
      }
 
      return this;
  }  
}
 
class ButtonComboBoxListener implements ActionListener {
   JComboBox combobox;
   JFrame frame;
 
   ButtonComboBoxListener(JFrame frame, JComboBox combobox) {
      this.frame = frame;
      this.combobox = combobox;
      combobox.setSelectedIndex(0);
   }
     
   public void actionPerformed(ActionEvent e) {
      Object selectedItem = combobox.getSelectedItem();
      if (selectedItem instanceof JButton) {
         ((JButton) selectedItem).doClick();
      }
   }
}