Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

How Java Hashtable Works ?

         Hashtable is an implementation of a key-value pair data structure in java. You can store and retrieve a ‘value’ using a ‘key’ and it is an identifier of the value stored. It is obvious that the ‘key’ should be unique.

     java.util.Hashtable extends Dictionary and implements Map. Objects with non-null value can be used as a key or value. Key of the Hashtable must implement hashcode() and equals() methods. By the end of this article you will find out the reason behind this condition.
 

Generally a Hashtable in java is created using the empty constructor Hashtable().
Which is a poor decision and an often repeated mistake.

Hashtable has two other constructors.
 
and  
Initial capacity is number of buckets created at the time of Hashtable instantiation. Bucket is a logical space of storage for Hashtable.

Hashing and Hashtable

       Before seeing java’s Hashtable in detail you should understand hashing in general. Assume that, v is a value to be stored and k is the key used for storage / retrieval, then h is a hash function where v is stored at h(k) of table. To retrieve a value compute h(k) so that you can directly get the position of v. So in a key-value pair table, you need not sequentially scan through the keys to identify a value.
 
h(k) is the hashing function and it is used to find the location to store the corresponding value v. h(k) cannot compute to a indefinite space. Storage allocated for a Hashtable is limited within a program. So, the hasing function h(k) should return a number within that allocated spectrum (logical address space).

Hashing in Java

Java’s hashing uses uses hashCode() method from the key and value objects to compute. Following is the core code from Hashtable where the hashCode ‘h’ is computed. You can see that both key’s and value’s hashCode() method is called.
 
It is better to have your hashCode() method in your custom objects. String has its own hashCode methode and it computes the hashcode value as below:  
 
If you don’t have a hashCode() method, then it is derived from Object class.
Following is javadoc comment of hashCode() method from Object class: 
  • Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.  
If you are going to write a custom hashCode(), then follow the following contract:
  • The general contract of hashCode is: Whenever it is invoked on the same object more than once during  an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.
The following is to improve performance of the Hashtable.
  • If two objects are equal according to the equals(Object)method, then calling the hashCode method on each of the two objects must produce the same integer result

hashCode() guarantees distinct integers by using the internal address of the object.

Collision in Hashtable

 

posted under | 0 Comments

How to resize an array in java

 
In General terms, As we know that we cannot resize an array once we initialized because array defination says that an array is an fixed size,sequence and collection of similar data type. But It is possible to resize an array, resizing an array is nothing but copy the content of old array to new index array as per our requirement. Following code snippets is usefull for resize an array. Java.lang.System.arraycopy() Method is responsible for resizing an array.
File Name : ResizeArray.java
 
What is Java.lang.System.arraycopy() Method :
The java.lang.System.arraycopy() method copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest.The number of components copied is equal to the length argument.
The components at positions srcPos through srcPos + length - 1 in the source array are copied into positions destPos through destPos + length - 1, respectively, of the destination array.
Syntax :
 
Parameters:
  • src       -- This is the source array.
  • srcPos -- This is the starting position in the source array.
  • dest -- This is the destination array.
  • destPos -- This is the starting position in the destination data.
  • length -- This is the number of array elements to be copied.
Return Value: Method does not return any value.
Exception Details:
  • IndexOutOfBoundsException  --if copying would cause access of data outside array bounds.
  • ArrayStoreException -- if an element in the src array could not be stored into the dest array because of a type mismatch.
  • NullPointerException -- if either src or dest is null.
Another Example : File Name :TestSystemDemo.java
output : array2 = 0 10 20 30 40

posted under | 0 Comments

How to read XML file in java

How To Read/Parse XML File In Java

Here you will find the program which read/parse xml file. It will provide you a basic guide to parse your XML document, Your codding may be different as per your requirement. Here you will find mathod called getAllStudentNames(String fileName). Please provide fileName as full path of your XML file source.
File Name : XMLParser.java
 
File Name : student.xml
 

posted under | 1 Comments

How to take screen shots in Java

How to take screen shots in Java

Following piece of code in Java that takes the screen shot of your desktop and save it in a PNG file. This example uses java.awt.Robot class to capture the screen pixels and returns a BufferedImage. Java.awt.Robot class is used to take the control of mouse and keyboard. Once you get the control, you can do any type of operation related to mouse and keyboard through your java code. This class is used generally for test automation. Copy and paste following code in your Java class and invoke the method captureScreen() with file name as argument. The screen shot will be stored in the file that you specified in argument. Please enter the full file path.
 

posted under | 0 Comments

Date Manipulation In Java

 
This Class will become very usefull when you are dealing with Dates in Java. This class provides method which you can call based on your needs.

File Name : DateManipulation.java

 

posted under , | 0 Comments

DateTimeFormater Class usefull while working with dates in java

This Class will become very usefull when you are dealing with Dates in Java. This class provides method which you can call based on your needs.
 

File Name : DateTimeFormater.java

posted under , | 0 Comments

How to Creating Web fragment projects ?

Steps by Step guide for creating Web fragment projects / web module or module project in java.

You can use the Web fragment project wizard to create Web fragment projects in your workspace.

A web fragment is a logical partitioning of the web application in such a way that the frameworks being used within the web application can define all the artifacts without requiring you to edit or add information in the web.xml. It can include almost all the same elements that the web.xml descriptor uses, with these requirements:

  • The top level element for the descriptor must be web-fragment
  • The corresponding descriptor file must be called web-fragment.xml
If a framework is packaged as a jar file and has metadata information in the form of deployment descriptor, then the web-fragment.xml descriptor must be in the META-INF/ directory of the jar file. 

A web fragment is a mechanism for either defining or extending the deployment descriptor of a web application by means of pluggable library jars that contain both the incremental deployment information (in the web-fragment.xml) and potentially any related or relevant classes. The web fragment is also packaged as a library (jar), with the web-fragment.xml in the META-INF directory. Consequently, the web fragment project is essentially a Utility project, with the addition of a web fragment facet to it. The web fragment facet enables you to add relevant context-sensitive functionality to the fragment project.

The stage needs to be set just so.
  1. In the Java EE perspective, select File > New > Web Fragment Project. Alternatively, right-click the Enterprise Explorer context menu, and select New > Web Fragment Project . The Web fragment wizard opens.
  2. In the Name field, type a name for the Web fragment project. To change the default Project contents, click the Browse button to select a new location. If you specify a non-default project location that is already being used by another project, the project creation fails.
  3. The Target runtime field is pre-populated with the selection from the enterprise project.
  4. Optional: Select a pre-defined project configuration from the Configurations drop-down list.
  5. Optional: If you want to modify the configuration details, click modify:
  6. Optional: Select one or more project facets from the Project Facets list. To specify server runtime environments, click Show Runtimes and select one or more runtimes. After making your selections, you can save your custom configuration by clicking Save.
  7. Optional: Select the Add project to Dynamic Web project check box to add the new module to an enterprise module (WAR) project. Type a new project name or select an existing enterprise module project from the drop-down list in the Dynamic Web project name combination box. Or, click New to launch the New EAR module Project wizard.
  8. Select Add project to working sets to add the Web fragment project to an existing working set, or click Select to locate a working set, and click Next.
  9. On the Configure project for building a Java application page, on the Source folders on build path field, click Add Folder... to add folders for your source on the build path, or accept the default value (src).
  10. In the Default output Folder: field, specify a folder for your output files or accept the default value (bin), and click Finish.

How to escaping comma and double quote for CSV file?

We have a solution to escape comma and double quoted characters for CSV file

There are several utilities to escape text for inclusion in a CSV file. One is Apache Commons Lang.

Apache Commons Lang includes a special class to escape a variety of other chains, according to need, StringEscapeUtils.

If you mention you could use something like the following:
It is also possible to invert the way for recover the original string:

posted under | 4 Comments

How to make logging facility in project using AOP in spring

Logging Facility using AOP Spring

 
package com.gea.utility;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect
{
    private Log log = LogFactory.getLog(this.getClass());
    
    //@Pointcut("execution(* *.*(..))")
    @Pointcut("execution(* com.gea..*.*(..))")
    protected void loggingOperation() {}
    
    @Before("loggingOperation()")
    @Order(1)
    public void logJoinPoint(JoinPoint joinPoint)
    {
      log.info("Join point kind : " + joinPoint.getKind());
     log.info("Signature declaring type : "+ joinPoint.getSignature().getDeclaringTypeName());
  log.info("Signature name : " + joinPoint.getSignature().getName());
        log.info("Arguments : " + Arrays.toString(joinPoint.getArgs()));
        log.info("Target class : "+ joinPoint.getTarget().getClass().getName());
        log.info("This class : " + joinPoint.getThis().getClass().getName());
     
     StringBuilder sb = new StringBuilder(joinPoint.getSignature().getDeclaringTypeName());
     sb.append(" -->");
     sb.append(joinPoint.getSignature().getName()+"() Method Start");
     log.info(sb.toString());
    }
        
    @AfterReturning(pointcut="loggingOperation()", returning = "result")
    @Order(2)
    public void logAfter(JoinPoint joinPoint, Object result)
    {
     log.info("Exiting from Method :"+joinPoint.getSignature().getName());
     log.info("Return value :"+result);

     StringBuilder sbLogAfter = new StringBuilder(joinPoint.getSignature().getDeclaringTypeName());
     sbLogAfter.append(" -->");
     sbLogAfter.append(joinPoint.getSignature().getName()+"() Method End");
     log.info(sbLogAfter.toString());
    }
    
    @AfterThrowing(pointcut="execution(* com.gea..*.*(..))", throwing = "e")
   // @AfterThrowing(pointcut="execution(* *.*(..))", throwing = "e")
    @Order(3)
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e)
    {
     log.error("An exception has been thrown in "+ joinPoint.getSignature().getName() + "()");
        log.error("Cause :"+e.getCause());
        
        StringBuilder sbLogAfter = new StringBuilder("An exception has been thrown in "+joinPoint.getSignature().getDeclaringTypeName());
     sbLogAfter.append(" -->");
     sbLogAfter.append(joinPoint.getSignature().getName()+"() Method End");
     log.error(sbLogAfter.toString());
    }
    
//    @Around("execution(* *.*(..))")
    @Around("execution(* com.gea..*.*(..))")
    @Order(4)
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable
    {
  log.info("The method " + joinPoint.getSignature().getName()+ "() begins with " + Arrays.toString(joinPoint.getArgs()));
        try
        {
            Object result = joinPoint.proceed();
            log.info("The method " + joinPoint.getSignature().getName()+ "() ends with " + result);
            return result;
        } catch (Throwable e)
        {
            log.error("Illegal argument "+ Arrays.toString(joinPoint.getArgs()) + " in "+ joinPoint.getSignature().getName() + "()");
            throw e;
        }        
    }
    
}


Note : Above code is usefull for spring annotation based project, We are required only one class to activate logging facility in our system. No need to define logger for all method in our code , when we entered into method and goes out from the method.

Following changes would required to implement logging facility in spring project.

File Name : spring-servlet.xml
   
   
   
   

Following two library must be avaiable in your class path with it's dependant library.
  1. spring-aop-3.2.3.RELEASE.jar
  2. spring-aspects-3.2.3.RELEASE.jar
How it's work ? 








 

View Facebook API Code

Before going to proceed further, following liberary must be available in your class path,
  • activation-1.1.jar
  • commons-lang-2.2.jar
  • commons-logging-1.1.1.jar
  • facebook-java-api-3.0.2.jar
  • facebook-java-api-annotation-processor-3.0.2.jar
  • facebook-java-api-schema-3.0.2.jar
  • jaxb-api-2.1.jar
  • jaxb-impl-2.1.9.jar
  • json-20080701.jar
  • restfb-1.6.12.jar
  • runtime-0.4.1.5.jar
  • stax-api-1.0-2.jar
We are using following two API to communicate with Facebook.
  1. Facebook API
  2. RestFB API
Create logging.properties file under src directory in your project. 

logging.properties 
create new servlet file which handles incoming and outgoing request from our application. We required only file to handle all the request. No need to worry about rest of the thing right now, just enjoy programming to integrate Facebook API. 

MainServlet.java  As you can see from the code, when the servlet called first time at that time code was null so it comes under the else part and redirect to facebook to validate their credential. 

once facebook gets approved it will return back with either code or token, depend upon our configuration.We have provided redirect_uri parameter to facebook to indicate that response came from facebook will be proceed by this servlet. 

in our case both servlet are same. Means we are using the same servlet to send a request to facebook and proceed response from facebook. Once we received code/token, one can send a request to get an access token of your application, Access token play very important role for communicating. 

Note : I have changed my API_KEY & SECRET_KEY so you can changed with yours. If you don't know how to get API & Secret key then visit this post Steps to FBI API. Before going to start with Facebook integration, Please refer documentation first that would be easy to understand code as well as flow.

posted under , | 1 Comments

Step by Step guide to integrate Facebook API using java

In this section, I will provide you step by step guide to integrate Facebook API using java. It would be very easy to implement Facebook API  but for that we need to follow certain steps in proper sequence.

Step 1  :  Create account on Facebook website. http://facebook.com/
Step 2  :  Login into your account on Facebook.
Step 3  :  Now go to following URL : https://developers.facebook.com
Step 4  :  You will find app tab in top menu, click to continue or directly go to following URL https://developers.facebook.com/apps  
Step 5  :  Now click on create new App.
Step 6  : This will open new model dialog box and ask you for app name. Please provide unique application name. skip rest of the details and click on continue.
Step 7  : This will redirect you to show list of registered application now click on edit settings. This page is very very important because it provides your application id (app-id) as well as application secret(app secret). Copy both app-id and app-secret to another file and save it. both credentials are required to communicate with Facebook API.
Now go under following section: Select how your app integrates with Facebook
and select Website with Facebook Login and provide Site URL path to your local web application path (in my case)  like :  http://localhost:8084/FBAPI
and make sure that you have enabled sandbox mode and save changes. 
That's it . There are many other settings but they are optional, you can set them as per your requirement. 
Step 8 : Now last and final step to set Facebook API to work. Getting an access token. Access token perform very important role while communicating with Facebook API. Without an access taken, it was not possible to get any information from Facebook API. These is a only step where people gets confused where to get an access token of our application. Don't worry I have provided steps to get an access token of your application.
Step 9 : Go to https://developers.facebook.com/tools/explorer
Facebook provide very powerful utility to get an access token of your application and provide a very dynamic feature to access Graph API on the fly.
We will discuss it later on. Now when you open above link you will find your list of application in selection box. Now select proper application if you have more then one application in your account otherwise no need to select any application. once you select application, now click on Get Access Token button to continue.
These will open new pop up box to select list of permission your application will be required from user to access their private data.
select permission details as per your requirement and finish it.
You will see your generated token inside the text box.
Note : Always keep in mind that if you change your permission, you request token gets changes accordingly so after every modification in permission you will get new access token. Access token plays very important role to communicate with Facebook, we have to send access token as parameter on each request.

  


posted under , | 1 Comments

How to create system notification popup like outlook using Swing in java

It would be very easy to make system notification pop up like Microsoft outlook in swing.

I have created following two java classes to make system notification works. First class handled the basic and core level implementation like creating a form and making AWT api to work. Second class is used for testing purpose. 

1. NotificationPopup.java 
package com.vsquaresolution.system.nofitifcation;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.LinearGradientPaint;
import java.awt.Toolkit;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class NotificationPopup extends JDialog {
  private final LinearGradientPaint lpg;

  public NotificationPopup() {
    setUndecorated(true);
    setSize(300, 50);
    // size of the screen
    final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

    // height of the task bar
    final Insets scnMax = Toolkit.getDefaultToolkit().getScreenInsets(getGraphicsConfiguration());
    final int taskBarSize = scnMax.bottom;

    setLocation(screenSize.width - getWidth(), screenSize.height - taskBarSize  - getHeight());

    // background paint
    lpg = new LinearGradientPaint(0, 0, 0, getHeight() / 2, 
 new float[] { 0f, 0.3f, 1f }, new Color[] 
 { new Color(1f, 1f, 1f), new Color(1f, 1f, 1f), 
  new Color(1f, 1f, 1f) });

    // blue background panel
    setContentPane(new BackgroundPanel());
  }

  private class BackgroundPanel extends JPanel {
    public BackgroundPanel() {
      setOpaque(true);
    }

    @Override
    protected void paintComponent(final Graphics g) {
      final Graphics2D g2d = (Graphics2D) g;
      // background
      g2d.setPaint(lpg);
      g2d.fillRect(1, 1, getWidth() - 2, getHeight() - 2);
      g2d.setColor(Color.ORANGE); //border color

      // border
      g2d.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
    }
  }

  public static void main(final String[] args) {

    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (final Exception e1) {
          e1.printStackTrace();
        }

        final NotificationPopup f = new NotificationPopup();

        final Container c = f.getContentPane();
        c.setLayout(new GridBagLayout());

        final GridBagConstraints constraints = new GridBagConstraints();
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.weightx = 1.0f;
        constraints.weighty = 1.0f;
        constraints.insets = new Insets(5, 5, 5, 5);
        constraints.fill = GridBagConstraints.BOTH;

        final JLabel l = new JLabel("You have got 2 new Messages.");
        l.setOpaque(false);

        c.add(l, constraints);

        constraints.gridx++;
        constraints.weightx = 0f;
        constraints.weighty = 0f;
        constraints.fill = GridBagConstraints.NONE;
        constraints.anchor = GridBagConstraints.NORTH;

//        final JButton b = new JButton(new AbstractAction("x") {
//
//          @Override
//          public void actionPerformed(final ActionEvent e) {
//            f.dispose();
//          }
//        });

//        b.setOpaque(false);
//        b.setMargin(new Insets(1, 4, 1, 4));
//        b.setFocusable(false);
//
//        c.add(b, constraints);

        f.setVisible(true);
      }
    });
  }
}
2. TestNotificationPopUp.java
package com.vsquaresolution.system.nofitifcation;

import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class TestNotificationPopUp extends javax.swing.JFrame {
    
    public TestNotificationPopUp() {
        initComponents();
        
    }
    
    // //GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Antenna");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(" System "));

        jButton5.setText("Open Notification");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
                .add(182, 182, 182)
                .add(jButton5)
                .add(256, 256, 256))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(28, 28, 28)
                .add(jButton5)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(29, Short.MAX_VALUE))
        );

        pack();
    }// //GEN-END:initComponents

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed

       SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            try {
              UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (final Exception e1) {
              e1.printStackTrace();
            }

            final NotificationPopup f = new NotificationPopup();

            final Container c = f.getContentPane();
            c.setLayout(new GridBagLayout());

            final GridBagConstraints constraints = new GridBagConstraints();
            constraints.gridx = 0;
            constraints.gridy = 0;
            constraints.weightx = 1.0f;
            constraints.weighty = 1.0f;
            constraints.insets = new Insets(5, 5, 5, 5);
            constraints.fill = GridBagConstraints.BOTH;

            final JLabel l = new JLabel("You have got 2 new Messages.");
            l.setOpaque(false);

            c.add(l, constraints);

            constraints.gridx++;
            constraints.weightx = 0f;
            constraints.weighty = 0f;
            constraints.fill = GridBagConstraints.NONE;
            constraints.anchor = GridBagConstraints.NORTH;

            f.setVisible(true);
          }
        });

    }//GEN-LAST:event_jButton5ActionPerformed
    
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TestNotificationPopUp().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton5;
    private javax.swing.JPanel jPanel2;
    // End of variables declaration//GEN-END:variables
    
}

posted under , | 3 Comments
Older Posts Home

Followers

Powered by Blogger.

Populares

Custom Search