Saturday, May 7, 2011

Ajax Programming setup instructions


Ajax Programming :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
 </HEAD>
<script type="text/javascript" language="javascript">
  // function to create an XMLHttpClient in a cross-browser manner
  function getAJAXRequest() {
      var xmlhttp=null;;  
      try {
          // Mozilla / Safari / IE7
          xmlhttp = new XMLHttpRequest();
      } catch (e) {
           // IE
           var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0',
                                     'MSXML2.XMLHTTP.4.0',
                                     'MSXML2.XMLHTTP.3.0',
                                     'MSXML2.XMLHTTP',
                                     'Microsoft.XMLHTTP' );
          var success = false;
          for (var i=0;i < XMLHTTP_IDS.length && !success; i++) {
              try {
                   xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);
                   success = true;
                   break;
                } catch (e) {}
          }
          if (!success) {
              return null;
          }
     }
     return xmlhttp;
 }

 function loadAjaxCall(){
   
    var http_request=getAJAXRequest();
    //open(method,url,async)    
    //Specifies the type of request, the URL, and if the request should be handled asynchronously or not.
    //method: the type of request: GET or POST
    //url: the location of the file on the server
    //async: true (asynchronous) or false (synchronous)

    var parameters="one="+FristVal+"&sec="+SecVal;

    //Note: When you use async=false, do NOT write an onreadystatechange function - just put the code after the send() statement:
    //Note: When using async=true, specify a function to execute when the response is ready in the onreadystatechange event:

    http_request.open('POST', "/projectName/SomeAction.do", false);
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http_request.setRequestHeader("Content-length", parameters.length);
    http_request.setRequestHeader("Connection", "close");
    http_request.send(parameters);
   
    // here the state is synch
    // getting the response as responseText or responseXML
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

    /*
     * Suppose if Asynch we are have to set the readyState
        // here the response is in ready state
         xmlhttp.onreadystatechange=function()
             {
                 if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                         document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
                     }
            }
     *
     */
// onreadystatechange     Stores a function (or the name of a function) to be called automatically each time the readyState property changes
//readyState :-
//Holds the status of the XMLHttpRequest. Changes from 0 to 4:

//0: request not initialized
//1: server connection established
//2: request received
//3: processing request
//4: request finished and response is ready

//status:-
//200: "OK"
//404: Page not found

 }

</script>

 <BODY>
   
 </BODY>
</HTML>

Captcha Programming

Captcha Programming in Java



package com.jit;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Vinay Guntaka
 * Servlet implementation class CaptchaServlet
 */
public class CaptchaServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
     
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CaptchaServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        createCatcha(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        createCatcha(request, response);
    }
    @SuppressWarnings("unchecked")
    protected void createCatcha(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {

        response.setContentType("image/jpg");

         try {
            Color textColor = Color.white;
            Font textFont = new Font("Georgia", Font.PLAIN, 18);
            int charsToPrint = 6;
            int width = 125;
            int height = 28;
            float horizMargin = 20.0f;
            float imageQuality = 0.95f; // max is 1.0 (this is for jpeg)
            double rotationRange = 0.7; // this is radians
            BufferedImage bufferedImage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);

            Graphics2D g = (Graphics2D) bufferedImage.getGraphics();

            // Draw an oval
            g.setColor(new Color(255, 153, 0));
            g.fillRect(0, 0, width, height);
            g.setColor(textColor);
            g.setFont(textFont);

            FontMetrics fontMetrics = g.getFontMetrics();
            int maxAdvance = fontMetrics.getMaxAdvance();
            int fontHeight = fontMetrics.getHeight();

            // i removed 1 and l and i because there are confusing to users...
            // Z, z, and N also get confusing when rotated
            // 0, O, and o are also confusing...
            // lowercase G looks a lot like a 9 so i killed it
            // this should ideally be done for every language...
            // i like controlling the characters though because it helps prevent
            // confusion
            String elegibleChars = "ABCDEFGHJKLMPQRSTUVWXYabcdefhjkmnpqrstuvwxy23456789";
            char[] chars = elegibleChars.toCharArray();

            float spaceForLetters = -horizMargin * 2 + width;
            float spacePerChar = spaceForLetters / (charsToPrint - 1.0f);
            StringBuffer finalString = new StringBuffer();

            for (int i = 0; i < charsToPrint; i++) {
                double randomValue = Math.random();
                int randomIndex = (int) Math.round(randomValue*(chars.length - 1));
                char characterToShow = chars[randomIndex];
                finalString.append(characterToShow);
                int charWidth = fontMetrics.charWidth(characterToShow);
                int charDim = Math.max(maxAdvance, fontHeight);
                int halfCharDim = (int) (charDim / 2);

                BufferedImage charImage = new BufferedImage(charDim, charDim,BufferedImage.TYPE_INT_ARGB);
                Graphics2D charGraphics = charImage.createGraphics();
                charGraphics.translate(halfCharDim, halfCharDim);
                double angle = (Math.random() - 0.5) * rotationRange;
                charGraphics.transform(AffineTransform.getRotateInstance(angle));
                charGraphics.translate(-halfCharDim, -halfCharDim);
                charGraphics.setColor(textColor);
                charGraphics.setFont(textFont);

                int charX = (int) (0.5 * charDim - 0.5 * charWidth);
                charGraphics.drawString("" + characterToShow,charX,
                                (int) ((charDim - fontMetrics.getAscent()) / 2 + fontMetrics
                                        .getAscent()));

                float x = horizMargin + spacePerChar * (i) - charDim / 2.0f;
                int y = (int) ((height - charDim) / 2);
                g.drawImage(charImage, (int) x, y, charDim, charDim,null, null);

                charGraphics.dispose();
            }

            // Write the image as a jpg
            Iterator iter = ImageIO.getImageWritersByFormatName("JPG");
            if (iter.hasNext()) {
                ImageWriter writer = (ImageWriter) iter.next();
                ImageWriteParam iwp = writer.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality(imageQuality);
                writer.setOutput(ImageIO.createImageOutputStream(response.getOutputStream()));
                IIOImage imageIO = new IIOImage(bufferedImage, null, null);
                writer.write(null, imageIO, iwp);
            } else {
                throw new RuntimeException("no encoder found for jsp");
            }

            // let's stick the final string in the session
            request.getSession().setAttribute("captcha", finalString.toString());
            g.dispose();

        } catch (IOException ioe) {
            throw new RuntimeException("Unable to build image", ioe);
        }

    }

}

----------------------------------
Captcha.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Captcha</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<center>
<form method="post">
<table cellspacing="15">
<tr>
<td>Are you human?</td>
<td><input type="text" name="code"></td>
</tr>

</table>

<br>
<img src="CaptchaServlet">

<br><br>
<input type="submit" value="submit">

</form>
<br><br>
<%
  String captcha = (String) session.getAttribute("captcha");
  String code = (String) request.getParameter("code");

  if (captcha != null && code != null) {

      System.out.println("Captcha Code:"+captcha);
      System.out.println("Code:"+code);

    if (captcha.equals(code)) {
      out.print("<p class='alert'>Correct</p>");
    } else {
          out.print("<p class='alert'>Incorrect</p>");
    }
  }
%>
</center>
</body>
</html>

--------------------------------
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Captcha</display-name>
  <welcome-file-list>
    <welcome-file>captcha.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>CaptchaServlet</display-name>
    <servlet-name>CaptchaServlet</servlet-name>
    <servlet-class>com.jit.CaptchaServlet</servlet-class>;
  </servlet>
  <servlet-mapping>
    <servlet-name>CaptchaServlet</servlet-name>
    <url-pattern>/CaptchaServlet</url-pattern>
  </servlet-mapping>
</web-app>



Saturday, April 23, 2011

Configure JNDI Connection Pooling:

Configure JNDI Connection Pooling:

For establishing the connection pool i have created a dynamic web-project with SampleConn, with MySql Database and loggers. So, make sure we have the mysql.jar in tomcat working lib directory and log4j.jar in your project library.

Here i am listing out the steps to follow:

------------------------------------------------------------------------------------------
Step 1) Configure web.xml file

Here i am invoking a servlet on startup of server (GetConnPool)

---------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SampleConn</display-name>
  <resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/JIT</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>
  <servlet>
    <servlet-name>Connection</servlet-name>
    <servlet-class>com.jit.servlets.GetConnPool</servlet-class>;
    <load-on-startup>1</load-on-startup>
  </servlet>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
----------------------------------------------------------------

Step 2) Create a context.xml in META-INF of your Project

-----------------------------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>

<Context privileged="true" antiResourceLocking="false"
    antiJARLocking="false" debug="1" reloadable="true" path="">
   
     <!-- maxActive: Maximum number of dB connections in pool. Make sure you
         configure your mysqld max_connections large enough to handle
         all of your db connections. Set to -1 for no limit.
         -->

    <!-- maxIdle: Maximum number of idle dB connections to retain in pool.
         Set to -1 for no limit.  See also the DBCP documentation on this
         and the minEvictableIdleTimeMillis configuration parameter.
         -->

    <!-- maxWait: Maximum time to wait for a dB connection to become available
         in ms, in this example 10 seconds. An Exception is thrown if
         this timeout is exceeded.  Set to -1 to wait indefinitely.
         -->

    <!-- username and password: MySQL dB username and password for dB connections  -->

    <!-- driverClassName: Class name for the old mm.mysql JDBC driver is
         org.gjt.mm.mysql.Driver - we recommend using Connector/J though.
         Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver.
         -->
   
    <!-- url: The JDBC connection url for connecting to your MySQL dB.
         -->
   
   
    <Resource name="jdbc/JIT" auth="Container" type="javax.sql.DataSource"
         username="root"
         password="root" maxActive="-1" maxIdle="-1" maxWait="-1"
         driverClassName="com.mysql.jdbc.Driver"
         url="jdbc:mysql://localhost:3306/sample?autoReconnect=true"
         />
   
</Context>

--------------------------------------------------------------------

Step 3) Configure your log4j.properties file in your project source directory

--------------------------------------------------------------------

# Set root category priority to INFO and its only appender to CONSOLE.
log4j.rootCategory=DEBUG, CONSOLE
#log4j.rootCategory=INFO, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=DEBUG
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%d{dd MMM yyyy HH:mm:ss}] %l - %m%n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.Threshold=DEBUG
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=[%d{dd MMM yyyy HH:mm:ss}] %l - %m%n

log4j.logger.org.apache.commons.digester.Digester=info


--------------------------------------------------------------------
Step 4)  GetConnPool.java
Here in the init() i am invoking & closing the connection

---------------------------------------------------------------------
package com.jit.servlets;
/**
 * @author Vinay Guntaka
 */
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jit.connections.ConnectionUtil;

/**
 * Servlet implementation class GetConnPool
 */
public class GetConnPool extends HttpServlet {
    private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetConnPool() {
        super();
        // TODO Auto-generated constructor stub
    }
     @Override
    public void init() throws ServletException {
        // TODO Auto-generated method stub
        super.init();
       
        ConnectionUtil.closeConnection(ConnectionUtil.getConnection());
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

------------------------------------------------
Step 5) ConnectionUtil.Java

This is the main program that we are fetching the JNDI Connection Pool Object
------------------------------------------------
package com.jit.connections;
/**
 * @author Vinay Guntaka
 */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

public class ConnectionUtil
{
    //Initlizing the Logger
    private static final Logger logger = Logger.getLogger(ConnectionUtil.class);
   
    public static Connection getConnection() {
        Connection conn = null;
        try {
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            DataSource ds = (DataSource) envCtx.lookup("jdbc/JIT");
            conn = ds.getConnection();
            if (conn != null) {
                logger.info("Successfully Obtained Connection From ConnectionPool");
            }
            return conn;
        } catch (SQLException se) {
            logger.error(se.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return conn;
    }
    public static Connection closeConnection(Connection conn){
        try {
            if(conn != null){
                conn.close();
                conn = null;
                logger.info("Successfully Closed Connection From ConnectionPool");
               
            }
        } catch (SQLException se) {
            logger.error(se.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return conn;
    }

   
}
----------------------------------------------------------------------




Monday, April 18, 2011

Retrieving multiple result sets from a stored procedure in a JDBC application

Hello,

Retrieving multiple result sets and OUT Parameters by passing IN Parameter from a stored procedure in a JDBC application.

Connection File:


package com.jit;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
 * @author Vinay Guntaka
 * Retrieving multiple result sets from a stored procedure in a JDBC application
 * All Connections are Configured in this Class
 */
public class ConnectionUtil {
  

    public static Connection closeConnection(Connection conn){
        try {
            if(conn != null){
                conn.close();
                conn = null;
            }
        } catch (SQLException se) {
            System.out.println(se.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return conn;
    }

    public static CallableStatement closeCallableStatement(CallableStatement clst){
        try{
            if(clst !=null){
                clst.close();
                clst = null;
            }
            }catch (SQLException e) {
                System.err.println(e.getMessage());
            }
            return clst;
        }
      
  

    public static ResultSet closeResultSet(ResultSet resultSet){
        try {
            if(resultSet != null){
                resultSet.close();
                resultSet = null;
            }
        } catch (SQLException se) {
            System.out.println(se.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return resultSet;
    }

  

    public static Connection getLocalConnection() {
        Connection conn = null;
        try {
          
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            String url = "jdbc:mysql://localhost:3306/sample";
            conn = DriverManager.getConnection(url, "root", "root");

            if (conn != null) {
                System.out.println("Successfully Obtained Connection From ConnectionPool");
            }
            return conn;
        } catch (SQLException se) {
            System.out.println(se.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return conn;
    }
}


Main Program To Execute Procedure:

package com.jit;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Types;
/**
 * @author Vinay Guntaka
 * We are Fetching the Results from MySQL Procedure by passing
 * one IN Param and fetching One OUT Param with Multiple Result sets.
 */
public class CallProcedure {
    public static void main(String[] args) {
        Connection conn =null;
        CallableStatement callStmt = null;
        ResultSet rs =null;
      
        try {
            conn = ConnectionUtil.getLocalConnection();
            callStmt = conn.prepareCall("call proc_getData(?,?)");
            //Passing param to Execute First Query
            callStmt.setInt(1, 22);
            //Registering the Out Parameter
            callStmt.registerOutParameter(2,Types.VARCHAR);
            //Fetching the First RS of OUT Param
            callStmt.execute();
            String outParam = callStmt.getString(2);           ; // OUT parameter
            System.out.println("First Result Set Out Param:-"+outParam);
            //Fetching the Second Result Set from Procedure
            rs = callStmt.executeQuery();
            while(rs.next()){
                System.out.println("Second Query Result Set");
                System.out.println(rs.getString(1));
                System.out.println(rs.getString(2));
                System.out.println(rs.getString(3));
                System.out.println(rs.getString(4));
                System.out.println(rs.getString(5));
            }
            //Checking is there any more result sets
            if(callStmt.getMoreResults())
            {
                System.out.println("One More Result Set is there");
                //Fetching the Thrid Result Set from the Procedure
                rs = callStmt.executeQuery();
                while(rs.next()){
                    System.out.println("Thrid Query Result Set");
                    System.out.println(rs.getString(1));
                    System.out.println(rs.getString(2));
                    System.out.println(rs.getString(3));
                    System.out.println(rs.getString(4));
                    System.out.println(rs.getString(5));
                }
            }else
            {
                System.out.println("No More Results Sets");
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }finally
        {  
            //Closing all connections
            ConnectionUtil.closeConnection(conn);
            ConnectionUtil.closeCallableStatement(callStmt);
            ConnectionUtil.closeResultSet(rs);
        }
      
    }
}

Here is the procedure:

DELIMITER $$

DROP PROCEDURE IF EXISTS `sample`.`proc_getData`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_getData`(in user_id int,out user_name varchar(64))
BEGIN
    select user_name from users where id=user_id into user_name ;
    select * from employee;
    select * from users;
   
    END$$

DELIMITER ;

Thursday, March 31, 2011

Installing an SSL Certificate in Tomcat 4.x/5.x/6.x


Installing an SSL Certificate in Tomcat 4.x/5.x/6.x

http://help.securepaynet.net/article/5239

SHA Alogorithm in Java

import java.security.MessageDigest;

public class Util {
    public static String getSHA(String text)throws Exception{
        MessageDigest md;
        md = MessageDigest.getInstance("SHA-1");
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        return convertToHex(md.digest());
    }
    private static String convertToHex(byte[] data) {
            StringBuffer buf = new StringBuffer();
            for (int i = 0; i < data.length; i++) {
                int halfbyte = (data[i] >>> 4) & 0x0F;
                int two_halfs = 0;
                do {
                    if ((0 <= halfbyte) && (halfbyte <= 9))
                        buf.append((char) ('0' + halfbyte));
                    else
                        buf.append((char) ('a' + (halfbyte - 10)));
                    halfbyte = data[i] & 0x0F;
                } while(two_halfs++ < 1);
            }
            return buf.toString();
    }
   
    public static void main(String[] args) throws Exception {
        System.out.println(Util.getSHA("Vinay Guntaka"));
       
    }
   
}

Generating Unique Number in Java


import java.util.Random;

public class UniqueIDGenerator {

    private static final long serialVersionUID = 1L;

    /**
     *
     * Random-number generator.
     */

    private static transient Random r = new Random();

    // use constanst to prevent warnings about magic numbers:

    private static final long HEX_3FFFFFFFFFFFFFFF = 0x3FFFFFFFFFFFFFFFL;

    private static final long HEX_8000000000000000 = 0x8000000000000000L;

    private static final long HEX_FFFFFFFFFFFF0FFF = 0xFFFFFFFFFFFF0FFFL;

    private static final long HEX_4000 = 0x4000;

    private static final long HEX_FFFFFFFF00000000 = 0xFFFFFFFF00000000L;

    private static final long HEX_FFFFFFFF = 0xFFFFFFFFL;

    private static final long HEX_FFFF0000 = 0xFFFF0000L;

    private static final long HEX_0000000000000000FFFF = 0x0000000000000000FFFFL;

    private static final long HEX_FFFF000000000000 = 0xFFFF000000000000L;

    private static final long HEX_FFFF = 0xFFFF;

    private static final long HEX_FFFFFFFFFFFF = 0xFFFFFFFFFFFFL;

    private static final int DEC_4 = 4;

    private static final int DEC_8 = 8;

    private static final int DEC_12 = 12;

    private static final int DEC_16 = 16;

    private static final int DEC_32 = 32;

    private static final int DEC_48 = 48;

    /**
     *
     * @return a string with a universally unique id of format:
     *
     *         xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx .
     */

    public static String generateUUID() {

        // calculate lsb and msb

        long leastSigBits = r.nextLong();

        long mostSigBits = r.nextLong();

        leastSigBits &= HEX_3FFFFFFFFFFFFFFF;

        leastSigBits |= HEX_8000000000000000; // set top two bits to variant 2

        mostSigBits &= HEX_FFFFFFFFFFFF0FFF;

        mostSigBits |= HEX_4000; // Version 4;

        // turn leastSigBits and mostSigBits into string of format:

        // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

        String id =

        padHex(((mostSigBits & HEX_FFFFFFFF00000000) >> DEC_32) & HEX_FFFFFFFF,
                DEC_8)

                + "-"

                + padHex(((mostSigBits & HEX_FFFF0000) >> DEC_16), DEC_4)

                + "-"

                + padHex((mostSigBits & HEX_0000000000000000FFFF), DEC_4)

                + "-"

                + padHex(
                        (((leastSigBits & HEX_FFFF000000000000) >> DEC_48) & HEX_FFFF),
                        DEC_4)

                + "-"

                + padHex(leastSigBits & HEX_FFFFFFFFFFFF, DEC_12);

        return id;

    }

    /**
     *
     * Returns a hex String from l, padded to n spaces.
     *
     * @param l
     *            .
     *
     * @param n
     *            .
     *
     * @return String
     */

    private static String padHex(long l, int n) {

        String s = Long.toHexString(l);

        while (s.length() < n) {

            s = "0" + s;

        }

        return s;

    }
    public static void main(String[] args) {
        System.out.println(generateUUID());
    }

}




Java 1.7 New Features Over 1.6

Automatic Resource Management Description: A proposal to support scoping of resource usage in a block with automatic resource cleanup. T...