Monday, 8 July 2013
Wednesday, 3 July 2013
Timer & TimerTask in Java
Whenever
we are asked to code scheduled processes , immediately Thread comes
into our mind & dealing with threads is the most complex task to be
handled while coding , at least for me. And if maintaining a timer with
the help of a thread with the other thread processes makes me lil'bit
annoyed.
Thanks to Timer and TimerTask classes in Java.
A Timer is required whenever any task is to be performed after regular interval of time. You know what task is to be done. We code for that task which performs its operation after particular duration as per defined in the timer.
Lets say you need to know no. of users dropped over server which might be due to network breakdown. As a naive programmer , you'll try to run a task which is supposed to bring no. of users over server after every minute and will calculate and compare with the previous user count of previous minute for example the difference comes out to be more than 50% then an alarm should be raised. [getting user count is indeed not the optimized solution for the defined problem]
Now the above process defined need to be performed after every 1 minute . It will be a foolishness to start a thread after every single minute to perform this task. The correct solution lies in Timer & TimerTask Class.
For Example:
We are going to write a code to generate a clock , a clock whose time is to be calculated after every single second & is even made to print.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Timer;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
*
* @author vaibhav
*/
public class timerclass extends Timer {
int i=0;
timerclass()
{
init();
}
public void init()
{
/* below timer is schedule to count 30 seconds from
* current second of current minute.
* scheduleAtFixedRate method : Schedules the specified
* task for repeated fixed-rate execution,
* beginning after the specified delay. Subsequent executions takes
* place at approximately regular intervals, separated by the specified period.
*/
scheduleAtFixedRate(new RunTimer(), 1000, 1000);
/* initail delay = 1000 milliseconds = 1 second
* period = 1000 milliseconds = 1 second (interval)
*/
}
class RunTimer extends TimerTask
{
@Override
public void run() {
if(i<=30)
{
System.out.println(new Date().getSeconds());
i++;
}
else
{
/*Cancels this timer task
* calling this method from within
* the run method of a repeating timer task
* absolutely guarantees that the timer task will not run again.
* i.e. you have to again create the schedular for re-running
* the timer
*/
cancel();
System.out.println("End") ;
System.exit(0);
}
}
}
}
package Timer;
/**
*
* @author vaibhav
*/
public class calltimer {
public static void main(String... s)
{
// init() in constructor of timer class will schedule timer for clock
timerclass tc = new timerclass();
}
}
Now the above written code runs a clock for 30 seconds.
We made use of :
a) scheduleAtFixedRate(Timer Task task, long delay, long period) of Timer Class
b) boolean cancel() : stops the timer of scheduler , method of TimerTask Class
c) run() : we overrided the run method , which is defined as abstract method in TimerTask Class.
Thanks to Timer and TimerTask classes in Java.
A Timer is required whenever any task is to be performed after regular interval of time. You know what task is to be done. We code for that task which performs its operation after particular duration as per defined in the timer.
Lets say you need to know no. of users dropped over server which might be due to network breakdown. As a naive programmer , you'll try to run a task which is supposed to bring no. of users over server after every minute and will calculate and compare with the previous user count of previous minute for example the difference comes out to be more than 50% then an alarm should be raised. [getting user count is indeed not the optimized solution for the defined problem]
Now the above process defined need to be performed after every 1 minute . It will be a foolishness to start a thread after every single minute to perform this task. The correct solution lies in Timer & TimerTask Class.
For Example:
We are going to write a code to generate a clock , a clock whose time is to be calculated after every single second & is even made to print.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Timer;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
*
* @author vaibhav
*/
public class timerclass extends Timer {
int i=0;
timerclass()
{
init();
}
public void init()
{
/* below timer is schedule to count 30 seconds from
* current second of current minute.
* scheduleAtFixedRate method : Schedules the specified
* task for repeated fixed-rate execution,
* beginning after the specified delay. Subsequent executions takes
* place at approximately regular intervals, separated by the specified period.
*/
scheduleAtFixedRate(new RunTimer(), 1000, 1000);
/* initail delay = 1000 milliseconds = 1 second
* period = 1000 milliseconds = 1 second (interval)
*/
}
class RunTimer extends TimerTask
{
@Override
public void run() {
if(i<=30)
{
System.out.println(new Date().getSeconds());
i++;
}
else
{
/*Cancels this timer task
* calling this method from within
* the run method of a repeating timer task
* absolutely guarantees that the timer task will not run again.
* i.e. you have to again create the schedular for re-running
* the timer
*/
cancel();
System.out.println("End")
System.exit(0);
}
}
}
}
package Timer;
/**
*
* @author vaibhav
*/
public class calltimer {
public static void main(String... s)
{
// init() in constructor of timer class will schedule timer for clock
timerclass tc = new timerclass();
}
}
Now the above written code runs a clock for 30 seconds.
We made use of :
a) scheduleAtFixedRate(Timer
b) boolean cancel() : stops the timer of scheduler , method of TimerTask Class
c) run() : we overrided the run method , which is defined as abstract method in TimerTask Class.
Tuesday, 2 July 2013
Tuesday, 9 April 2013
Wednesday, 3 April 2013
Tuesday, 2 April 2013
Saturday, 30 March 2013
Settai film Official Trailer - Arya -Santhanam - Premgi - Hansika - Anjali - Nasser
Settai film Official Trailer
Wednesday, 2 January 2013
Struts 2 File Upload & Save Example
Let us see how to work with file uploads in struts 2 frame work, things to remember while working with this type of application
- See in index.jsp i have taken <s:file name=”uploadFile” i mean my file tag name is uploadFile
- We used to write setters, getters for this property in Action class right, but while writing we need to write setters, getters for 2 more properties with names uploadFileFileName & uploadFileContentType
- I mean name format must be [ our file property name ]ContentType & [ our file property name ]FileName
- Actually at run time struts 2 container will injects the required file details into these properties, and thing is see struts.xml - line 23 fileUpload is the predefined interceptor class, this will take cares every thing
- Once file uploaded, struts 2 will stores the file with some temp name, its our responsibility to convert and save that file, see line numbers 39,40,41,42 in Action class of LogingEx.java
File Upload Example
required files….- index.jsp
- success.jsp
- web.xml
- struts.xml
- LogingEx.java
Directory Structure
index.jsp
1
2
3
4
5
6
7
8
9
10
11
12
| <%@ taglib prefix="s" uri="/struts-tags" %> < html > < head > < s:head /> </ head > < s:actionerror /> < s:form action = "uploadAction" method = "POST" enctype = "multipart/form-data" > < s:file name = "uploadFile" label = "Choose File" size = "40" /> < s:submit value = "Upload" name = "submit" /> </ s:form > |
success.jsp
1
2
3
4
5
6
7
8
| <%@ taglib prefix="s" uri="/struts-tags" %> < html > File uploaded successfully...!!! File Name : < s:property value = "uploadFileFileName" /> < br > Content Type : < s:property value = "uploadFileContentType" /> < br > Temp File Name : < s:property value = "uploadFile" /> |
LogingEx.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
| package java4s; import java.io.File; import org.apache.commons.io.FileUtils; import com.opensymphony.xwork2.ActionSupport; public class LogingEx extends ActionSupport{ private static final long serialVersionUID = 1L; private File uploadFile; private String uploadFileContentType; private String uploadFileFileName; public File getUploadFile() { return uploadFile; } public void setUploadFile(File uploadFile) { this .uploadFile = uploadFile; } public String getUploadFileContentType() { return uploadFileContentType; } public void setUploadFileContentType(String uploadFileContentType) { this .uploadFileContentType = uploadFileContentType; } public String getUploadFileFileName() { return uploadFileFileName; } public void setUploadFileFileName(String uploadFileFileName) { this .uploadFileFileName = uploadFileFileName; } public String execute() { try { String filePath = "c:/Myuploads" ; // Path where uploaded file will be stored System.out.println( "Server path:" + filePath); // check your path in console File fileToCreate = new File(filePath, uploadFileFileName); // Create file name same as original FileUtils.copyFile(uploadFile, fileToCreate); // Just copy temp file content tos this file } catch (Exception e) { e.printStackTrace(); addActionError(e.getMessage()); return INPUT; } return SUCCESS; } } // Context pirnt..... //private HttpServletRequest servletRequest; //String filePath = servletRequest.getSession().getServletContext().getRealPath("/"); //System.out.println("Server path:" + filePath); //File fileN = new File(filePath, this.uploadFileFileName); //FileUtils.copyFile(this.userImage, fileToCreate); |
web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
< web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id = "WebApp_ID" version = "2.5" > < filter > < filter-name >struts2</ filter-name > < filter-class >org.apache.struts2.dispatcher.FilterDispatcher</ filter-class > </ filter > < filter-mapping > < filter-name >struts2</ filter-name > < url-pattern >/*</ url-pattern > </ filter-mapping > < welcome-file-list > < welcome-file >index.jsp</ welcome-file > </ welcome-file-list > </ web-app > |
struts.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" < struts > < include file = "struts-default.xml" /> < package name = "a" extends = "struts-default" > < action name = "uploadAction" class = "java4s.LogingEx" > < interceptor-ref name = "exception" /> < interceptor-ref name = "alias" /> < interceptor-ref name = "servletConfig" /> < interceptor-ref name = "prepare" /> < interceptor-ref name = "i18n" /> < interceptor-ref name = "chain" /> < interceptor-ref name = "debugging" /> < interceptor-ref name = "profiling" /> < interceptor-ref name = "scopedModelDriven" /> < interceptor-ref name = "modelDriven" /> < interceptor-ref name = "fileUpload" > < param name = "maximumSize" >10240</ param > < param name = "allowedTypes" >text/plain</ param > </ interceptor-ref > < interceptor-ref name = "checkbox" /> < interceptor-ref name = "staticParams" /> < interceptor-ref name = "actionMappingParams" /> < interceptor-ref name = "params" > < param name = "excludeParams" > dojo\..*,^struts\..*</ param > </ interceptor-ref > < interceptor-ref name = "conversionError" /> < interceptor-ref name = "validation" > < param name = "excludeMethods" > input,back,cancel,browse</ param > </ interceptor-ref > < interceptor-ref name = "workflow" > < param name = "excludeMethods" > input,back,cancel,browse</ param > </ interceptor-ref > < result name = "success" >/success.jsp</ result > < result name = "input" >/index.jsp</ result > </ action > </ package > </ struts > |
Output
Output If if we take wrong file
Output If file accepted
Tuesday, 1 January 2013
Struts2 Interceptors Tutorial with Example
Struts 2 Interceptors: Basics
Struts2 provides very powerful mechanism of controlling a request using Interceptors. Interceptors are responsible for most of the request processing. They are invoked by the controller before and after invoking action, thus they sits between the controller and action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc.The request processing lifecycle of Struts2 framework is pretty much discussed Part 1 – Introduction to Struts2 Framework.
- Request is generated by user and sent to Servlet container.
- Servlet container invokes FilterDispatcher filter which in turn determines appropriate action.
- One by one Intercetors are applied before calling the Action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc.
- Action is executed and the Result is generated by Action.
- The output of Action is rendered in the view (JSP, Velocity, etc) and the result is returned to the user.
Struts2 comes with default list of Interceptors already configured in the application in
struts-default.xml
file. We can create our own custom Interceptors and plugin into a Struts2 based web application.Framework creates an object of ActionInvocation that encapsulates the action and all the interceptors configured for that action. Each interceptors are called before the action gets called. Once the action is called and result is generated, each interceptors are again called in reverse order to perform post processing work. Interceptors can alter the workflow of action. It may prevent the execution of action.
Our Goal
Our goal will be to create a customer interceptor MyLoggingInterceptor, which will log the request before any action is called. Also it will prints the Action class name and execution time of action in milliseconds.Create Logging Interceptor
Create a java classMyLoggingInterceptor
in package net.viralpatel.struts2.interceptors
and copy following content into it.package net.viralpatel.struts2.interceptor; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.Interceptor; public class MyLoggingInterceptor implements Interceptor{ private static final long serialVersionUID = 1L; public String intercept(ActionInvocation invocation) throws Exception { String className = invocation.getAction().getClass().getName(); long startTime = System.currentTimeMillis(); System.out.println( "Before calling action: " + className); String result = invocation.invoke(); long endTime = System.currentTimeMillis(); System.out.println( "After calling action: " + className + " Time taken: " + (endTime - startTime) + " ms" ); return result; } public void destroy() { System.out.println( "Destroying MyLoggingInterceptor..." ); } public void init() { System.out.println( "Initializing MyLoggingInterceptor..." ); } } |
Configuring Interceptor in struts.xml
Once we have created an interceptor class, all we need to do is to configure it instruts.xml
file and use it with actions.To configure newly created interceptor, add following code in struts.xml
< interceptors > < interceptor name = "mylogging" class = "net.viralpatel.struts2.interceptor.MyLoggingInterceptor" > </ interceptor > < interceptor-stack name = "loggingStack" > < interceptor-ref name = "mylogging" /> < interceptor-ref name = "defaultStack" /> </ interceptor-stack > </ interceptors > |
Here we have configured a new interceptor mylogging with tag
We can make the new loggingStack as default interceptor stack or can configure it at each action level. In order to make it default stack, we should add following in struts.xml
< default-interceptor-ref name = "loggingStack" ></ default-interceptor-ref > |
Also we may want to apply the custom interceptor stack to only certain actions. To do so, we must add interceptor-ref tag in action.
< action name = "login" class = "net.viralpatel.struts2.LoginAction" > < interceptor-ref name = "loggingStack" ></ interceptor-ref > < result name = "success" type = "tiles" >/welcome.tiles</ result > < result name = "error" >Login.jsp</ result > </ action > |
That’s All Folks
If we execute our StrutsHelloWorld application in Eclipse and see the console logs, we will find the log statements that we print in our interceptor.Initializing MyLoggingInterceptor... .. .. .. Before calling action: net.viralpatel.struts2.LoginAction .. .. After calling action: net.viralpatel.struts2.LoginAction Time taken: 313 ms .. .. .. Destroying MyLoggingInterceptor... |
Download Source Code
Click here to download Source Code without JAR files (17KB)
Subscribe to:
Posts (Atom)