Monday, April 13, 2015

jQuery Validation at least one checkbox is selected by name


JSP Code:

<c:forEach items="${alerts.npUserList}"  var="alertsUser">
                                    <c:if test="${not empty fn:trim(alertsUser.email)}">
                                        <p>
                                            <input type="checkbox" id="pageTrack_<c:out value='${alertsUser.id}' />" class='pageTrack' name="pageTrack" value="<c:out value='${alertsUser.id}' />" />
                                            <c:out value="${alertsUser.email}" />
                                        </p>
                                        </c:if>  
                                     </c:forEach>

Jquery Code:
var pageTrack = (jq("input[type='checkbox'][name='pageTrack']:checked").length > 0);

The above jquery code will return true when one or more than one check box selected.

Thursday, March 26, 2015

Calling a Rest service from Springs

In Springs we have RestTemplate class. from this class we call the rest services.Below are the sample code for Get and Post requests.

@Autowired
RestTemplate restTemplate;


Calling a Get method:
Map<String, String> domainCategories = restTemplate.getForObject("http://test.com?reportId=100" Map.class);

Calling a Post Method:

TriageFirstCutResponse response = restTemplate.postForObject(
"rest URL", triageFirstCutRequest,TriageFirstCutResponse.class);

here triageFirstCutRequest is an object.which is the post parameter.

Tuesday, March 17, 2015

Marshalling and un-marshalling.

In few words, "marshalling" refers to the process of converting the data or the objects inbto a byte-stream, and "unmarshalling" is the reverse process of converting the byte-stream beack to their original data or object. The conversion is achieved through "serialization".

The purpose of the "marshalling/unmarshalling" process is to transfer data between the RMI system.


JAXB(Java Architecture for XML Binding) allows Java developers to map Java classes to XML representations. JAXB provides two main features: the ability to marshal Java objects into XML and the inverse, i.e. to unmarshal XML back into Java objects. JAXB mostly is used while implementing webservices or any other such client interface for an application where data needs to be transferred in XML format instead of HTML format which is default in case of visual client like web browsers.

Tuesday, March 10, 2015

Method level Injection with spring (Injecting prototype model in to singleton model)

When we want to inject prototype model object into singleton object we will be having an issue.

How we can achieve this in spring? we have a concept calling method injection. All beans in the spring's are singleton by default,
meaning spring instantiates them during context creation,caches them in context, when ever it needed it will load from cache,
if you make a particular object scope as prototype and you want to inject this object into other singleton object the actual problem arrives.

public class Singleton {

    private Prototype prototype;

    public Singleton(Prototype prototype) {

        this.prototype = prototype;
    }

    public void doSomething() {

        prototype.foo();
    }

    public void doSomethingElse() {

        prototype.bar();
    }
}

The below code displays the correct code of method injection:

public abstract class Singleton {

    protected abstract Prototype createPrototype();

    public void doSomething() {

        createPrototype().foo();
    }

    public void doSomethingElse() {

        createPrototype().bar();
    }
}

As you noticed, code doesn’t specify the createPrototype() implementation. This responsibility is delegated to Spring, hence the following needed configuration:

<bean id="prototype" class="ch.frankel.blog.Prototype" scope="prototype">

<bean id="singleton" class="sample.MySingleton">
  <lookup-method name="createPrototype" bean="prototype">
</lookup-method></bean></bean>





Friday, February 27, 2015

Some Design Pattern

Factory Pattern:

Abstract Factory Pattern:called as factory of factories

Singleton Pattern: 


public class SingleObject {
   //create an object of SingleObject
   private static SingleObject instance = new SingleObject();
   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}
   //Get the only object available
   public static SingleObject getInstance(){
      return instance;
   }
   public void showMessage(){
      System.out.println("Hello World!");
   }

}

Builder Pattern:
Builds a complex object using simple objects and using a step by step approach.
Builder Pattern UML Diagram
Facade Patterns:
pattern hides the complexities of the system and provides an interface to the client using which the client can access the system.

Prototype Pattern:
This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when creation of object directly is costly. For example, an object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.

Proxy Pattern:
session.load() is the best example for prototype pattern: It will just create a proxy object when its really required then it loads from data base.




Friday, February 20, 2015

Simple Web Service.

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

@WebService()
public class DomainSearchWebService {

public void TmProntoWebService() {
}

@WebMethod()
@WebResult(name = DOMAINS)
public DomainName[] query(@WebParam(name = QUERY) final String query) {
return getDomainByQuery(query, null, null).getDomainNames();
}

Friday, February 6, 2015

Hibernate

SessionFactory:

S.F. is an interface. The main contract here is the creation of Session instances. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.
The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping.
Implementors must be threadsafe.

SessionFactory sessionFactory = configuration.buildSessionFactory();
Simple words: S.F. is threadSafe. from the factory we will get session objects.


Session: 

Session is an interface and is a main runtime interface between a Java application and Hibernate. This is the central API class abstracting the notion of a persistence service.

The lifecycle of a Session is bounded by the beginning and end of a logical transaction. (Long transactions might span several database transactions.)

The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states:

transient: never persistent, not associated with any Session
persistent: associated with a unique Session
detached: previously persistent, not associated with any Session.

It is not intended that implementors be threadsafe. Instead each thread/transaction should obtain its own instance from a SessionFactory.

A typical transaction should use the following idiom:

 Session sess = factory.openSession();
 Transaction tx;
 try {
     tx = sess.beginTransaction();
     //do some work
     ...
     tx.commit();
 }
 catch (Exception e) {
     if (tx!=null) tx.rollback();
     throw e;
 }
 finally {
     sess.close();

 }
Simple Words: Session is a single threaded and shot lived object.

Query & Criteria interfaces

Load vs get:
session.load()
load will through an exception when there is no record found and it will always return proxy object/fake object.
It will always return a proxy object with the given identity value, even the identity value is not exists in database. However, when you try to initialize a proxy by retrieve it’s properties from database, it will hit the database with select statement. If no row is found, a ObjectNotFoundException will throw.


 Stock stock = (Stock)session.get(Stock.class, new Integer(2));
get will return null when the objects was not available in data base. It always get the value from data base real value. select statement will be run in data base and get the actual value.

Simple Words :When we use load it just create proxy object, when we actually call an method's of that proxy object it will hit the data base, in case if that object not available in data base it will through ObjectNotFoundException.

Update() and Merge() :

update will be executed with in the same persistence, ex.
Session session = sessionFactory.getSession();
Employee employee = session.get(Employee.class,3);
session.close();
employee.setName("I am name");
Session session1 = sessionFactory.getSession();
session1.update(session);

//It will through an exception.. stating session was closed...etc. In this case we can use merge() method irrespective of state of session it will update.


Mege:

Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session.


Cascade and Inverse:

1. inverse: This is used to decide which side is the relationship owner to manage the relationship (insert or update of the foreign key column).

2. cascade: In cascade, after one operation (save, update and delete) is done, it decide whether it need to call other operations (save, update and delete) on another entities which has relationship with each other.


Conclusion: In short, the “inverse” is decide which side will update the foreign key, while “cascade” is decide what’s the follow by operation should execute. Both are look quite similar in relationship, but it’s totally two different things. Hibernate developers are worth to spend time to research on it, because misunderstand the concept or misuse it will bring serious performance or data integrity issue in your application.

Basic criteria example:

List employees = session.createCriteria(Employee.class)
        .add(Restrictions.like("name", "a%") )
        .add(Restrictions.like("address", "Boston"))
.addOrder(Order.asc("name") )

.list();
Mappings:

one-to-many-relationship-diagram

@Entity
@Table(name="EMPLOYEE")
public class Employee {

    @Id
    @GeneratedValue
    @Column(name="employee_id")
    private Long employeeId;
   
 @ManyToOne
    @JoinColumn(name="department_id",
                insertable=false, updatable=false,
                nullable=false)
    private Department department;

public class Department{

@OneToMany(cascade={CascadeType.ALL})
    @JoinColumn(name="department_id")
    @IndexColumn(name="idx")
    private Set<employee> employees;

first-level:

The first-level cache is the Session cache and is a mandatory cache through which all requests must pass. The Session object keeps an object under its own power before committing it to the database.
If you issue multiple updates to an object, Hibernate tries to delay doing the update as long as possible to reduce the number of update SQL statements issued. If you close the session, all the objects being cached are lost and either persisted or updated in the database.


second level cache:
Second level cache is an optional cache and first-level cache will always be consulted before any attempt is made to locate an object in the second-level cache. The second-level cache can be configured on a per-class and per-collection basis and mainly responsible for caching objects across sessions.


Any third-party cache can be used with Hibernate. An org.hibernate.cache.CacheProvider interface is provided, which must be implemented to provide Hibernate with a handle to the cache implementation.

Query-level cache:

Hibernate also implements a cache for query resultsets that integrates closely with the second-level cache.


This is an optional feature and requires two additional physical cache regions that hold the cached query results and the timestamps when a table was last updated. This is only useful for queries that are run frequently with the same parameters.


Dialect:
which SQL language should be use to perform data base operations.

Composit-key:

@Entity
public class Project {
    @EmbeddedId ProjectId id;
     :
}

@Embeddable
Class ProjectId {
    int departmentId;
    long projectId;
}

joins in sql:
EmployeeLocation
EmpIDEmpName
13Jason
8Alex
3Ram
17Babu
25Johnson
EmpIDEmpLoc
13San Jose
8Los Angeles
3Pune, India
17Chennai, India
39Bangalore, India


select * from employee left join location
on employee.empID = location.empID;
Employee.EmpIDEmployee.EmpNameLocation.EmpIDLocation.EmpLoc
13Jason13San Jose
8Alex8Los Angeles
3Ram3Pune, India
17Babu17Chennai, India
25JohnsonNULLNULL

select * from employee right join location
on employee.empID = location.empID;

Employee.EmpIDEmployee.EmpNameLocation.EmpIDLocation.EmpLoc
13Jason13San Jose
8Alex8Los Angeles
3Ram3Pune, India
17Babu17Chennai, India
NULLNULL39Bangalore, India

The difference is simple – in a left outer join, all of the rows from the “left” table will be displayed, regardless of whether there are any matching columns in the “right” table. In a right outer join, all of the rows from the “right” table will be displayed, regardless of whether there are any matching columns in the “left” table.




Groovy&Grails get the message resource properties values in service layer


import org.springframework.context.i18n.LocaleContextHolder

def messageSource

messageSource.getMessage('auto.update.zone.failed', null, LocaleContextHolder.locale)
def value =  ["test","test2"].toArray();
messageSource.getMessage('auto.update.zone.success.message',value , LocaleContextHolder.locale)

Messageresources.properties
auto.update.zone.failed=Auto update failed for newly approved zones

auto.update.zone.success.message=Successfully updated newly approved zones and loading took {0}  {1} ms.

Get the environment in groovy.

def environment = Environment.current.name

Thursday, February 5, 2015

Information On OOPS, Collections,Exceptions & Threads.

oop:


InheritanceObject-oriented programming allows classes to inherit commonly used state and behavior from other classes. (Extending the super class properties in to sub class)

class MountainBike extends Bicycle {

    // new fields and methods defining
    // a mountain bike would go here

}
Polymorphism:
Over ridding and over loading

  • Over loading will happen at compile time,
int add(int a,int b)
 float add(float a,int b)
 float add(int a ,float b)
  • Over ridding will be choose at run time.(Super class method overridden in sub class)


Abstraction:
Interfaces and abstract classes

Encapsulation:
wrapping data in to single unit called encapsulations. Java beans..all java object are

Collections


1) Sorting on collections:


A List l may be sorted as follows.

Collections.sort(l);
If the List consists of String elements, it will be sorted into alphabetical order. If it consists of Date elements, it will be sorted into chronological order. How does this happen? String and Date both implement the Comparable interface.

If you try to sort a list, the elements of which do not implement Comparable, Collections.sort(list) will throw a ClassCastException.

Comparable example:

public class Name implements Comparable<Name> {
    private final String firstName, lastName;

    public Name(String firstName, String lastName) {
        if (firstName == null || lastName == null)
            throw new NullPointerException();
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String firstName() { return firstName; }
    public String lastName()  { return lastName;  }

    public boolean equals(Object o) {
        if (!(o instanceof Name))
            return false;
        Name n = (Name) o;
        return n.firstName.equals(firstName) && n.lastName.equals(lastName);
    }

    public int hashCode() {
        return 31*firstName.hashCode() + lastName.hashCode();
    }

    public String toString() {
return firstName + " " + lastName;
    }

    public int compareTo(Name n) {
        int lastCmp = lastName.compareTo(n.lastName);
        return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));
    }
}

import java.util.*;

public class NameSort {
    public static void main(String[] args) {
        Name nameArray[] = {
            new Name("John", "Smith"),
            new Name("Karl", "Ng"),
            new Name("Jeff", "Smith"),
            new Name("Tom", "Rich")
        };

        List<Name> names = Arrays.asList(nameArray);
        Collections.sort(names);
        System.out.println(names);
    }
}

Comparator example:


package com.javacodegeeks.java.util.comparator;

import java.util.Comparator;

public class GradeComparator implements Comparator {

@Override
public int compare(Student o1, Student o2) {

// descending order (ascending order would be:
// o1.getGrade()-o2.getGrade())
return o2.getGrade() - o1.getGrade();
}

}
Collections.sort(arrayListObject,new GradeComparator ()); 
Here arrayListObject contains the list of Student objects, when we call Collections.sort method it will sort based on the grade.

or other way of implementaion:

public class EmpSort {
    static final Comparator<Employee> SENIORITY_ORDER =
                                        new Comparator<Employee>() {
            public int compare(Employee e1, Employee e2) {
                return e2.hireDate().compareTo(e1.hireDate());
            }
    };

    // Employee database
    static final Collection<Employee> employees = ... ;

    public static void main(String[] args) {
        List<Employee> e = new ArrayList<Employee>(employees);
        Collections.sort(e, SENIORITY_ORDER);
        System.out.println(e);
    }
}

2)Collection, List,Set,Map.

Two interface trees, one starting with Collection and including Set, SortedSet, List, and Queue, and the other starting with Map and including SortedMap.

Set: is collection interface, which doesn't contain duplicate elements.
List: is an order collection, it allow you to write duplicate objects.In the list each element is inserted and can access elements by their integer index (position)
Deque: can be used both as FIFO (first-in, first-out) and LIFO (last-in, first-out). In a deque all new elements can be inserted, retrieved and removed at both ends
Queue: FIFO
Map:an object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value.

To get all keys from a Map:
map.keySet(); ->Retrieve all keys from a map.

keySet — the Set of keys contained in the Map.
values — The Collection of values contained in the Map. This Collection is not a Set, because multiple keys can map to the same value.
entrySet — the Set of key-value pairs contained in the Map. The Map interface provides a small nested interface called Map.Entry, the type of the elements in this Set.
Set<Map.Entry<K,V>> entrySet()
Returns a Set view of the mappings contained in this map.

Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Use Iterator instead of the for-each construct when you need to:

Remove the current element. The for-each construct hides the iterator, so you cannot call remove. Therefore, the for-each construct is not usable for filtering.
Iterate over multiple collections in parallel.

ConcurrentHashMap<K,V>:
ConcurrentHashMap in Java is introduced as an alternative of Hashtable, which can be safely used in a concurrent and multi-threaded Java program, than, you only have Hashtable or synchronized Map because HashMap is not thread-safe. With ConcurrentHashMap, now you have better choice; because, not only it can be safely used in concurrent multi-threaded environment but also provides better performance over Hashtable and synchronizedMap. ConcurrentHashMap performs better than earlier two because it only locks a portion of Map, instead of whole Map, which is the case with Hashtable and synchronized Map. allows concurred read operations and same time, maintains integrity by synchronizing write operations





3) equals & hashcode methods.

different key objects could potentially have the same hash code, the hash code itself is no guarantee that the right key is found. The hashtable then iterates this area (all keys with the same hash code) and uses the key's equals() method to find the right key. Once the right key is found, the object stored for that key is returned.

class Employee {
private Long id;

public Long getId() {
return id;
}
public void setId(Long id) {
this.id=id;
}
}

Employee e= new Employee();
e.setId(100);

Employee e1= new Employee();
e1.setId(100);

Set <Employee> employeeSet = new HashSet<Employee>();
employeeSet.add(e);
employeeSet.add(e1);

When iterate the above set it will display the 2 Objects. But as per Set it wont inset the duplicate object. Here there is no equals and hascode method implemented in Employee class, When you implement equals and hashCode method it will not insert duplicate object.

In the case of HashMap, it replaces the old value with the new one.

In the case of HashSet, the item isn't inserted.




4) String -> why it is immutable how it works!

String is immutable and StringBuffer is mutable. In java all immutable objects are thread safe meaning no 2 threads can access same time, String is stored in the  Constant String Pool, from this we can say String is a thread safe.
StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap .  StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .

String s="Sachin";
   s.concat(" Tendulkar");
   System.out.println(s);

Output = "Sachin"

Heap diagram
Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

----------------------------------------------------------------------------------
                                    String                    StringBuffer         StringBuilder
----------------------------------------------------------------------------------                 
Storage Area | Constant String Pool           Heap                       Heap 
Modifiable     |  No (immutable)            Yes( mutable )          Yes( mutable )
Thread Safe   |           Yes                                  Yes                              No
 Performance |         Fast                                Very slow                    Fast
-----------------------------------------------------------------------------------


String str1="Hello";
String str2="Hello";
String str3=new String("Hello") //Using constructor.

If(str1 == str2)
        System.out.println("Equal 1");
Else
        System.out.println("Not Equal 1");

If(str1 == str3)
        System.out.println("Equal 2");
Else
         System.out.println("Not Equal 2");

If( str1.equals(str3) )
        System.out.println("Equal 3");
Else

        System.out.println("Not Equal 3");

The output would be,
Equal 1
Not Equal 2
Equal 3

Note that == compares the references not the actual contents of the String object; Where as equals method compares actual contents of two String objects.

Load Balancing:(Cached information)

An important issue when operating a load-balanced service is how to handle information that must be kept across the multiple requests in a user's session. If this information is stored locally on one backend server, then subsequent requests going to different backend servers would not be able to find it. This might be cached information that can be recomputed, in which case load-balancing a request to a different backend server just introduces a performance issue.

Ideally the cluster of servers behind the load balancer should be session-aware, so that if a client connects to any backend server at any time the user experience is unaffected. This is usually achieved with a shared database or an in-memory session database, for example Memcached.

Threads:

Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable example:

public class HelloRunnable implements Runnable {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }

}
Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the HelloThread example:

public class HelloThread extends Thread {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new HelloThread()).start();
    }

}

Life cycle of a Thread:

    New
    Runnable
    Running
    Non-Runnable (Blocked)
    Terminated

sleep() is a method which is used to hold the process for few seconds or the time you wanted but in case of wait() method thread goes in waiting state and it won’t come back automatically until we call the notify() or notifyAll().

wait(): until call notify(), notifyAll() from object
sleep(): until at least time expire or call interrupt().

volatile:
The Java volatile keyword is used to mark a Java variable as "being stored in main memory". More precisely that means, that every read of a volatile variable will be read from the computer's main memory, and not from the CPU cache, and that every write to a volatile variable will be written to main memory, and not just to the CPU cache.



When two threads are accessing the same shared variable, if any one of the thread updated the shared value it will stored in to CPU cache, this will leads to inconsistency value's . To make sure all way to store in to main memory we will use volatile key word.


Exception handling:

The Throwable class and its most significant subclasses.

The first kind of exception is the checked exception. These are exceptional conditions that a well-written application should anticipate and recover from. For example, suppose an application prompts a user for an input file name, then opens the file by passing the name to the constructor for java.io.FileReader. Normally, the user provides the name of an existing, readable file, so the construction of the FileReader object succeeds, and the execution of the application proceeds normally. But sometimes the user supplies the name of a nonexistent file, and the constructor throws java.io.FileNotFoundException. A well-written program will catch this exception and notify the user of the mistake, possibly prompting for a corrected file name.

Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.

The second kind of exception is the error. These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. For example, suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError. An application might choose to catch this exception
Checked Exception:
SQLException
IOException
DataAccessException
ClassNotFoundException
InvocationTargetException


throw new Exception("Something went wrong!!");
public void sample() throws ArithmeticException{

Wednesday, February 4, 2015

Marker interfaces in JAVA

Serializable, Clonnable and Remote interface are the marker interfaces in JAVA.

To know the JVM saying this object can be Serializable or this can be clonnable ..etc. with out implementing a marker interface compiler or JVM doesn't automatically do respective types.

Some information on Spring with hibernate

Spring:

Open source and light weight, Loose coupling, Container will manage the application objects. 
It provides the consistent transaction management and exception handling.
AOP: separates application business logic from system services.
Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO) into consistent, unchecked exceptions.

IOC in spring:

Spring container will responsible to create, maintain and destroy objects. Container will take the related information from metadata.In springs we can specific this meta information through XML or Annotation based and Java base(@configuration.). All so container uses dependency injection.
Can do unit test easy because of loose coupling.

Dependency Injection can achieve through Construction based or through setter.If it is a mandatory then we better choose construction based DInjection, else we can use setter based.

  • Spring object's can be configured in XML, Annotation based/java based configuration @configuraion and @ beans...etc,
  • There are two important bean life cycle methods we can override in spring beans: @PostConstruct and @PreDestroy

Method level Injection with spring (Injecting prototype model in to singleton model)

When we want to inject prototype model object into singleton object we will be having an issue.

How we can achieve this in spring? we have a concept calling method injection. All beans in the spring's are singleton by default,
meaning spring instantiates them during context creation,caches them in context, when ever it needed it will load from cache,
if you make a particular object scope as prototype and you want to inject this object into other singleton object the actual problem arrives.

Spring Architecture:

Spring Framework Architecture



Bean scopes in Springs:


All beans in a spring IOC default is singleton.

Here is list of available bean scopes in springs:

ScopeDescription
singletonThis scopes the bean definition to a single instance per Spring IoC container (default).[Singleton beans are not thread safe.]
prototypeThis scopes a single bean definition to have any number of object instances.
requestThis scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
sessionThis scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
global-sessionThis scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.


singleton beans are not thread-safe in Spring framework.

Spring with Hibernate Integration:
We can define resources such as SessionFactory ..etc as a beans in spring container
First to create a SessionFactory:
In applicationcontext.xml file write as below
<beans>

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>

    <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <property name="mappingResources">
            <list>
                <value>product.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.HSQLDialect
            </value>
        </property>
    </bean>

<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="mySessionFactory" />
</bean>
    
   <bean id="myProductDao" class="product.ProductDaoImpl">
        <property name="template" ref="mySessionFactory"/>
    </bean>

</beans>



Create Dao Layer :

public class ProductDaoImpl implements ProductDao {

    private HibernateTemplate template = null;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.template = new HibernateTemplate(sessionFactory);
    }

    public Collection<Person> findPersons() throws DataAccessException {
        return (Collection<Person>) template.find("from Person");
    }
}

To make annotation based transaction management use below command in applicationcontext.xml file.
<tx:annotation-driven/>

We can do transaction management in 3 ways:
1) Using spring AOP.
2) Declarative transaction management.
3) Programmatic transaction.

In this we are going to discuss about declarative transaction management:
To make Declarative transactions in Springs with hibernate follow below steps:

All you need to provide is the TransactionManager implementation and a "<tx:annotation-driven/>" entry.

Add the below code into your application context file make sure you mention <tx:annotaion-driver/>

<bean id="transactionManager"

            class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <tx:annotation-driven/>

To handle multiple data source with different transactions:

public class TransactionalService {

    @Transactional("order")
    public void setSomething(String name) { ... }

    @Transactional("account")
    public void doSomething() { ... }
}
could be combined with the following transaction manager bean declarations in the application context.

<tx:annotation-driven/>

    <bean id="transactionManager1" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        ...
        <qualifier value="order"/>
    </bean>
    <bean id="transactionManager2" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        ...
        <qualifier value="account"/>
    </bean>

Transaction propagation: 

MANDATORY
Support a current transaction, throw an exception if none exists.
NESTED
Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else.
NEVER
Execute non-transactionally, throw an exception if a transaction exists.
NOT_SUPPORTED
Execute non-transactionally, suspend the current transaction if one exists.
REQUIRED
Support a current transaction, create a new one if none exists.
REQUIRES_NEW
Create a new transaction, and suspend the current transaction if one exists.
SUPPORTS
Support a current transaction, execute non-transactionally if none exists.

What is sorted collection and order collection in hibernate.

A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause

Developing a simple Rest service using spring 4

@RestController annotation which marks the class as a controller where every method returns Domain Object instead of a view.

@RestController
public class RestTestController {

    @RequestMapping("/sayHello")
    public Greeting sayHello(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(name);
    }
}

The above rest controller URL: http://localhost:8080/sayHello?name=Kiran

where as Request mapping has URL:sayHello and its accepting a parameter named name and the return type of this method is Object as said earlier all the methods inside a @RestController will return the domain object istead of view. The return type will automatically converted into JSON object.

This Greeting object contain a setter and getter method of name.

In the case of @Controller annotation you need to manually specify the @ResponseBody annotation to controller specifying and object is returning instead of a view.

Tuesday, February 3, 2015

Java 7 VS Java 6

1) Numeric  literals with underscores 

int i =100;
int i=100000;

Java 7:
int i = 1_00;
int i = 1_000_00;

2) Bracket notation for collections :

Collection <String>coll = new ArrayList<String>();
coll.add("kiran");
coll.add("kiran1");

Java 7:
Collection <String>coll = new ArrayList{"kiran","kiran1"};

3) try with resources :

BufferedReader reader = null;
try{
reader  =new BufferedReader( ...) ;

}catch(IOException exception) {
...
}finally {
try {
   reader .close();
}catch(IOException e) {
}
}

Java 7:
Ex 1:
 try (BufferedReader br = new BufferedReader(new FileReader(path)); 
BufferedWriter bw = new BufferedWriter(new FileWriter(path)); )
{ //File code
 } catch(IOException ioEx) {
} With Java7 try-with-resource the resources BufferedReader & BufferedWriter implements java.lang. AutoCloseable and will be closed automatically
Ex 2:
try (Statement stmt = con.createStatement())
 { ResultSet rs = stmt.executeQuery(query); while (rs.next()) String coffeeName = rs.getString("Name”); } catch (SQLException e) {
} With Java7 try-with-resource the resource javax.sql. Statement implements java.lang.AutoCloseable and will be closed automatically

4) Multiple Catch statement :

try{
..
}catch(Exception 1) {
}catch(Exception 1) {
}

Java 7:
try{
}catch(Exception 1 | Exception 2 | Exception 3) {
}
Clean code with multiple catch statements in one catch block.

5) Switch with string case

Previous java is not allowed string in switch case


java 7
switch(day) {
 case "monday" :...
}

6) Simple Generic

Simple Generic Instance Old-Way List<String> strings = new ArrayList<String>(); Map<String, List<String>> myMap = new HashMap<String, List<String>>(); New-Way (Simple) List<String> strings = new ArrayList<>(); Map<String, List<String>> myMap = new HashMap<>();

This is not a final list yet to write few more...

Developing a simple Rest service using spring 4

@RestController annotation which marks the class as a controller where every method returns Domain Object instead of a view.

@RestController
public class RestTestController {

    @RequestMapping("/sayHello")
    public Greeting sayHello(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(name);
    }
}

The above rest controller URL: http://localhost:8080/sayHello?name=Kiran

where as Request mapping has URL:sayHello and its accepting a parameter named name and the return type of this method is Object as said earlier all the methods inside a @RestController will return the domain object istead of view. The return type will automatically converted into JSON object.

This Greeting object contain a setter and getter method of name.

In the case of @Controller annotation you need to manually specify the @ResponseBody annotation to controller specifying and object is returning instead of a view.

Thursday, January 29, 2015

Generating the client files from a WSDL in JAVA6 [Windows]

Every JDK has wsimport bat file. You can find in JAVA_HOME\bin.

Go to specific location and run wsimport command as shown in below

The above command will generate client files in c:\tmp\uploaded, Here is the wsimport options.

Option
Description
-d <directory>  
Specify where to place generated output files
-b <path>  
Specify external JAX-WS or JAXB binding files (Each <file> must have its own -b)
-B <jaxbOption>
Pass this option to JAXB schema compiler
-catalog
Specify catalog file to resolve external entity references, it supports TR9401, XCatalog, and OASIS XML Catalog format. Please read the documentation of catalog and see catalog sample.
-extension  
Allow vendor extensions (functionality not specified by the specification). Use of extensions may result in applications that are not portable or may not interoperate with other implementations
-help  
Display help
-httpproxy:<host>:<port>  
Specify an HTTP proxy server (port defaults to 8080)
-keep  
Keep generated files
-p  
Specifying a target package via this command-line option, overrides any wsdl and schema binding customization for package name and the default package name algorithm defined in the specification
-s <directory>  
Specify where to place generated source files
-verbose  
Output messages about what the compiler is doing
-version  
Print version information
-wsdllocation <location> 
@WebServiceClient.wsdlLocation value
-target  
Generate code as per the given JAX-WS specification version. version 2.0 will generate compliant code for JAX-WS 2.0 spec.
-quiet  
Suppress wsimport output

To generate in specific package format use below command:

Sample command:
wsimport -d c:\tmp -p com.csc.kiran.classes http://xyz?wsdl

here all the geneated classes will be inside the package : com.csc.kiran.classes

Monday, January 5, 2015

To delete duplicate entries from a table in oracle


To delete a duplicate entry from a table use the below query:

delete from np_tld where rowid in (select max(rowid) from np_tld group by tld having count(*) > 1)

The above query return the all the group by tld's which is having count more than 1 with in that it will select the max row id , we are going to delete all those records.