Sunday, December 1, 2013

Hibernate Util

package com.impetus.smarttravelportal.dao.impl;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * @author premkumar.bharti HibernateUtil creates sessions for daolayer
 */
@SuppressWarnings("all")
public final class HibernateUtil {
    private static SessionFactory sessionFactory = null;
   
    /**
     * creates a session with the database.
     *
     * @return session factory object.
     */
    @SuppressWarnings("deprecation")
    private static SessionFactory buildSessionFactory() {
       
        if (sessionFactory == null) {
            try {
               
                if (sessionFactory == null) {
                    sessionFactory = new AnnotationConfiguration().configure()
                            .buildSessionFactory();
                } else {
                    return sessionFactory;
                }
            } catch (Exception ex) {
               
                throw new ExceptionInInitializerError(ex);
            }
        }
        return sessionFactory;
    }
   
    /**
     * return SessionFactory to get new Session out of it
     *
     * @return SessionFactory
     */
    public static SessionFactory getSessionFactory() {
        return buildSessionFactory();
    }
   
    private HibernateUtil() {
       
    }
}

Logging Interceptor

import org.sonar.report.pdf.util.Logger;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * @author premkumar.bharti Logging Interceptor handles logging.
 */
public class LoggingInterceptor implements Interceptor {
   
    private static final long serialVersionUID = 1L;
   
    /**
     * Interceptor acts when Action Class starts and exists
     */
    public String intercept(ActionInvocation invocation) {
        String result = null;
       
        @SuppressWarnings("unused")
        String className = invocation.getAction().getClass().getName();
        try {
            result = invocation.invoke();
        } catch (Exception ex) {
            return null;
        }
        return result;
    }
   
    /**
     * called at destruction of Action
     */
    public void destroy() {
        Logger.info("Destroyed-----------");
       
    }
   
    /**
     * called at initialisation of Action
     */
    public void init() {
        Logger.info("Initialised-----------");
       
    }
}

Date Converter Util

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author premkumar.bharti DateUtil mainly handle date operation like
 *         converting from one form to another.
 */
public final class DateUtil {
    /**
     * private Constructor
     */
    private DateUtil() {
    }
   
    /**
     * converts date to format yyyy/mm/dd.
     *
     * @param date
     * @return
     * @throws ParseException
     */
    public static Date dateConvertor(String date, String format)
            throws ParseException {
       
        DateFormat parser = new SimpleDateFormat(format);
        return parser.parse(date);
    }
   
    /**
     * adds date with the number of days present
     *
     * @param date
     * @param days
     * @return
     */
    @SuppressWarnings("static-access")
    public static String myAddDate(Date date, int days) throws ParseException {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(cal.DATE, Const.THREE);
        String fdate = cal.get(Calendar.DATE) + "/"
                + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
        return fdate;
    }  
}

Password and Retype Password check

1. pwd => first password field id
2. rpassword => retype password field id
3. notmatch=> where info will be displayed id


function check() {
var pwd = document.getElementById("pwd").value;
var rpassword = document.getElementById("rpassword").value;
if (pwd == rpassword) {
document.getElementById("notmatch").innerHTML = "";
} else {
document.getElementById("rpassword").value = "";
document.getElementById("notmatch").innerHTML = "Password don't match";
}
}

Ajax Form Submit

1. ('#register') => Form's id
2. $('#advert') => where response has to load

<script>
$('#register').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data : $(this).serialize(), // get the form data
type : $(this).attr('method'), // GET or POST
url : $(this).attr('action'), // the file to call
success : function(response) { // on success..
$('#advert').load('Views/userAdded.jsp'); }
});
return false; // cancel original event to prevent form submitting
});
</script>

Date Picker (Past date disabled)

Add jquery and jquery ui src in top
and paste this. and put id datepicker in input type where to show date



<script>
$(function() {
$("#datepicker").datepicker({
minDate : "0d",
maxDate : "+3M",
dateFormat : 'dd/mm/yy',
showAnim:'slide'
});
});
</script>

Favicon

add this in the head tag


<!-- Add favicon -->
<link rel="icon" type="image/ico" href="Views/images/favicon.ico"></link>
<link rel="shortcut icon" href="Views/images/favicon.ico"></link>
<!-- -- -->

MD5 encryption and Captcha

import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;

public class CommonUtil {

/**
* does MD5 encryption for password
* @param text
* @return
*/
    public static String getMD5(String text) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            byte[] array = md.digest(text.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
                        .substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
        }
        return null;
    }
   
    /**
     * Creates random Captcha as per given filepath and image format
     * @param filePath
     * @param ext
     * @throws IOException
     */
    public void writeCaptcha(String filePath,String ext) throws IOException {
int width = 150;
int height = 50;
Random r = new Random();
String var = "";
for (int i = 0; i < 6; i++) {
char ran = (char) Math.abs(65 + Math.abs(r.nextInt() % 25));
var += ran;
}
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);

Graphics2D g2d = bufferedImage.createGraphics();

Font font = new Font("Georgia", Font.BOLD, 18);
g2d.setFont(font);

RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);

rh.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);

g2d.setRenderingHints(rh);

GradientPaint gp = new GradientPaint(0, 0, Color.red, 0, height / 2,
Color.black, true);

g2d.setPaint(gp);
g2d.fillRect(0, 0, width, height);

g2d.setColor(new Color(255, 153, 0));
int x = 0;
int y = 0;

for (int i = 0; i < var.length(); i++) {
x += 10 + (Math.abs(r.nextInt()) % 15);
y = 20 + Math.abs(r.nextInt()) % 20;
g2d.drawChars(var.toCharArray(), i, 1, x, y);
}

g2d.dispose();
File file = new File(filePath);
ImageIO.write(bufferedImage, ext, file);
}
}