Posts

Showing posts from 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

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

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

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 Ava

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]

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        )

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>

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

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.Lin

Google Ads Developer Blog: Google App Engine for Java meet DFP API, Part 1: H...

Google Ads Developer Blog: Google App Engine for Java meet DFP API, Part 1: H... : We are excited to start discussing how to use the DFP API from within the Google App Engine (Java) environment. This first blog post in th...

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

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.

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

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.

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.array

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

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

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" 

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

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 co
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(

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.