Featured Articles
All Stories
Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Thursday, April 23, 2015

Spring Batch- Creating Job Repository,Job Launcher Configuration - With Out DB

<batch:job id="simpleJob"
job-repository="jobRepository" restartable="true" abstract="true">
<batch:listeners/>
</batch:job>


<!-- Repository and Launcher -->
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>

<!-- Job Repository configuration this is important and must -->
<bean id="jobRepository"
    class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
    <property name="transactionManager" ref="transactionManager" />
</bean>



<bean id="transactionManager"
class="org.springframework.batch.support.transaction.ResourcelessTransactionManager">
</bean>

</beans>
1:11 PM - By Manu 0

Spring Batch- Creating Job Repository,Job Launcher Configuration - With DB

In this post we will discuss job repository configuration.
If you application data source(schema) is different from spring batch data source you need to create two data sources one for application and the other for spring batch

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util" xmlns:batch="http://www.springframework.org/schema/batch"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd"
default-lazy-init="true">


<!-- ************************************************************************************************************** -->
<!-- * To work with Spring Batch We need a job repository, this job repository
is used to store the spring batch job meta meta data information such as
who is launched the job with which parameters job got launched etc etc following
Configuration explains the job repository configuration -->
<!-- ************************************************************************************************************** -->

<batch:job id="simpleJob" incrementer="jobIncrementor"
job-repository="jobRepository" restartable="true" abstract="true">
<batch:listeners>
<batch:listener ref="listener"></batch:listener>
</batch:listeners>
</batch:job>


<bean id="listener" class="com.springbatchdemo.parallel.JobProcessTimeListener" />
//Below configuration for job incrementor
<!--<bean id="jobIncrementor" class="com.springbatchdemo.incrementor.JobIncrementor" />-->

<!-- Repository and Launcher -->
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>

<!-- Job Repository configuration this is important and must -->
<batch:job-repository id="jobRepository"
data-source="jdbc.dataSource" transaction-manager="batch.transactionManager"
max-varchar-length="2500" />
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="jdbc.dataSource" />
</bean>
<bean id="batch.transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="jdbc.dataSource" />
</bean>

<!-- ********************************************************************************************************** -->
<!-- Data Source Configuration -->
<!-- ********************************************************************************************************** -->
<bean id="jdbc.dataSource" class="com.ibm.db2.jcc.DB2SimpleDataSource">
<property name="driverType" value="4" />
<property name="serverName" value="${jdbc.host}" />
<property name="portNumber" value="${jdbc.port}" />
<property name="databaseName" value="${jdbc.dbName}" />
<property name="currentSchema" value="DB SCHEMA" />
<property name="user" value="${jdbc.userName}" />
<property name="password" value="${jdbc.password}" />
<property name="resultSetHoldability" value="1" />
<property name="clientApplicationInformation" value="Test" />
<property name="clientProgramName" value="Test :SpringBatch" />
<property name="clientUser" value="XXX" />
</bean>

<!-- Jdbc Template Configuration -->
<bean id="jdbc.template" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="jdbc.dataSource" />
</bean>


</beans>

The values in bold can be used for db tracking

12:59 PM - By Manu 0

Thursday, April 16, 2015

Spring Batch Tutorial


Spring batch is a very interesting frame work , In this post we will discuss various examples on  spring batch.

All the example discussed in the post based on spring batch version 2.X

Spring batch framework internally provides 6 spring batch tables , to start working with with spring batch we need to create following tables.

BATCH_JOB_EXECUTION
BATCH_JOB_EXECUTION_CONTEXT
BATCH_JOB_INSTANCE
BATCH_JOB_PARAMS
BATCH_STEP_EXECUTION
BATCH_STEP_EXECUTION_CONTEXT

Spring  batch uses these tables to store job related meta data information, such as 
1)When Particular job got triggered
2)who triggered the job.
3)When the job got triggerd.
4)How much time job took to complete.
5)How many records processed during the job process.
6) what is the status of the job (Completed,Failed ..) etc.

We can work with Spring batch without database also .


1) Creating Job repository,Job launcher in spring batch-- To work with spring batch It is mandatory to create Job repository whether it may be resource less(with out db) with DB.

a) Creating  Job Repository: Please refer below link to create a Job repository
     Click here
b) Creating bob Repository : With Resource less Transaction manager
Without DB Configuration



6:48 PM - By Manu 0

Advanced Java(J2EE) Interview Questions

Hi Friends In this post we would like to share you commonly asked J2EE interview questions.


Q)What is Servlet
Servlet is server side component, a servlet is small plug gable extension to the server and servlets are used to extend the functionality of the java-enabled server. Servlets are durable objects means that they remain in memory specially instructed to be destroyed. Servlets will be loaded in the Address space of web server.
->Servlet are loaded 3 ways
 1) When the web sever starts
 2) You can set this in the configuration file
 3) Through an administration interface.

Q) What is Temporary Servlet?
 When we sent a request to access a JSP, servlet container internally creates a 'servlet' & executes it. This servlet is called as 'Temporary servlet'. In general this servlet will be deleted immediately to create & execute a servlet base on a JSP we can use following command.
Java weblogic.jspc—keepgenerated *.jsp

Q) What is the difference between Server and Container?
A) A server provides many services to the clients, A server may contain one or more containers such as ejb containers,servlet/jsp container. Here a container holds a set of objects.

Q)What is  Servlet Container
The servlet container is a part of a Web server (or) Application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses.
1) A servlet container also contains and manages servlets through their lifecycle.
2) A servlet container can be built into a host Web server, or installed as an add-on component to a Web Server via that server‘s native extension API.
3)All servlet containers must support HTTP as a protocol for requests and responses, but additional request/response-based protocols such as HTTPS (HTTP over SSL) may be supported.

Q) Generally Servlets are used for complete HTML generation. If you want to generate partial HTML's that include some static text as well as some dynamic text, what method do you use?
Using 'RequestDispather.include(―xx.html‖) in the servlet code we can mix the partial static HTML Directory page.
Ex: - RequestDispatcher rd=ServletContext.getRequestDispatcher(―xx.html‖);
rd.include(request,response);

Q) Can you explain Servlet Life cycle
Life Cycle sates: new born state, ready state, running state, Idle/wait and dead
Below are the life cycle methods of servlet.
Public void init (ServletConfig config) throws ServletException
public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy ()
a) The Web server when loading the servlet calls the init method once. (The init method typically establishes database
connections.)
b)Any request from client is handled initially by the service () method before delegating to the doXxx () methods in the
case of HttpServlet. If u put ―Private‖ modifier for the service() it will give compile time error.
c) When your application is stopped (or) Servlet Container shuts down, your Servlet's destroy () method will be called.
This allows you to free any resources you may have got hold of in your Servlet's init () method, this will call only once.
ServletException :Signals that some error occurred during the processing of the request and the container should
take appropriate measures to clean up the request.
IOException : Signals that Servlet is unable to handle requests either temporarily or permanently.

Q) Why there is no constructor in servlet?
 A servlet is just like an applet in the respect that it has an init() method that acts as a constructor, an initialization code you need to run should e place in the init(), since it get called when the servlet is first loaded.

Q) Can we use the constructor, instead of init(), to initialize servlet?
 Yes, of course you can use. There‘s nothing to stop you. But you shouldn‘t. The original reason for init() was that ancient versions of Java couldn‘t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won‘t have access to a ServletConfig or ServletContext.

Q) Can we leave init() method empty and insted can we write initilization code inside servlet's constructor?
 No, because the container passes the ServletConfig object to the servlet only when it calls the init method. So ServletConfig will not be accessible in the constructor.

Q) Explain ServletConfig Interface & ServletContex Interfaces
ServletConfig :  ServletConfig object is used to obtain configuration data when it is loaded. There can be multiple ServletConfig objects in a single web application.
This object defines how a servlet is to be configured is passed to a servlet in its init method. Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters. The container, in turn, passes these parameters to the servlet via the ServetConfig.
Ex:-
<web-app>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>TestServlet</servlet-class>
<init-param>
<param-name>driverclassname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
<init-param>
<param-name>dburl</param-name>
<param-value>jdbc:odbc:MySQLODBC</param-value>
</init-param>
</servlet>
</web-app>
--------------------------------------
public void init()
{
ServletConfig config = getServletConfig();
String driverClassName = config.getInitParameter("driverclassname");
String dbURL = config.getInitParameter("dburl");
Class.forName(driverClassName);
dbConnection = DriverManager.getConnection(dbURL,username,password);
}

ServletContext:  ServletContext is also called application object. ServletContext is used to obtain information about environment on which a servlet is running.
There is one instance object of the ServletContext interface associated with each Web application deployed into a container. In cases where the container is distributed over many virtual machines, a Web application will have an instance of the ServletContext for each JVM.
Servlet Context is a grouping under which related servlets run. They can share data, URL namespace, and other resources. There can be multiple contexts in a single servlet container.

Q) How to add application scope in Servlets?
 In Servlets Application is nothing but ServletContext Scope.
ServletContext appContext = servletConfig.getServletContext();
appContext.setAttribute(paramName, req.getParameter(paramName));
appContext.getAttribute(paramName);

Q) Diff between HttpSeassion & Stateful Session bean? Why can't HttpSessionn be used instead of of Session bean?
 HttpSession is used to maintain the state of a client in webservers, which are based on Http protocol. Where as
Stateful Session bean is a type of bean, which can also maintain the state of the client in Application servers, based on RMI-IIOP.

Q) Can we store objects in a session?
session.setAttribute("productIdsInCart",productIdsInCart);
session.removeAttribute("productIdsInCart");

Q) Are Servlets multithread?(This is most important question)
Yes, the servlet container allocates a thread for each new request for a single servlet. Each thread of your servlet runs as if a single user were accessing using it alone, but u can use static variable to store and present information that is common to all threads, like a hit counter for instance.

Q) what is Session Tracking ?
Session tracking is the capability of the server to maintain the single client sequential list.

Q) what us Servlet chaining?
Is a technique in which two are more servlets cooperating in servicing a single client sequential request, where one servlet output is piped to the next servlet output. The are 2 ways
(i) Servlet Aliasing (ii) HttpRequest
Servlet Aliasing : allow you to setup a single alias name for a comma delimited list of servlets. To make a servlet chain open your browser and give the alias name in URL.
HttpRequest: construct a URL string and append a comma delimited list of servlets to the end.

Q)What is  HttpTunnelling
Is a method used to reading and writing serializes objects using a http connection. You are creating a sub protocol inside http protocol that is tunneling inside another protocol.

Q) Diff GET & POST (This is most important question)
* GET & POST are used to process request and response of a client.
* GET method is the part of URL, we send less amount of data through GET. The amount of information limited is 240-255 characters (or 1kb in length).
*Using POST we can send large amount of data through hidden fields.
* Get is to get the posted html data, POST is to post the html data.

Q) Diff Http & Generic Servlet (This is most important question)
* HttpServlet class extends Generic servlet , so Generic servlet is parent and HttpServlet is child.
* Generic is from javax.servlet package, HttpServlet is from javax.servlet.Http package.
* Http implements all Http protocols, Generic servlet will implements all networking protocol
* Http is stateless protocol, which mean each request is independent of previous one, In generic we cannot maintain the state of next page only main state of current page.
* A protocol is said to be stateless if it has n memory of prior connection.
* Http servlet extra functionality is capable of retrieving Http header information.
*Http servlet can override doGet(), doDelete(), doGet(), doPost(), doTrace(), generic servlet will override Service() method only.

Q)What are all various types of Session tracking Techniques
Below are the various session tracking techniques in servlets
(i) URL Rewriting
(ii) Hidden form Field
(iii) Persistence Cookies
(iv) Session Tracking API
(v) User Authorization

URL RewritingURL rewriting is a technique in which the requested URL is modified with the session id.
URL rewriting is another way to support anonymous session tracking. With URL rewriting, every local URL the user might click on is dynamically modified, or rewritten, to include extra information.
http://server:port/servlet/Rewritten?sessionid=123 added parameter

Hidden form Field
Hidden form fields are HTML input type that are not displayed when read by the browser. They are sent back to the server when the form that contains them is submitted. You include hidden form fields with HTML like this:
<FORM ACTION="/servlet/TrainFinder" METHOD="POST">
<INPUT TYPE=hidden NAME="trainNumeber" VALUE="94040">
<INPUT TYPE=hidden NAME="station" VALUE="expert">
</FORM>
In a sense, hidden form fields define constant variables for a form. To a servlet receiving a submitted form, there is no difference between a hidden field and a visible field.

Persistence Cookie
A cookie is a bit of information sent by a web server to a browser that can later be read back from that browser.
When a browser receives a cookie, it saves the cookie and thereafter sends the cookie back to the server each time it accesses a page on that server, subject to certain rules. Because a cookie's value can uniquely identify a client, cookies are often used for session tracking. Because cookies are sent using HTTP headers, they should be added to the response before you send any content. Browsers are only required to accept 20 cookies per site, 300 total per user, and they can limit each cookie's size to 4096 bytes.

Session Tracking API
In Java the javax.servlet.http.HttpSession API handles many of the details of session tracking. It allows a  session object to be created for each user session, then allows for values to be stored and retrieved for each session.
A session object is created through the HttpServletRequest using the getSession() method:
HttpSession session = request.getSession(true);
This will return the session for this user or create one if one does not already exist. Values can be stored for a user session using the HttpSession method putValue():
session.putValue("valueName", valueObject);
Session objects can be retrieved using getValue(String name), while a array of all value names can be retrieved using getValueNames().
Values can also be removed using removeValue(String valueName)

User Authorization
Servers can be set up to restrict access to HTML pages (and servlets). The user is required to enter a user name and password. Once they are verified the client re-sends the authorisation with requests for documents to that site in the http header.
Servlets can use the username authorisation sent with request to keep track of user data. For example, a hashtable can  be set up to contain all the data for a particular user. When a user makes another request the user name can be used to add new items to their cart using the hashtable.
5:34 PM - By Manu 0

Wednesday, April 15, 2015

Core Java Interview Questions

Hello friends In this post we would like to share most of the frequently asked java interview questions.These interview questions are sufficient to clear interview :)
These interview questions are really helpful for the people who are having  2,3 and 4+ Years exp in Java
In this FAQS we will cover all the concepts  , we tried to cover almost all the concepts in Java

Q) Explain  Oops concepts?

  Oops : Object oriented programming system
     Following are the important oops concepts
     1) Abstraction
     2) Encapsulation
     3) Ploymorphism
     4) Inheritance

Abstraction :  
Nothing but representing the essential futures without including background details.

Encapsulation:
Wrapping of data and function into a single unit called encapsulation, the single unit formed is called object.
 Ex:- all java programs.
(Or)
Nothing but restricting data, like the variables declared under private of a particular class are accessed only in that class and cannot access in any other the class. Or Hiding the information from others is called as Encapsulation.
Or
Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse.

Ploymorphism:
Ability to take more than one form, in java we achieve this using Method Overloading (compile time polymorphism),

Method overriding (runtime polymorphism)
Ex:  calculateSum(int x,int y), calculateSum(int x, int y,int z)
If observe above calculateSum() is having polymorphic nature,  two methods are having same method name but with different parameters one with two and one with three, the same method will return sum of two numbers or sum of three numbers depending upon the parameters passed

Inheritance:
Is the process by which one object acquires the properties of another object.
The advantages of inheritance are
Reusability of code and accessibility of variables and methods of the super class by subclasses(Please note this is very important point in interview).

For example refer --

Q)What is class and Object , how to create Object for a class?
Class - class is a blue print of an object
Object- instance of class.
Object Creation:
Hello h= new Hello();
In the above statement Hello is the class name , h is  reference variable for Hello class and new is the key word which is responsible for creation object for class Hello and Hello() is the constructor. 

Q) What is Constructor?
Constructor
The automatic initialization is performed through the constructor
a) Constructor has same name has class name.
b) Constructor has no return type not even void. We can pass the parameters to the constructor.
c) this()  is used to invoke a constructor of the same class.
d) Super () is used to invoke a super class constructor.
e)Constructor is called immediately after the object is created before the new operator completes.

Note: this and super are the keywords

1) Constructor can use the access modifiers public, protected, private or have no access modifier
2) Constructor can not use the modifiers abstract, static, final, native, synchronized or strictfp
3) Constructor can be overloaded, we cannot override.
4) You cannot use this () and Super() in the same constructor.

Ex programme:
Class A(
A(){
System.out.println("hi");
}}
Class B extends A {
B(){
System.out.println("India");
}}
Class print {
Public static void main (String args []){
B b = new B();
}
Output is : hi India

Q) Differences between constructors and methods
Differences between constructors and methods explained in below table
If method is having same name as class name and having void return type , then it is not a constructor, its a just method.



Q) Where Objects,Methods and Variables are created ?
Object is constructed either on a memory heap or on a stack.
Memory heap
Generally the objects are created using the new keyword. Some heap memory is allocated to this newly created object. This memory remains allocated throughout the life cycle of the object. When the object is no more referred,the memory allocated to the object is eligible to be back on the heap.
Stack
During method calls, objects are created for method arguments and method variables. These objects are created on stack.

Q) Explaing System.out.println()?
System: is the final  class of java.lang package.
Out: is an instance variable of java.lang.System class.
println(): is a methd of java.io.printWriter.Which is used to print to console.

We will discuss more about final and instance varibale in coming questions.













9:16 PM - By Manu 0

© 2014 GSDUNIA. WP Theme-junkie converted by Bloggertheme9
Powered by Blogger.
back to top