Friday, September 2, 2016

inserting record from xsjs to HANA DB


// sample to insert a record in Database  (Very basic code to insert a record)

// create a connection
var conn = $.db.getConnection();

// prepare the statement 
var stmt =  "insert into \"WORKSHOPA_00\".\"workshop.sessiona.00.data::address\" values('65','chennai','chennai','Tamil Nadu')";

// syntax for the above  stmt 
   //  "insert into <schema name >.<table> values('','','') "

// execute the statement 
conn.prepareStatement(stmt).execute();

// commit it in order to reflect the data chnages in hana DB
conn.commit(); 

// and finally close the connection
conn.close(); 


Thursday, September 1, 2016

Java interview questions for experienced - set 1

What is the major advantage of autoboxing?
   Autoboxing is the automatic conversion that the Java compiler makes between the primitive types     and their corresponding object wrapper classes. For example, converting an int to an Integer, a     double to a Double, and so on. If the conversion goes the other way, this is called unboxing.
 
   For Ex : Arraylist.add(5);  // here primitive type converted to object using autoBoxing
 
   Advantage : lesser code , looks clear
   DisAdvantage : Can lead to unexpected behaviour :  esp in comparission "equal / == " .. equal meant for object whereas == meant for primitive type
             NPE : You can get a NullPointerException, if the wrapper object is null and is unboxed. Pointing out the obvious there can’t be a NullPointer  with primitive variables, but they can have the value zero.


Difference between IsInstance and Instanceof.
   Instanceof : when you know the type in compile time   (  obj instanceof MyCustomActivity)
   IsInstance  : type at runtime  ( Class.forName(arg[0]).Isinstance(obj) )

Reason Why Wait , Notify and NotifyAll are in Object Class.
  a) Wait and notify is not just normal methods or synchronization utility, more than that they are communication mechanism between two threads in Java
  b) Locks are made available on per Object basis, which is another reason wait and notify is declared in Object class



Synchronized and Concurrenthashmap

SynchronizedHashMap
       1.Synchronization at Object level.
       2. Every read/write operation needs to acquire lock.
       3. Locking the entire collection is a performance overhead.
          This essentially gives access to only one thread to the entire map & blocks all the other threads.
    ConcurrentHashMap
       1. You should use ConcurrentHashMap when you need very high concurrency in your project.
       2. It is thread safe without synchronizing the whole map.
       3. Reads can happen very fast while write is done with a lock.
       4. There is no locking at the object level.
    The locking is at a much finer granularity at a hashmap bucket level.


to know hashmap internal


String vs StringBuffer vs StringBuilder










Wednesday, August 31, 2016

HashMap internals

Write operation in Hashmap

         API call à hashmap.put(KEY,VALUE);
         1.  When you call this function, KEY (object) hashcode function gets called.
         2.  return value of the hashcode() is integer.
         3.  This value is divided by max_bucket value    
         4.   key,value and hashcode are stored respective buckets new entry        

NOTE : So far, we haven’t discussed about the equals function.





Read opearion in Hashmap

API call à hashmap.get(KEY);
         1.  When you call this function, KEY (object) hashcode function gets called.
         2.  return value of the hashcode() is integer.
         3. from the hashcode, it finds the bucket and traverse to the list to find the hashcode
         4. Once it matches with hashcode, it checks with object equality using equals() method defined in KEY class ( from this point, you can infer another point.
          a) if objects are equal, then hashcode must be same. So that it fall in same bucket
          b) if hashcode is same, it doesn’t mean that objects are equals  )
  

Tuesday, August 30, 2016

Configure Spark on windows , some error and solution


Step 1 : Download and install latest version of scala
Step 2 : Download and install latest version of sbt
Step 3 : download any spark version and extract using linux environment
Step 4 : Go to the root folder of the spark  and run "sbt package" command
        This will download few jar file , it may take some time.
       add proxy in sbtconfig.txt (sbt\conf\sbtconfig.txt) in case you are behind proxy

Step 5: run spark-shell
  Error :
 C:\Program Files (x86)\spark-2.0.0-bin-hadoop2.7\bin>spark-shell
'Files' is not recognized as an internal or external command,
operable program or batch file.
Failed to find Spark jars directory.
You need to build Spark before running this program.

Solution : move your spark folder to C:\













You may end up below error while running Spark in local mode
16/08/30 17:40:29 ERROR RetryingBlockFetcher: Exception while beginning fetch of 1 outstanding blocks
java.io.IOException: Failed to connect to /10.91.152.141:62303
        at org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:228)

Solution for above error
     Spark/bin > spark-shell --master local


Error :
  ERROR Shell: Failed to locate the winutils binary in the hadoop binary path
java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries.

Solution :
     Add new environmental variable HADOOP_HOME and value should be path of the winutils.exe





Monday, August 29, 2016

what is Immutable and benefit of Immutable

What is immutable class
         Value of the member variable can’t change once its set

What is the benefit of having immutable?
     As immutable class is read only, it can be used in multi-threading environment without worrying about race condition
        
How to create a class as immutable
   Goal : Create a class, if you have created object for that class, then value should be changed
   Let’s take a class employee
Step 1:  create employee class

  class employee{  
    private int emp_id;  
    private String emp_name;  
    private int emp_age;  
    }  

Problem :  Anyone can declare public function through which can change the value of the variable.
Solution : Declare those variable as final, So that only constructor can assign the value to  the variable

Step 2 : Declare member variable as final

 class employee{  
    private final int emp_id;  
    private final String emp_name;  
    private final int emp_age;  
    public employee (int ID,String NAME , int age){  
        emp_id = ID;  
        emp_name = NAME;  
        emp_age = age;   
     }  
    }  

Remember, if you are passing any object as an input param, then that needs to be deep copied.
Problem : How to retrieve the value of the class
Solution:  Add getter method  , scope is public

Step 3 : Add getter method to retrieve the value

 public int getID(){  
   return emp_id;  
 }  
 public String getName(){  
     return emp_name;  
 }   
        

Step 4 : declare class as final, So that it can’t be inherited

 public final class employee{  
 …  
 …  
 }  

What are the immutable classes available in java ?

         String   class is the best example of the immutable 

Wednesday, August 24, 2016

Hashcode and Equals method


Both methods are declared in Object.java (which is parent for all the java classes)

Below snapshot taken from Object.java file



 public boolean equals(Object o) {  
     return this == o;  
   }  
 public int hashCode() {  
     int lockWord = shadow$_monitor_;  
     final int lockWordMask = 0xC0000000; // Top 2 bits.  
     final int lockWordStateHash = 0x80000000; // Top 2 bits are value 2 (kStateHash).  
     if ((lockWord & lockWordMask) == lockWordStateHash) {  
       return lockWord & ~lockWordMask;  
     }  
     return System.identityHashCode(this);  
   }  


Equals method : To check the equality of the two object
    from the above code , if you are not overriding the equals method, then it will check memory address rather than the object . 

  Assume you have a employee class where emp_id is unique , then you need to override the eqquls like below 


 @Override
 public boolean equals(Object o) {  
     return this.emp_id == o.emp_id;  
   }  



Hashcode method : 
       hashcode method will comes in to the picture , if you are using this class's object  as a key in hashmap.
you no need to override this method if you are not using this class as a key.

Nowadays, modern editor will implement hashcode() for you to get the decent hashcode value.


Ok, now we have seen hashcode and equals method separately.. 
  Now ,Question is , any contract between this two method ...

Contract between the two methods Yes ,  in case two object is equal , then hashcode value should be same.
         if hashcode of the two object is same , then object may or may not be equal.

Well, to understand the above statement , we need to know the internal implementation of the hashmap and how read and write happens.

will talk about the those topic soon. stay tuned.   
         

Tuesday, August 23, 2016

Solution for error : java.lang.AbstractMethodError: javax.ws.rs.core.UriBuilder.uri


Error :
javax.servlet.ServletException: Servlet execution threw an exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause

java.lang.AbstractMethodError: javax.ws.rs.core.UriBuilder.uri(Ljava/lang/String;)Ljavax/ws/rs/core/UriBuilder;
javax.ws.rs.core.UriBuilder.fromUri(UriBuilder.java:119)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:626)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)


Pom.xml file

<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
</dependency>

<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.2</version>
</dependency>

Solution:
there is a conflict , you need to remove javax.ws.rs dependency .. anyway com.sun.jersy have the same classes to do the task.