Friday, February 14, 2014

How To Upload a Image into Database using Jsp, Servlet and Hibernate?


Here is the Way To Upload Image into Database .
In My Example  i have

1.Jsp                                                                          
2.Servlet
3.POJO class
4.DAO Class
5.web.xml
6.hibernate configuration file
and mysql database.

and i am using "commons file uploading library".For This we need 2 jar files

commons-fileupload-(version)[1.3.1].jar
commons-io-(version)[2.4].jar

ImageUpload.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>



Image Upload
     
       
ImageUploadServlet.java

package p1;

import java.io.IOException;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class ImageUploadServlet extends HttpServlet {

    private static final long serialVersionUID = -1623656324694499109L;
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
       
    response.setContentType("text/html;charset=UTF-8");
    try {
    if (! ServletFileUpload.isMultipartContent(request)) {
                 System.out.println("sorry. No file uploaded");
                 return;
             }
   
            // Apache Commons-Fileupload library classes
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload sfu  = new ServletFileUpload(factory);

         // parse request
            List items = sfu.parseRequest(request);
         
         // get uploaded file
            FileItem file = (FileItem) items.get(0);
            System.out.println("file size: "+file.getSize());
            new ImageUploadDAO().upload(file.getInputStream());
    }catch(Exception e){
    e.printStackTrace();
    }
    }
}

Image.java(POJO)
package p1;

import java.sql.Blob;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;

@Entity
@Table(name="image", catalog="TEST")
public class Image {

@Id
@GeneratedValue
@Column(name="id")
private int id;

@Column(name="image")
@Lob
private Blob image;

/**
* @return the id
*/
public int getId() {
return id;
}

/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}

/**
* @return the image
*/
public Blob getImage() {
return image;
}

/**
* @param image the image to set
*/
public void setImage(Blob image) {
this.image = image;
}
}

ImageUploadDAO.java


package p1;

import java.io.InputStream;
import java.sql.Blob;

import org.apache.commons.io.IOUtils;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class ImageUploadDAO {
private SessionFactory sessionFactory=null;
public void upload(InputStream is){

try{
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory();
Session session=sessionFactory.openSession();
Image image=new Image();
byte[] bytes = IOUtils.toByteArray(is);
Blob blob = Hibernate.createBlob(bytes, session);
image.setImage(blob);
session.save(image);
System.out.println("Image uploded successfully");

}catch(Exception e){
System.err.println("Exception in ImageUploadDAO");
e.printStackTrace();
}
}
}

web.xml

   
    ImageUploadServlet
    ImageUploadServlet
    p1.ImageUploadServlet
 
 
    ImageUploadServlet
    /ImageUploadServlet
 

Hibernate configuration file

        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">


   
       
        com.mysql.jdbc.Driver
        jdbc:mysql://localhost:3306/TEST
        root
        ********
     
        1
        org.hibernate.dialect.MySQLDialect
        thread
   
        true
        update

 
     


This is working example. Enjoy Coding..!!

*Note: if uploading image through Ajax request
add a field fileElementId:'brandimage(image field id in html)', send the remaining data in data:{...} field.
In servlet check the each  'FileItem '  object whether it 'isFormField()'  or not,if yes that is the image ,take InputStream and forward to DAO.There create Blob object and insert into database.It requires ajaxfileupload.js Library along with the commons api in this application.

If You Got any problems  please Feel Free To Make Comments...!!!
Happy coding.

Saturday, February 8, 2014

Activation of Spring Container in Web Application

                                           
One of the ways to Activate Spring 'ApplicationContext'  Container is
First Configure the Spring configuration file in web.xml file
eg:

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/Spring.cfg.xml</param-value>
</context-param>


and next Configure the ContextLoaderListener

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


and finally in Servlet


ApplicationContext context=WebApplicationContextUtils.
getRequiredWebApplicationContext(config.getServletContext());


It is Done. Now ApplicationContext Container will be Activated.

How To Enable Logging Feature in Our Web Application?

One of the ways That we can Enable Logging Functionality in Our Web Applications is as Follows.....
                                                                             
Firstly

we need a file that has all properties related to Logging functionality
Ex:


# Root logger option  
      
   # log4j.rootLogger=INFO, file, stdout  
    log4j.rootLogger=ALL, file, stdout 
      
    # Direct log messages to a log file  
    log4j.appender.file=org.apache.log4j.RollingFileAppender  
    log4j.appender.file.File=/home/imadas/simplrdapilogs/logingFile.log

     #The Maximum size of a backup file.
    log4j.appender.file.MaxFileSize=1MB  

    #To maintain only one backup file.
    log4j.appender.file.MaxBackupIndex=1  

    log4j.appender.file.layout=org.apache.log4j.PatternLayout  
    log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n  
    
    #=======
    # Set the immediate flush to true (default)
    log4j.appender.FILE.ImmediateFlush=true

    # Set the threshold to debug mode
    log4j.appender.FILE.Threshold=debug
    #======
      
    # Direct log messages to stdout  
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
    log4j.appender.stdout.Target=System.out  
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
    log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n  



Now Configure the above file in application "web.xml"  and Logger Listener  like:

<!-- Log4j Configuration -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- End -->


Now we can use the Logging Feature in Our Application

Logger logger=new Logger.getLogger(The class); 


 Now we can use as we like

logger.info("...");
logger.debug,
logger.error.....etc.


Wednesday, December 18, 2013

Quartz Scheduler in Spring

 Quartz Scheduler is used to scheduling of all kinds of jobs. For this it uses Trigger, Job and JobDetail objects
   
                                           

 JobDetail objects contain all information needed to run a job. The Spring Framework provides a JobDetailBean that makes the JobDetail more of an actual JavaBean with sensible defaults

For Ex:
<bean name="exampleJob" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="example.ExampleJob" />
<property name="jobDataAsMap">
<map>
<entry key="timeout" value="5" />
</map>
</property>
</bean>

The timeout is specified in the job data map. The job data map is available through the JobExecutionContext (passed to you at execution time), but the JobDetailBean also maps the properties from the job data map to properties of the actual job. So in this case, if the ExampleJob contains a property named timeout,the JobDetailBean will automatically apply it.
Ex:

package example;
public class ExampleJob extends QuartzJobBean {
private int timeout;
/**
* Setter called after the ExampleJob is instantiated
* with the value from the JobDetailBean (5)
*/
public void setTimeout(int timeout) {
this.timeout = timeout;
}
protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException {
// do the actual work
}
}

MethodInvokingJobDetailFactoryBean:
Oftenly we need to invoke a method on a specific Class. The
"MethodInvokingJobDetailFactoryBean" can do this exactly. 

Ex Configuration:

<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="exampleBusinessObject" />
<property name="targetMethod" value="doIt" />
</bean>

The above example will call the doIt method on the ExampleBusinessObject class.
The class:

public class ExampleBusinessObject {
// properties and collaborators
public void doIt() {
// do the actual work
}
}

Using the MethodInvokingJobDetailFactoryBean, we don't need to create one-line jobs that just invoke a method, and we only need to create the actual business object and wire up the detail object.

By default Quartz jobs are stateless. Since they are stateless there is a possibility of interfering each other.

If we specify 2 triggers for the same JobDetails there is a possibility of starting the second one before First one is Completed.

To avoid this and to make jobs of 'MethodInvokingJobDetailFactoryBean'  
non-concurrent set 'concurrent' flag to 'false'.


<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="exampleBusinessObject" />
<property name="targetMethod" value="doIt" />
<property name="concurrent" value="false" />
</bean>

Wiring up jobs using triggers & the 'SchedulerFactoryBean':

We have created JobDetails and Jobs.
we still needs to schedule the jobs themselves this can be done using 'triggers' and a 'SchedulerFactoryBean'.
There are several triggers are available with in Quartz and Spring Provides 2 Quartz FactoryBean implementations with convenient defaults

CronTriggerFactoryBean
SimpleTriggerFactoryBean.

Triggers need to be Scheduled.For this Spring offers a 'SchedulerFactoryBean' that exposes triggers to be set as properties.
SchedulerFactoryBean schedules the actual jobs with those triggers.

Ex. Configurations:

<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<!-- see the example of method invoking job above -->
<property name="jobDetail" ref="jobDetail" />
<!-- 10 seconds -->
<property name="startDelay" value="10000" />
<!-- repeat every 50 seconds -->
<property name="repeatInterval" value="50000" />
</bean>

<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="exampleJob" />
<!-- run every morning at 6 AM -->
<property name="cronExpression" value="0 0 6 * * ?" />
</bean>

Now we've set up two triggers, 
First one running every 50 seconds with a starting delay of 10 seconds and
Second one runs every morning at 6 AM. And Finally we need to set up the

SchedulerFactoryBean:

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger"/>
<ref nean="simpleTrigger"/>
</list>
</property>
</bean>

there are some more properties to use.

Scheduling in Spring

 The Spring Framework provides abstractions for asynchronous execution and scheduling of tasks with the 'TaskExecutor' and 'TaskScheduler' ibsp;                                                                                     Spring also Provided Implementations of these Interfaces which supports  'Thread Pools' or delegation to CommonJ within an application server environment.

Spring also features integration classes for supporting scheduling with the Timer, part of the JDK since1.3, and the Quartz Scheduler.

Both of those schedulers are set up using a FactoryBean with optional references to Timer or Trigger instances, respectively. And, a convenience class for both the Quartz Scheduler and the Timer is available that allows you to invoke a method of an existing target object (analogous to the normal MethodInvokingFactoryBean operation).

Spring's TaskExecutor interface has a single method execute(Runnable task) that accepts a task for execution based on the semantics and configuration of the thread pool.

The TaskExecutor was originally created to give other Spring components an abstraction for thread pooling where needed. Components such as the ApplicationEventMulticaster, JMS's AbstractMessageListenerContainer, and Quartz integration all use the TaskExecutor abstraction to pool threads. However, if your beans need thread pooling behavior, it is possible to use this abstraction for your own needs.

TaskExecutor types:
There are a number of pre-built implementations of TaskExecutor

SimpleAsyncTaskExecutor
SyncTaskExecutor
ConcurrentTaskExecutor
and etc.

Using a TaskExecutor:
Spring's TaskExecutor implementations are used as simple JavaBeans
as Following

import org.springframework.core.task.TaskExecutor;

public class TaskExecutorExample {
private class MessagePrinterTask implements Runnable {
private String message;
public MessagePrinterTask(String message) {
this.message = message;
}
public void run() {
System.out.println(message);
}
}
private TaskExecutor taskExecutor;
public TaskExecutorExample(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
public void printMessages() {
for(int i = 0; i < 25; i++) {
taskExecutor.execute(new MessagePrinterTask("Message" + i));
}
}
}

As you can see, rather than retrieving a thread from the pool and executing yourself, you add your Runnable to the queue and the TaskExecutor uses its internal rules to decide when the task gets
executed.
To configure the rules that the TaskExecutor will use, simple bean properties have been exposed.

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="5" />
<property name="maxPoolSize" value="10" />
<property name="queueCapacity" value="25" />
</bean>
<bean id="taskExecutorExample" class="TaskExecutorExample">
<constructor-arg ref="taskExecutor" />
</bean>

Task Scheduler:

In addition to the 'TaskExecutor' abstraction, Spring 3.0 introduces a TaskScheduler with a variety of methods for scheduling tasks to run at some point in the future.

Methods in TaskScheduler Interface

ScheduledFuture schedule(Runnable task, Trigger trigger);
ScheduledFuture schedule(Runnable task, Date startTime);
ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);
ScheduledFuture scheduleAtFixedRate(Runnable task, long period);
ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);
ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);

The simplest method is the one named 'schedule' that takes a Runnable and Date only. That will cause the task to run once after the specified time. All of the other methods are capable of scheduling tasks to run repeatedly. The fixed-rate and fixed-delay methods are for simple, periodic execution, but the method that accepts a Trigger is much more flexible.

Trigger:

public interface Trigger {
Date nextExecutionTime(TriggerContext triggerContext);
}

The 'TriggerContex' is the most important part. It encapsulates all of the relevant data.The 'TriggerContext' is an interface (a 'SimpleTriggerContext' implementation is used by default). The methods are available for Trigger implementations.

public interface TriggerContext {
Date lastScheduledExecutionTime();
Date lastActualExecutionTime();
Date lastCompletionTime();
}

Trigger implementations:

Spring provides two implementations of the Trigger interface. The most interesting one is the
CronTrigger. It enables the scheduling of tasks based on cron expressions. For example the following
task is being scheduled to run 15 minutes past each hour but only during the 9-to-5 "business hours"
on weekdays.

scheduler.schedule(task, new CronTrigger("* 15 9-17 * * MON-FRI"));

And Another Implementations is

implementation is a 'PeriodicTrigger' that accepts a fixed period, an
optional initial delay value, and a boolean to indicate whether the period should be interpreted as a fixed-rate or a fixed-delay.