Spring Exception Handling Example

Spring Exception Handling Example

The following example show how to write a simple web based application using Spring MVC Framwork, which can handle one or more exceptions raised inside its controllers. To start with it, let us have working Eclipse IDE in place and follow the following steps to develope a Dynamic Form based Web Application using Spring Web Framework:

Step 1: Create a Dynamic Web Project with a name SpringException and create following 3 new folder under src folder in the created project
1. Controller
2. Service
3. Dao

Step 2: Copy Spring and other project specific libraries into the folder WebContent/WEB-INF/lib

Step 3 : Now create below packages in specific folder 
1. In Controller folder create package : com.gea.controller  
2. In Service folder create package : com.gea.services  
3. In Dao folder create package : com.gea.dao  

Step 4:  Create Spring configuration files Web.xml and spring-servlet.xml under the WebContent/WEB-INF folder.
 
Step 5: Create a sub-folder with a name jsp under the WebContent/WEB-INF folder. Create a view files 404error.jsp,errro.jsp,ExceptionPage.jsp,index.jsp,viewForm.jsp.

Step 6: Now Follow below steps and run program in your browser.

WelcomeController.java


SpringException.java
WelcomeServices.java

posted under , | 0 Comments

Spring MVC Fast Tutorial: Hello World

How Spring MVC works

Basically the same way as Struts: 

 

  •  Based on the HTTP request URL, the DispatcherServlet calls the corresponding Controller.
  • A View is rendered and sent as HTTP response.

Spring Servlet Declaration

In 'WEB-INF/web.xml', we declare Spring DispatcherServlet and map '*.html' URLs to it:

 
  
    springmvc
    org.springframework.web.servlet.DispatcherServlet
    1
  
 
  
    springmvc
    *.html
  
 
  
    
      jsp/index.jsp
    
  
 

Spring Servlet Configuration

Let's now create the Spring configuration file 'WEB-INF/springmvc-servlet.xml' (name based on the servlet name above):

 
  
 
  
      
      
      
  
 

Map URL /hello_world.html to Controller HelloWorldController Declare View Resolver: when view 'view_name' is called (from the Controller), the file '/jsp/view_name.jsp' will be used.

Controller

Let's create the Controller 'WEB-INF/src/springmvc/web/HelloWorldController.java':
package springmvc.web;
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
 
public class HelloWorldController implements Controller {
 
 public ModelAndView handleRequest(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
 
  String aMessage = "Hello World MVC!";
 
  ModelAndView modelAndView = new ModelAndView("hello_world");
  modelAndView.addObject("message", aMessage);
 
  return modelAndView;
 }
}
This Controller calls the view 'hello_world', passing 'message' to it (like a Struts attribute).

View

Displays the message attribute previously set in the Controller.

Make it work

 

 

http://localhost:8180/springmvc/hello_world.html

  • We declared Spring servlet in web.xml 
  • We created a Spring configuration file where we mapped an URL to a controller and defined a way to resolve views. 
  • We created a controller and a view

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

Only allow number in textfield using javascript

JavaScript function that allow only number in text field

function onlyIntegerNumber(evt){
  var e = evt; // for trans-browser compatibility
  var charCode = e.which || e.keyCode;
  if(charCode == 9){
    return true;
  }
  if((charCode >=35 && charCode <38) || charCode ==39 || e.which ==0){
   alert("Please enter only digit (0-9)");
   return false;
  }
  
  if ((charCode > 31) && (charCode < 48 || charCode > 57) ){
          alert('Please enter only digit (0-9)');
         return false;
   }else{
    return true;
   }
}

function isNumberKey(evt){
    var e = evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;
    
    if(charCode == 46 || charCode == 9){
     return true;
    }
    if((charCode >=35 && charCode <38) || charCode ==39 || e.which ==0){
     alert("Allow only numeric characters (0-9 or .)");
        return false;
    }
    if ((charCode > 31) && (charCode < 48 || charCode > 57) ){
       noty(options);
           return false;
     }else{
    return true;
     }
}

posted under | 0 Comments
Newer Posts Older Posts Home

Followers

Powered by Blogger.

Populares

Custom Search