Tuesday, March 26, 2013

Hibernate and Oracle sequence

 For  Hibernate beginners using orcale db doing some examples then they will be confused over mapping file with auto increment . So for my experience I gave sample code as below to avoid 

1. Use Sequence increment in mapping File :

Create Tabele :

CREATE TABLE EMPLOYEE (
  ID          NUMBER        NOT NULL,
  FIRST_NAME  VARCHAR2 (20),
  LAST_NAME   VARCHAR2 (20),
  SALARY      NUMBER        DEFAULT null,
  CONSTRAINT EMPLOYEE_PK
  PRIMARY KEY ( ID ) ) ;

create sequence EMPLOYEE_ID_SEQ; 
 
In Mapping File :

Employee.hbm.xml


           


2. Mapping with Database trigger on sequence


Create table as like above

For trigger :

create sequence EMPLOYEE_ID_SEQ;

CREATE OR REPLACE TRIGGER EMPLOYEE_insert
before insert on EMPLOYEE
for each row
begin
    select EMPLOYEE_ID_SEQ.nextval into :new.id from dual;
end;
/

In Mapping File :

Employee.hbm.xml

Monday, March 25, 2013

Difference between EnumMap and HashMap in Java

 
S No
EnumMap
HashMap
1
EnumMap is optimized for enum keys
HashMap is a general purpose Map implementation similar to Hashtable



2
you can not use any type other than Enum as key in EnumMap




you can use both Enum and any other Object as key in HashMap




3
Due to specialized optimization done for Enum keys, EnumMap is likely to perform better than HashMap when using enum as key object



-
4
Since Enum is internally maintain as array and they are stored in there natural order using ordinal(), as shown in following code which is taken from put() method of EnumMap

    int index = ((Enum)key).ordinal();
    Object oldValue = vals[index];
    vals[index] = maskNull(value);



-

These were some notable difference between EnumMap and HashMap in Java. In short EnumMap is best suited for enum keys, for which it has optimized and perform better than HashMap in Java. Use EnumMap whenever you can use enum as keys.

Thursday, March 21, 2013

Introduction about Hibernate


Hibernate is an Object/Relational Mapping solution for Java Environments.
It takes care of the mapping from Java calsses to database tables and provides
data query and retrival facility.

Why choose Hibernate over the others?


Popular Open Source Persistence Frameworks in Java

1. Hibernate – http://www.hibernate.org/
2. EJB3 – http://java.sun.com/products/ejb/index.jsp
3. Oracle Top Links – http://www.oracle.com/technology/products/ias/toplink/index.html
4. Cayenne – http://cayenne.apache.org/
5. Open JPA – http://openjpa.apache.org/
6. IBATIS- http://ibatis.apache.org/javadownloads.cgi
7. JPOX – http://www.jpox.org/

Reason of choosing Hibernate
1. Productivity, Maintainability, Portability
Hibernate provides all above O/R benefits. (Productivity, Maintainability, Portability).
2. Free – Cost Effective
Hibernate is free and open source – Cost Effective
3. Learning curve is short
Since we all have working experience in using Hibernate, and Hibernate is totally object orientated concept, it will shorted our learning curve.
4. Code generation tool
Hibernate tools provided by community helps developer generate or develop hibernate application very fast and easy. (Eclipse’s Plugin & Code generation tools)
5. Popular
Hibernate is popular, when we goes wrong with Hibernate, we can easily find the answer from Google. In addition, there are many books, communities and forums on Hibernate.
6) Market demand it
Java Market need Hibernate developer, demand of Hibernate developer is in decent growth and compare to the other tools. Hibernate working experience definitely add advantages for my next jump.

Why hibernate is used?

Hibernate makes the application development process easy
   1. Hibernate saves the development time
   2. Hibernate allows to map the Java objects to the relational database
   3. Hibernate provides HQL for performing selective search
   4. Hibernate also supports SQL Queries (Native Query)
   5. Hibernate provides primary and secondary level caching support
   6. Can be used in both console and web based applications
   7. Developers can use the components from the Hibernate framework selectively.
   8. Hibernate can be used with JPA
   9. It supports both xml file and annotations as metadata
  
Finally why we are using hibernate means
    To make the application developemnt more productive. its saves development time and also mainly it deals with Objects(POJO)
and .xml file is nothing but mapping between database column and POJO variable.
you can easily switch the database like MySql to Oracle you need not to change any of your code...
just you can change a simple dylect in cfg file of hibernate to oracle it works with no error.
Addition to that we have visual paradigm tool which helps to create the object model.














Wednesday, March 20, 2013

Using Java , How to escape a string from regular expression?

import org.apache.commons.lang.StringEscapeUtils;
 
public class testEscapeHTML{
 
 public static void main(String args[]){
 
  String testStr = "< > \" &";
 
  System.out.println("Original : " + testStr);
 
  System.out.println("Escaped : " + StringEscapeUtils.escapeHtml(testStr));
 
 } 
}


 or




This asks the regular expression parser to ignore any special characters in the string.
This is also very simple as the first method.
All you have to do is to put “\Q” in front of the string and “\E” at the end of the string.

Example : " Some Special characters (!@#$%^&*()?":;)" =>
"\Q Some Special characters (!@#$%^&*()?":;)\E"

This is however already available as a function in java

String escapedString=java.util.regex.Pattern.quote(myStringToEscape)

You can use this method to make parts of a string escape as a regular expression.


Wednesday, March 6, 2013

Java Program : Open Excel File

 Below Program is used to open Excel File :
import java.awt.Desktop;
import java.io.*;

public class OpenExcel {

    /**
     * @param args
     */
    public static void main(String[] args) {
        if (Desktop.isDesktopSupported()) {
            try {
                Desktop.getDesktop().open(new File("File.xls"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + new File("File.xls"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Monday, March 4, 2013

Dynamically Adding Panel Based on Tree items in JTabbedPane

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jtabbedpanedemo;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;

/**
 *
 * @author R.Amirtharaj
 */
public class MainFrame {

    private JTabbedPane tabbedPane;
    private static final Icon CLOSE_TAB_ICON = new ImageIcon("Image location");
    // Key as Panel Name and Value as Panel index
    static final HashMap hmPanel = new HashMap();
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTree jTree1;

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                createAndShowGUI();
            }
        });
    }

    /**
     * Create Tree . Panel1 an Panel2 under Root
     */
    public void createTreeComponents() {
        DefaultMutableTreeNode top = new DefaultMutableTreeNode("Root");
        DefaultMutableTreeNode tp1 = new DefaultMutableTreeNode("Panel1");
        DefaultMutableTreeNode tp2 = new DefaultMutableTreeNode("Panel2");
        top.add(tp1);
        top.add(tp2);

        // Create a new tree control
        DefaultTreeModel treeModel = new DefaultTreeModel(top);
        jTree1.setModel(treeModel);


        jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        jTree1.addTreeSelectionListener(new TSL());
    }

    // Tree Selection Listioner
    public class TSL implements TreeSelectionListener {

        public void valueChanged(TreeSelectionEvent e) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();

            if (node == null) //Nothing is selected.
            {
                return;
            }

            Object nodeInfo = node.getUserObject();
            if (node.isLeaf()) {
                if (node.toString().equals("Panel1")) {
                    if (!hmPanel.containsKey("Panel1")) {
                        int index = hmPanel.size();
                        hmPanel.put("Panel1", index);
                        JPanel pan = new JPanel();
                        pan.add(new JLabel("Panel1"));
                        pan.setToolTipText("Panel1");
                        addClosableTab(tabbedPane, pan, "Panel1", null);
                    } else {
                        //System.out.println(hmPanel.get("Panel1"));
                        tabbedPane.setSelectedIndex(hmPanel.get("Panel1"));
                    }

                } else if (node.toString().equals("Panel2")) {
                    if (!hmPanel.containsKey("Panel2")) {
                        int index = hmPanel.size();
                        hmPanel.put("Panel2", index);
                        JPanel pan = new JPanel();
                        pan.add(new JLabel("Panel2"));
                        pan.setToolTipText("Panel2");
                        addClosableTab(tabbedPane, pan, "Panel2", null);
                    } else {
                        //System.out.println(hmPanel.get("Panel2"));
                        tabbedPane.setSelectedIndex(hmPanel.get("Panel2"));
                    }
                }

            } else {
            }
        }
    }

    private static void createAndShowGUI() {
        //Create and set up the frame.
        //The string passed as an argument will be displayed
        //as the title.

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JTabbedPane Demo [=]");

        //Create and set up the content pane.
        MainFrame demo = new MainFrame();
        demo.addContentPane(frame.getContentPane());

        // The other bits and pieces that make our program a bit more stable.
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setVisible(true);
    }

    public void addContentPane(Container container) {
        tabbedPane = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        createTreeComponents();

        container.add(tabbedPane, java.awt.BorderLayout.CENTER);

        jScrollPane1.setViewportView(jTree1);
        container.add(jScrollPane1, java.awt.BorderLayout.WEST);
    }

    /**
     * Adds a component to a JTabbedPane with a little "close tab" button on the
     * right side of the tab.
     * @param tabbedPane the JTabbedPane
     * @param c any JPanel
     * @param title the title for the tab
     * @param icon the icon for the tab, if desired
     */
    public static void addClosableTab(final JTabbedPane tabbedPane, final JPanel c, final String title,
            final Icon icon) {
        // Add the tab to the pane without any label
        tabbedPane.addTab(null, c);
        int pos = tabbedPane.indexOfComponent(c);

        // Create a FlowLayout that will space things 5px apart
        FlowLayout f = new FlowLayout(FlowLayout.CENTER, 5, 0);

        // Make a small JPanel with the layout and make it non-opaque
        JPanel pnlTab = new JPanel(f);
        pnlTab.setOpaque(false);

        // Add a JLabel with title and the left-side tab icon
        JLabel lblTitle = new JLabel(title);
        lblTitle.setIcon(icon);

        // Create a JButton for the close tab button
        JButton btnClose = new JButton();
        btnClose.setOpaque(false);

        // Configure icon and rollover icon for button
        btnClose.setIcon(new ImageIcon("D:\\def.png"));

        // Set border null so the button doesn't make the tab too big
        btnClose.setBorder(null);

        // Make sure the button can't get focus, otherwise it looks funny
        btnClose.setFocusable(false);

        // Put the panel together
        pnlTab.add(lblTitle);
        pnlTab.add(btnClose);

        // Add a thin border to keep the image below the top edge of the tab
        // when the tab is selected
        pnlTab.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));

        // Now assign the component for the tab
        tabbedPane.setTabComponentAt(pos, pnlTab);

        // Add the listener that removes the tab
        ActionListener listener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // The component parameter must be declared "final" so that it can be
                // referenced in the anonymous listener class like this.

                hmPanel.remove(c.getToolTipText());
                tabbedPane.remove(c);
            }
        };
        btnClose.addActionListener(listener);

        // Optionally bring the new tab to the front
        tabbedPane.setSelectedComponent(c);

        //-------------------------------------------------------------
        // Bonus: Adding a keystroke binding to close the tab
        //-------------------------------------------------------------
        AbstractAction closeTabAction = new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                tabbedPane.remove(c);
            }
        };

        // Create a keystroke
        KeyStroke controlW = KeyStroke.getKeyStroke("control W");

        // Get the appropriate input map using the JComponent constants.
        // This one works well when the component is a container.
        InputMap inputMap = c.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

        // Add the key binding for the keystroke to the action name
        inputMap.put(controlW, "closeTab");

        // Now add a single binding for the action name to the anonymous action
        c.getActionMap().put("closeTab", closeTabAction);
    }
}

Dynamically Adding Panel to JTabbedpane

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jtabbedpanedemo;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

/**
 *
 * @author R.Amirtharaj
 */
public class MainFrame {

    private JTabbedPane tabbedPane;
    private javax.swing.JPanel buttonPanel;
    private javax.swing.JButton createTabButton;
    private static final Icon CLOSE_TAB_ICON = new ImageIcon("Image Location");
    private int tabCount = 0;

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        //Create and set up the frame.
        //The string passed as an argument will be displayed
        //as the title.

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JTabbedPane Demo [=]");

        //Create and set up the content pane.
        MainFrame demo = new MainFrame();
        demo.addContainer(frame.getContentPane());

        // The other bits and pieces that make our program a bit more stable.
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setVisible(true);
    }

    public void addContainer(Container container) {
        tabbedPane = new javax.swing.JTabbedPane();
        buttonPanel = new javax.swing.JPanel();

        container.add(tabbedPane, java.awt.BorderLayout.CENTER);

        createTabButton = new javax.swing.JButton();

        createTabButton.setText("Add New Tab");
        createTabButton.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createTabButtonActionPerformed(evt);
            }
        });
        buttonPanel.add(createTabButton);

        container.add(buttonPanel, java.awt.BorderLayout.SOUTH);


    }

    private void createTabButtonActionPerformed(java.awt.event.ActionEvent evt) {
        tabCount++;
        JScrollPane scrollPane = new JScrollPane(new JTextArea("New tab number " + tabCount));
        addClosableTab(tabbedPane, scrollPane, "Tab " + tabCount);
    }

    /**
     * Adds a component to a JTabbedPane with a little "close tab" button on the
     * right side of the tab.
     * @param tabbedPane the JTabbedPane
     * @param c any JComponent
     * @param title the title for the tab
     */
    public static void addClosableTab(final JTabbedPane tabbedPane, final JComponent c, final String title
            ) {
        // Add the tab to the pane without any label
        tabbedPane.addTab(null, c);
        int pos = tabbedPane.indexOfComponent(c);

        // Create a FlowLayout that will space things 5px apart
        FlowLayout f = new FlowLayout(FlowLayout.CENTER, 5, 0);

        // Make a small JPanel with the layout and make it non-opaque
        JPanel pnlTab = new JPanel(f);
        pnlTab.setOpaque(false);

        // Add a JLabel with title and the left-side tab icon
        JLabel lblTitle = new JLabel(title);

        // Create a JButton for the close tab button
        JButton btnClose = new JButton();
        btnClose.setOpaque(false);

        // Configure icon and rollover icon for button
        btnClose.setIcon(CLOSE_TAB_ICON);

        // Set border null so the button doesn't make the tab too big
        btnClose.setBorder(null);

        // Make sure the button can't get focus, otherwise it looks funny
        btnClose.setFocusable(false);

        // Put the panel together
        pnlTab.add(lblTitle);
        pnlTab.add(btnClose);

        // Add a thin border to keep the image below the top edge of the tab
        // when the tab is selected
        pnlTab.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));

        // Now assign the component for the tab
        tabbedPane.setTabComponentAt(pos, pnlTab);

        // Add the listener that removes the tab
        ActionListener listener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // The component parameter must be declared "final" so that it can be
                // referenced in the anonymous listener class like this.
                tabbedPane.remove(c);
            }
        };
        btnClose.addActionListener(listener);

        // Optionally bring the new tab to the front
        tabbedPane.setSelectedComponent(c);

        //-------------------------------------------------------------
        // Bonus: Adding a keystroke binding to close the tab
        //-------------------------------------------------------------
        AbstractAction closeTabAction = new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                tabbedPane.remove(c);
            }
        };

        // Create a keystroke
        KeyStroke controlW = KeyStroke.getKeyStroke("control W");

        // Get the appropriate input map using the JComponent constants.
        // This one works well when the component is a container.
        InputMap inputMap = c.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

        // Add the key binding for the keystroke to the action name
        inputMap.put(controlW, "closeTab");

        // Now add a single binding for the action name to the anonymous action
        c.getActionMap().put("closeTab", closeTabAction);
    }
}