Posts

Showing posts from 2012

Get UnixTimeStamp in Java

Current UnixTimeStamp:

long currentUnixTimestamp = System.currentTimeMillis()/1000;

In  MYSQL:
 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

$.ajax({
      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) {
e.printStackTrace();
}
return difference;

    }

java.security.InvalidKeyException: Illegal key size or default parameters

java.security.InvalidKeyException: Illegal key size or default parameters
Caused by: java.security.InvalidKeyException: 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 java.security.NoSuchAlgorithmException;

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());
   System.out.print…

Blowfish encryption decryption in Java

Blowfish Encryption Decryption using KeyGenerator

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

import java.security.NoSuchAlgorithmException;

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="/"> 

 Or 

 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 com.google.appengine.runtime.Request.process-c326aa443556893f(Request.java) at sun.security.util.ManifestEntryVerifier.verify(ManifestEntryVerifier.java:210) at java.util.jar.JarVerifier.processEntry(JarVerifier.java:218) at java.util.jar.JarVerifier.update(JarVerifier.java:205) at java.util.jar.JarVerifier$VerifierStream.read(JarVerifier.java:428) at sun.misc.Resource.getBytes(Resource.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:273) at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) at javax.mail.Session.getService(Session.java:482) at javax.mail.Session.getTransport(Session.java:379) 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

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

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>
           </result>
</action>

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.io.NotSerializableException

java.lang.RuntimeException: java.io.NotSerializableException: com.example.web.dto.SessionObjectDTO
at com.google.apphosting.runtime.jetty.SessionManager.serialize(SessionManager.java:373)
at com.google.apphosting.runtime.jetty.DatastoreSessionStore.createEntityForSession(DatastoreSessionStore.java:71)
at com.google.apphosting.runtime.jetty.DatastoreSessionStore.saveSession(DatastoreSessionStore.java:93)
at com.google.apphosting.runtime.jetty.SessionManager$AppEngineSession.save(SessionManager.java:164)
at com.google.apphosting.runtime.jetty.SaveSessionFilter.doFilter(SaveSessionFilter.java:41)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandl…

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(NamingContext.java:836)
at org.apache.naming.NamingContext.rebind(NamingContext.java:208)
at org.apache.naming.SelectorContext.rebind(SelectorContext.java:207)
at javax.naming.InitialContext.rebind(InitialContext.java:412)
at org.hibernate.util.NamingHelper.bind(NamingHelper.java:74)
at org.hibernate.impl.SessionFactoryObjectFactory.addInstance(SessionFactoryObjectFactory.java:90)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:306)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1294)
at com.example.persistence.dao.impl.HibernateConnection.<init>(HibernateConnection.java:74)
at com.example.persistence.dao.impl.HibernateConnection.<init>(HibernateConnection.java:68)
at com.example.persistence.dao.impl.HibernateConnection.getInstance(HibernateConnection.java:55)
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.
-------------------------------------------------------------------------


import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;
----------------------------------------------------------------------




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

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

        log.info(this.getCl…

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..
https://developers.google.com/appengine/docs/java/googlestorage/overview

-----------------------------------------------------------------------------
1) index.html
------------------------------------------------------------------------------

<html>
<body>
   <div>
      <form action="testStorage.do" 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">
      </form>
   </div>
</body>
</html>

--------------------------------------------------------------------------------
2) web.xml


<?xml vers…

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

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

Solution:
function replaceAllBackSlash(targetStr){
      var index=targetStr.indexOf("\\");
      while(index >= 0){
          targetStr=targetStr.replace("\\","");
          index=targetStr.indexOf("\\");
      }
      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(AnnotationScannerListener.java:133)
    at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner$1.f(FileSchemeScanner.java:86)
    at com.sun.jersey.core.util.Closing.f(Closing.java:71)
    at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner.scanDirectory(FileSchemeScanner.java:83)
    at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner.scan(FileSchemeScanner.java:71)
    at com.sun.jersey.core.spi.scanning.PackageNamesScanner.scan(PackageNamesScanner.java:223)
    at com.sun.jersey.core.spi.scanning.PackageNamesScanner.scan(PackageNamesScanner.java:139)
    at com.sun.jersey.api.core.ScanningResourceConfig.init(ScanningResourceConfig.java:80)
    at com.sun.jersey.api.core.PackagesResourceConfig.init(PackagesResourceConfig.java:104)
    at com.sun.jersey.api.core.PackagesResource…

facebook share button

-------------------------------------------------------------------
1) Using javascript
<div >
<script>var fbShare = {google_analytics: 'true', size: 'small',url: 'http://knowledgeserve.in'}</script>
<script src="http://widgets.fbshare.me/files/fbshare.js"></script>
</div>

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

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); js.id = id;
          js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=APP_ID"; // 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 : domain.com
username : abcd
pass : ******
port : 21


Change this,
host : ftpes://domain.com
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: http://docs.oracle.com/javaee/1.4/tutorial/doc/Servlets12.html

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 …