IT Certificaions

Google Cloud Platform

Thursday, December 27, 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);

Saturday, December 15, 2012

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

Monday, November 19, 2012

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') {
               alert('Ajax request aborted.');
           } else {
               alert('Uncaught Error.\n' + jqXHR.responseText);
           }
       }

 });

Wednesday, October 31, 2012

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

Tuesday, October 30, 2012

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 extracted jce directory (local_policy.jar and US_export_policy.jar) to $JAVA_HOME/jre/lib/security.

For  JDK1.6 visit , download these jars and see the installation instructions.

Or
Just you can copy and paste these jars into jdk1.6/jars/lib/security and rebuild your application.

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.println("blowfish encryption...firstEncrypted::"+new String(firstEncrypt));
   
   byte[] encodedBytes = Base64.encodeBase64(firstEncrypt);
   System.out.println("Base64 decoded encryption: encodedBytes::"+new String(encodedBytes));
   
   System.out.println("Double decryption starts now..................");
   byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
   System.out.println("Base64 decryptions........decodedBytes:: " +new String(decodedBytes));
   
   cipher = Cipher.getInstance("Blowfish");
   cipher.init(Cipher.DECRYPT_MODE, secretkey);   
   byte[] decryptedFinal = cipher.doFinal(decodedBytes);
   System.out.println("Finally...blowfish decryption....decryptedFinal::"+new String(decryptedFinal));
 
   System.exit(0);
 }
 
}

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 message
    byte[] encrypted = cipher.doFinal(inputText.getBytes());

   // re-initialise the cipher to be in decrypt mode
   cipher.init(Cipher.DECRYPT_MODE, secretkey);

   // decrypt message
   byte[] decrypted = cipher.doFinal(encrypted);

   // and display the results
   System.out.println("encrypted text: " + new String(encrypted) + "\n" + "decrypted text: " + new String(decrypted));

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

Blowfish Encryption using existing secret key

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 {

String keyStr="CEM8hHSuL4nuXDydDn8Ey5jd"; // Let's assume you have this key

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

    // create a secret key
   SecretKeySpec secretkey = new SecretKeySpec(keyStr.getBytes(), "Blowfish");


    // 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 message
    byte[] encrypted = cipher.doFinal(inputText.getBytes());

    // re-initialise the cipher to be in decrypt mode
   cipher.init(Cipher.DECRYPT_MODE, secretkey);

    // decrypt message
   byte[] decrypted = cipher.doFinal(encrypted);

    // and display the results
   System.out.println("encrypted text: " + new String(encrypted) + "\n" + "decrypted text: " + new String(decrypted));

  
  }
 
}

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


================================================================

Friday, October 5, 2012

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 rotate an image. The following command takes an image named howtogeek.jpg, rotates it by 90 degrees and saves the rotated image as howtogeek-rotated.jpg:

 convert a.jpg -rotate 90 b.jpg


 ------------------------------------------------------------------------------
If you failed to install it like below...
...
...

  Unable to fetch some archives, maybe run apt-get update or try with --fix-missing
Then go for this...

sudo apt-get update

sudo apt-get install imagemagick --fix-missing 

For more Info please go: https://help.ubuntu.com/community/ImageMagick

Monday, September 24, 2012

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.

Friday, September 21, 2012

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.getTransport(Session.java:339)
 at javax.mail.Session.getTransport(Session.java:368)
 at javax.mail.Transport.send(Transport.java:67)
 at javax.mail.Transport.send(Transport.java:48)......
........
.......
........

Solution: Please remove all jar related to mail or smpt from your lib and then re-deploy on app engine. Google app engine provides all required.

Thursday, September 20, 2012

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.




Thursday, September 13, 2012

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.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.handle(AppVersionHandlerMap.java:249)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
at com.google.apphosting.runtime.jetty.RpcRequestParser.parseAvailable(RpcRequestParser.java:76)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:135)
at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:447)
at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:452)
at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:458)
at com.google.tracing.TraceContext.runInContext(TraceContext.java:698)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:336)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:328)
at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:456)
at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:251)
at java.lang.Thread.run(Thread.java:679)
Caused by: java.io.NotSerializableException: com.example.web.dto.SessionObjectDTO
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1180)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
at java.util.HashMap.writeObject(HashMap.java:1018)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:962)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1480)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
at com.google.apphosting.runtime.jetty.SessionManager.serialize(SessionManager.java:370)
... 29 more
-----------------------------------------------------------------------------------------------------

Solution: Please make your object Serializable that you want to put in HttpSession if you are running it on Google App Engine.

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.persistence.dao.impl.HibernateBaseDAO.createSession(HibernateBaseDAO.java:35)
at com.example.persistence.dao.impl.HibernateBaseDAO.getSession(HibernateBaseDAO.java:24)
at com.example.persistence.dao.impl.PostalCodeDAO.getAllCitiesPostCodes(PostalCodeDAO.java:45)
at com.example.web.util.exampleProperties.<clinit>(exampleProperties.java:74)
at com.example.web.action.WelcomeHomeAction.mobileView(WelcomeHomeAction.java:73)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)


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

Solution: Please see your hibernate-cfg.xml and see <session-factory name=""> name attribute. Remove it.

Thursday, September 6, 2012

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.getClass()+"After resize newImage height:"+newImage.getHeight()+" and width:"+newImage.getWidth());

      

        return  newImageData ;
}

Wednesday, September 5, 2012

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

   <servlet>
<servlet-name>CloudStorageServlet</servlet-name>
<servlet-class>com.vicwalks.web.servlet.TestCloudStorageServlet</servlet-class>
</servlet>
  
<servlet-mapping>
<servlet-name>CloudStorageServlet</servlet-name>
<url-pattern>/testStorage.do</url-pattern>
</servlet-mapping>
  
<welcome-file-list>
   <welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
-------------------------------------------------------

3) appengine-web.xml


<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
  <application>your-app-engine-id</application>
  <version>1</version>



  <threadsafe>true</threadsafe>
  <sessions-enabled>true</sessions-enabled>

  <!-- Configure java.util.logging -->
  <system-properties>
    <property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>
  </system-properties>

  <!--
    HTTP Sessions are disabled by default. To enable HTTP sessions specify:

      <sessions-enabled>true</sessions-enabled>

    It's possible to reduce request latency by configuring your application to
    asynchronously write HTTP session data to the datastore:

      <async-session-persistence enabled="true" />

    With this feature enabled, there is a very small chance your app will see
    stale session data. For details, see
    http://code.google.com/appengine/docs/java/config/appconfig.html#Enabling_Sessions
  -->

</appengine-web-app>



=====================================================================

4) TestCloudStorageServlet.java

------------------------------------------------------
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;


import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class TestCloudStorageServlet extends HttpServlet{

private static final long serialVersionUID = 1L;
private StorageService storage = new StorageService();
private static final int BUFFER_SIZE = 1024 * 1024;
private static final Logger log = Logger.getLogger(TestCloudStorageServlet.class.getName()); 
@Override
 public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
   log.info(this.getServletInfo()+" Servlets called....");
   resp.setContentType("text/plain");
   resp.getWriter().println("Now see here your file content, that you have uploaded on storage..");
   
   ServletFileUpload upload = new ServletFileUpload();
   FileItemIterator iter;
try {
iter = upload.getItemIterator(req);
while (iter.hasNext()) {
       FileItemStream item = iter.next();
       String fileName = item.getName();
       String mime = item.getContentType();
       
       storage.init(fileName, mime);
       InputStream is = item.openStream();

       byte[] b = new byte[BUFFER_SIZE];
       int readBytes = is.read(b, 0, BUFFER_SIZE);
       while (readBytes != -1) {
           storage.storeFile(b, readBytes);
           readBytes = is.read(b, 0, readBytes);
       }

       is.close();
       storage.destroy();
       
resp.getWriter().println("File uploading done");

       //resp.getWriter().println("READ:" + storage.readTextFileOnly(fileName));
       
                         log.info(this.getServletName()+" ended....");        

}
} catch (FileUploadException e) {
System.out.println("FileUploadException::"+e.getMessage());
log.severe(this.getServletName()+":FileUploadException::"+e.getMessage());
e.printStackTrace();
} catch (Exception e) {
log.severe(this.getServletName()+":Exception::"+e.getMessage());
System.out.println("Exception::"+e.getMessage());
e.printStackTrace();
}
}

}

========================================================================

5) StorageService.java

--------------------------------------------------------------------------
import com.google.appengine.api.files.*;
import com.google.appengine.api.files.GSFileOptions.GSFileOptionsBuilder;
import java.io.*;
import java.nio.channels.Channels;
import java.util.logging.Logger;

public class StorageService {

public static final String BUCKET_NAME = "mybucket";  

private FileWriteChannel writeChannel = null;
FileService fileService = FileServiceFactory.getFileService();
private OutputStream os = null;
private static final Logger log = Logger.getLogger(StorageService.class.getName());

public void init(String fileName, String mime) throws Exception {
System.out.println("Storage service:init() method:  file name:"+fileName+" and mime:"+mime);
log.info("Storage service:init() method:  file name:"+fileName+" and mime:"+mime);
    
    GSFileOptionsBuilder builder = new GSFileOptionsBuilder()
            .setAcl("public_read")
            .setBucket(BUCKET_NAME)
            .setKey(fileName)
            .setMimeType(mime);
    AppEngineFile writableFile = fileService.createNewGSFile(builder.build());
    boolean lock = true;
    writeChannel = fileService.openWriteChannel(writableFile, lock);
    os = Channels.newOutputStream(writeChannel);
}

public void storeFile(byte[] b, int readSize) throws Exception {
    os.write(b, 0, readSize);
    os.flush();
}



// Only to read uploaded text files

public String readTextFileOnly(String fileName) throws Exception{  
log.info("Reading the txt file from google cloud storage...........");
String filename = "/gs/" + BUCKET_NAME + "/" + fileName;
    AppEngineFile readableFile = new AppEngineFile(filename);
    FileReadChannel readChannel = fileService.openReadChannel(readableFile, false);
    BufferedReader reader = new BufferedReader(Channels.newReader(readChannel, "UTF8"));
    String line = reader.readLine();
    readChannel.close();
    return line;

}
public void destroy() throws Exception {
log.info("Storage service: destroy() method");
    os.close();
    writeChannel.closeFinally();
}
}
========================================================================

Now deploy your project on app engine and upload file.

Thursday, August 30, 2012

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.PackagesResourceConfig.<init>(PackagesResourceConfig.java:78)
    at com.sun.jersey.api.core.PackagesResourceConfig.<init>(PackagesResourceConfig.java:89)
    at com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:700)
    at com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:678)
    at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:203)
    at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374)
    at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557)
    at javax.servlet.GenericServlet.init(GenericServlet.java:212)
    at org.mortbay.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:440)
    at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:263)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685)
    at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
    at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
    at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
    at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.createHandler(AppVersionHandlerMap.java:202)
    at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.getHandler(AppVersionHandlerMap.java:171)
    at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:123)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:447)
    at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:452)
    at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:458)
    at com.google.tracing.TraceContext.runInContext(TraceContext.java:698)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:336)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:328)
    at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:456)
    at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:251)
    at java.lang.Thread.run(Thread.java:679)

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


    Solution: Please remove dupliacte asm.jar if it is there from WEB-INF/lib folder and then upload code again on google app engine nad then run.

Friday, August 24, 2012

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="button" href=" http://knowledgeserve.in ">
        </fb:share-button>

Tuesday, August 21, 2012

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

Friday, August 10, 2012

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 using Iterator......with the help of entrySet() method

Using Generics:

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();   //entrySet() returns set
while (entries.hasNext()) {
    Map.Entry<Integer, Integer> entry = entries.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

Without Generics:

Map map = new HashMap();
Iterator entries = map.entrySet().iterator();        //entrySet() returns set
while (entries.hasNext()) {
    Map.Entry entry = (Map.Entry) entries.next(); 
    Integer key = (Integer)entry.getKey();
    Integer value = (Integer)entry.getValue();
    System.out.println("Key = " + key + ", Value = " + value);
}

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

4: Iterating over keys and then searching for values with the help of keys(Not good).

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
    Integer value = map.get(key);
    System.out.println("Key = " + key + ", Value = " + value);
}