Sunday, December 21, 2014

Integer wrapper return true from range -128 to 127

We are already familiar with boxing and auto boxing of wrapper to premitives and vice-verse.

See the below example.

    Integer integer1=127;
    Integer integer2=127;

    System.out.println(integer1==integer2);//The output will be true.
   
But as we increase the value from 127 to 128 you will see the output is different.
   
    Integer integer1=128;
    Integer integer2=128;

    System.out.println(integer1==integer2);//The output will be False.

As per JLC the boxed value returns true for int or short in the range of -128 to 127(included). It also returns true for a byte or a char in the range of \u0000 to \u007f.



Thursday, December 18, 2014

Finding all elements whose Id starts with a specific word using jQuery

Some time we come across with a problem where we have a lots of elements in HTML or JSP page which is generated dynamically and their ID starts with some special word.
Like as follows


<input id="item_1fruit" name="fruit" type="text"  value=" Mango" />
<input id="item_2veg" name="vegetable" type="text" value="Potato" />
<input id="item_3eggs" name="eggs" type="text" value="Eggs" />
<input id="item_4nuts" name="nuts" type="text" value="Almonds"/>

So above we can get all elements in jQuery as follow

$("[div^=item_]")   // do whatever you want
 In below code we are iterating all the elements and setting some values.

$("[div^=item_]").each(function(){

     var text_value= $(this).val();
      alert("Text box value "+text_value);
        });


Autoboxing and Unboxing in Java



Autoboxing means conversion of java premitives to their corresponding wrapper object class, it happens automatically by the java compiler.
For example int to Integer, double to Double.

Unboxing is quite opposite to the autoboxing means java wrapper objects are automatically converts to their premiteves by compiler.
For example Integer to int, Boolean to boolean,Double to double.

See the below written code snap
Autoboxing
a.       int x=100;
                     Integer int_val=x;
b.     double amount=10.50;
  Double amount_val=amount;
Unboxing
a.       Integer int_val=new Integer(100);
 int score=int_val;
b.    Double amount=new Double(100.50);
                    double total_amount=amount;

Using this java feature we can  also assign any value to the super class Object.
For example you can write code as follows using Autoboxing.

        Object x=1;
       Object name="Singh";
       System.out.println(x);
       System.out.println(name);

The above code will run successfully.
 This feature was introduced in Java 5 realease in September 2004.

Sunday, December 14, 2014

Accessing Private Methods and Variables in Java using Reflection API


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//Accessing Private methods using Reflection

public class Test {
 public static void main(String ag[])
 {
  A obj=new A();

  try {
   Class c=obj.getClass();
   Method method=c.getDeclaredMethod("msg", null);
   //System.out.println(method);
   try {

    method.setAccessible(true);
    method.invoke(obj,null);//Calling Private method of a class.

   } catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (InvocationTargetException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  } catch (SecurityException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (NoSuchMethodException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }


 }
}
////////////second class************Having Private methods
class A
{
 private void msg()
 {
  System.out.println("In class A of private Mehod");
 }
}


//Hi Guys we can access the private fields of a java class using reflection in the same way.
Thanks
Pankaj Kumar Singh

Sunday, September 7, 2014

Double Locking Or Double check in Singleton Class

Double Locking Or Double Check in Singleton


Now these days it is a frequently asked question that how you will create double locking singleton class.

It is nothing new as earlier we were using Synchronize key-work before method, the same key world we will use while creating instance of the singleton class.

See the below written code snap.


private SingletonInstance instance=null;

 public SingletonInstance getInstance() {
        if (instance == null) {
            synchronized (SingletonInstance.class) {
                if (instance == null) {
                    instance = new SingletonInstance();
                }
            }
        }
        return instance;
    }

Wednesday, September 3, 2014

MongoDB with Spring MVC Example

BigData MongoDb With Spring MVC



1. POM.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>springData</groupId>
    <artifactId>springData</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>springData</name>
    <url>http://maven.apache.org</url>

    <properties>
        <java.version>1.6</java.version>
        <spring.version>3.2.3.RELEASE</spring.version>
        <cglib.version>2.2.2</cglib.version>
    </properties>

    <dependencies>
        <!-- Spring core & mvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>${spring.version}</version>
 
 
</dependency>

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-beans</artifactId>
  <version>${spring.version}</version>
</dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- CGLib for @Configuration -->
        <dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>2.2.2</version>
</dependency>
        <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.14</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.7.3</version>
</dependency>
   <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.7.3</version>
</dependency>
<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.0</version>
</dependency>
<dependency>
   <groupId>asm</groupId>
   <artifactId>asm-all</artifactId>
   <version>2.1</version>
</dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>${cglib.version}</version>
            <!-- <scope>runtime</scope> -->
        </dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>${spring.version}</version>
</dependency>

<!--Mongo DB dependency  -->

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.4.1.RELEASE</version>
</dependency>

        <!-- Servlet Spec -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.4</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

<!-- Build Functionality.... -->
    <build>
        <finalName>springData</finalName>
       
          <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.4</version>
        <configuration>
                        <source>${java.version}</source>
                    <target>${java.version}</target>
        </configuration>
      </plugin>
    </plugins>
    </build>
</project>

2. Spring Context .xml Configuration


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans    
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/data/mongo
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
       
       
   
   

    <context:component-scan base-package="com.springData.controller" />
    <context:annotation-config/>


  <!-- Factory bean that creates the Mongo instance -->
    <bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
        <property name="host" value="localhost" />
    </bean>
    
    <!-- MongoTemplate for connecting and quering the documents in the database -->
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongo" ref="mongo" />
        <constructor-arg name="databaseName" value="mongoTest" />
    </bean>

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/views/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>


3. WEB.XML File..

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>springData</display-name>
   

    <servlet>
        <servlet-name>springData</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springData</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
    <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
   
</web-app>

4. Controller and Model classes
a.Controller
**************************
package com.springData.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.springData.dao.Person;

@Controller
public class HomeController {

     @Autowired
        private PersonService personService;
    @RequestMapping("/welcome.htm")
    public String welcomePage(HttpServletRequest request,HttpServletResponse response)
    {
        System.out.println("Calling WElcome Controller");
        Person person=new Person();
        person.setId("13");
        person.setName("Pankaj");
        personService.addPerson(person);
        List<Person> personList= personService.listPerson();
   
       
        return "welcome";
    }
}

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

Bean
****************************

package com.springData.dao;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class Person {

    @Id
    private String id;
    private String name;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
******************************
service Repository
*********************************

package com.springData.controller;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;

import com.springData.dao.Person;

@Repository
public class PersonService {
   
    @Autowired
    private MongoTemplate mongoTemplate;
    
    public static final String COLLECTION_NAME = "person";
    
    public void addPerson(Person person) {
        if (!mongoTemplate.collectionExists(Person.class)) {
            mongoTemplate.createCollection(Person.class);
        }     
        person.setId(UUID.randomUUID().toString());
        mongoTemplate.insert(person, COLLECTION_NAME);
    }
    
    public List<Person> listPerson() {
        return mongoTemplate.findAll(Person.class, COLLECTION_NAME);
    }
    
    public void deletePerson(Person person) {
        mongoTemplate.remove(person, COLLECTION_NAME);
    }
    
    public void updatePerson(Person person) {
        mongoTemplate.insert(person, COLLECTION_NAME);    
    }

}
************************************









Wednesday, June 4, 2014

Dynamic insert and Dynamic update in Hibernate



Hibernate Dynamic insert and Dynamic update


1.       Dynamic insert: In hibernate by default dynamic insert attribute is false it means when an object is inserted to the database it will include all columns whose values are null i.e. it will generate an insert statement with all unnecessary columns. For example see below code.
        Stock stockTran = new Stock ();
        //stockTran.setPriceOpen(new Float("1.2"));
        //stockTran.setPriceClose(new Float("1.1"));
        //stockTran.setPriceChange(new Float("10.0"));
        stockTran.setVolume(2000000L);
        stockTran.setDate(new Date());
        stockTran.setStock(stock);

        session.save(stockTran);

make show_sql true in hibernate configuration and you will see following insert statement generated by Hibernate SQL.

INSERT 
    INTO
stock
        (DATE, PRICE_CHANGE, PRICE_CLOSE, PRICE_OPEN, STOCK_ID, VOLUME) 
    VALUES
        (?, ?, ?, ?, ?, ?)

Hibernate will generate the unnecessary columns (PRICE_CHANGE, PRICE_CLOSE, PRICE_OPEN) for the insertion.


Now make dynamic insert attribute true and try to insert the same stock object data and you will see that hibernate insert statement excludes all the null property values.
Now hibernate generates the following insert statement.
    INSERT 
    INTO
        stock
        (DATE, STOCK_ID, VOLUME) 
    VALUES
        (?, ?, ?)


Hibernate will generate only the necessary columns (DATE, STOCK_ID, VOLUME) for the insertion.

The main concern is performance issue
In some situations, such as a very large table with hundreds of columns (legacy design), or a table contains extremely large data volume, insert something not necessary definitely will drop down your system performance. So it is highly recommended to use the Dynamic Insert attribute true.

a.       Dynamic insert configuration using Annotation
@Entity
@Table(name = "stock ")
@org.hibernate.annotations.Entity(
              dynamicInsert = true
)
public class Stock implements java.io.Serializable {}
 
 
b.      Dynamic insert configuration using XML
<class ... table="stock " dynamic-insert="true">
        <id name="stockId" type="java.lang.Integer">
            <column name="STOCK_ID" />
        </id>

 



2.       Dynamic Update: By default hibernate set this attribute false means when we updated an object to the database using hibernate it generate the update SQL for all columns i.e. also for the columns those are not modified due to this update statement we face the system performance issue if we are playing with a table which has many columns or more data.
For example see the below code.

Query q = session.createQuery("from Stock where stockId = : stockId");
   q.setParameter("stockId ", 11);
   Stock stock = (Stock)q.list().get(0);
 
   stock.setVolume(4000000L);
   session.update(stock);
 
 
Hibernate will generate the following update statement
 
    UPDATE
        stock 
    SET
        DATE=?,
        PRICE_CHANGE=?,
        PRICE_CLOSE=?,
        PRICE_OPEN=?,
        STOCK_ID=?,
        VOLUME=? 
    WHERE
        STOCK_ID=?
 
That is hibernate will update all the unmodified columns.
 
But when we make dynamic update attribute true which means all the unmodified columns will be excluded from the updated statement.
For the above written update code hibernate will generate the following sql.
 
UPDATE
stock 
    SET
        VOLUME=? 
    WHERE
        STOCK_ID=?
 
That is hibernate will updated the modified columns only.
 
Performance Concern: 
In a large table with many columns (legacy design) or contains large data volumes, update some unmodified columns are absolutely unnecessary and great impact on the system performance. So we should use the dynamic update attribute true.

a.       Dynamic update configuration using Annotation
@Entity
@Table(name = "stock ")
@org.hibernate.annotations.Entity(
         dynamicUpdate = true
)
public class Stock implements java.io.Serializable {}
 
b.      Dynamic update configuration using XML
<class ... table="stock " dynamic-update="true">
        <id name="stockId" type="java.lang.Integer">
        <column name="STOCK_ID" />
 
//add generator
        </id>
 


Tuesday, June 3, 2014

Prefer lists to arrays or Generic List VS Array

Generic List Vs Array


Consider the below mentioned code fragments.
// Fails at runtime!
Object[] objectArray = new Long[1];
objectArray[0] = "I don't fit in"; // Throws ArrayStoreException

but this one is not:
// Won't compile!
List<Object> ol = new ArrayList<Long>(); // Incompatible types
ol.add("I don't fit in");

Either way you can’t put a String into a Long container, but with an array you
find out that you’ve made a mistake at runtime; with a list, you find out at compile
time. Of course you’d rather find out at compile time.

The second major difference between arrays and generics is that arrays are
reified [JLS, 4.7]. This means that arrays know and enforce their element types at
runtime. As noted above, if you try to store a String into an array of Long, you’ll
get an ArrayStoreException. Generics, by contrast, are implemented by erasure
[JLS, 4.6]. This means that they enforce their type constraints only at compile
time and discard (or erase) their element type information at runtime. Erasure is
what allows generic types to interoperate freely with legacy code that does not use
generics

Thursday, April 17, 2014

Why it happens?

String s1="hello"; String S2= s1+ " world"; String S3="helloworld"; is (s2==s3)?? if no why,  if yes why?

Saturday, February 15, 2014

Make an option in select box readonly not disabled using jquery.

HTML

//HTML Code
<select name="select1" id="select1">
    <option>No Match</option>
    <option value="1">Test</option>
    <option value="2">Test 2</option>
    <option value="3">Test 3</option>
</select>

<select name="select2" id="select2">
    <option>No Match</option>
    <option value="1">Test</option>
    <option value="2">Test 2</option>
    <option value="3">Test 3</option>
</select>

Jquery Code

//JavaScript Code

$('#select1').change(function() {
    
    var value = $(this).val();
  $('#select2').children('option').each(function() {
        if ( $(this).val() != value ) {
            $(this).attr('disabled', true);   
        }
    });
    
});

Spring Boot Config Server and Config Client.

 In Spring cloud config we can externalise our configuration files to some repository like GIT HUT, Amazon S3 etc. Benefit of externalising ...