IT Certificaions

Google Cloud Platform

Tuesday, December 24, 2013

Send POST request with JSON data on Google App Engine

Tag: Fusion Table Rest API, Send POST request with JSON data on Google App Engine

1) Create fusion table using post request on Google App Engine

// postURL= "https://www.googleapis.com/fusiontables/v1/tables?access_token=**********"
// access_token - Use Oauth2 for this

public static String sendPostRequest(String postURL) throws Exception{
        String responseStr=null;
        //make POST request
        String jsonContent = "{'name': 'newIndia','columns': [{'name': 'Species','type': 'STRING'}],'description': 'Insect Tracking Information.','isExportable': true}";
        //String data = "{\"document\" : {\"_id\": \"" + id+ "\", \"context\":" + context +"}}";
        URL url = new URL(postURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(jsonContent.getBytes().length));
        connection.setUseCaches(false);

        OutputStreamWriter  writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writer.write(jsonContent);       
        writer.close();
        responseStr="Response code: "+connection.getResponseCode()+" and mesg:"+connection.getResponseMessage();
       
        System.out.println(connection.getResponseMessage());
       
       
        InputStream response;                  

        // Check for error , if none store response
        if(connection.getResponseCode() == 200){
            response = connection.getInputStream();
        }else{
            response = connection.getErrorStream();
        }
        InputStreamReader isr = new InputStreamReader(response);
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(isr);
        String read = br.readLine();
        while(read != null){
            sb.append(read);
            read = br.readLine();
        }  
        // Print the String    
        System.out.println(sb.toString());
       
        connection.disconnect();
        return responseStr;
    }

Monday, November 18, 2013

Best way to Format a Double value to nth Decimal places in Java

Best way to Format a Double value to nth Decimal places in Java
------------------------------------------------------------------
public static double getDoubleValue(String value,int digit){
        if(value==null){
            value="0";
         }
        double i=0;
         try {
             DecimalFormat digitformat = new DecimalFormat("#.##");
             digitformat.setMaximumFractionDigits(digit);
            return Double.valueOf(digitformat.format(Double.parseDouble(value)));
           
        } catch (NumberFormatException numberFormatExp) {
            return i;   
        }
    }


Friday, November 15, 2013

Append option into a select using jquery

You can use jquery to append data from select from a array of data. See the java script function where you can pass the dataArray like dataArray=["A","B"] and elementId , means the id attribute of your select element;


function appendDataToSelectDropDown(dataArray,elementId){
      if(dataArray !=null && dataArray.length>0){
          $('#'+elementId).find('option').remove().end()
            .append('<option value="-1">Select Creative Size</option>');

          $.each(dataArray, function( index, value ) {   
                $('#'+elementId).append(new Option(value, value));
          });
      }
  }

Thursday, November 14, 2013

Fusion table layer: data may be still loading

On hitting fusion table layer on Maps, it says data may be still loading

Answer: Check your query syntex, new query syntex is as given below with an example
(Non numeric fields must be enclosed with '' quotes)
function fetchDataFromFusionTable(){
   try{   
             
          var fusionOptions = {
             
              query: {
                select: 'Geometry',
                //from: "1QTnVfSO-agR4ueOAVa-uUzYrmNwE4DQ6l0e22EA",
                from: "1Fhnl0uOC3Ol3rMHI5FQIiTDIP3gw7QbRjldvFgY",
                where: " 'Start_Date' >= '"+startDate+"' AND 'End_Date' <= '"+endDate+"' " +
                        " AND  'DMA_Code' >0 " //'Start_Date >= '+startDate+' 00:00:00'
              },           
                   
            styles: [{
                 
                  where: 'Available_Impressions > 0 AND Available_Impressions <= 1000',
                  polygonOptions: {
                    fillColor: '#ffffff',
                    fillOpacity: 0.4
                  }
                }, {
                  where: 'Available_Impressions > 1000 AND Available_Impressions <=100000',
                  polygonOptions: {
                    fillColor: '#88bad8',
                    fillOpacity: 0.4
                  }
                }, {
                  where: 'Available_Impressions > 100000 AND Available_Impressions <=1000000',
                  polygonOptions: {
                    fillColor: '#5792c3',
                    fillOpacity: 0.4
                  }
                }, {
                  where: 'Available_Impressions > 1000000',
                  polygonOptions: {
                    fillColor: '#4572ab',
                    fillOpacity: 0.4
                  }
             }]           
       
           
        }
     
        layer.setOptions(fusionOptions);
   
    }catch(err){
      alert(err);
    }   
  }

Tuesday, August 27, 2013

CSC Interview Question: how to find common elements between two collections

Solution: retainAll method do this.
 
public boolean retainAll(Collection<?> c)

Example:
public class Test {   

    public static void main(String [] args){

         LinkedHashSet hs = new LinkedHashSet();
          // add elements to the hash set
          hs.add("B");
          hs.add("A");
          hs.add("D");
          hs.add("E");
          hs.add("C");
          hs.add("F");
          System.out.println(hs);
         
          LinkedHashSet hs2 = new LinkedHashSet();
          hs2.add("E");
          hs2.add("C");
          hs2.add("G");
          System.out.println(hs2);
          boolean retain=hs.retainAll(hs2);
          System.out.println("retain:"+retain);
          System.out.println(hs2);
          System.out.println(hs);       
    }

}
**********************************************
Output:
[B, A, D, E, C, F]
[E, C, G]
retain:true
[E, C, G]
[E, C]

Wednesday, July 17, 2013

nth Highest salary

Find the Nth highest salary

Solution: Common logic for all database is as...

select t.name,t.salary from employee t
  where N= (
              select count(u.salary) from
                  (select distinct salary from employee ) as u
                  where t.salary<= u.salary
       )

Monday, July 15, 2013

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role

Errror: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role.......

Solution: Add lazy=false in your hbm file where you have declare collection...
Example:
<set name="hhResume" inverse="true" lazy="false">
            <key>
                <column name="UID" not-null="true" />
            </key>
            <one-to-many class="com.example.HhCandidate" />
        </set>

Friday, July 5, 2013

Read gzip response from a URL using Java

Here is a code template.....

public static String readGZFile(String url) throws IOException {
           StringBuffer dataBuffer =new StringBuffer();
           InputStream gzipStream = new GZIPInputStream((new URL(url)).openStream());
           Reader decoder = new InputStreamReader(gzipStream, "UTF-8");
           BufferedReader buffered = new BufferedReader(decoder);
           int i=0;
           String line=buffered.readLine();
           while(line !=null){
               dataBuffer.append(line);
               line=buffered.readLine();
               i++;
           }       
           return dataBuffer.toString();          
    }

Tuesday, June 25, 2013

DFP with Google App Engine

See the code
*************************************************************************************
package com.lin.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.api.ads.common.lib.exception.ValidationException;
import com.google.api.ads.dfp.appengine.oauth.CredentialException;
import com.google.api.ads.dfp.jaxws.factory.DfpServices;
import com.google.api.ads.dfp.jaxws.v201302.ApiException_Exception;
import com.google.api.ads.dfp.jaxws.v201302.Network;
import com.google.api.ads.dfp.jaxws.v201302.NetworkServiceInterface;
import com.google.api.ads.dfp.lib.client.DfpSession;
import com.lin.web.util.ClientLoginAuth;
import com.lin.web.util.LinMobiileProperties;
import com.lin.web.util.LinMobileConstants;


@SuppressWarnings("serial")
public class DfpV302Servlet extends HttpServlet {
 
  private static final Logger log = Logger.getLogger(DfpV302Servlet.class.getName());
  
  private String clientLoginToken = null;

 public void init(ServletConfig config) throws ServletException {
      super.init(config);     
      try {
        clientLoginToken = regenerateAuthToken();
        log.info(" clientLoginToken : "+clientLoginToken);
      } catch (Exception exception) {
       log.severe("init(), Exception.."+exception);
       exception.printStackTrace();        
      }
 }
 

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
     log.info("started.......");
     PrintWriter out=resp.getWriter();
     resp.setContentType("text/plain");
     out.println("============================================================");
     
     try {
   log.info("going to make DfpSession instance...");
   DfpSession session = new DfpSession.Builder()
     .withClientLoginToken(clientLoginToken)     
     .withNetworkCode(LinMobileConstants.DFP_NETWORK_CODE)
     .build();
   System.out.println("session:"+session.getNetworkCode());
   log.info("going to make DfpServices instance...");
   DfpServices dfpServices = new DfpServices();
   
   log.info("going to make networkService instance...");
   
   log.info("loading networks.......");
   List<Network> networks = loadNetworks(dfpServices, session);
      
      for (Network network : networks) {
       out.println(
            "Network with network code"+network.getNetworkCode()+"  and display name "+
             network.getDisplayName());
      }
   
      log.warning("done....");
   
  } catch (ValidationException e) {
   log.severe("ValidationException :"+e.getMessage());
   e.printStackTrace();
  } catch (ApiException_Exception e) {
   log.severe("ApiException_Exception:"+e.getMessage());
   e.printStackTrace();
  } catch (CredentialException e) {
   log.severe("CredentialException:"+e.getMessage());
   e.printStackTrace();
  }

  out.println("============================================================");
  }
  
  private List<Network> loadNetworks(DfpServices dfpServices,DfpSession session) throws ValidationException, ApiException_Exception,
  CredentialException{   
   NetworkServiceInterface networkService =
         dfpServices.get(session, NetworkServiceInterface.class);
 log.info("Fetching networks.......");
 List<Network> networks = networkService.getAllNetworks();
 return networks;
  }
  public String regenerateAuthToken() throws Exception {
   String clientLoginToken=LinMobiileProperties.getAuthToken();
   if(clientLoginToken ==null){
    ClientLoginAuth clientLoginAuth = new ClientLoginAuth(LinMobileConstants.EMAIL_ADDRESS, LinMobileConstants.EMAIL_PASSWORD);
    clientLoginToken =clientLoginAuth.getAuthToken();
    LinMobiileProperties.setAuthToken(clientLoginToken);
   }     
     return clientLoginToken;
 }
  
}

*************************************************************************************

See error comes at line:(List<Network> networks = networkService.getAllNetworks();)

***************************************************************************
Jun 26, 2013 10:50:57 AM com.lin.web.servlet.DfpV302Servlet doGet
INFO: going to make networkService instance...
Jun 26, 2013 10:50:57 AM com.lin.web.servlet.DfpV302Servlet doGet
INFO: loading networks.......
Jun 26, 2013 10:51:04 AM com.lin.web.servlet.DfpV302Servlet loadNetworks
INFO: Fetching networks.......
Jun 26, 2013 10:51:04 AM com.google.apphosting.utils.jetty.JettyLogger warn
WARNING: Error for /dfpLatest.do
java.lang.AbstractMethodError: com.google.api.ads.common.lib.soap.jaxws.JaxWsHandler.putAllHttpHeaders(Ljava/lang/Object;Ljava/util/Map;)V
 at com.google.api.ads.dfp.lib.soap.DfpHttpHeaderHandler.setHttpHeaders(DfpHttpHeaderHandler.java:53)
 at com.google.api.ads.dfp.jaxws.DfpJaxWsHeaderHandler.setHeaders(DfpJaxWsHeaderHandler.java:86)
 at com.google.api.ads.dfp.jaxws.DfpJaxWsHeaderHandler.setHeaders(DfpJaxWsHeaderHandler.java:1)
 at com.google.api.ads.common.lib.client.AdsServiceClient.setHeaders(AdsServiceClient.java:111)
 at com.google.api.ads.common.lib.soap.SoapServiceClient.invoke(SoapServiceClient.java:92)
 at $Proxy55.getAllNetworks(Unknown Source)
 at com.lin.web.servlet.DfpV302Servlet.loadNetworks(DfpV302Servlet.java:112)
 at com.lin.web.servlet.DfpV302Servlet.doGet(DfpV302Servlet.java:83)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
 at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
 at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:123)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
 at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
 at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
 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 com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
 at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
 at com.google.appengine.tools.development.DevAppServerServersFilter.doDirectRequest(DevAppServerServersFilter.java:369)
 at com.google.appengine.tools.development.DevAppServerServersFilter.doDirectServerRequest(DevAppServerServersFilter.java:352)
 at com.google.appengine.tools.development.DevAppServerServersFilter.doFilter(DevAppServerServersFilter.java:115)
 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.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:97)
 at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
 at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:438)
 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 org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:547)
 at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
 at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
 at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
 at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
--------------------------------------------------------------------------------------------------------

Thursday, May 16, 2013

Date using Java: create Data using year, month, day, hour, minute, seconds in Java

Creating  custom date using java
1) Using java.util.Date
 int year=2013;
int month=5;   // months starts from 0 to 11, as 0 stands January and 11 stands for December
int day=15;
int hour=12;
int minute=58;
int seconds=47;

*** Date utilDateObj=new Date(year,month,day,hour,minute,seconds);

***  This is depricated.

We recommend to use Calander as given below:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.YEAR, year);

calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.HOUR, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, seconds);

Date lastUpdatedDate = calendar.getTime();

Monday, March 25, 2013

Impetus Interview questions: Code-2

What will be the output of the following...
class A{
public static void main(String [] arg){
        String s1="hello";
        String s2=new String("hello");
        System.out.println(s1==s2);
        String s3=new String("world");
        String s4=new String("world");
       
        System.out.println(s3==s4);
        System.out.println(s1.equals(s2));
        System.out.println(s3.equals(s4));
        String s5="hello";
        System.out.println(s1==s5);
    }

}

Output:  See here.....
false
false
true
true
true

s1 == s2 : false, both refernece variable pointing to different objects
s3 == s4 : false, both refernece variable pointing to different objects
s1.equals(s2): true:  Different objects but values are same
s3.equals(s4): true: Different objects but values are same

 s1 == s5 : true, both refernece variable pointing to same object

Impetus Interview Questions: Code Snipet 1

What will be the output of the code?


interface TestOne{
    int limit=100;
    void display();   
}

interface TestTwo{
    int limit=200;
    void display();   
}

public class TestInterface implements TestOne,TestTwo{
    //int limit=0;
    @Override
    public void display() {
        System.out.println("Hello... Test interface...."+limit);
       
    }
   
    public static void main(String [] arg){
        TestInterface obj=new TestInterface();
        obj.display();
     }


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

Output: Compiler error at System.out.println(....) : The field "limit" is ambiguous.

Monday, March 11, 2013

Read file from google cloud storage using Java

You can read file from google cloud storage using following code....

public void readTextFileOnly(String fileName) { 
        log.info("Reading from google cloud storage,fileName:"+fileName);
        FileService fileService = FileServiceFactory.getFileService();
        String filename = "/gs/" + BUCKET_NAME + "/" + fileName;
        log.info("Reading from google cloud storag: filename:"+filename);
        AppEngineFile readableFile = new AppEngineFile(filename);
        FileReadChannel readChannel;
        try {
                readChannel = fileService.openReadChannel(readableFile, false);
                BufferedReader reader = new BufferedReader(Channels.newReader(readChannel, "UTF8"));
                String line = reader.readLine();
                readChannel.close();
        } catch (FileNotFoundException e) {
            log.severe("FileNotFoundException:"+e.getMessage());
            e.printStackTrace();
        } catch (LockException e) {
            log.severe("LockException:"+e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log.severe("IOException:"+e.getMessage());
            e.printStackTrace();
        }

}

Wednesday, March 6, 2013

Blowfish decryption: javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher

Problem : Blowfish decryption+  javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher

Solution: Always check your data whether it is a multiple of 8 bit or not.

             if(decodedBytes.length % 8 != 0){ //not a multiple of 8
                   System.out.println("decodedBytes is not padded properly in 8 bits");
                   //create a new array with a size which is a multiple of 8
                   byte[] padded = new byte[decodedBytes.length + 8 - (decodedBytes.length % 8)];
                   //copy the old array into it
                   System.arraycopy(decodedBytes, 0, padded, 0, decodedBytes.length);
                   decodedBytes = padded;
               }else{
                   System.out.println("decodedBytes is padded properly in 8 bits");
               }


For complete example, see here... . http://knowledge-serve.blogspot.in/2013/03/encryption-and-decryption-using.html

Encryption and decryption using Blowfish and base64 on Google App Engine

Encryption and Decryption  using Blowfish and base64 on Google App Engine using Java

1.. Encryption double using blowfish and then base64

  public static String doubleEncryption_Blowfish_Base64(String to_encrypt,String key,String charEncoding){
           //charEncoding="UTF-8";
           Cipher cipher;
            try {
               byte[] encodedBytes =to_encrypt.getBytes(charEncoding);       
              
               if(encodedBytes.length % 8 != 0){ //not a multiple of 8
                   System.out.println("encodedBytes is not padded properly in 8 bits");
                   //create a new array with a size which is a multiple of 8
                   byte[] padded = new byte[encodedBytes.length + 8 - (encodedBytes.length % 8)];
                   //copy the old array into it
                   System.arraycopy(encodedBytes, 0, padded, 0, encodedBytes.length);
                   encodedBytes = padded;
               }else{
                   System.out.println("encodedBytes is padded properly in 8 bits");
               }
              
               byte[] keyBytes=key.getBytes(charEncoding);
               SecretKeySpec secretkey = new SecretKeySpec(keyBytes, "Blowfish");                  
               cipher = Cipher.getInstance("Blowfish/ECB/NoPadding");
               cipher.init(Cipher.ENCRYPT_MODE, secretkey);      
               byte[] encryptedBlowFish = cipher.doFinal(encodedBytes);
               byte[] encryptedFinalBase64 = Base64.encodeBase64(encryptedBlowFish);             
               return new String(encryptedFinalBase64);
            } catch (Exception e) {
                 log.warning("Exception:"+e.getMessage());
                 e.printStackTrace();              
                 return null;
            }
       }


2.. Decryption double using base64 and then blowfish

public static String doubleDecryption_Base64_Blowfish(String to_decrypt,String key,String charSet){          
          // charSet="UTF-8";
           Cipher cipher;
            try {
               byte[] decodedBytes = Base64.decodeBase64(to_decrypt.getBytes(charSet));
               if(decodedBytes.length % 8 != 0){ //not a multiple of 8
                   System.out.println("decodedBytes is not padded properly in 8 bits");
                   //create a new array with a size which is a multiple of 8
                   byte[] padded = new byte[decodedBytes.length + 8 - (decodedBytes.length % 8)];
                   //copy the old array into it
                   System.arraycopy(decodedBytes, 0, padded, 0, decodedBytes.length);
                   decodedBytes = padded;
               }else{
                   System.out.println("decodedBytes is padded properly in 8 bits");
               }
              
               byte[] keyBytes=key.getBytes(charSet);
               SecretKeySpec secretkey = new SecretKeySpec(keyBytes, "Blowfish");
               cipher = Cipher.getInstance("Blowfish/ECB/NoPadding");
               cipher.init(Cipher.DECRYPT_MODE, secretkey);      
               byte[] decryptedFinal = cipher.doFinal(decodedBytes);
               return new String(decryptedFinal);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
       }      


encrypt in php and decrypt in java using blowfish/base64 on Google App Engine

encrypt in php and decrypt in java using blowfish/base64 on Google App Engine
--------------------------------------------------------------------------------

Suppose you have a encryptedData with some key using blowfish and base64 from PHP code and you want to decrypt it using Java....

public static String doubleDecryption_Base64_Blowfish(String to_decrypt,String key,String charSet){          
          // charSet="UTF-8";
           Cipher cipher;
            try {
               byte[] decodedBytes = Base64.decodeBase64(to_decrypt.getBytes(charSet));
               if(decodedBytes.length % 8 != 0){ //not a multiple of 8
                   System.out.println("decodedBytes is not padded properly in 8 bits");
                   //create a new array with a size which is a multiple of 8
                   byte[] padded = new byte[decodedBytes.length + 8 - (decodedBytes.length % 8)];
                   //copy the old array into it
                   System.arraycopy(decodedBytes, 0, padded, 0, decodedBytes.length);
                   decodedBytes = padded;
               }else{
                   System.out.println("decodedBytes is padded properly in 8 bits");
               }
              
               byte[] keyBytes=key.getBytes(charSet);
               SecretKeySpec secretkey = new SecretKeySpec(keyBytes, "Blowfish");
               cipher = Cipher.getInstance("Blowfish/ECB/NoPadding");
               cipher.init(Cipher.DECRYPT_MODE, secretkey);      
               byte[] decryptedFinal = cipher.doFinal(decodedBytes);
               return new String(decryptedFinal);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
       }      

Wednesday, February 13, 2013

Send POST request using java.net.URLConnection and parse xml response

Send POST request on server....
-------------------------------------------------------------------

public static StringBuffer getWebServiceResponse(String urlString,
String to, String from, String subject, String mailBody) {
StringBuffer dataBuffer = new StringBuffer();
String charset = "UTF-8";

String query;
OutputStream output = null;
try {
query = String.format(
"to=%s&from=%s&subject=%s&mailBody=%s",
URLEncoder.encode(to, charset),
URLEncoder.encode(from, charset),
URLEncoder.encode(subject, charset),
URLEncoder.encode(mailBody, charset));
            log.info("query:"+query);
URLConnection connection;
if (ETradeConstants.PROXY_URL != null) {
connection = new URL("http", "10.10.10.1", 3128, urlString)
.openConnection(); // For MA local machine
} else {
connection = new URL(urlString).openConnection(); // For AppEngine
}

connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + charset);

output = connection.getOutputStream();
output.write(query.getBytes(charset));

InputStream response = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(
response));
String line;
while ((line = rd.readLine()) != null) {
dataBuffer.append(line);
}

} catch (UnsupportedEncodingException e) {
log.severe("UnsupportedEncodingException:" + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
log.severe("IOException:" + e.getMessage());
e.printStackTrace();
} finally {
if (output != null)
try {
output.close();
} catch (IOException logOrIgnore) {
}
}

return dataBuffer;
}
----------------------------------------------

Parse this XML response. from StringBuffer....



public static EmailResponse parseXMLResponse(StringBuffer xml) {
EmailResponse emailResponse = new EmailResponse();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputStream is = new StringBufferInputStream(xml.toString());
Document doc = db.parse(is);
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName("info");
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt
.getElementsByTagName("result");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();

emailResponse.setResult(((Node) fstNm.item(0))
.getNodeValue());
NodeList lstNmElmntLst = fstElmnt
.getElementsByTagName("error");
Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
NodeList lstNm = lstNmElmnt.getChildNodes();
String error;
if(lstNm !=null && lstNm.item(0) !=null){
error=((Node) lstNm.item(0)).getNodeValue();
}else{
error="None";
}
emailResponse.setError(error);
}
}
} catch (Exception e) {
log.severe("emailResponse:parseXMLResponse: Exception:"+ e.getMessage());
e.printStackTrace();
}
return emailResponse;
}

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

Where Email response...



public class EmailResponse {
private String result;
private String error;

public EmailResponse() {

}

public String toString(){
StringBuilder builder = new StringBuilder();
builder.append("EmailResponse [result=");
builder.append(result);
builder.append(", error=");
builder.append(error);
builder.append("]");
return builder.toString();
}
public void setResult(String result) {
this.result = result;
}

public String getResult() {
return result;
}

public void setError(String error) {
this.error = error;
}

public String getError() {
return error;
}


}





Tuesday, January 29, 2013

Change timestamp by adding seconds in Java


1) Using Timestamp 
                long myDate= System.currentTimeMillis();
       int sec = 300;
       Timestamp originalTime = new Timestamp(myDate);
       Calendar calender = Calendar.getInstance();
        calender.setTimeInMillis(originalTime.getTime());
        calender.add(Calendar.SECOND, sec);
        Timestamp afterAdd = new Timestamp(calender.getTime().getTime());

       System.out.println(originalTime);
       System.out.println(afterAdd);

2) Using given date
          public void addTimeBySecondsDemo(Date date,int sec){
        //int sec = 300;
        System.out.println("Given date:"+date);
        Calendar calender = Calendar.getInstance();
        calender.setTimeInMillis(date.getTime());
        calender.add(Calendar.SECOND, sec);
        Date changeDate=cal.getTime();
        System.out.println("changeDate ..:"+changeDate);
   }

Friday, January 25, 2013

com.google.appengine.api.memcache.MemcacheServiceException: Memcache put: Error setting single item


Uncaught exception from servlet
com.google.appengine.api.memcache.MemcacheServiceException: Memcache put: Error setting single item (SearchedMvNews_key)
at com.google.appengine.api.memcache.AsyncMemcacheServiceImpl$7.transform(AsyncMemcacheServiceImpl.java:423)
at com.google.appengine.api.memcache.AsyncMemcacheServiceImpl$7.transform(AsyncMemcacheServiceImpl.java:415)
at com.google.appengine.api.memcache.MemcacheServiceApiHelper$RpcResponseHandler.convertResponse(MemcacheServiceApiHelper.java:57)
at com.google.appengine.api.memcache.MemcacheServiceApiHelper$1.wrap(MemcacheServiceApiHelper.java:101)
at com.google.appengine.api.memcache.MemcacheServiceApiHelper$1.wrap(MemcacheServiceApiHelper.java:96)
....
....
Sol: Please see the size that you are going to put in Memcache. It should not cross max size allowed.

Jquery Mobile issue: data-direction="reverse" changes transition direction


 Jquery Mobile issue: data-direction="reverse" changes transition direction
   It modified transition from left to right for that page always...
 
Solution:    use : data-back="true" data-ajax="false" inplace of data-direction="reverse" 

Tuesday, January 22, 2013

Execute scripts inside document.getElementById().innerHTML


 Execute <script> (Java Script) tag from innerHTML
 -------------------------------------------------------------
 1. Replace <script> your script data to be executed. </script> tag
    with <div class="javascript">your script data to be executed. </div> 


2. add a style in your page...
   <style type="text/css"> .javascript { display: none; } </style>

3. Now run  eval using jquery(Jquery js should be already included)
     $('.javascript').each(function() {
      eval($(this).text());
    });

Thursday, January 17, 2013

com.google.appengine.api.datastore.DatastoreNeedIndexException:


Uncaught exception from servlet
com.google.appengine.api.datastore.DatastoreNeedIndexException: The index for this query is not ready to serve. See the Datastore Indexes page in the Admin Console.
The suggested index for this query is:
    <datastore-index kind="TrackUserDetails" ancestor="false" source="manual">
        <property name="userId" direction="asc"/>
        <property name="inTime" direction="desc"/>
    </datastore-index>


at com.google.appengine.api.datastore.DatastoreApiHelper.translateError(DatastoreApiHelper.java:39)
at com.google.appengine.api.datastore.DatastoreApiHelper$1.convertException(DatastoreApiHelper.java:70)
at com.google.appengine.api.utils.FutureWrapper.get(FutureWrapper.java:94)
at com.google.appengine.api.utils.FutureWrapper.get(FutureWrapper.java:86)
at com.google.appengine.api.datastore.FutureHelper.getInternal(FutureHelper.java:71)
at com.google.appengine.api.datastore.FutureHelper.quietGet(FutureHelper.java:32)
at com.google.appengine.api.datastore.QueryResultsSourceImpl.peekQueryResultAndIfFirstRecordIndexList(QueryResultsSourceImpl.java:161)
at com.google.appengine.api.datastore.QueryResultsSourceImpl.loadMoreEntities(QueryResultsSourceImpl.java:104)
at com.google.appengine.api.datastore.QueryResultsSourceImpl.loadMoreEntities(QueryResultsSourceImpl.java:91)
at com.google.appengine.api.datastore.QueryResultIteratorImpl.ensureLoaded(QueryResultIteratorImpl.java:142)
at com.google.appengine.api.datastore.QueryResultIteratorImpl.hasNext(QueryResultIteratorImpl.java:62)
at com.googlecode.objectify.util.TranslatingIterator.hasNext(TranslatingIterator.java:29)
at com.googlecode.objectify.impl.QueryImpl.get(QueryImpl.java:389)
at com.minyanville.bnb.etrade.web.Util.UserDetailsDataStoreUtil.updateOutTime(UserDetailsDataStoreUtil.java:218)
at com.minyanville.bnb.etrade.web.action.LoginAction.execute(LoginAction.java:119)
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:43)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:452)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:254)
at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:166)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.struts2.gae.interceptor.GaeFileUploadInterceptor.intercept(GaeFileUploadInterceptor.java:203)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at 
......
....
---------------------------------------

Solution: If you are using Java on Google app engine, please add a file datastore-indexes.xml in WEB-INF folder with following content...


<?xml version="1.0" encoding="UTF-8"?>
<datastore-indexes autoGenerate="true">
   <datastore-index kind="TrackUserDetails" ancestor="false" source="manual">
        <property name="userId" direction="asc"/>
        <property name="inTime" direction="desc"/>
   </datastore-index>
</datastore-indexes>


You can define index here for datastore.



Monday, January 14, 2013


HibernateException:Cannot convert value '0000-00-00 00:00:00' from column 15 to TIMESTAMP.
org.hibernate.exception.GenericJDBCException: Cannot convert value '0000-00-00 00:00:00' from column 15 to TIMESTAMP.
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at $Proxy9.executeQuery(Unknown Source)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1953)
at org.hibernate.loader.Loader.doQuery(Loader.java:829)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:289)
at org.hibernate.loader.Loader.doList(Loader.java:2438)
at org.hibernate.loader.Loader.doList(Loader.java:2424)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2254)
at org.hibernate.loader.Loader.list(Loader.java:2249)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:470)
....
....
....
....

------------------------------------------------------------------------------------------
Solution 
   1): Put <property name="hibernate.connection.zeroDateTimeBehavior">convertToNull</property>  in hibernate-cfg.xml 


mysql local instance setup error on google app engine


 Exception:java.lang.ClassNotFoundException: com.mysql.jdbc.Driver java.lang.IllegalStateException: 
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at com.google.appengine.api.rdbms.dev.LocalRdbmsServiceLocalDriver.registerDriver(LocalRdbmsServiceLocalDriver.java:95)


----------------------------------
Sol: Put mysql-connectorXXXX.jar into .....XXX\appengine-java-sdk-1.7.3\lib\impl and run again.