Sunday, December 1, 2013

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

Tuesday, November 26, 2013

Dynamic processing of Query using JDBC on blur


STEP -1

1. make input type like below which will call function loadXMLDoc on blur and will pass three arguements
a) url of jsp file where query will be executed by jsp i.e. "Views/Query/cancelQuery.jsp"
b)id(parameter for query)  i.e. "fid" used here
c) id of that part where to load the data(result). i.e. "err" used here
 ______________________________________________________________________
<input type="text" name="fid" onblur='if(this.length.value!=0){loadXMLDoc("Views/Query/cancelQuery.jsp","fid","err")}' id="fid"/>

<span id="err"></span></td>
_______________________________________________________________________


STEP -2

Add this script on top of page.
it receives the parameter and makes an ajax call (Ex- var urls = passedurl+"?ver=" + k;)  by combining url and parameter and gets the result and as per result process it. and feed result in required element.
_____________________________________________________________________
<script>
function loadXMLDoc(passedurl,id,loadingId) {
            var xmlhttp;
            var k = document.getElementById(id).value;
            var urls = passedurl+"?ver=" + k;

            if (window.XMLHttpRequest) {
                  xmlhttp = new XMLHttpRequest();
            } else {
                  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function() {
                  if (xmlhttp.readyState == 4) {
                        var result = xmlhttp.responseText;
                       
                        if(result==0){
                       
                            result="<br/><br/>&nbsp;&nbsp;&nbsp;<font color=red>FlightID: "+document.getElementById(id).value+" is not Available ..!!</font>";
                            document.getElementById(id).value="";   
                        }
                        else{
                       
                            result="<br/><br/>&nbsp;&nbsp;&nbsp;<font color=green>Flight is Available in Database</font>";                     
                        }
                        document.getElementById(loadingId).innerHTML=result;  
                  }
            };
            xmlhttp.open("GET", urls, true);
            xmlhttp.send();
      }
</script>
 _______________________________________________________________________

STEP -3

URL of JSP called by AJAX for executing the query using parameter.
 ______________________________________________________________________
<%@ page import="java.io.*,java.sql.*" %>
<%@ page contentType="text/html" pageEncoding="UTF-8"%>

<%
            String sn=request.getParameter("ver");

                    Class.forName("com.mysql.jdbc.Driver");
                    Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/travportal","root","tiger");
                    Statement st=con.createStatement();
                    ResultSet rs = st.executeQuery("select fid from flight where fid="+sn);  // this is for name
                    if(rs.next())
                    {  
                         out.println("<font color=green>");
                         out.println("Flight is Availabe in Database");
                         out.println("</font>");
                    }else {
                         out.println("<font color=red>");
                         out.println("Flight is not Available in the Database");
                         out.println("</font>");
                    }
rs.close();
st.close();
con.close();
%>
 ______________________________________________________________________

Same thing can be done for called action files in STRUTS also.

Thursday, November 7, 2013

How to increase permSize of Tomcat

1. Double click on Tomcat Server icon and above overview will come
2. Go to Open Lauch Configuration then arguement option



3.  paste below properties.

-XX:MaxPermSize=512m
-XX:+UseConcMarkSweepGC -XX:+CMSPermGenSweepingEnabled -XX:+CMSClassUnloadingEnabled

Monday, October 21, 2013

CustomDao

package com.impetus.travelportal.daoimpl;

import java.io.Serializable;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import com.impetus.travelportal.models.Passenger;
import com.impetus.travelportal.util.HibernateUtil;

public class CustomDao {

    Session session = HibernateUtil.getSessionFactory().openSession();

    @SuppressWarnings("unchecked")
    public <E> E getUniqueResult(String hql, E obj, boolean commit) {
        try {
            if (!session.getTransaction().isActive()) {
                session.beginTransaction();
            } else {
                session.getTransaction();
            }
            obj = (E) session.createQuery(hql).uniqueResult();
        } catch (HibernateException e) {
            session.getTransaction().rollback();
            return null;
        }
        if (commit) {
            session.getTransaction().commit();
        }
        return obj;
    }

    @SuppressWarnings("unchecked")
    public <E> E getResultList(String hql, E objList, boolean commit) {
        try {
            if (!session.getTransaction().isActive()) {
                session.beginTransaction();
            } else {
                session.getTransaction();
            }

            objList = (E) session.createQuery(hql).list();
        } catch (HibernateException e) {

            session.getTransaction().rollback();
            return null;
        }
        if (commit) {
            session.getTransaction().commit();
        }
        return objList;
    }

    public <E> E add(E object, boolean commit) {
        if (!session.getTransaction().isActive()) {
            session.beginTransaction();
        }
        try {
            session.save(object);
            if (commit) {
                session.getTransaction().commit();
            }
        } catch (HibernateException e) {

            session.getTransaction().rollback();
        }
        return object;
    }

    public <E> E delete(E obj, boolean commit) {
        try {
            if (!session.getTransaction().isActive()) {
                session.beginTransaction();
            }

            session.delete(obj);
        } catch (HibernateException e) {

            session.getTransaction().rollback();
        }
        if (commit) {
            session.getTransaction().commit();
        }

        return obj;
    }

    public <E> E update(E obj, boolean commit) {
        try {
            if (!session.getTransaction().isActive()) {
                session.beginTransaction();
            }
            session.saveOrUpdate(obj);
            if (commit) {
                session.getTransaction().commit();
            }
            return obj;
        } catch (HibernateException e) {
            session.getTransaction().rollback();
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public String updateQuery(String hql, boolean commit) {
        try {
            if (!session.getTransaction().isActive()) {
                session.beginTransaction();
            } else {
                session.getTransaction();
            }
            session.createQuery(hql).executeUpdate();
        } catch (HibernateException e) {
            session.getTransaction().rollback();
            return null;
        }
        if (commit) {
            session.getTransaction().commit();
        }
        return "updated";
    }
}


Friday, September 13, 2013

PDF generator program using iText

Maven dependency
_______________________
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.0.6</version>
        </dependency>
________________________

Make a class and Run it Output will be saved in Given path i.e. D:-> Test.pdf
__________________
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class GeneratePdf {

    public static void main(String[] args) {
        try {
            OutputStream file = new FileOutputStream(new File("D:\\Test.pdf"));

            Document document = new Document();
            PdfWriter.getInstance(document, file);

            document.open();
            document.add(new Paragraph("Hello World, iText"));
            document.add(new Paragraph(new Date().toString()));

            document.close();
            file.close();

        } catch (Exception e) {

            e.printStackTrace();
        }
    }
}

Scheduler Program Using Quartz

Maven Dependencies
__________________________
<dependency>
            <groupId>opensymphony</groupId>
            <artifactId>quartz</artifactId>
            <version>1.6.3</version>
        </dependency>

        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.directory.studio</groupId>
            <artifactId>org.apache.commons.logging</artifactId>
            <version>1.1.1</version>
        </dependency>
_______________________________

Make Two Classes : 1. HelloJob.java 2. SimpleTriggerExample.java

1. Hello.java
__________________________
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class HelloJob implements Job
{
    public void execute(JobExecutionContext context)
    throws JobExecutionException {

        System.out.println("Hello Quartz!");   

    }

}
______________________________
2. SimpleTriggerExample.java
______________________________
import java.util.Date;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;

public class SimpleTriggerExample
{
    public static void main( String[] args ) throws Exception
    {
           JobDetail job = new JobDetail();
        job.setName("dummyJobName");
        job.setJobClass(HelloJob.class);

        //configure the scheduler time
        SimpleTrigger trigger = new SimpleTrigger();
        trigger.setName("mytrigger");
        trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
        trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
        trigger.setRepeatInterval(3000);

        //schedule it
        Scheduler scheduler = new StdSchedulerFactory().getScheduler();
        scheduler.start();
        scheduler.scheduleJob(job, trigger);
    }
}
______________
save both and Run SimpleTriggerExample
it will repeat the job at interval of 3 second.