Monday, 1 September 2014

Speed up a Slow Android AVD or Emulator

Leave a Comment
One thing you must have noticed that emulators are dead slow by default. I mean they are so much slow that you can take your lunch in the mean time and they will be loading all the time.

Can we improve this slow emulators? Ye, we can. Let’s see how.

Step 1) Download HAXM Driver using SDK Manager
To improve the performance of an emulator first thing you will need is installing the “Intel Hardware Accelerated Execution Manager Driver” from SDK Manager you get with Android ADT. Look at the screen shot below.

Step 2) Execute IntelHaxm.exe to install the HAXM driver
This will create the IntelHaxm.exe inside “extra” folder in your android ADT package. Execute this file to install the HAXM Driver which is responsible for virtualization in your system.

Step 3) Update BIOS if driver installation failed
There are chances that above installation process failed and you are advised to update the BIOS configuration related to “Intel Virtualization Technology“. Go ahead and do it. For related information to this step, read the manual received with motherboard when you purchased it.

Generally, when you go to BIOS options by pressing “DEL” key during boot process, you can easily find the menu option “Intel Virtualization Technology” in third tab. Enable this option and restart the machine.
Step 4) Use Host GPU Option
Once Virtualization Technology is enabled, you can use this feature while creating the Emulator by checking the checkbox “Use Host GPU“. This will enable the system’s native support for virtualization for emulator.

Step 5) Test the configuration changes
Now start the emulator and see the major performance gain you obtained using above steps.

Read More...

Friday, 29 August 2014

Get value of struts property tag into jsp variable

Leave a Comment
Hello friends when you work on Struts request property  then you can get the value of form by
<s:property value="a"/>
Same question arise by my friends :
Can anybody tell how to assign a value coming from "<s:property value="a">" into jsp variable ?
You can use the following to get the value in to variable
how to Get value of struts property tag into jsp variable,Get value of struts property tag into jsp variable,value of struts property tag into jsp variable,struts property tag into jsp variable,property tag into jsp variable,

For example there is a string avalue,
String avalue="";
Now you can assign a property value to it by using,
<s:property value="a"/>avalue=request.getAttribute("a");
above will gives the property value to a string variable. otherwise you can set the value and then assign it through getAttribute
Read More...

Tuesday, 26 August 2014

How to convert number into word in java

Leave a Comment
What if someone asks you a java program for writing numbers in words .The problem with the question is that we dont know how big the input number can be. So first question we need to ask  what would be the range of the input. After getting the range , we can answer through algorithm or code of program.We provided two answers to this question as the countries like USA, UK uses million,billion,trillion terminology while Asian countries like India,Pakistan ,Srilanka uses lakh,crore,arab,kharab terminology.
How to convert number into word in java,convert number into word in java,number into word in java,word in java,

So lets find out the logic and java program for writing numbers in words.

public class NumberToWord  
 
{
    private static final String[] specialNames = {
        "",
        " thousand",
        " million",
        " billion",
        " trillion",
        " quadrillion",
        " quintillion"
    };
    
    private static final String[] tensNames = {
        "",
        " ten",
        " twenty",
        " thirty",
        " fourty",
        " fifty",
        " sixty",
        " seventy",
        " eighty",
        " ninety"
    };
    
    private static final String[] numNames = {
        "",
        " one",
        " two",
        " three",
        " four",
        " five",
        " six",
        " seven",
        " eight",
        " nine",
        " ten",
        " eleven",
        " twelve",
        " thirteen",
        " fourteen",
        " fifteen",
        " sixteen",
        " seventeen",
        " eighteen",
        " nineteen"
    };
    
    private String convertLessThanOneThousand(int number) {
        String current;
        
        if (number % 100 < 20){
            current = numNames[number % 100];
            number /= 100;
        }
        else {
            current = numNames[number % 10];
            number /= 10;
            
            current = tensNames[number % 10] + current;
            number /= 10;
        }
        if (number == 0) return current;
        return numNames[number] + " hundred" + current;
    }
    
    public String convert(int number) {

        if (number == 0) { return "zero"; }
        
        String prefix = "";
        
        if (number < 0) {
            number = -number;
            prefix = "negative";
        }
        
        String current = "";
        int place = 0;
        
        do {
            int n = number % 1000;
            if (n != 0){
                String s = convertLessThanOneThousand(n);
                current = s + specialNames[place] + current;
            }
            place++;
            number /= 1000;
        } while (number > 0);
        
        return (prefix + current).trim();
    }
    
    public static void main(String[] args) {
        NumberToWord obj = new NumberToWord();
        System.out.println("*** " + obj.convert(123456789));
        System.out.println("*** " + obj.convert(-55));
    }
}

Logic behind this :
After thousand number , there is a symmetry in special names like million,billion,trillion,quadrillion,quintillion.
The symmetry is if you multiply 1000 with thousand than we will get a million. If we multiply 1000 with million then we will get billion. If we multiply 1000 with billion then we get trillion.Similarly,1000 multiply trillion equals quadrillion. 1000 multiply quadrillion equals quintillion.This symmetry starts after we reach 1000 number . So we will divide the program into two parts .
First part that is function convertLessThanOneThousand(int number) will convert any number smaller than 1000 into words.

Second part, starting from extreme-right of input number, we  will use modulus operator by1000, to get the last three extreme right digits of the input number.Taking three digits at a time from right to left , we will scan the whole input number until it is fully converted into the word.
Read More...

Sunday, 24 August 2014

How to Make KeyLogger in Java

Leave a Comment
Are you agree on statement "We can't create key logger in Java". I know most of you say this statement is correct. Because we know that Java can't read anything outside of JVM (Java Virtual Machine). Even I was thinking same but my colleague was searching on the same. He found API called jNativeHook which makes it happen..
Features of jNative Hook API

  1. Global Keyboard Listener
  2. Global Mouse Listener
  3. Global Mouse Wheel Listener
How it manage to capture key strokes from other application or anywhere in system?
How to Make KeyLogger in Java,Make KeyLogger in Java,KeyLogger in Java,how to create keylogger in java,create keylogger in java,java keylogger

Well jNativeHook using other programming language to capture key strokes and pass it to your application. Its using
  1. .dll (Dynamic Link Library) for windows.
  2. .dylib (Xcode Dynamic Library) for mac
  3. .so (Shared object) for linux
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
/**
 * @author javaQuery
 * Global Keyboard Listener
 */
public class jNativeHookExample implements NativeKeyListener {

    /* Key Pressed */
    public void nativeKeyPressed(NativeKeyEvent e) {
        System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));

        /* Terminate program when one press ESCAPE */
        if (e.getKeyCode() == NativeKeyEvent.VK_ESCAPE) {
            GlobalScreen.unregisterNativeHook();
        }
    }

    /* Key Released */
    public void nativeKeyReleased(NativeKeyEvent e) {
        System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
    }

    /* I can't find any output from this call */
    public void nativeKeyTyped(NativeKeyEvent e) {
        System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
    }

    public static void main(String[] args) {
        try {
            /* Register jNativeHook */
            GlobalScreen.registerNativeHook();
        } catch (NativeHookException ex) {
            /* Its error */
            System.err.println("There was a problem registering the native hook.");
            System.err.println(ex.getMessage());
            System.exit(1);
        }

        /* Construct the example object and initialze native hook. */
        GlobalScreen.getInstance().addNativeKeyListener(new jNativeHookExample());
    }
}
Known Issues 

  • The library does not receive events after waking from a sleep state on Unix/Linux.
  • Users on Windows may experience a lapse in event data while using Remote Desktop in full screen mode.


Useful Links
Download API: https://code.google.com/p/jnativehook/downloads/list
Examples: https://code.google.com/p/jnativehook/wiki/examples 
Read More...

Saturday, 23 August 2014

Some fact on public static void main String(args[])

Leave a Comment
In most of the java interviews either for freshers or experience guys frequently facing this question. This will be easy when you have full idea about access specifiers and modifiers in java. Lets discuss about our mantra
public static void main(String args[])
What is the Importance of the public static void main(String args[ ])
Whether a class contains main( ) or not and whether the main( ) is declared based on  requirement, these all are things are won't be checked by compiler,these things are checked by JVM at Runtime.


Note: If JVM is unable to find main( ) then we will get a Runtime Exception saying : Exception in thread "main" java.lang.NoSuchMethodError: main

Here we can observe that's why the main( ) prototype must be public static void main(String args[]) Let's see .

  • public: JVM calls main( ) from anywhere, so it should be public
  • static: without creating object also JVM has to call this method.
  • void: here main( ) won't return anything to JVM
  • main( ): this is the method which has configured already in the JVM
  • String[] args: commandline- arguments in the form of array of instances of the class String

Change 1: 
The Order of the modifiers is not important, i.e instead of public static ,we can use static public also.
Change 2: 
We can declare String array in any acceptable form i.e
(String[] args)
(String []args)
(String args[])
Change 3:
Instead of 'args' we should take any java valid identifier
public class Test {
 public static void main(String geekonjava[]) {
  System.out.println("Hello Test");
 }
}
the above code will execute without error.
Change 4: 
We can replace 'String[] args' with 'var-args' parameter. i.e
main(String[] args) to main(String...args)
public class Test {
 public static void main(String...args) {
  System.out.println("Hello Test");
 }
}
Change 5:
We can declare main( ) with the following modifiers also
  1. final
  2. synchronized
  3. strictfp
The following program consits of all above changes.
public class Test {
 final synchronized strictfp static public void main(String... args) {
  System.out.println("This is acceptable main method");
 }
}
This class will print the value without any error. 

Here some more information about main method
Case 1: 
Overloading of the main( ) is possible,But JVM always call (String[] args) of main( ) only see below Example.
public class Test {
 public static void main(String[] args) {
  System.out.println("String[]");
 }
 
 public static void main(int[] args) {
  System.out.println("int[]");
 }
}
Output:  String[]
Here we can say that above method is Overloaded. Method names are same with different signatures.
Case 2: 
Inheritance is possible/applicable on main( ),while executing child class ,if child class doesn't contains main( ),then parent main( ) will be executed.
public class Test {
 public static void main(String args[]) {
  System.out.println("iam from main()");
 }
}
class Demo extends Test {
}
w.r.to{java test} parent class: Output: iam from main( )
w.r.to {java Demo}child class: Output: iam from main( )
Case 3:
It seems Overriding concept is applicable for main( ),but it is not Overriding it is method hiding.
class Test {
 public static void main(String args[]) {
  System.out.println("iam from Test");
 }
}
 
class Demo extends Test {
 public static void main(String[] args) {
  System.out.println("iam from Demo");
 }
}
w.r.to Parent: Output:  iam from Test
w.r.to Child: Output:  iam from Demo

Note: Overloading and inheritence is applicable for main method. But overriding concept is not applicable,instead of overriding concept method hiding concept is applicable.

Interview Question on main method is given below take a look on it. 
Which of the following are valid main( ) declarations as shown bellow?
1) public static void main(String args[])
     [invalid because in main the letter m is Capital]
2) public static int main(String[] args )
     [invalid because the main method is return int value]
3) public static void main(string  args))
     [invalid because the String arr[] is not declared]
4) public final synchronized strictfp void main(String...args)
     [invalid because static is missing] 
5) public static void main(String...args)
    [Valid]
6) public static final synchronized strictfp void main(String...args)
    [Valid]





Read More...

Friday, 22 August 2014

How to find Bluetooth device services in Java

Leave a Comment
Today I'm going to demonstrate "How to use BlueCove to search near by Bluetooth devices?" and "How to find Bluetooth device services in Java using BlueCove".
BlueCove
It is a Java library for Bluetooth (JSR-82 implementation) that currently interfaces with the Mac OS X, WIDCOMM, BlueSoleil and Microsoft Bluetooth stack found in Windows XP SP2 or Windows Vista and WIDCOMM and Microsoft Bluetooth stack on Windows Mobile.
How to find Bluetooth device services in Java,find Bluetooth device services in Java,Bluetooth device services in Java,device services in Java,services in Java,How to use BlueCove to search near by Bluetooth devices,BlueCove to search near by Bluetooth devices,search near by Bluetooth devices,search near by Bluetooth devices in java,

RemoteDeviceDiscovery
RemoteDeviceDiscovery class is used to find paired and near by devices.
import java.util.Enumeration;
import java.util.Vector;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;

public class RemoteDeviceDiscovery {

    public Vector getDevices() {
        /* Create Vector variable */
        final Vector devicesDiscovered = new Vector();
        try {
            final Object inquiryCompletedEvent = new Object();
            /* Clear Vector variable */
            devicesDiscovered.clear();

            /* Create an object of DiscoveryListener */
            DiscoveryListener listener = new DiscoveryListener() {

                public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
                    /* Get devices paired with system or in range(Without Pair) */
                    devicesDiscovered.addElement(btDevice);
                }

                public void inquiryCompleted(int discType) {
                    /* Notify thread when inquiry completed */
                    synchronized (inquiryCompletedEvent) {
                        inquiryCompletedEvent.notifyAll();
                    }
                }

                /* To find service on bluetooth */
                public void serviceSearchCompleted(int transID, int respCode) {
                }

                /* To find service on bluetooth */
                public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
                }
            };

            synchronized (inquiryCompletedEvent) {
                /* Start device discovery */
                boolean started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, listener);
                if (started) {
                    System.out.println("wait for device inquiry to complete...");
                    inquiryCompletedEvent.wait();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /* Return list of devices */
        return devicesDiscovered;
    }
}
ServicesSearch 
ServicesSearch class used to find specific service on Bluetooth device. Each service identified using UUID (Universally unique identifier).
All UUID listed on https://www.bluetooth.org/en-us/specification/assigned-numbers/service-discovery .
Replace your required UUID in following code.
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.bluetooth.*;

public class ServicesSearch {

    /** 
     * UUID used to find specific service supported by bluetooth device
     * https://www.bluetooth.org/en-us/specification/assigned-numbers/service-discovery
     * Find UUIDs for all types of bluetooth services.
     */
    /* To find push object service */
    private UUID OBEX_OBJECT_PUSH_PROFILE = new UUID(0x1105);
    /* To find file transfer service */
    private UUID OBEX_FILE_TRANSFER_PROFILE = new UUID(0x1106);
    /* To find hands free service */
    private UUID HANDS_FREE = new UUID(0x111E);
    /* Get URL attribute from bluetooth service */
    private int URL_ATTRIBUTE = 0X0100;
    
    public Map<String, List<String>> getBluetoothDevices() {        
        /**
         * Find service on bluetooth device 
         * Note: In following line you can use one service at a time. I'm new to bluetooth programming it might me wrong perception.
         * UUID[] searchUuidSet = new UUID[]{OBEX_FILE_TRANSGER_PROFILE};
         * 
         * CORRECT: UUID[] searchUuidSet = new UUID[]{OBEX_FILE_TRANSGER_PROFILE};
         * WRONG: UUID[] searchUuidSet = new UUID[]{OBEX_FILE_TRANSGER_PROFILE, OBEX_OBJECT_PUSH_PROFILE};
         */
        /* Initialize UUID Array */
        UUID[] searchUuidSet = new UUID[]{HANDS_FREE};
        final Object serviceSearchCompletedEvent = new Object();
        int[] attrIDs = new int[]{URL_ATTRIBUTE};
        
        /* Create an object to get list of devices in range or paired */
        RemoteDeviceDiscovery remoteDeviceDiscovery = new RemoteDeviceDiscovery();
        /* Create map to return Bluetooth device address, name and URL */
        final Map<String, List<String>> mapReturnResult = new HashMap<String, List<String>>(); 

        try {
            /* Create an object of DiscoveryListener */
            DiscoveryListener listener = new DiscoveryListener() {

                /* To find bluetooth devices */
                public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
                }

                /* To find bluetooth devices */
                public void inquiryCompleted(int discType) {
                }

                /* Find service URL of bluetooth device */
                public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
                    for (int i = 0; i < servRecord.length; i++) {
                        /* Find URL of bluetooth device */
                        String url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                        if (url == null) {
                            continue;
                        }
                        String temporaryString = "";
                        /* Get object of bluetooth device */
                        RemoteDevice rd = servRecord[i].getHostDevice();
                        /* Get attribute from ServiceRecord */
                        DataElement serviceName = servRecord[i].getAttributeValue(URL_ATTRIBUTE);
                        if (serviceName != null) {         
                            temporaryString = serviceName.getValue() + "\n" + url;
                            /* Put it in map */
                            mapReturnResult.get(rd.getBluetoothAddress()).add(temporaryString);
                        } else {
                            temporaryString = "Uknown service \n" + url;
                            /* Put it in map */
                            mapReturnResult.get(rd.getBluetoothAddress()).add(temporaryString);
                        }
                    }
                }

                public void serviceSearchCompleted(int transID, int respCode) {
                    /* Notify thread when search completed */
                    synchronized (serviceSearchCompletedEvent) {
                        serviceSearchCompletedEvent.notifyAll();
                    }
                }
            };

            /* Get list of bluetooth device from class RemoteDeviceDiscovery */
            for (Enumeration en = remoteDeviceDiscovery.getDevices().elements(); en.hasMoreElements();) {
                /* Get RemoteDevice object */
                RemoteDevice btDevice = (RemoteDevice) en.nextElement();
                /* Create list to return details */
                List<String> listDeviceDetails = new ArrayList<String>();
                
                try {
                    /* Add bluetooth device name and address in list */
                    listDeviceDetails.add(btDevice.getFriendlyName(false));
                    listDeviceDetails.add(btDevice.getBluetoothAddress());
                } catch (Exception e) {
                }
                
                /* Put bluetooth device details in map */
                mapReturnResult.put(btDevice.getBluetoothAddress(), listDeviceDetails);
                synchronized (serviceSearchCompletedEvent) {
                    LocalDevice.getLocalDevice().getDiscoveryAgent().searchServices(attrIDs, searchUuidSet, btDevice, listener);
                    serviceSearchCompletedEvent.wait();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /* Return bluetooth devices detail */
        return mapReturnResult;
    }
}
BluetoothDevices 
BluetoothDevices is simple JFrame used to give Uter Interface for program. Its created in NetBeans IDE, You may find some code unexplained which is generated by IDE.
import com.javaquery.bluetooth.ServicesSearch;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.UIManager;

public class BluetoothDevices extends javax.swing.JFrame {

    /* DefaultListModel to attach it with JList */
    private DefaultListModel defaultModel;
    /* Map to get device details list */
    private Map<String, List<String>> mapReturnResult = new HashMap<String, List<String>>();
    /* Map to identify device on user click of JList */
    private Map<Integer, List<String>> mapDevicePosition = new HashMap<Integer, List<String>> ();

    public BluetoothDevices() {
        initComponents();
        defaultModel = new DefaultListModel();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        JListBluetoothDevices = new javax.swing.JList();
        lblDeviceName = new javax.swing.JLabel();
        lblRuntimeDeviceName = new javax.swing.JLabel();
        lblDeviceAddress = new javax.swing.JLabel();
        lblRuntimeDeviceAddress = new javax.swing.JLabel();
        lblServiceDetails = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        JTextAreaServiceDetails = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Bluecove Bluetooth Discovery");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        JListBluetoothDevices.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                JListBluetoothDevicesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(JListBluetoothDevices);

        lblDeviceName.setText("Bluetooth Device Name");

        lblDeviceAddress.setText("Bluetooth Device Address");

        lblServiceDetails.setText("Service Details");

        JTextAreaServiceDetails.setColumns(20);
        JTextAreaServiceDetails.setRows(5);
        jScrollPane2.setViewportView(JTextAreaServiceDetails);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblDeviceName)
                            .addComponent(lblDeviceAddress))
                        .addGap(73, 73, 73)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblRuntimeDeviceAddress)
                            .addComponent(lblRuntimeDeviceName, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(lblServiceDetails)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblDeviceName)
                            .addComponent(lblRuntimeDeviceName))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblDeviceAddress)
                            .addComponent(lblRuntimeDeviceAddress))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblServiceDetails)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

 /* Search for bluetooth device when window opened */
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        int intDevicePosition = 0;
        JListBluetoothDevices.setModel(defaultModel);        

        /* Create an object of ServicesSearch */
        ServicesSearch ss = new ServicesSearch();
        /* Get bluetooth device details */
        mapReturnResult = ss.getBluetoothDevices();

        /* Add devices in JList */
        for (Map.Entry<String, List<String>> entry : mapReturnResult.entrySet()) {            
            defaultModel.addElement(entry.getValue().get(0));
            mapDevicePosition.put(intDevicePosition, entry.getValue());
            intDevicePosition++;
        }
    }//GEN-LAST:event_formWindowOpened

 /* On click of any item in List Box */
    private void JListBluetoothDevicesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JListBluetoothDevicesMouseClicked
  /* Get bluetooth device details from temporary list */
        List<String> tmpDeviceDetails = mapDevicePosition.get(JListBluetoothDevices.getSelectedIndex());
  /* Set bluetooth device name */
        lblRuntimeDeviceName.setText(tmpDeviceDetails.get(0));
  /* Set bluetooth device Address */
        lblRuntimeDeviceAddress.setText(tmpDeviceDetails.get(1));       
        
        if(tmpDeviceDetails.size() > 2 && tmpDeviceDetails.get(2) != null){
   /* Set bluetooth device service name and URL */
            JTextAreaServiceDetails.setText(tmpDeviceDetails.get(2));
        }else{
            JTextAreaServiceDetails.setText("Service not found");
        }
    }//GEN-LAST:event_JListBluetoothDevicesMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                 /* To set new look and feel */
                JFrame.setDefaultLookAndFeelDecorated(true);
                try {
                    /**
                     * Change look and feel of JFrame to Nimbus 
                     * For other look and feel check
      * http://www.geekonjava.blogspot.com
                     */
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
                } catch (Exception ex) {
                   ex.printStackTrace();
                }
                /* Create an object of BluetoothDevices */
                BluetoothDevices bluetoothDevicesFrame = new BluetoothDevices();
                /* make BluetoothDevices visible */
                bluetoothDevicesFrame.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList JListBluetoothDevices;
    private javax.swing.JTextArea JTextAreaServiceDetails;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblDeviceAddress;
    private javax.swing.JLabel lblDeviceName;
    private javax.swing.JLabel lblRuntimeDeviceAddress;
    private javax.swing.JLabel lblRuntimeDeviceName;
    private javax.swing.JLabel lblServiceDetails;
    // End of variables declaration//GEN-END:variables
}


If you're fine then like and share that post.
Read More...

Wednesday, 20 August 2014

What are Difference between load( ) vs get( ) in Hibernate

Leave a Comment
The following Hibernate code snippet retrieves a User object from the database:
What are Difference between load( ) vs get( ) in Hibernate,Difference between load( ) vs get( ) in Hibernate,between load( ) vs get( ) in Hibernate,load( ) vs get( ) in Hibernate,get( ) in Hibernate,

load()

1). Only use the load()method if you are sure that the object exists.
2). load() method will throw an exception if the unique id is not found in the database.
3). load() just returns a proxy by default and database won’t be hit until the proxy is first invoked.

Session session = << Get session from SessionFactory >>
Long itemId = << Get the item id from request >>
 
try{
   Item item = session.load(Item.class, itemId);
   Bid bid = new Bid();
   bid.setItem(item);
   session.saveOrUpdate(bid);
} catch(ObjectNotFoundException e) {
   log.error("Bid placed for an unavailable item");
   // Handle the error condition appropriately
}

get( )

1). If you are not sure that the object exists, then use one of the get() methods.
2). get() method will return null if the unique id is not found in the database.
3). get() will hit the database immediately.

Session session = << Get session from SessionFactory >>
Long itemId = << Get the item id from request >>
 
Item item = (Item) session.get(Item.class, itemId);
 
if(item != null) {
   Bid bid = new Bid();
   bid.setItem(item);
   session.saveOrUpdate(bid);
} else {
   log.error("Bid placed for an unavailable item");
   // Handle the error condition appropriately
}

Read More...