Saturday, October 25, 2014

What is Nested class or Inner class ?


Defining a class within another class is called Nested / Inner class.
Nested classes are divided into 2 Categories,
  • static
  • non-static

Eg: 

class OuterClass {
    ...
    static class StaticNestedClass {
        ...
    }
    class InnerClass {
        ...
    }
  • Nested class is a member of it's outer or enclosing class.
  • non-static nested classes have access to other members of the enclosing class, even they are declared as 'private'.
  • static nested classes do not have access to other members of the enclosing class.
  • As a member of outer class a nested class can be declared private,public and protected or package-private(if a class has no modifier it is visible within own package, this is also known as package-private).
Uses of nested classes:
It is a way of Logically grouping classes that are only used in one place - If a class is useful to only one other class, then it is logical to Embed it in that class and keep the two classes together.Nesting such 'helper classes' makes their package streamlined. 
It Increases Encapsulation: Consider there are two high-level classes A,B. Where B needs access to members of A. By hiding class B within class A , A's members can be declared private and B can access them. In addition B itself can be hidden from outside world.
It can lead more reliable and maintainable code: nesting small classes within Top-Level classes places the code closer to where it used.
static nested classes:
  • Like static class methods, a static nested class can not refer directly to instance variables or methods defined in it's enclosing class.It can use them only through an object reference.
  • In java we can not make Top level class as static, only nested classes can be static.
  • An instance of inner class can not be created without an instance of outer class.
  • static nested classes are accessed using the enclosing class name.
                       OuterClass.StaticNestedClass
    To create an object for static nested class
          OuterClass.StaticNestedClass  staticnestedclsobj=new 
OuterClass.StaticNestedClass();
To Create Object for non-static inner class
OuterClass.NestedClass nestedclsobj=new OuterClass().new NestedClass();

Is Java pure Object Oriented language?


  1. Java is not Pure Object Oriented Language, because it supports Primitive datatypes such as int, byte, long... etc, which are not objects.This Contrast with a 'pure OOP language' like Smalltalk, where there are no primitive types, and boolean, int and methods are all objects.

Difference Between JDK,JVM and JRE ?

JDK: Java Development Kit (JDK) is for development purpose and JVM is a part of it. JDK provides all the tools, executables and binaries required to compile, debug and execute a Java Program.

JVM: Java Virtual Machine(JVM) is Executes to Java Programs.It is responsible for Execution of Java Programs.

JRE: Java Runtime Environment (JRE) is the implementation of JVM. JRE consists of JVM and java binaries and other classes to execute any program successfully. JRE doesn't contain any development tools like java compiler, debugger etc. 



Wednesday, September 17, 2014

Difference between HashSet and TreeSet in Java?

HashSet Vs TreeSet :
  1. First major difference between HashSet and TreeSet is performance. HashSet is faster than TreeSet.
  2. In HashSet and TreeSet the HashSet allows null object but TreeSet doesn't allow null Object and throw NullPointerException, Why, because TreeSet uses compareTo() method to compare keys and compareTo() will throw java.lang.NullPointerException.
  3.  HashSet is backed by HashMap while TreeSetis backed by TreeMap.
  4. HashSet uses equals() method to compare two object in Set and for detecting duplicates while TreeSet uses compareTo() method for same purpose.
  5. HashSet doesn't guaranteed any order while TreeSet maintains objects in natural Sorted order or the Order defined by either Comparable or Comparator method in Java.
Important*-The TreeSet allows NULL object while it is Empty. If it is not empty then only it doesn't allows NULL Object.

HashSet. TreeSet.
Faster. Slower(when compared to HashSet).
Doesn't Guaranteed Any Order. Natural Sorted Order or Order Provided by the Comparable/Comparator.
Uses equals() method to compare elements. Uses compareTo() method to compare elements.
backed by HashMap. backed by TreeMap.

Monday, August 4, 2014

Drawbacks of JDBC?

Drawbacks of JDBC:


  • JDBC uses the software dependent sql queries,so the JDBC Persistence logic is database software dependent.
  • All Exceptions of JDBC are checked exceptions, so  the Exception Handling is Mandatory.
  • There is no proper support of Transaction Management.
  • There is no built-in support of Caching/Buffering to reduce network round trips between Java App & Database.
  • We can not keep objects in relationship while underlying Database tables are in relationship.

Thursday, June 12, 2014

Thursday, June 5, 2014

How to backup only database schema without data in mysql?

Here is the command to backup only schema without data


                                                                                                               
 >mysqldump -u root -p****  --no-data database_name > filename.sql

Wednesday, June 4, 2014

How to delete foreign key from a table in mysql?

The following command drops foreign KEY Constraint from table in mysql.

                       
                                                                 
 alter table table_name drop foreign key foreignkey_name;
Eg:
 alter table MerchantOfferImage drop foreign key Merchant_ibfk_1;

How to add Foreign Key to existing table column in mysql?

It is simple to add a foreign key to a column in Existing table.The Following command adds foreign key to the table


alter table table_name add CONSTRAINT foreign_key_constraint_name FOREIGN KEY (column_name)  REFERENCES reference_table_name (reference_table_column_name) ON UPDATE CASCADE ON DELETE CASCADE;  
                       
Eg:    
alter table MerchantOfferImage add CONSTRAINT banner_image_id_fk FOREIGN KEY (banner_image_id)  REFERENCES MerchantOffer (offer_id) ON UPDATE CASCADE ON DELETE CASCADE;
                                                                   or
alter table MerchantOfferImage add foreign key(offer_id) references MerchantOffer (offer_id)  ON UPDATE CASCADE ON DELETE CASCADE;

How to remove primary key Constraint in mysql?

.





We should remove the autoincrement property before dropping the key

ALTER TABLE table_name MODIFY column_name datatype NOT NULL;
Eg: 
ALTER TABLE User MODIFY id int NOT NULL;

Then delete the primary key Constraint            

ALTER TABLE table_name DROP PRIMARY KEY;                      
Eg: 
ALTER TABLE User DROP PRIMARY KEY;


Thursday, May 29, 2014

Spring MVC

Introduction:
              Spring MVC has the most flexible architecture to develop web applications in java/spring environment.It provides clear separation of different layers components, with this MVC Architecture we can use different types front-end technologies like Jsp,freemaker etc.

Basic architecture and flow of Spring MVC Architecture


Dispatcher Servlet: 'Dispatcher Servlet'  which receives  requests and forward them to controllers and also allows to use Other all Features.It traps and takes the requests  and dispatches them to the appropriate controllers with the help of Handler Mappings.

Handler Mapping: Handles the execution of a list of pre-processors and post-processors and controllers if they match certain(Ex: matching URL specified with a controller).It maps requests with Intended Controllers.

Controller: Controller interpret user input and transforms it into a model that represented to the user by View. It serves the user requests and returns Model and View Object.

ViewResolver:  resolves view names to views.

View:  A view is a generated HTML output to the User.

Lets take an Example to explain flow of Spring MVC.

1. Take a new DynamicWebApplication in your IDE with name 'Spring3MVC'.
                       

    
2. go to WEB-INF  Folder and Add the following code to web.xml file.

 <!-- Dispatcher Servlet -->    <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.htm</url-pattern>
  </servlet-mapping>

By adding the above code we are configuring the 'DispatcherServlet'  or Front Controller which controls the entire application execution flow of control.

3. Next add some list of jar file as shown below in lib Folder.
          
     

I am using spring 3.2.2 in my application.you can get 'commons-logging.jar' from spring 2.5 and download 'jstl.jar' .

4.Add a Controller class to service/process client request.
In my application i want to display some 'hello world ' kind of message so i use my     Controller to do this.add this controller in some package like 'com.controller'

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {

   @RequestMapping("/hello")
   public ModelAndView helloWorld() {

       String message = "Hello World, Spring 3.2.2..!!";
       return new ModelAndView("hello", "message", message);
   }
}


In the above code there are 2 Annotations
  •       @Controller
  •       @RequestMapping("/hello")
 @Controller-tells to spring that this bean is a Controller bean to process client  
                         requests.
@RequestMapping("/hello")-tells to spring that this bean should process all the requests beginning  with '/hello'. 

This controller returns Model and View Object with a message ''Hello World, Spring 3.2.2..!!".

5. To display this result to the client we need View.we are using jsp in view layer. So we have to create a jsp with name hello.jsp. place this jsp file in WEB-INF/jsp folder.

    

the code in hello.jsp 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>hello</title>
    <title>Spring 3.2.2 MVC: Hello World</title>
</head>
<body>
    ${message}
</body>
</html>

This 'message' displays Hello World, Spring 3.2.2..!! ,Because message is the name in Model and View Object which return by the Controller.

And also we need one more jsp to send request, for this take a jsp with name 'index.jsp' and place in in /WEB-INF/jsp/ Folder.


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring 3.2.2 SpringMVC</title>
</head>
<body>
    <a href="hello.htm">demo request</a>
</body>
</html>

make this 'index.jsp' as the welcome file for Application,to do this add following code to web.xml file.

<display-name>Spring3MVC</display-name>
  <welcome-file-list>
    <welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
  </welcome-file-list>

Finally we need spring bean configuration file with name 'springmvc-servlet.xml'. Because when DispatcherServlet initialized it looks for file with name [value of <servlet-name> tag in DispatcherServlet configuration]-servlet.xml in WEB-INF Folder.So in our example the spring bean configuration file name should be ''springmvc-servlet.xml".

This file contains Handler Mappings, ViewResolvers, Controllers and Other Spring Bean configuration.
our file contains

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
.......>

     <context:component-scan  base-package="com.controller" />
       
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
   </beans>

The '<context:component-scan  base-package="com.controller" />' tag tells Spring to load components from 'com.controller' package and it's sub packages.
The ViewResolver  bean resolves the view and add prefix  '/WEB-INF/jsp/' and suffix '.jsp' . In this app Controller HelloWorldController have return Model and View Object with view hello ,this resolver resolves that to '/WEB-INF/jsp/hello.jsp'.

Final structure of Application
                  


Flow:
1. request sent from index.jsp.

2. DispatcherServlet traps and Takes the request and dispatches it to Controller HelloWorldController by looking at HadlerMapping(this was done by annotations).

3. Controller HelloWorldController process use request and returns a Model and View Object with View name hello and other details.

4. DispatcherServlet resolves the view name to '/WEB-INF/jsp/hello.jsp' by looking at into ViewResolver Configuration in Spring bean configuration file springmvc-servlet.xml. The hello.jsp rendered by the spring and send to the client.

That is the end of Spring MVC First App.


Monday, April 14, 2014

Auto wiring in Spring

Assigning  dependent values to spring bean resources is technically known as "WIRING". There are 2 types in wiring. They are

  • Explicit wiring                                             
  • Auto wiring
Explicit wiring
The setter injection,constructor injections are considered as explicit wiring. In this approach programmer has to pass/provide dependent value the spring container to inject to the reference bean.

Auto wiring: 
In this approach spring container itself choose the dependent value to assian to resource. To let Spring container do this we use '<autowire>' attribute in bean tag.

There are 4 types of auto wiring,
byName:  
In this type of auto wiring the spring container assigns value to the dependent bean by  name of the bean property, i.e the id of the dependent bean object and the name of the spring bean property must be same.
In this approach spring container use setter injection to assign value.

Look at the following example ...how a java.util.Date value is assigning to the bean
in this example

beans.xml (spring configuration file)
DemoBean.java (spring bean)
MainApp.java (client program)

DemoBean.java 
//DemoBean.java
public class DemoBean{
private String uname;
private Date date;

 /**
* @return the uname
*/
public String getUname() {
return uname;
}
/**
* @param uname the uname to set
*/
public void setUname(String uname) {
this.uname = uname;
}
/**
* @return the date
*/
public Date getDate() {
return date;
}
/**
* @param date the date to set
*/
public void setDate(Date date) {
this.date = date;
  System.out.println("date: "+date);
}
}

MainApp.java 
//MainApp.java
public class MainApp{
public static void main(String a[]){
FileSystemResource res=new FileSystemResource("beans.xml");
XmlBeanFactory factory=new XmlBeanFactory(res);
Demo beanobj=(Demo)factory.getBean("demobean");
}
}

beans.xml
//beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
............................>

    <bean id="demobean" class="DemoBean" autowire="byName">
     <property name="uname" value="raju"/>
    </bean>

<bean id="date" class="java.util.Date"/>
</beans>

with the  autowire="byName"  the spring container look for  bean object which has 'date' as id (here date is property name)  if found assigns to the resource other wise no value will be assigned.

byType:
In this type of auto wiring the spring container assigns value to the dependent bean by  type(data type) of the bean property, i.e the type(data type) of the dependent bean object and the type(data type) of the spring bean property must be same.
In this approach spring container use setter injection to assign value.

Look at the following example ...how a java.util.Date value is assigning to the bean
in this example

beans.xml (spring configuration file)
DemoBean.java (spring bean)
MainApp.java (client program)

DemoBean.java & MainApp.java are same,but change in beans.xml

beans.xml
//beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
............................>

    <bean id="demobean" class="DemoBean" autowire="byType">
     <property name="uname" value="raju"/>
    </bean>

<bean id="date" class="java.util.Date"/>
</beans>

with the  autowire="byType"  the spring container look for  bean object 'java.util.Date'  type if found assigns to the resource other wise no value will be assigned.
If more than one 'java.util.Date'  type object found in spring configuration file Exception will be thrown by container.

constructor:
In this type of auto wiring the spring container assigns value to the dependent bean through parameterized constructor  of bean , i.e the the spring container calls
parameterized constructor to assign dependent values to the resource.This is similar to byTtype  mode.

Look at the following example ...how a java.util.Date value is assigning to the bean
in this example

beans.xml (spring configuration file)
DemoBean.java (spring bean)
MainApp.java (client program)

in this example MainApp.java is same and changes are needed in beans.xml,
DemoBean.xml.

beans.xml
//beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
............................>

    <bean id="demobean" class="DemoBean" autowire="constructor">
     <property name="uname" value="raju"/>
    </bean>

<bean id="date" class="java.util.Date"/>
</beans>

DemoBean.java 
//DemoBean.java
public class DemoBean{
private String uname;
private Date date;

 /**
 * @return the uname
 */
public String getUname() {
return uname;
}
/**
 * @param uname the uname to set
 */
public void setUname(String uname) {
this.uname = uname;
 System.out.println("uname:  "+uname);
}
/**
*constructor
**/
public DemoBean(Date d){
date=d;
  System.out.println("date: "+date);
}
}

with the  autowire="constructor"  the spring container look for  bean object 'java.util.Date'  type if found assigns to the resource otherwise Exception will be thrown by container.
If more than one 'java.util.Date'  type object found in spring configuration file Exception will be thrown by container.

autodetect:
In this mode of auto wiring spring container first try to assigns a value to dependent bean using constructor mode if this mode is not possible then container go to byType mode, i.e if we place a constructor in bean class container choose constructor mode else you place setter methods container use byType mode.

Lets take the same example

beans.xml (spring configuration file)
DemoBean.java (spring bean)
MainApp.java (client program)

in this example MainApp.java is same and changes are needed in beans.xml,
DemoBean.xml.

beans.xml
//beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
............................>

    <bean id="demobean" class="DemoBean" autowire="autodetect">
     <property name="uname" value="raju"/>
    </bean>

<bean id="date" class="java.util.Date"/>
</beans>

DemoBean.java 
//DemoBean.java
public class DemoBean{
private String uname;
private Date date;

 /**
 * @return the uname                                                                  1
 */
public String getUname() {
return uname;
}
/**
 * @param uname the uname to set
 */
public void setUname(String uname) {
this.uname = uname;
 System.out.println("uname:  "+uname);
}

/**
*constructor
**/
public DemoBean(Date d){
date=d;
  System.out.println("constructor autowiring: "+date);
}
}

DemoBean.java 
//DemoBean.java
public class DemoBean{
private String uname;
private Date date;
                                                                                                             2
 /**
 * @return the date
 */
public Date getDate() {
return date;
}
/**
 * @param date the date to set
 */
public void setDate(Date date) {
System.out.println("setter method autodetect: "+date);
this.date = date;
}

 /**
 * @return the uname
 */
public String getUname() {
return uname;
}
/**
 * @param uname the uname to set
 */
public void setUname(String uname) {
this.uname = uname;
 System.out.println("uname:  "+uname);
}
}

with 1 'DemoBean.java' spring container performs constructor based auto wiring and
with 2 'DemoBean.java' spring container performs byType(setter injection) based auto wiring.
if neither constructor nor setter method found container don't assign a value.

Limitations of Autowiring:
  1. Autowiring is possible only on reference type Bean Propertied(we can inject only object,simple values can not be injected).
  2. There is chance of getting ambiguity.
  3. Kills readability of spring configuration file.


Wednesday, April 9, 2014

Bean Scopes in Spring

Spring Provides Multiple types of Scopes.Here we can consider scope is availability of bean Object.The different types of scopes are
  1. singleton                                                             
  2. prototype
  3. request
  4. session
  5. globalsession

singleton: The singleton means creating only one object/ instance per JVM.
The class which allow to create only one object per JVM is known as singleton class.
  • This is the default scope of spring bean.
  • spring container returns the same object every time you access  from BeanFactory or ApplicationContext objects.

Ex for specifying scope in spring configuration file of a bean is

<bean id="beanid" class="beanclass" scope="singleton"/>
                                              or
<bean id="beanid" class="beanclass" scope="singleton">
....
...
</bean>

for singleton scope no need to specify it in spring configuration file ,because it is the default scope.

prototype: In this prototype scope the spring container creates and returns a new object for each time when you access  from BeanFactory or ApplicationContext objects.

Ex for specifying scope in spring configuration file of a bean is

<bean id="beanid" class="beanclass" scope="prototype"/>
                                              or
<bean id="beanid" class="beanclass" scope="prototype">
....
...
</bean>

request:
  • The request scoped bean object will be created one per HTTP request .
  • This bean object will become request object attribute value.
Ex for specifying scope in spring configuration file of a bean is

<bean id="loginAction" class="com.foo.LoginAction" scope="request"/>
                                                            or
<bean id="loginAction" class="com.foo.LoginAction" scope="request">
....
...
</bean>

  • With the above bean definition  the Spring container will create a brand new instance of the LoginAction bean using the 'loginAction' bean definition for each and every HTTP request.
  • When the request is finished the bean that is scoped to the request will be discarded.
  • It is useful only in web Environment.

session:
The session scoped beans will be created one per HTTP session.
This bean object will become HTTP session scope object.

Ex for specifying scope in spring configuration file of a bean is

<bean id="loginAction" class="com.foo.LoginAction" scope="session"/>
                                                            or
<bean id="loginAction" class="com.foo.LoginAction" scope="session">
....
...
</bean>

  • With the above bean definition  the Spring container will create a brand new instance of the LoginAction bean using the 'loginAction' bean definition for each and every HTTP session.
  • When the HTTP session is finished the bean that is scoped to the session will be discarded.
  • It is useful only in web Environment.

globalsession: 
  • This is similar to the session scope.
  • But this is useful in Spring based portlet development environment.
Ex for specifying scope in spring configuration file of a bean is

<bean id="loginAction" class="com.foo.LoginAction" scope="globalsession"/>
                                                            or
<bean id="loginAction" class="com.foo.LoginAction" scope="globalsession">
....
...
</bean>

These are the scopes in Spring Framework.

Saturday, March 29, 2014

Spring Containers


  • Spring Containers are Provided to take care of Spring Beans Life Cycle.
  • Spring containers are also perform Dependency Injection on Spring beans in 2 ways, in configuration file every bean/resource configured with '<bean>' tag.
  • If we use '<property>' tag to perform dependency injection then container performs 'setter-injection' ,if we use '<constructor-arg>'    tag to perform dependency injection  then container performs 'Constructor-Injection' mode dependency injection.
  • The Java classes that we are using as resources of spring application are called as Spring Resources.
  • To configure these Spring Beans we need Spring configuration file. 'anyname'.xml can be taken as spring configuration file.
  • Underlying container will use this configuration file to recognize resources.
Spring Provides 2 containers,They are
  1. BeanFactory                                                          
  2. ApplicationContext
BeanFactory:
  • To Activate 'BeanFactory'  we need an Object of class which implements "org.springframework.beans.factory.BeanFactory"  interface.
  • "org.springframework.beans.factory.xml.XmlBeanFactory" is most commonly used implementation class of 'BeanFactory' interface.
  • To create Object of 'XmlBeanFactory' we need 'FileSystemResource' Object

Activating 'BeanFactory' Container.....

//Creating a resource
FileSystemRecource res=new FileSystemResource("springcfgfile.xml");
                                   or
ClassPathResource res=new ClassPathReosurce("springcfgfile.xml");

//Activate 'BeanFactory' container.
XmlBeanFactory factory=new XmlBeanFactory(res);


FileSystemResource: locates the given spring configuration file from the specified path of File System.

ClassPathResource: locates the given spring configuration file from the directories & jars that are added in class-path.

ApplicationContext:
  • ApplicationContext container is Enhancement of BeanFactory Container. 
  • To Activate 'ApplicationContext'  we need an Object of class which implements "org.springframework.context.ApplicationContext"  interface.
  • There are 3 popular classes implementing the this Interface

  • FileSystemAmlApplicationContext: Activates Spring Container by reading the spring configuration file from the specified path of 'File System'.
FileSystemXmlApplicationContext context=new FileSystemXmlApplicationContext("springconfigurationfile.xml");
                                                   or
ApplicationContext context=new FileSystemXmlApplicationContext("springconfigurationfile.xml");
  • ClassPathXmlApplicationContext: Activates Spring Container by reading the spring configuration file from the class path folders & jars.
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("springconfigurationfile.xml");
                                                 or
ApplicationContext context=new ClassPathXmlApplicationContext("springconfigurationfile.xml");
    • WebXmlApplicationContext: Activates Spring Container by reading the spring configuration file from web application resources(in web environment).

    Monday, March 24, 2014

    Dependency Injection

    " If The Underlying Technology or server or run-time environment or Framework is assigning dependent values to resources Dynamically even though the resources are not satisfying any contract,then it is called Dependency Injection".

    This type of approach is also called Inversion of Control.

    Majorly there are 2 types of Dependency-Injections.
                                 
    • Setter Injection.                                                       
    • Constructor Injection.

    setter Injection:
    •  In setter Injection approach we use setter & getter Methods to assign dependent values to resources dynamically. 
    • To Configure these methods in spring configuration file we use '<property>' tag.
    • These setter methods will be called after Constructor  creation of that resource(POJO) class.
    Eg configuration:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"................>

     <bean id="fb" class="firstbean">

    <property name="msg" value="hai..!"/>
    (or)<!-- You Can Use Either one of these ways. -->
    <property name="msg">  
    <value>     hello    </value>
    </property>

    </bean>
    </beans>

    in the above example   'msg'  is the name of the property of resource.

    Example application on spring setter injection.
    In this application i have
    jar files:
    commons-logging.jar
    spring-beans-3.2.2.RELEASE.jar
    spring-context-3.2.2.RELEASE.jar
    spring-core-3.2.2.RELEASE.jar
    spring-expression-3.2.2.RELEASE.jar

    You can get all the spring jars from spring 3.2.2 software and the commons-logging from spring 2.5.

    UserImpl class:
    It Contains Business Logic.

    package com.javagreat.springSI;

    import java.util.Calendar;
    import com.javagreat.springSI.Interface.User;

    public class UserImpl implements User {
    String msg;

    /**
    * @return the msg
    */
    public String getMsg() {
    return msg;
    }

    /**
    * @param msg the msg to set
    */
    public void setMsg(String msg) {
    this.msg = msg;
    }

    @Override
    public void displayMsg(String user_name) {
    Calendar c=Calendar.getInstance();
    int h=c.get(Calendar.HOUR_OF_DAY);
    if(h<12){
    System.out.println(msg+" Good Morning "+user_name);
    }else if(h<16){
    System.out.println(msg+" Good Afternoon "+user_name);
    }else if(h<20){
    System.out.println(msg+" Good Evening "+user_name);
    }else {
    System.out.println(msg+" Good Night "+user_name);
    }
    }
    }


    Spring Configuration file:
    To Configure Beans.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    .......................>

    <bean id="userbean" class="com.javagreat.springSI.UserImpl">
    <!-- <property name="msg">
    <value>Hello...!</value>
    </property>
    -->
    <!-- You Can Use Either one of these ways. -->
    <property name="msg" value="Hai...!"></property>
    </bean>
    </beans>

    Userdemo class:
    This is to run the Application.

    package com.javagreat.springSI;

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.FileSystemXmlApplicationContext;
    import com.javagreat.springSI.Interface.User;

    public class UserDemo {
    public static void main(String s[]){
    ApplicationContext context=new FileSystemXmlApplicationContext("/Context.xml");
    User ui= (UserImpl) context.getBean("userbean");
    ui.displayMsg("raju");
    }
    }

    With this Application we can inject dependent values to resource from Outside(xml file). In This demo application we injected a string value But,in real time we need to inject 'Datasource','connection'  etc objects.

    Constructor Injection:

    • In Constructor Injection we use parameterized  constructors to assign dependent values to resources.
    • To pass dependent values to these parameterized  constructors we use '<constructor-arg>' in spring configure   file. 
    • In Constructor Injection dependent values will be assigned to resources at the time of object creation.
    Example Configuration:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"................>

     <bean id="fb" class="firstbean">

    <constructor-arg  value=''hello"/>

    (or)<!-- You Can Use Either one of these ways. -->

    <constructor-arg >
    <value>     hai    </value>
    </constructor-arg>

    </bean>
    </beans>

    When Spring Container reads the above data it generates a 1-param constructor and assigns hello/hai to property of the 'firstbean' class.

    Constructor-Injection based example application is contains  same files as setter-injection based application.But small changes are need in spring configuration file and  UserImpl class.

    UserImpl class:
    It Contains Business Logic.

    package com.javagreat.springSI;

    import java.util.Calendar;
    import com.javagreat.springSI.Interface.User;

    public class UserImpl implements User {
    String msg;

    public UserImpl(String msg){
    this.msg=msg;
    }//This is the only change needed in this file.

    @Override
    public void displayMsg(String user_name) {
    Calendar c=Calendar.getInstance();
    int h=c.get(Calendar.HOUR_OF_DAY);
    if(h<12){
    System.out.println(msg+" Good Morning "+user_name);
    }else if(h<16){
    System.out.println(msg+" Good Afternoon "+user_name);
    }else if(h<20){
    System.out.println(msg+" Good Evening "+user_name);
    }else {
    System.out.println(msg+" Good Night "+user_name);
    }
    }
    }

    Spring Configuration file:
    To Configure Beans.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    .......................>

    <bean id="userbean" class="com.javagreat.springSI.UserImpl">
    <!-- <constructor-arg>
    <value>Hello...!</value>
    </constructor-arg>
    -->
    <!-- You Can Use Either one of these ways. -->
    <constructor-arg value="Hai...!"/>
    </bean>
    </beans>

    Except these 2 changes Everything is same as above example. If you run the above application with these changes you can assign dependent value through constructor.

    Saturday, March 22, 2014

    Linux Commands

    There are multiple ways to copy file...                  

    To Copy File From your system to remote system

    $ scp -i  key_file  'path to copy file' username@host_name:'target_location_to_paste'.


    To Copy File from remote System to your system

    $ scp -i  key_file  username@host_name:'target_location_to_copy' 'path to paste file'.

    To Find id of a Process.

    ps aux | grep 'name_of_software'

    Eg:  ps aux | grep tomcat

    Note: remove ' 'quotations.

    How to Find out Size of file in linux/unix environment,
    There are multiple commands to do this...

    1. ls
    2. du
    3. stat
    Each one display result(size) in different way.

    let see about ls command
    If you want to to check size of a zip file 

    >$ ls -l filename.zip
    -rw-rw-r--. 1 root root 24882 Oct 26 18:44  filename.zip

    if you want to see some more user friendly response, then try with 
    $ ls -lh filename.zip 
    -rw-rw-r--. 1 root root 25K Oct 26 18:44 filename.zip

    Now try with du command
    >$ du -h filename.sql
    3.8M filename.sql

    and lastly see the output for stat command
    >$  stat filename.sql
      File: `filename.sql'
      Size: 3902512   Blocks: 7624       IO Block: 4096   regular file
    Device: ****/***** Inode: 23859810    Links: 1
    Access: (0664/-rw-rw-r--)  Uid: (  500/  root)   Gid: (  500/  root)
    Access: 2014-04-26 11:56:06.941036903 +0530
    Modify: 2014-04-26 11:55:07.927037477 +0530
    Change: 2014-04-26 11:56:04.802038739 +0530