Creating Google Cloud project in Eclipse

Today, I installed Google Cloud sdk on my ubuntu OS and then created a Cloud project in Eclipse.

  • Firstly, you need to create an account in Google cloud platform( https://cloud.google.com/) where you need to link your credit/debit card.
  • Then install Google cloud sdk in your systems. Follow the installation steps from this link, for respective OS. I just ran few commands for Ubuntu OS.
  • After successful installation, open your Eclipse.
  • Go to Help -> Eclipse Marketplace. A dialog appears.
  • Search for ‘google cloud’ and click Go. Install Google Cloud Tools which appears in search results.Screenshot from 2017-07-22 10-38-39

 

  • After the installation of tools, an icon for Google cloud platform appears in Menu bar.
  • Click that icon and select Create New Project -> Maven-based Google app engine standard java project.
  • Fill the Group ID and Artifact ID. Check the App engine API in the Libraries to add to build path section.Screenshot from 2017-07-22 10-52-20
  • Select Hello World template in next section.  Then click Finish.Screenshot from 2017-07-22 10-54-57
  • After the project is created in Eclipse, come to Google cloud platform.
  • Create a new project.Screenshot from 2017-07-22 10-58-41
  • After project is created, come back to eclipse.
  • Select the Project you created. Click on Google cloud platform icon in Menu bar and click on Deploy to app Engine Standard.
  • A dialog appears showing all your projects in Cloud platform. Select the one which you created now in google cloud platform.
  • Click Deploy.
  • Your project will be deployed on cloud.

Spring MVC

Hello viewers ! Today, I learnt about Spring MVC framework which is much used widely. We have three important parameters in any web application-

  • Model: Application data represented as POJO/Bean class.
  • View: Front-end showing data after execution of business logic
  • Controller: Which actually performs the business operations

Spring MVC allows the loose coupling between them and allows to manage them independently.

As, I have discussed the advantages of using Maven this blog, so I will tell you how to integrate both of them i.e. Spring MVC and Maven.

  • Create a Maven project

I have told about this in my previous blog. Just go through that.

  • Add the required dependencies in pom.xml

You need to include three dependencies- Spring core, Spring web, Spring webmvc. Go to https://mvnrepository.com/ and add the dependencies for three of them in pom.xml.

Second thing, Maven allows you to specify the version of any dependency in separate tag . You can specify the version variable name as I have specified as and used this in required dependencies as a variable. This gives  a great advantage of changing the version for new release at single place rather than going to every dependency and modifying. Cool! 😎

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mitaly</groupId>
  <artifactId>SpringMVC</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVC Maven Webapp</name>
  <url>http://maven.apache.org</url>

   <properties>
  	<spring-version>4.3.9.RELEASE</spring-version>
  </properties>

  <dependencies>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

       <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-core</artifactId>
	    <version>${spring-version}</version>
	</dependency>

	<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-web</artifactId>
	    <version>${spring-version}</version>
	</dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-webmvc</artifactId>
	    <version>${spring-version}</version>
	</dependency>

  </dependencies>
  <build>
    <finalName>SpringMVC</finalName>
  </build>
</project>

 

  • Check the project structure

Once you have created the Maven project, see the project structure. If your project structure is something like the shown below then you need to modify this.

projectStrOld

Actually, Java Resources here only contains src/main/resources and Libraries. Though it should contain src/main/java where we create our beans and controller.

If you have this problem, go through this stackoverflow answer. Then project structure will look something like this.

projectStrNew

  • Create index.jsp page

Create the index page where you will write the code which needs to be submitted to Controller which will process the data.

See, the action is hello. This is  actually the pattern which you specify for particular controller method which needs to be called. We’ll see that later.

<html>
<body>
<h2>Spring MVC</h2>
<form action="hello" method="post">
		Enter Name

		<input type="text" name="name">

		Enter Message

		<input type="text" name="message">

		<input type="submit" value="Enter">
	</form>

</body>
</html>

 

  • Create the controller class ‘HelloWorld.java’

As previously we had Servlets for receiving the user data and process that. Now, we have a simple class which acts as Controller. Use the @Controller annotation for that.

Define the @RequestMapping annotation for the business method to be executed. Here, we provide the mapping name to be /hello. Remember we used the form action to be hello. This means when form is submitted this method is executed.

Through @RequestParam we are getting the form input fields’ value.

The method must return ModelAndView object. In this object we specify all the data that needs to be transferred to view helloworld.jsp. We passed this view name in constructor of ModelAndView but we need not to specify .jsp, the reason for this we’ll see later.

package com.mitaly;

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

@Controller
public class HelloWorld {

	@RequestMapping("/hello")
	public ModelAndView showMessage(
			@RequestParam(value = "name", required = false, defaultValue = "World") String name,
			@RequestParam(value = "message", required = false, defaultValue = "Message") String message) {

		ModelAndView mv = new ModelAndView("helloworld");
		mv.addObject("message", message);
		mv.addObject("name", name);
		return mv;
	}
}

 

  • Create the view file ‘helloworld.jsp’

Create a folder named views, though it can be named anything. Create a jsp file and the ModelAndView object’s data.

<%@ 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>Insert title here</title>
</head>
<body>
	Welcome, ${name}

	Message : ${message}
</body>
</html>

 

  • Configure web.xml

Even if we don’ create any Servlet, a servlet known as DispatcherServlet gets created when application is loaded. We provide the entry for this servlet in web.xml file.  This servlet class is responsible for invoking the required controller class or more specifically which business method in the controller class.

An xml file named dispatcher-servlet.xml is created in WEB-INF directory whose entry has to be specified in web.xml as context parameter.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

	<display-name>Archetype Created Web Application</display-name>

	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>
			org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
	</context-param>

									<listener>
										<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>
</web-app>

 

  • Create and configure the ‘dispatcher-servlet.xml’

Here , we need to specify context:component-scan which is nothing but the package name where DispatcherServlet will search for the required Controller.

There’s entry of InternalResourceViewResolver class which is a view resolver whose task is to pick and show the desired view. We here, specify prefix of view file as directory in which it is contained and suffix as .jsp. Remember, at the time of specifying the view name in ModelAndView constructor, there was no need of specifying .jsp because in this file we specify the suffix as .jsp.

<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" 	xsi:schemaLocation="http://www.springframework.org/schema/beans 	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 	http://www.springframework.org/schema/context 	http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<context:component-scan base-package="com.mitaly" />
        <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>

This was all till now, but not the end 😉 . Now, I have to merge all the concepts like Hibernate, JDBC, AOP, Services etc. in this.

Maven

Today, I came across one new term Maven. I am going to share what I learnt about it.

Introduction to Maven:

If we are to create a project say a web application, there are lots of jars need to be added, example for Hibernate, Spring, Servlet, Driver etc. Sometimes in future, we wish to replace our jar with latest version. It becomes very difficult to search for particular jar in the pool of so many jar files.

Second problem arises when in our project some dependencies are to be added and some of the dependencies, say, are dependent on few more dependencies.  It that case also, it becomes very difficult to manage all such dependencies and adding them in such a way such that there is no mismatch of versions.

Maven solves all such problem and much more also. It is an automated build tool. Maven is also used for project management. It generates reports for the project on its own.


Integration of Maven with eclipse:

    1. Open Eclipse. Do, New-> Maven Project. Make your Java EE perspective is on.
    2. A window will open as shown below. Just click Next.1
    3. In the Next screen, select catalog as ‘Internal’ and select the archetype which you require. I am creating a web application, so I have selected maven-archetype-webapp. Click Next.Archetype is project structure basically. In the introduction, I mentioned that maven is used as project management tool. Here, there comes its application. Maven will automatically create the project structure which you specify as archetype; like for web application, it will create src, webapp, WEB_INF, web.xml etc.2
    4. In next screen, fill the Group Id and Artifact Id. Group Id is reverse of domain name. Artifact Id is name of output of project(jar, war, ear etc. For Web Application, output is war file).  Click Finish.3
    5. Now, project is created. Expand your project structure and expand the target folder. You will see a file named pom.xml.POM(Project Object Model), is an XML file containing details of the project like project name, version, package type, dependencies, Maven plugins, etc.Switch to its source view, you will see something like this.4
    6. You must have noticed an error in your project in project structure. Go to src -> main -> webapp. Open the error containing file, index.jsp(in most cases). When you will hover the cursor on red cross in file(at first line), it says-“The superclass “javax.servlet.http.HttpServlet” was not found on the Java Build Path”.This error comes because Servlet dependency is not included in the project. Just add the dependency in pom.xml. Then press Ctrl+S.5

You will see error has gone. Write your Web application code and enjoy with maven 🙂

If you want to go ahead with Maven and learn more about it, go for this video tutorial.

Web Services

Today, I came to know about Web Services. I am gonna discuss what I learnt today.

What is a web service?

Web service is a piece if code that runs on the server all the time. I will give an example of MakeMyTrip for the better understanding of concept and it’s usage. MakeMyTrip provides online travel services including flight tickets, domestic, hotel reservations, rail and bus tickets, etc. Let’s talk about flight tickets. This website shows the status of seats availability and prices of airline companies like Air India, Go Air, Jet airways etc. So, the question comes how MakeMyTrip has that information that is stored in different airline companies’ databases. Their is no possibility that MakeMyTrip has access to their databases since it is a privacy concern. So, what happens actually is, all the airline companies create web services and provide the API’s to access those web services by invoking the methods in web service class with suitable parameters.

I hope you got an idea of why there comes a need of web service. Besides this examples, there are so many examples in the world where we can see web services coming into picture; like Trivago that compares prices and features of different hotels in a place.

Behind the scene:

Now, I am gonna tell about how the communication takes place between the client  and server. From my MakeMyTrip example, you can consider MakeMyTrip as a Client and other airline companies’ web application as server or you say service provider. So, how the communication is happening-

  • At server-side, web service is created. This is nothing but a class having business methods that client may invoke.
  • After web service is created, the information about this web service is stored in WSDL(Web Services Description Language) file which is XML based. This file contains information such as methods in web service, their parameters, return type etc.
    XML is universal language that is platform and language independent. XML is used because the communicating web applications may be built in different languages and working on different platforms.
    This WSDL file is generated by WSDL generation tool.
  • Server also provides the endpoint information which is nothing but the URL of web-service denoting it’s location.
  • Now, question comes, how client comes to know about WSDL file. For that, WSDL file is registered in UDDI(Universal Description, Discovery, and Integration) registery where WSDL files are registered with unique names.
  • Now, come to client side. Client now requests UDDI which will provide requested WSDL file.
  • Client then generates Stub/proxies. This is actually generated by Stub generation tool. Stub is just a class having same methods as we had in web-service of server but having different implementation of the methods.
    One more thing, if client application is made in Java, the Stub class is also in Java; meaning in whatever language client web application is made, in the same language Stub class is generated.
  • Now, when client has to invoke any method of web service, it’s gonna create object of Stub by passing the required parameter values.
  • Stub, then stores this information(method, parameter values) in XML document. Now, a SOAP request is generated using this XML file.
  • HTTP protocol now transfers the soap request from client to server.
  • At server, their is another program Skeleton which is predefined class. Skeleton class is made using same language as server web application is made.
    Skeleton reads the SOAP request(XML) which has arrived and passes the parameter values to the actual method in web service.
  • Then, Skeleton prepares the XML document which is nothing but SOAP response containing the response from invoked method.
  • HTTP again transfers the SOAP request from server to client and handed over to Stub.
  • Response is read by Stub and given shown to client.

I mentioned about WSDL generation tool and Stub generation tool. These tools are provided by API’s such as JAX-RPC, JAX-WS, JAX-RS. These API’s are provided by Sun Microsystems if we are creating web application in Java.

I referred this video for the above explanation.

Spring DAO- Spring+Hibernate

Hello viewers ! I have today learnt how to integrate the most popular ORM framework i.e. Hibernate with Spring. I will mention the key points of how the process has to be followed.

  • Adding jar files in project
    Firstly, add all the required jar files which includes Spring core jars, Hibernate jars, Spring persist jars, Type 4 driver, DBCP jar and pool jar.
    If you are creating a simple java project(which I am discussing here), then you need to add these jars, Just do right click the project folder in package explorer -> Build Path -> Configure Build Path -> Add External jars(After that browse for required jar files) -> Apply and Close.
    But, if you are creating a Dynamic web project, then link the jars. Just copy and paste these jar files in Web content -> WEB-INF -> lib directory.
  • Create a Bean class
    Create a bean class for which you want table to be created.
  • Create mapping file
    Now, also create the mapping file(anyname.hbm.xml) where class to table mapping information is present.
  • Create class(Hibernate based DAO) with defined business methods
    It’s time to create a class where all the business methods(createSomething, deleteSomething, updateSomething, retrieveSomething etc.) are defined. Here, we’ll a use life saver 😀 API HibernateTemplate as it saves us from writing tedious code to create Configuration, SessionFactory, Session, Transaction instances and then beginTransaction, closing session..bla bla.
    In this code, we’ll use SessionFactory instance to instantiate HibernateTemplate. SessionFactory instance is injected which we’ll see later.

    package com.mitaly;
    
    import org.hibernate.SessionFactory;
    import org.springframework.orm.hibernate3.HibernateTemplate;
    
    public class TemplateDAO {
    	HibernateTemplate temp;
    
    	public void setSessionFactory(SessionFactory factory) {
    		temp = new HibernateTemplate(factory);
    	}
    	//business methods executed using HibernateTemplate's instance
    }
    
  • Create an xml file for bean configuration
    In this file, configure the bean for BasicDataSource class which contains the information about driverClassName, url of database, username, password. Remember, we have added DBCP jar and pool jar at the beginning. This BasicDataSource class is located in DBCP jar.

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    		<property name="url" value="jdbc:mysql://localhost/JavaEEPractice"/>
    		<property name="username" value="root"/>
    		<property name="password" value=""/>
    </bean>
    

    Now, create the bean for LocalSessionFactoryBean. FactoryBean creates the SessionFactory. SessionFactory can then be passed to DAO class we created earlier through dependency injection. Mapping resources and hibernate properties are specified in this bean(similar to as we write in cfg.xml file).

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    		<property name="dataSource"  ref="dataSource"/>
    
    		<property name="mappingResources">
    				<list>
    				<value>student.hbm.xml</value>
    			</list>
    		</property>
    
    		<property name="hibernateProperties">
    			<props>
    				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    				<prop key="show_sql">true</prop>
    				<prop key="hibernate.hbm2ddl.auto">update</prop>
    			</props>
    		</property>
    </bean>
    

    Now, create the bean for DAO class, where you will simply do the setter injection of LocalSessionFactoryBean(which creates SessionFactory) to the reference of SessionFactory in DAO class.

    <bean id="templateDAO" class="com.mitaly.TemplateDAO">
    		<property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    
  • Create a class with main method
    Now, there come the last step of creating a class having main method where we would get instantiate ApplicationContext and get the bean of templateDAO class created and call the required business methods. That’s it.

AJAX and Spring DAO- Spring+JDBC

AJAX stands for Asynchronous Javascript and XML. This is the technology used to create interactive web pages where web page is updated within seconds without reloading the page. When user fills a form and submits it, the inputs get checked at server side and if any credential is wrong, user has to again fill and again submit that form. This is what a user doesn’t want. AJAX is a client-side scripting that communicates with server/database without the need for a postback or complete page refresh.

Example: Everyone must have seen cricbuzz site. The score gets updated automatically there without the need of refreshing the page. This eases the user and that is through AJAX.

I am gonna illustrate the concept through an example. What I will do is that I will create an input field. When user starts typing something, the text will be matched against the name attribute in Student table in database using LIKE clause. Then matching rows will be shown in table.

index.html-

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My web page</title>
<style>

table, th, td{
	border:1px solid black;
}
table{
	width:100%;
}
</style>

<script type="text/javascript">
 var request;
	function loadTable(){
		var nameusr = document.getElementsByName('nameusr')[0].value;
		var url = "showdata.jsp?name="+nameusr;
		if(window.XMLHttpRequest){
			request = new XMLHttpRequest();
		}else{
			request = new ActiveXObject("Microsoft.XMLHTTP");
		}

		try{
			request.onreadystatechange = getInfo;
			request.open("GET", url, true);
			request.send();
		}catch(e){
			window.alert("Some exception");
		}
	}

	function getInfo(){
		if(request.readyState == 4){
			var res = request.responseText;
			document.getElementById('table').innerHTML = res;
		}
	}

</script>
</head>
<body>
	<center>
<h4>Enter Name</h4>
<input type="text" name="nameusr" onkeyup="loadTable()"/>

		<span id="table"></span>
	</center>
</body>
</html>

showdata.jsp-

<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.DriverManager"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8"%>
<%
	String name = request.getParameter("name");

    if(name.trim().equals("")){
    	out.print("
No record to display");
    }else{
    	try{
    		Class.forName("com.mysql.jdbc.Driver");
    		String url = "jdbc:mysql://localhost/JavaEEPractice";
    		Connection conn = DriverManager.getConnection(url,"root","");

    		String sql = "Select * from Student where name like '"+name+"%'";

    		Statement stmt = conn.createStatement();

    		ResultSet rs = stmt.executeQuery(sql);
    		if(rs.next()){
    			rs.beforeFirst();
    			out.print("
<table>");
    			out.print("
<tr>");
    			out.print("
<th>ROll</th>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
<th>Age</th>
");
    			out.print("</tr>
");
    			while(rs.next()){
    				out.print("
<tr>
<td>"+rs.getInt(1)+"</td>
<td>"+rs.getString(2)+"</td>
<td>"+rs.getString(3)+"</td>
<td>"+rs.getString(4)+"</td>
<td>"+rs.getInt(5)+"</td>
</tr>
");
    			}
    			out.print("</table>
");
    		}else{
    			out.print("
No record to display");
    		}

     		conn.close();
    	}catch(Exception e){
    		out.print("Some error "+e);
    	}
    }

%>

Database table-

db1

Output-scusers1


Spring DAO(Data Access Objects):

DAO’s function is to read and write data to and from the persistent devices such as database, files, XML, spreadsheet. DAO has to serve the business problems of accessing and manipulating data. Earlier, in JDBC, we were supposed to create connection, close connection, close the result set etc. But DAO says not to care for such stuff rather focus on implementing the business logic.

Spring provides many data access frameworks such as JDBC, JPA, Hibernate, iBATIS etc. DAO provides a much simpler way to use them. As Enterprise editions keep on updating to newer technologies, so with DAO, problem of converting the code to newer technology becomes a lot easy.

One more good thing, DAO framework don’t throw technology specific exceptions. All these technology specific(Hibernate, JDBC, JPA etc.)  exceptions are subclasses of DataAccessException. So, there’s no need to handle such exceptions.


Spring+JDBC:

DAO package removes the need to do tedious JDBC coding. I am going to specify how to use JDBC module provided by spring framework-

  • Add required jar files.
  • Create a POJO/Model/Bean for which you have table in database.
  • Create an interface where you would declare all the methods(business methods).
  • Create a class that implements the above created interface. In this class, there are two important attributes- JdbcTemplate reference and DataSource reference. Let’s see what are they.JdbcTemplate is an API which allows to not write time consuming stuff like open connection, close connection, exception handling, holding the transactions etc., which we used to do in JDBC.

    Another API we have is DataSource which contains properties like driver class name, url, username, password and creates connection with database. We can use DriverManagerDataSource class or BasicDataSource(DBCP) class. The former doesn’t provide connection pooling but later does.

    We need to write the configuration for data source in XML and also inject it’s dependency to the attribute of DataSource in this class.

  • Then write the code in the main method to call the business method  according to requirement.

BeanPostProcessor and Spring AOP

Today, I got to know about methods through which we can manipulate the objects before even their initialization. BeanPostProcessor interface allows to play with the object before and after it’s initialization. Then, I got familiarized with Spring AOP(Aspect Oriented Programming) to manage the cross-cutting concerns. Let me tell you, what things I explored in them.

BeanPostProcessor:

As, I mentioned about this API that allows to manipulate the objects according to our requirement.

A real life example would be- During user login, validation is performed. So, before actual cross-checking the credentials with database, for the security purpose, data can be encrypted(before initialization). When that’s done, validate the data and decrypt it too(after initialization), so as to show to the user.

Example-

Let say, we have a POJO class, Employee.

Employee.java-

public class Employee {
	String empName;
	int empSalary;
	int empAge;
        public void initMeth() {
		System.out.println("Init called");
	}

	public void destroyMeth() {
		System.out.println("Destroy called");
	}
       public Employee() {
		System.out.println("Default constructor called");
	}
//getters setters
}

MyBeanProcessor-

Now, we create a MyBeanProcessor which implements BeanPostProcessor which has two methods we need to implement.

  • postProcessBeforeInitialization- This method is invoked before initialization method of a bean instance is invoked.
  • postProcessAfterInitialization- This method is invoked after the initialization method of a bean instance is invoked.

Both these methods take two parameters- Object type and String type. Object reference is the object of POJO class. String value is the ID of the bean we specify in the bean configuration.

package com.spring1;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanProcessor implements BeanPostProcessor{

	@Override
	public Object postProcessAfterInitialization(Object obj, String str) throws BeansException {

		System.out.println("postProcessAfterInitialization");
		System.out.println("Object: "+obj);
		System.out.println("String: "+str);
		return obj;
	}

	@Override
	public Object postProcessBeforeInitialization(Object obj, String str) throws BeansException {
		System.out.println("postProcessBeforeInitialization");
		return obj;
	}

}

employee.xml-

<?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"     xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     http://www.springframework.org/schema/context     http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    	<bean id="e1" class="com.spring1.Employee" init-method="initMeth" destroy-method="destroyMeth">
    		<property name="empName" value="Sheena"/>
    		<property name="empSalary" value="20000"/>
    		<property name="empAge" value="21"/>
    	</bean>

    	<bean class="com.spring1.MyBeanProcessor"/>

  </beans>

Client.java-

Write the code in main method of Client class.

public class Client {
      public static void main(String[] args) {
	   ApplicationContext context = new ClassPathXmlApplicationContext("employee.xml");
	}
}

Output-

Default constructor called
postProcessBeforeInitialization
Init called
postProcessAfterInitialization
Object: Employee [ empName=Sheena, empSalary=20000, empAge=21]
String: e1

 


Spring AOP(Aspect Oriented Programming):

In AOP, we write logic to entertain cross-cutting concerns. Cross-cutting concern is a concern that cannot be ignored at any layer(Presentation, Business, Data access layer). Example- security, transaction processing etc. The logics are written using advices. Advice is an action taken at a particular  join point(execution of a method).

We have different types of advices-

  • Before Advice: Executes before method invocation.
  • After Returning Advice: Executes after method execution has completed.
  • After Throwing Advice: Executes if method throws an exception.
  • After Advice:  Executes regardless of  whether method executed normally or resulted in exception.
  • Around Advice: Executes before and after a method.

Around advice powerful of all though it’s recommended to use less powerful advice which fulfils the requirement.

I am gonna mention real life example where it’s used.

Let say, a client sends request to server. Basically user at client is registering oneself. So, what can be done in that situation. Timestamp can be noted when user starts the registration and timestamp is again noted when user finishes the registration. In this way, the developer will get an idea that how much time it takes to register user in that web application.

To use AOP in project:

  • Firstly link all the jar files(AOP). Make sure, you must have linked the spring core jar files as AOP has requirement that it internally uses spring core.
  • Create a class where you would want to use AOP.User.java-
    public class User {
    	int uid;
    	String name;
    	int age;
    
    //constructor
    //getters setters
    
    public void registerUser(){
    		System.out.println("--registration started--");
    //Assuming 2 seconds for database operation(Register user)
    		try {
    			Thread.sleep(2000);
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    		System.out.println("--registration done--");
    	}
    }
    
  • Create class that implements the required Advice. For before advice, class must implement MethodBeforeAdvice interface. For After advice, implement AfterReturningAdvice.BeforeAdvice.java-
    import java.lang.reflect.Method;
    import org.springframework.aop.MethodBeforeAdvice;
    
    public class BeforeAdvice implements MethodBeforeAdvice{
    
    	@Override
    	public void before(Method method, Object[] objArr, Object obj) throws Throwable {
    		System.out.println("--BeforeAdvice executed--");
    
    	        for(Object ob : objArr)
    				System.out.println("Object in array: "+ob);
    
    		System.out.println("Objec1: "+obj);
    		System.out.println("------------------------------");
    	}
    }
    

    AfterAdvice.java

    import java.lang.reflect.Method;
    import org.springframework.aop.AfterReturningAdvice;
    
    public class AfterAdvice implements AfterReturningAdvice{
    
    	@Override
    	public void afterReturning(Object obj1, Method method, Object[] objArr, Object obj2) throws Throwable {
    		System.out.println("--AfterAdvice executed--");
    
    		for(Object ob : objArr)
    			System.out.println("Object in array: "+ob);
    
    		System.out.println("Objec1: "+obj1);
    		System.out.println("Objec2: "+obj2);
    		System.out.println("------------------------------");
    
    	}
    }
    
  • Configure the beans in xml file. You must configure the bean for BeforeAdvice and AfterAdvice as well. Configure the bean for ProxyFactoryBean which has two properties- target and interceptorNames.user.xml-
    <?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"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
        
        	<bean id="user1" class="com.springaop.User">
        		<property name="uid" value="111"/>
        		<property name="name" value="Sneha"/>
        		<property name="age" value="23" />
        	</bean>
        	
        	<bean id="bfrAdv" class="com.springaop.AfterAdvice" />
        	<bean id="aftAdv" class="com.springaop.BeforeAdvice" />
        	
        	<bean id="userProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        	  <property name="target" ref="user1" />
        	  <property name="interceptorNames">
        	  	<list>
        	  		<value>bfrAdv</value>
        	  		<value>aftAdv</value>
        	  	</list>
        	  </property>
        	</bean>
        	
        </beans>
    
  • Client.java-
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    public class Client {
               public static void main(String[] args) {
    		ApplicationContext cxt = new ClassPathXmlApplicationContext("user.xml");
    		User user = (User)cxt.getBean("userProxy");
    		user.registerUser();
    	}
    
    }
    
  • Output-
    --BeforeAdvice executed--
    Objec1: User [uid=111, name=Sneha, age=23]
    ------------------------------
    --registration started--
    --registration done--
    --AfterAdvice executed--
    Objec1: null
    Objec2: User [uid=111, name=Sneha, age=23]
    ------------------------------
    

Spring core(Part 2)

Today, I got familiarized with Dependency Injection in springs, collection injection, inheritance relation in springs and autowiring. Now, I am going to discuss what I learnt about them.

Dependency Injection-

I will take an example of two classes Person and Address to explain what is dependency injection.

Address class-

public class Address {
	String area;
	String city;
	String state;
	int zipCode;
//constructors

//getters and setters
}

Person class-

public class Person {
	String name;
	String email;
	int age;
	Address address;

	public Person() {
	     address = new Address();
	}
 //getters and setters

Person class has reference to Address class as an attribute. When Person object gets created, then only object of Address type is created as constructor of Person will be called then only. So, clearly we can see that creation of Address object is highly coupled to creation of Person object. The method for object construction of Address, you saw above lead to many problems. So, we should rather implement loosely coupled way for this. That is done by dependency injection. It can be done by two ways:

  • DI through constructors-

This says, create constructor of Person and pass reference of already created Address object to it.


public Person(Address address) {

this.address = address; }

XML for constructor based DI- Write the bean attributes for both the class in the same way. Just add the following line in Bean for Person as specified below. ‘adrs’ is the id of bean of Address.

<constructor-arg ref="adrs1" />
  • DI through setters-

This says, create a setter method in Person and pass reference of already created Address object to it.

    public void setAddress(Address address) {
this.address = address; }

XML for setter based DI- Write the bean attributes for both the class in the same way. Just add another property in Bean for Person as specified below. ‘adrs’ is the id of bean of Address.

<property name="address" ref="adrs" />

 


Injecting Collection:

Let say, we have an attribute in class which is not primitive datatype; rather it is a collection. Ok, let’s take an example of Manager class. A manager can have certificates(0 or more). So, it possesses a list of certificates.

public class Manager {

	String name;
	String email;
	int salary;

	List<String> certificates;
//getters and setters
}

In XML file, the code for bean of Manager is as under-

<bean id="mngr" class="com.spring2.Manager">
    	<property name="name" value="Sheena"/>
    	<property name="email" value="sheena@ex.com"/>
    	<property name="salary" value="50000"/>
    	<property name="certificates">
    	        		<list>
    		        <value>AWS</value>
    			<value>OCJP</value>
    			<value>CCNA</value>
    		</list>
    	</property>
    </bean>

 


Inheritance Relation in springs:

The concept is same as java class inheritance. In XML configuration, we just introduce a new attribute parent, specifying the parent bean as the value of this attribute.

I will demonstrate this by an example. Let say, there’s a class named Father having attributes as:

 public class Father {

	String fname;
	String lname;
	int wealth;
}

There’s another class Child which extends Father. Here, we have those attributes which are unique to Child.

public class Child extends Father{

	String hobby;
	int vehicles;
}

Now, coming to XML file. Define the bean configuration for both the classes. In Child bean, we can define the properties of Father class(as Child extends Father), which are fname, lname, wealth and obviously it’s own properties as well. Notice, there’s a parent attribute in Child bean whose value is same as the id of Father class.

<bean id="father" class="com.spring2.Father">
    	<property name="fname" value="Rakesh"/>
    	<property name="lname" value="Sharma"/>
    	<property name="wealth" value="100000"/>
</bean>
<bean id="child" class="com.spring2.Child" parent="father">
    	<property name="fname" value="Rohan"/>
    	<property name="hobby" value="Singing"/>
    	<property name="vehicles" value="2"/>
</bean>

Now, you can simply fetch the object in main method and display that.

public static void main(String[] args) {
		ApplicationContext cxt = new
                ClassPathXmlApplicationContext("container.xml");

		Child child = cxt.getBean("child", Child.class);
		System.out.println("Firstname: "+child.getFname());
		System.out.println("Lastname: "+child.getLname());
		System.out.println("Wealth: "+child.getWealth());
		System.out.println("Hobbies: "+child.getHobby());
		System.out.println("Vehicles: "+child.getVehicles());
	}

You will get output as:

Firstname: Rohan
Lastname: Sharma
Wealth: 100000
Hobbies: Singing
Vehicles: 2

 


AutoWiring:

Dependencies can be injected internally by autowiring. It makes the development faster since we need not define the dependency explicitly. We have two ways to do this- Autowiring through XML and @Autowired annotation. I will discuss about annotation way. If one has to see the XML way, visit this.

For this, let’s consider the Person-Address relation we saw above and inject dependency of Address in respective attribute in Person class using autowiring.

Come to Person class. Add the @Autowire annotation on the setter method, constructor or field itself. I have added this on setter method for Address.

public class Person {
	//other attributes
	Address address;
	@Autowired
	public void setAddress(Address address) {
		this.address = address;
	}
 //constructor
//other getters and setters
}

In XML file, you need to register AutowiredAnnotationBeanPostProcessor. For registering, just include ” line as shown below in XML file.

<context:annotation-config />
    	<bean id="prsn" class="com.spring2.Person">
    		<!--Define properties and values of attributes of Person except the attribute for Address type -->
    	</bean>

    	<bean id="address" class="com.spring2.Address">
    		<!-- Define the properties and values of all attributes of Address -->
    	</bean>

Now, simply add the code in main method to fetch the Person object, then you will see the Address fields are also initialized as written in bean definition.

For finding more information on Autowiring through annotation, go through the link I provided below. 🙂

http://www.mkyong.com/spring/spring-auto-wiring-beans-with-autowired-annotation/

Spring core(Part 1)

Today, sir gave an introduction to Spring framework and discussed spring core. So, what is spring?The Spring Framework is an application framework and inversion of control container for the java platform. It can be called as framework of frameworks. It provides plenty of features like predefined templates, lightweight, easy testing, fast development, loose coupling, etc.

Now, coming to the architecture of spring framework:

spring_arch

Spring framework has a modular N-layered architecture. Several modules are provided by this framework. One can always choose the desired module(needed by the application to be developed) and skip the rest.

  • Core container:

The important functionalities of IOC(Inversion of Control) and DI(Dependency Injection) are provided in this module specifically in core. Beans provides BeanFactory and Context provides ApplicationContext which we will discuss soon. Expression languages are similar to expression languages in jsp which are used for querying and manipulating objects.

  • AOP(Aspect Oriented Programming):

This helps in handling cross cutting concerns like security and caching. Basically, helping to decouple cross-cutting concerns from the objects that they affect.

  • Data Access/ Integration:

A good news, we don’t have to care much for JDBC, Hibernate, ORM, tranasction etc. They are built in already in this framework. Provision of database management modules has eased the development of applications.

  • Web Module:

Now, we need not care about MVC pattern. That too is provided by Spring framework. It comes already with MVC framework for easy development of applications.


IOC(Inversion Of Control):

This is a very important feature provided by spring framework. What it tells that you don’t need to care about object creation, it will done by the framework itself. IOC is basically provided by a container(Spring container) that is responsible for object creation, its management and destruction. Now, we will look deeper into Spring container to have better clarity of IOC.

We have two different spring containers. They are BeanFactory and ApplicationContext. BeanFactory possess mechanism capable of managing any type of object. ApplicationContext also works the same way. But there exists differences between them. Let’s look into that.

Difference between BeanFactory and ApplicationContext-

  • The first difference is that ApplicationContext is an implementation of BeanFactory. So, we can say it is superset of BeanFactory providing more implementations.
  • Second big difference, I came to know today is that BeanFactory creates the object only when requested by user explicitly but ApplicationContext creates objects specified in the configuration file even if user has not requested for the objects.

So, now we will see an example. Before that just know how to create a project using spring framework. The procedure is as-

    1. Link all the jar files for spring core. Though it depends on the requirement. I am using spring core because the example I am going to demonstrate has that requirement only. For this first create a simple java project. Right click project name in package explorer -> Build Path -> Configure Build Path -> Add External Jars(make sure, Libraries tab is selected) -> Now browse for jar files in your system. After selecting those, click Apply and Close.
    2. Now, create a Bean/POJO class. I have created Employee class. It’s time to create an XML file for configuring the objects for the POJO. Configuring means specifying the values for all the attributes of object. For this, simply create an XML file in src directory. Give a name of your choice.                        Employee.java-
      
      public class Employee {
       String empName;
       int empSalary;
       int empAge;
      
      public Employee() {
       empName = null;
       empSalary = 0;
       empAge = 0;
       System.out.println("Default constructor called");
       }
       public Employee( String empName, int empSalary, int empAge) {
       super();
      
      this.empName = empName;
       this.empSalary = empSalary;
       this.empAge = empAge;
      }
       public String getEmpName() {
       return empName;
       }
       public void setEmpName(String empName) {
       this.empName = empName;
       }
       public int getEmpSalary() {
       return empSalary;
       }
       public void setEmpSalary(int empSalary) {
       this.empSalary = empSalary;
       }
       public int getEmpAge() {
       return empAge;
       }
       public void setEmpAge(int empAge) {
       this.empAge = empAge;
       }
       @Override
       public String toString() {
       return "Employee [ empName=" + empName + ", empSalary=" +
       empSalary + ", empAge=" + empAge + "]";
       }
       }
      
      

      employee.xml-

      <?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"     xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     http://www.springframework.org/schema/context     http://www.springframework.org/schema/context/spring-context-3.0.xsd">
      
          	<bean id="e1" class="com.spring1.Employee" init-method="initMeth" destroy-method="destroyMeth">
          		<property name="empName" value="Sheena"/>
          		<property name="empSalary" value="20000"/>
          		<property name="empAge" value="21"/>
          	</bean>
      
          	<bean id="e2" class="com.spring1.Employee" init-method="initMeth" destroy-method="destroyMeth">
          		<property name="empName" value="Riya"/>
          		<property name="empSalary" value="25000"/>
          		<property name="empAge" value="23"/>
          	</bean>
          </beans>
      
    3. Now, create a class having main method where we will use spring container(BeanFactory or ApplicationContext) to get the access of objects from xml file created in the previous step.
      public class Client {
      
      	public static void main(String[] args) {
      		Resource resource = new ClassPathResource("employee.xml");
      
      		BeanFactory factory = new XmlBeanFactory(resource);
      		Employee e1 = (Employee)factory.getBean("e1");
      		System.out.println("e1: "+e1);
      
      		ApplicationContext context = new ClassPathXmlApplicationContext("employee.xml");
      		Employee e2 = (Employee)context.getBean("e2");
      		System.out.println("e2: "+e2);
      	}
      
      }
      
      

      Now, see the output:

      Default constructor called
      e1: Employee [ empName=Sheena, empSalary=20000, empAge=21]
      Default constructor called
      Default constructor called
      e2: Employee [ empName=Riya, empSalary=25000, empAge=23]
      

      Observation: Default constructor is called, means object is created first for e1 when requested by BeanFactory. Similarly it has to be for e2 which is requested by ApplicationContext. But main point to be noted is that constructor is called two times before printing e2 employee. One was invoked for e1 and other for e2. Although, e1 has not been requested by ApplicationContext, still the object for e1 gets created. This is the main difference between BeanFactory and ApplicationContext.

 


Bean Lifecycle:

One interesting thing,  you can have lifecycle methods for your bean class. Means, now you can see when object gets initialized and when it is destroyed. Just define two methods in POJO class- one for init and other for destroy. Name them anything you want.

In XML file, modify the Bean by adding init-method and destroy-method. Make sure, you pass the values to these parameters as the method name(for init and destroy) you created in POJO class.

Now, whenever objects are created and destroyed, the respective method gets executed.

 


Bean Scope:

We can define scope for objects in XML file. scope parameter can be set to singleton, prototype, session, etc.

By default, it’s singleton. This means, even if we create two reference variables having same objects. Then they will be containing same address for object location. Means, single object is created in heap and both the reference variables will be pointing to that.

Scope can be prototype. Object having this scope will be created again and again for different reference variables.


IOC in Android:

Lastly, sir discussed about IOC in android. We have XML files in android where we design layout for apps. Views or viewgroups specified in XML have specific id. Whenever we call, findViewById in java code for id of particular view or viewgroup then IOC creates object for that particular view. So, everything in Android is also an object.  🙂

An Intro to Hibernate

Today, I got to know about an exciting framework, Hibernate. I am calling it exciting for many reasons and that’s why it is much in use by developers.

In JDBC, we used to set the driver class, create connection,  close connection, manage the transactions, code for batch processing and most importantly create table manually in database. Now, question comes, how Hibernate helps in that issue. Here’s the answer, below.

  • Hibernate is an ORM(Object Relational Mapping) tool that itself maps the objects in our program with tuples in the table. It creates table on its own with the help of POJO class which we create.
  • Not only this, hibernate allows to write less code for transaction management and many other queries.
  • Here, we mention the configuration information such as Driver class name, database name, username, password, url etc. in separate file (in most cases, hibernate.cfg.xml file). So, we need not to go to code for changing any parameter in future. We just have to modify the cfg.xml file.
  • A very important feature it provides is the Hibernate Query Language(HQL). HQL is database independent. So, it avoids database portability hassles.

Configuring the Hibernate:

  1. Link the jar files.
  2. Configure hibernate.cfg.xml
  3. Configure anyname.hbm.xml file
  4. Write the hibernate statements
  • Link the jar files

Create a java project. Download the jar files for hibernate. Right click project -> Build Path -> Configure Build Path. Click Add external jars. Choose all jars and click Apply an Close.

  • Configure hibernate.cfg.xml

Create an xml file by ‘hibernate.cfg.xml’ name. You can give any name but it’s better to give this name as it this file will be automatically read, otherwise we have to specify the name explicitly in the code.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/HibernateProject</property>
        <property name="hibernate.connection.username">root</property>
        <property name="connection.password"></property>
        <property name="connection.pool_size">10</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping resource="employee.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

It contains information such as driver class, url, username, password.

connection.pool_size- indicates the maximum number of pooled connections.

hibernate.dialect- Dialect class writes the query statements on our behalf. I told earlier about HQL that is database independent which operates on objects and not on table directly. So, queries for table will be written and fired by Dialect class which we specify here.

show_sql- If this property is true, then you can see the query statements fired by dialect class in console when you run the project.

hibernate.hbm2ddl.auto- If the value of this property is create, then table will be created again by deleting the previous table if present by the same name. If its value is update, then already created table will be modified.

mapping resource- Here, you will specify the hbm.xml mapping file, about which I’ll tell soon.

  • Configure anyname.hbm.xml file

Firstly you will have to create a POJO class. I created Employee class.

package com.mitaly;

public class Employee {

	int id;
	String name;
	String phone;
	int salary;
// constructor
//getters and setters
}

Now, create an xml file named ‘employee.hbm.xml‘. This file contains the mapping information. You will specify the attributes in POJO and corresponding column names.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC   "-//Hibernate/Hibernate Mapping DTD//EN"  "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="com.mitaly.Employee" table="Employee">
      <id name="id" column="eId">
         <generator class="increment"/>
      </id>
      <property name="name" column="eName"/>
      <property name="phone" column="ePhone"/>
      <property name="salary" column="eSalary"/>
   </class>
</hibernate-mapping>

 

  • Write the hibernate statements

Create a main class and write the following code to create an object of Employee class and store in database.

package com.mitaly;

public class Client {
	public static void main(String[] args) {

		Configuration config = null;
		SessionFactory factory = null;
		Session session = null;
		Transaction transaction = null;

		try {

			config = new Configuration();
			// this will read the hibernate.cfg.xml file
			config.configure();

			factory = config.buildSessionFactory();

			session = factory.openSession();

			transaction = session.beginTransaction();

			Employee emp = new Employee(1, "Shanaya", "90909 99993",19000);

			//for saving the data in table
			session.save(emp2);

			transaction.commit();

		}catch (Exception e) {

			transaction.rollback();
		}finally {
			session.close();
		}
	}

}