Showing posts from 2012

Get UnixTimeStamp in Java

Current UnixTimeStamp:

long currentUnixTimestamp = System.currentTimeMillis()/1000;

 1) From date to UnixTimestamp:  SELECT UNIX_TIMESTAMP('2012-12-27 08:03:00');

2) From UnixTimeStamp to date:  SELECT FROM_UNIXTIME(1356618379);

Auto scroll to a DIV on page

You can set your page focus to a DIV on the basis of id element.

Let's say you have an element...
<div id="my_div" >  Scroll here.... </div>

Always Use: document.getElementById('my_div').scrollIntoView();

Ajax request using jquery

      type : "POST",
      url : "/login",
      cache: false,
      data : {userId:'test-user' , timestamp:'20121119'},
      dataType: 'json',
      success: function (data) {
          $.each(data, function(index, element) {        
 alert(index+" and "+element);

      error: function(jqXHR, exception) {
           if (jqXHR.status === 0) {
               alert('Not connect.\n Verify Network.');
           } else if (jqXHR.status == 404) {
               alert('Requested page not found. [404]');
           } else if (jqXHR.status == 500) {
               alert('Internal Server Error [500].');
           } else if (exception === 'parsererror') {
               alert('Requested JSON parse failed.');
           } else if (exception === 'timeout') {
               alert('Time out error.');
           } else if (exception === 'abort') {

Calculate Time difference in Java

public static long checkTimeDifference(String time1,String time2){

 //time1 and time 2 must be in HH:mm:ss format

SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1;
Date date2;
long difference=0;
try {
date1 = format.parse(time1);
date2 = format.parse(time2);
difference = date2.getTime() - date1.getTime();
} catch (ParseException e) {
return difference;

    } Illegal key size or default parameters Illegal key size or default parameters
Caused by: Illegal key size or default parameters
    at javax.crypto.Cipher.a(DashoA13*..) ~[na:1.6]
    at javax.crypto.Cipher.a(DashoA13*..) ~[na:1.6]
    at javax.crypto.Cipher.a(DashoA13*..) ~[na:1.6]
    at javax.crypto.Cipher.init(DashoA13*..) ~[na:1.6]
    at javax.crypto.Cipher.init(DashoA13*..) ~[na:1.6]


There are key size restrictions with the default crypto files local_policy.jar and US_export_policy.jar comes with JDK – which limits it to 128.

If the security policy you are using has a key size larger than this limit– then the above exception is thrown.

Please follow these instructions...
You need to patch your JDK with Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files.

For JDK1.5 visit , download the crypto files and copy the two jar files from the extracte…

Double encryption decryption (Blowfish+Base64) in java

Double Encryption and decryption using Blowfish and Base64



import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class BlowfishCipher {

 public static void main(String[] args) throws Exception {

   KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");

    SecretKey secretkey = keygenerator.generateKey();

   Cipher cipher = Cipher.getInstance("Blowfish");

   // get the text to encrypt
   String inputText = "User_ID=Test12&User_Timestamp=20121030040002";

   System.out.println("Double Encryption..................for :"+inputText);
   cipher.init(Cipher.ENCRYPT_MODE, secretkey);
   byte[] firstEncrypt = cipher.doFinal(inputText.getBytes());

Blowfish encryption decryption in Java

Blowfish Encryption Decryption using KeyGenerator



import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class BlowfishCipherExample {

 public static void main(String[] args) throws Exception {

   // create a key generator based upon the Blowfish cipher
   KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");

   // create a secret key
   SecretKey secretkey = keygenerator.generateKey();

   // create a cipher based upon Blowfish
   Cipher cipher = Cipher.getInstance("Blowfish");

   // initialise cipher to with secret key
     cipher.init(Cipher.ENCRYPT_MODE, secretkey);

   // get the text to encrypt
   String inputText = "User_ID=Test12&User_Timestamp=20121030040002";

   // encrypt me…

Base 64 encryption decryption in java using apache codec

First download jar from apache.. commons-codec-1.7.jar and add this to your lib...

import org.apache.commons.codec.binary.Base64;

public class Base64TestUsingApacheCodec {
  public static void main(String[] args) {
    String testStr="Hello ! test this";
    byte[] encodedBytes = Base64.encodeBase64(testStr.getBytes());
    System.out.println("encodedBytes " + new String(encodedBytes));
    byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
    System.out.println("decodedBytes " + new String(decodedBytes));


Compress images on Linux (ubuntu)

Image resizing/compression for linux

 ImageMagick isn’t included in the default installations of Ubuntu and many other Linux distributions. To install it on Ubuntu, use the following command:

sudo apt-get install imagemagick

Converting Between Formats
convert a.png b.jpg

You can also specify a compression level for JPEG images:

convert a.png -quality 95 b.jpg
Resizing Images

The convert command can also quickly resize an image.
Here you can asks ImageMagick to resize an image to 100 pixels in width and 50 pixels in height:

convert a.jpg -resize 100×50 b.jpg

  Reduce size of  all images with same name (No name change after reducing)

 for fileName in *.jpg; do convert $fileName -quality 50 $fileName; done

 Rotating an Image

ImageMagick can quickly…

Struts 2 : Warning :No configuration found for the specified action: 'Login.action' in namespace: '/'

No configuration found for the specified action: 'Login.action' in namespace: '/'''. Form action defaulting to 'action' attribute's literal value.

Solution:To remove this warning you need to change following...

See your struts.xml file what name you have specified...

If you are using namespace / and your action name is 'Login' then  replace Login.action to Login as given below...

<s:form action="Login.action" method="post" > 

 Use below with namespace 

1) <s:form action="Login" method="post" namespace="/"> 


 2) <s:form action="/Login" method="post" > 

 Now you will not get this warning.

Google App Engine: Java mail API : Mail failed

Uncaught exception from servlet java.lang.SecurityException: SHA1 digest error for com/sun/mail/smtp/SMTPTransport.class at at at java.util.jar.JarVerifier.processEntry( at java.util.jar.JarVerifier.update( at java.util.jar.JarVerifier$ at sun.misc.Resource.getBytes( at at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke( at java.lang.reflect.Method.invoke( at java.lang.ClassLoader.loadClass( at javax.mail.Session.getService( at javax.mail.Session.getTransport( at javax.mail.Session.getTranspo…

Google App engine :Struts 2 : There is no Action mapped for namespace [/] and action name .

here is a code from my web.xml


where index.jsp is redirected to a struts 2 action...

But when I access http://localhost:8888 I received the error below:

There is no Action mapped for namespace [/] and action name .


Solution:   Please edit your struts.xml and enter this action as last action( only after all actions as a default action).

<action name="*">
           <result type="redirectAction">
             <param name="actionName">Home.action</param>

Now this must be the last action and it will work like a default action for your application.

Google App Engine: java.lang.RuntimeException:

java.lang.RuntimeException: com.example.web.dto.SessionObjectDTO
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(
at org.mortbay.jetty.servlet.ServletHandler.handle(

Hibernate with Struts 2 : Warning : javax.naming.NamingException

[13-09-2012 16:25:41] [WARN ] - Could not bind factory to JNDI
javax.naming.NamingException: Name is not valid
at org.apache.naming.NamingContext.bind(
at org.apache.naming.NamingContext.rebind(
at org.apache.naming.SelectorContext.rebind(
at javax.naming.InitialContext.rebind(
at org.hibernate.util.NamingHelper.bind(
at org.hibernate.impl.SessionFactoryObjectFactory.addInstance(
at org.hibernate.impl.SessionFactoryImpl.<init>(
at org.hibernate.cfg.Configuration.buildSessionFactory(
at com.example.persistence.dao.impl.HibernateConnection.<init>(
at com.example.persistence.dao.impl.HibernateConnection.<init>(
at com.example.persistence.dao.impl.HibernateConnection.getInstance(
at com.example.persis…

Java IO Package: Convert byte[] data array to InputStream

If you want to make InputStream using data array of bytes like byte [], you can use following,
Let's suppose your file data is copied in following byte array.

byte []  newImageData contains all data which have been read from some file.
InputStream inputStream = new ByteArrayInputStream(newImageData);

Google App engine: Image Scaling

You can use following app engine classes to resize images using Java.


public byte[] resizedImage(byte[] oldImageData,int width,int height) throws IOException{

ImagesService imagesService = ImagesServiceFactory.getImagesService();
        Image oldImage = ImagesServiceFactory.makeImage(oldImageData);":oldImage height:"+oldImage.getHeight()+" and width:"+oldImage.getWidth());
  Transform resize = ImagesServiceFactory.makeResize(width,height);
        Image newImage = imagesService.applyTransform(resize, oldImage);
        byte[] newImageData = newImage.getImageData();…

Upload file on Google cloud storage using Java servlet on google app engine

Hopefully you have configured all jars and settings to run and deploy your project on google app engine using eclipse,

if not then visit google app engine-->google cloud storage java api link..

1) index.html

      <form action="" method="post" enctype="multipart/form-data">
         <p> Please write a file to test cloud storage... </p>
         <input type="file" name="cloudFile" />
         <input type="submit" value="Write a  file on cloud Storage">

2) web.xml

<?xml vers…

JavaScript: Remove all backslash (\) from a String in JavaScript

How to remove  all backslash (\) from a String in JavaScript

function replaceAllBackSlash(targetStr){
      var index=targetStr.indexOf("\\");
      while(index >= 0){
      return targetStr;

Google App Engine: Cloud Storage: java.lang.NoSuchMethodError: org.objectweb.asm.ClassReader.accept(Lorg/objectweb/asm/ClassVisitor;I)V

Uncaught exception from servlet
java.lang.NoSuchMethodError: org.objectweb.asm.ClassReader.accept(Lorg/objectweb/asm/ClassVisitor;I)V
    at com.sun.jersey.spi.scanning.AnnotationScannerListener.onProcess(
    at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner$1.f(
    at com.sun.jersey.core.util.Closing.f(
    at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner.scanDirectory(
    at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner.scan(
    at com.sun.jersey.core.spi.scanning.PackageNamesScanner.scan(
    at com.sun.jersey.core.spi.scanning.PackageNamesScanner.scan(
    at com.sun.jersey.api.core.ScanningResourceConfig.init(
    at com.sun.jersey.api.core.PackagesResourceConfig.init(
    at com.sun.jersey.api.core.PackagesResource…

facebook share button

1) Using javascript
<div >
<script>var fbShare = {google_analytics: 'true', size: 'small',url: ''}</script>
<script src=""></script>


2) You can use FBML.....

<div id="fb-root"></div>
        <script>(function(d, s, id) {
          var js, fjs = d.getElementsByTagName(s)[0];
          if (d.getElementById(id)) return;
          js = d.createElement(s); = id;
          js.src = "//"; // appId must be valid; 
//  for example: APP_ID=172095742912464

          fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));</script>
        <fb:share-button type="b…

FileZila error: 421: Could not connect to server

FileZila connection error:

421 Sorry, cleartext sessions are not accepted on this server. 
Error:Could not connect to server


Please add a ftpes:// before the domain name

Previous One,
host :
username : abcd
pass : ******
port : 21

Change this,
host : ftpes://
username : abcd
pass : ******
port : 21

Timesgroups interview questions: Servlet lifecycle : who called destroy() method of servlet

destroy() method is called by the servlet container. It is to indicate to a servlet that the servlet is being taken out of service. This method is only called once all threads within the servlet's service() method have exited or after a timeout period has passed.
  public void destroy() {
      anyDB = null;
How container knows that all the threads are exited and where we specify the timeout period for a servlet.

For more, visit link:

Timesgroups Interviews questions: Iterate hashmap in java

You can use the following different ways.....

1: Iterating HashMaps over entries using For-Each loop.

Use this if you need both map keys and values in the loop.

Map<String, String> map = new HashMap<String, String>();
for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
2. Filterating over keys or values using for-each loop.......

If you need only keys or values from the map, you can iterate over keySet or values instead of entrySet.

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//iterating over keys only
for (Integer key : map.keySet()) {
    System.out.println("Key = " + key);

//iterating over values only
for (Integer value : map.values()) {
    System.out.println("Value = " + value);
3.: Iterating …