Wednesday, July 10, 2013

Solution for server port is already in use

For developer while running server based application will get error like as

Starting of Tomcat failed, the server port 8080 is already in use.

This problem may occur in following reasons :

1. if another application used same port(then we need to select different port)

2. we already stopped application but port is still in used ,
then we need to stop port use and make it available for running application

goto command prompt

netstat -aon

it will show you something like

 TCP    192.1.200.48:8080     24.43.246.60:443       ESTABLISHED     248
 TCP    192.1.200.48:8080      24.43.246.60:443       ESTABLISHED     248
 TCP    192.1.200.48:2126      213.146.189.201:12350  ESTABLISHED     1308
 TCP    192.1.200.48:3918      192.1.200.2:8073       ESTABLISHED     1504
 TCP    192.1.200.48:3975      192.1.200.11:49892     TIME_WAIT       0
 TCP    192.1.200.48:3976      192.1.200.11:49892     TIME_WAIT       0
 TCP    192.1.200.48:4039      209.85.153.100:80      ESTABLISHED     248
 TCP    192.1.200.48:8080      209.85.153.100:80      ESTABLISHED     248

check which process has binded your port. here in above example its 248 now if you are sure that you need to kill that process fire

Linux:

kill -9 248

Windows:

taskkill /f /pid 248

it will kill that process

Friday, May 17, 2013

A Small Intro for Software Testing

What is software testing ?
  •  It is the process of evolution a software item to detect difference between given input and expected output , also to assess the feature of a software system.
  •  Testing assesses the quality of the product.
  •  It should be done in development phase.
  • It is a verification and validation process.

Verification :  
  • It is the process to make sure the product satisfies the conditions imposed at start of the development phase.
  • To make sure the product behaves the way we want.
Validation :  
  • It is the process to make sure the product satisfies the specified requirements at end of the development phase.
  • To make sure the product is built as per customer requirement.

There are two basics of software testing

1. Blackbox Testing :
  •    It is a testing technique that ignores internal mechanism of the system and focusses on the output generated against any input and execution of the system.
  •    It is often used for Validation.
  
2. Whitebox Testing  :
  •    It is a testing technique that takes into account the internal mechanism of the system.
  •    It is often used for Verification.
  
Types:

There are many types of testing like as below

Unit Testing :
  •   It is the testing of an individual unit or group of related units.
  •   It is done by programmer to test that the unit he has implemented is producing expected output against input.
  •   It falls under class of whitebox testing.

Integration Testing:
  •   It is testing in which the group of components are combined  to produce the output.
  •   It is also interaction between hardware and software is tested if hardware and software components have any relation.
  •   It may fall both blockbox and whitebox testing.

Functional Testing:
  •   It is the testing to ensure that the specified fuctionalities required in the system requirements works.
  •   It falls under class of Blackbox testing.

System Testing:
  •   It is the testing to ensure that by putting the software in different environments (diff OS) it still works.
  •   It is done with full system implementation and environments.
  •   It falls under class of Blackbox testing.

Performance Testing:
  •   It is the testing to assess the speed and effectiveness of the system and to make sure it's generating results in
  • specified time as an in performance requirements.
  •   It falls under class of Blackbox testing.

Usability Testing:
  •   It is performed to the perspective of the client , to evaluate how the GUI is user-friendly .How easily can the client learn? After learning how to use, how proficiently can the client perform? How pleasing is it to use its design?
  •   It falls under class of Blackbox testing.

Acceptance Testing
  •   It is often done by the customer to ensure that the delivered product meets the requirements and works as the customer expected.
  •   It falls under the class of black box testing.

Regression Testing
  •   It is the testing after modification of a system, component, or a group of related units to ensure that the modification is working correctly and is not damaging or imposing other modules to produce unexpected results.
  •   It falls under the class of black box testing.

Beta Testing
  •   It is the testing which is done by end users, a team outside development, or publicly releasing full pre-version of the product which is known as beta version. The aim of beta testing is to cover unexpected errors.
  •   It falls under the class of black box testing.

 

Thursday, April 25, 2013

AutoCompletionTestFieldDemo using Java

import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.*;
import javax.swing.event.*;
/**
 * Example for AutoCompletionTestFieldDemo
 * @author R.Amirtharaj
 */
public class AutoCompletionTestFieldDemo {

    public static void main(String[] args) throws Exception {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        JFrame frame = new JFrame();
        frame.setTitle("Auto Completion Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(200, 200, 500, 400);

        ArrayList items = new ArrayList();
        // To get Locale
        Locale[] locales = Locale.getAvailableLocales();
        for (int i = 0; i < locales.length; i++) {
            String item = locales[i].getDisplayName();
            items.add(item);
        }
        JTextField txtInput = new JTextField();

        // set autocmplete
        setAutoComplete(txtInput, items);
        txtInput.setColumns(30);
        frame.getContentPane().setLayout(new FlowLayout());
        frame.getContentPane().add(txtInput, BorderLayout.NORTH);
        frame.setVisible(true);
    }

    private static boolean isAdjusting(JComboBox cbInput) {
        if (cbInput.getClientProperty("is_adjusting") instanceof Boolean) {
            return (Boolean) cbInput.getClientProperty("is_adjusting");
        }
        return false;
    }

    private static void setAdjusting(JComboBox cbInput, boolean adjusting) {
        cbInput.putClientProperty("is_adjusting", adjusting);
    }

    public static void setAutoComplete(final JTextField txtInput, final ArrayList items) {
        final DefaultComboBoxModel model = new DefaultComboBoxModel();
        final JComboBox cbInput = new JComboBox(model) {
            public Dimension getPreferredSize() {
                return new Dimension(super.getPreferredSize().width, 0);
            }
        };
        setAdjusting(cbInput, false);
        for (String item : items) {
            model.addElement(item);
        }
        cbInput.setSelectedItem(null);
        cbInput.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!isAdjusting(cbInput)) {
                    if (cbInput.getSelectedItem() != null) {
                        txtInput.setText(cbInput.getSelectedItem().toString());
                    }
                }
            }
        });

        txtInput.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                setAdjusting(cbInput, true);
                if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                    if (cbInput.isPopupVisible()) {
                        e.setKeyCode(KeyEvent.VK_ENTER);
                    }
                }
                if (e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN) {
                    e.setSource(cbInput);
                    cbInput.dispatchEvent(e);
                    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                        // User may enter Other than list
                        try {
                            txtInput.setText(cbInput.getSelectedItem().toString());
                        }
                        catch(Exception ex)
                        {
                        }
                        cbInput.setPopupVisible(false);
                    }
                }
                if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                    cbInput.setPopupVisible(false);
                }
                setAdjusting(cbInput, false);
            }
        });

        txtInput.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                updateList();
            }

            public void removeUpdate(DocumentEvent e) {
                updateList();
            }

            public void changedUpdate(DocumentEvent e) {
                updateList();
            }

            private void updateList() {
                setAdjusting(cbInput, true);
                model.removeAllElements();
                String input = txtInput.getText();
                if (!input.isEmpty()) {
                    for (String item : items) {
                        if (item.toLowerCase().startsWith(input.toLowerCase())) {
                            model.addElement(item);
                        }
                    }
                }
                cbInput.hidePopup();
                cbInput.setPopupVisible(model.getSize() > 0);
                setAdjusting(cbInput, false);
            }
        });
        txtInput.setLayout(new BorderLayout());
        txtInput.add(cbInput, BorderLayout.SOUTH);
    }
}

Monday, April 22, 2013

The Seven Phases of the Systems Development Life Cycle (SDLC):

The Seven Phases of the Systems Development Life Cycle :

1. Information Gathering : In this phase Bussiness Analyst will gather all the information from customer requirement and prepare BRS/CRS/URS(Buiseness/Customer/User Requirement Specification) document. Mainly this done by Buisness Anlayst as they are the one who are completely involved in SDLC.

2. Analysis : In this phase Senior Business Analyst will prepare SRS(Software Requirement Specification). The Features and functions are put in the project are determined.

3. Design : Actual flow of the project is done here. Deciding upto logical functionality, ER Diagram , Flow chart etc are made. Cheif Architect will prepare HLD and LLD(High Level Document and Low Level Document)
  • HLD : Defines the overall Hierarchy of the function.Example : Login into Net Banking. From the root level to the least level is defines in HLD.
  • LLD: Internal logic of the project is defined. Focuses on the internal functionality of the program. Each and every module logic is defined.

4. Code : Based on the design document , small-small modules are prepared . All the modules are summed together to form a .exe. Unit testing , integration testing & white box testing comes in this phase.       

5. Testing : Actuall system testing take place here.

6. Implementation : All sr.department will release the product .

7. Maintenance : In maintenance the maintenance team will change the software if necessary. 

Thursday, April 18, 2013

Java Collection loop throw elements

import java.util.*;

/**
 *
 * @author Amirtharaj
 */
public class CollectionLoopThroDemo {

    public static void main(String arg[]) {
        CollectionLoopThroDemo cd = new CollectionLoopThroDemo();

        List al = new ArrayList();
        al.add("C");
        al.add("A");
        al.add("B");
        cd.iterateList(al);

        Set setDet = new HashSet();
        setDet.add("B");
        setDet.add("A");
        setDet.add("C");
        cd.iterateSet(setDet);

        Map mapDet = new HashMap();
        mapDet.put("B", 2.0);
        mapDet.put("A", 1.0);
        mapDet.put("C", 3.0);
        cd.iterateMap(mapDet);

    }

    public void iterateList(List al) {
        //access via Iterator
        Iterator iterator = al.iterator();
        while (iterator.hasNext()) {
            String str = (String) iterator.next();
            System.out.println(str);
        }
        //access via new for-loop
        for (String str : al) {
            System.out.println(str);
        }
    }

    public void iterateSet(Set setDet) {

        //access via Iterator
        Iterator iterator = setDet.iterator();
        while (iterator.hasNext()) {
            String str = (String) iterator.next();
            System.out.println(str);
        }


        //access via new for-loop
        for (String str : setDet) {
            System.out.println(str);
        }
    }

    public void iterateMap(Map mapDet) {
        //access via Iterator
        Iterator iterator = mapDet.keySet().iterator();
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            Double value = (Double) mapDet.get(key);
            System.out.println(key + "," + value);
        }

        //access via new for-loop
        for (String key : mapDet.keySet()) {
            Double value = mapDet.get(key);
            System.out.println(key + "," + value);
        }

    }
}

Tuesday, April 2, 2013

To get Motherboard serial number, Hard disk serial number, IP Address and MAC Address from Java

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;

public class MyPC {

    public static String getMotherBoardSerialNumber() {
        String result = "";
        try {
            File file = File.createTempFile("realhowto", ".vbs");
            file.deleteOnExit();
            FileWriter fw = new java.io.FileWriter(file);
            String vbs =
                    "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                    + "Set colItems = objWMIService.ExecQuery _ \n"
                    + "   (\"Select * from Win32_BaseBoard\") \n"
                    + "For Each objItem in colItems \n"
                    + "    Wscript.Echo objItem.SerialNumber \n"
                    + "    exit for  ' do the first cpu only! \n"
                    + "Next \n";

            fw.write(vbs);
            fw.close();
            Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
            BufferedReader input =
                    new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                result += line;
            }
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.trim();
    }

    public static String getHardDiskSerialNumber(String drive) {
        String result = "";
        try {
            File file = File.createTempFile("realhowto", ".vbs");
            file.deleteOnExit();
            FileWriter fw = new java.io.FileWriter(file);

            String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
                    + "Set colDrives = objFSO.Drives\n"
                    + "Set objDrive = colDrives.item(\"" + drive + "\")\n"
                    + "Wscript.Echo objDrive.SerialNumber";  // see note
            fw.write(vbs);
            fw.close();
            Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
            BufferedReader input =
                    new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                result += line;
            }
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.trim();
    }

    public static String getIPAddress() {
        String strIP = "127.0.0.1";
        try {
            InetAddress ip = InetAddress.getLocalHost();
            strIP = ip.getHostAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strIP;
    }

    public static String getMACAddress() {
        String strMAC = "127.0.0.1";
        try {
            InetAddress ip = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            byte[] mac = network.getHardwareAddress();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            }
            strMAC = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strMAC;
    }

    public static void main(String[] args) {
        System.out.println("Motherboard serial number : " + MyPC.getMotherBoardSerialNumber());
        System.out.println("Hard disk serial number : " + MyPC.getHardDiskSerialNumber("C"));
        System.out.println("IP Address : " + MyPC.getIPAddress());
        System.out.println("MAC Address : " + MyPC.getMACAddress());
    }
}

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);
    }
}

Wednesday, January 2, 2013

Solution for Oracle 11g import export problem

If any table contain blank data export won't be proper in Oracle 11g.
Solution is Before Export we need to allocate extent to empty table.
Need to execute below query

select 'alter table '||table_name||' allocate extent;' from user_tables where segment_created = 'NO'

     above query will give  list of query to allocate extent to empty table like below

    alter table ELTRIX_TAG_MASTER allocate extent;
    alter table ELTRIX_TREND_CONFIG allocate extent;
    ...etc


   Then need to execute above list of queries , after that as usual  exp and imp commands will work without any issue.

Tuesday, January 1, 2013

How to find Query Execution Time in Oracle database?

select * from v$sql;

You will notice that you can further filter on lot of useful stuff.

For example:
Lets say you want to see only those queries coming via a JDBC Thin Driver, you can do:

select LAST_LOAD_TIME, ELAPSED_TIME, MODULE, SQL_TEXT elasped from v$sql
WHERE MODULE='JDBC Thin Client'
ORDER BY LAST_LOAD_TIME DESC


To see all the columns in this table:
desc v$sql

Finding open Cursor in particular user : 

select  sql_text, count(*) as "OPEN CURSORS", user_name from v$open_cursor where user_name='XXXXX' group by sql_text, user_name order by count(*) desc;