Tuesday, December 25, 2012

Run Wowza as Startup Service in Linux

Run Wowza as Startup Service in Linux:

1) Login as root user

2) create a file "WowzaMediaServer.sh" in "/etc/init.d/" directory, copy & paste the following script and save the file.

#!/bin/bash
#
# Startup script for Wowza Media Server
#
# chkconfig: - 80 20
# description: Wowza Media Server is a media server
#
#### BEGIN INIT INFO
# Provides:          WowzaMediaServer
# Required-Start:    $syslog $time $local_fs $remote_fs
# Required-Stop:     $syslog $time $local_fs $remote_fs
# Default-Start:     3 4 5
# Default-Stop:      S 0 1 2 6
# Short-Description: Wowza Media Server 3 Init Script
# Description:       Wowza Media Server 3 Init Script
### END INIT INFO

WMCOMMAND=${1}

FUNCTIONS_EXIST=false
if [ -f /etc/rc.d/init.d/functions ] ; then
     . /etc/rc.d/init.d/functions
     FUNCTIONS_EXIST=true
fi
if [ -f /etc/init.d/functions ] ; then
     . /etc/init.d/functions
     FUNCTIONS_EXIST=true
fi

if ! $FUNCTIONS_EXIST ; then
failure() {
  return 0
}
success() {
  return 0
}
fi

# define vars
RETVAL=0
WMSBASE_NAME=WowzaMediaServer
#WMSCONFIG_SCRIPT="/etc/WowzaMediaServer/$WMSBASE_NAME.conf"
WMSCONFIG_SCRIPT="/usr/local/WowzaMediaServer/bin/setenv.sh"
WMSLICENSE_FILE="/usr/local/WowzaMediaServer/conf/Server.license"
AMAZONEC2_INSTALL_SCRIPT="/usr/local/WowzaMediaServer/bin/AmazonEC2Install.sh"
WMSDAEMON_CMD=/usr/bin/WowzaMediaServerd
WMSPID_FILE="/var/run/$WMSBASE_NAME.pid"
WMSLOCK_FILE="/var/run/$WMSBASE_NAME"
if test -w "/var/lock/subsys" ; then
    WMSLOCK_FILE="/var/lock/subsys/$WMSBASE_NAME"
fi
SHUTDOWN_WAIT=20

[ -r "$WMSCONFIG_SCRIPT" ] && . "$WMSCONFIG_SCRIPT"

if ! test -f "${WMSLICENSE_FILE}" ; then
        echo ""
        echo "ERROR: Missing license file: (${WMSLICENSE_FILE})"
        echo "You must first run Wowza Media Server 3 in "
        echo "standalone mode to enter serial number. Execute the "
        echo "following commands to run in standalone mode:"
        echo ""
        echo "cd /usr/local/WowzaMediaServer"
        echo "./startup.sh"
        echo ""
        exit 0
fi

testjava=`which ${_EXECJAVA} 2>/dev/null`
if ! test -f "$testjava" ; then
    echo ""
    echo "ERROR: The Java command (${_EXECJAVA}) could not be found."
    echo "Search path: $PATH"
    echo "In most cases this problem can be fixed by adding a symbolic "
    echo "link to the Java command in the /usr/bin directory. "
    echo "To do this first execute the command \"which java\" to identify "
    echo "the full path to the Java executable. Next, create a symbolic "
    echo "link to this file with the command"
    echo "\"ln -sf [path-to-java] /usr/bin/java\" where [path-to-java] is "
    echo "the path returned by the \"which\" command."
    echo ""
    exit 0
fi

#
start() {

if [ -f $WMSPID_FILE ]; then
    read kpid < $WMSPID_FILE
    kill -9 $kpid
    echo $"$WMSBASE_NAME is already running ($kpid): stopping"
    rm -f $WMSPID_FILE
fi

echo -n $"$WMSBASE_NAME: starting"
#$AMAZONEC2_INSTALL_SCRIPT
$WMSDAEMON_CMD $WMSCONFIG_SCRIPT $WMSPID_FILE start >/dev/null 2>&1 &
success "$WMSBASE_NAME startup"
echo
touch $WMSLOCK_FILE

return 0
}

stop() {

if [ -f $WMSPID_FILE ]; then

    echo -n $"$WMSBASE_NAME: stopping"
    read kpid < $WMSPID_FILE


    $WMSDAEMON_CMD $WMSCONFIG_SCRIPT $WMSPID_FILE stop >/dev/null 2>&1 &

    let kwait=$SHUTDOWN_WAIT
    count=0;
    until [ `ps -p $kpid | grep -c $kpid` = '0' ] || [ $count -gt $kwait ]
    do
        echo -n -e "\nwaiting for processes to exit";
        sleep 1
        let count=$count+1;
    done

    if [ $count -gt $kwait ]; then
        echo -n -e "\nkilling processes which didn't stop after $SHUTDOWN_WAIT seconds"
        kill -9 $kpid
    fi

    rm -f $WMSPID_FILE
    success "$WMSBASE_NAME shutdown"
else
    echo -n $"$WMSBASE_NAME: not running"
fi
echo
rm -f $WMSLOCK_FILE
return 0
}

localstatus() {
if [ -f $WMSLOCK_FILE ]; then
    echo "$WMSBASE_NAME started"
else
    echo "$WMSBASE_NAME stopped"
fi
RETVAL=0
}

# See how we were called.
case "$WMCOMMAND" in
start)
start
;;
stop)
stop
;;
status)
localstatus
;;
restart)
stop
start
;;
*)
echo $"Usage: $WMSBASE_NAME {start|stop|restart|status}"
exit 1
esac

exit $RETVAL

3) Restart the machine

Saturday, December 22, 2012

How to Create Shared Folder for VM Palyer

Using Shared Folders

With shared folders, you can easily share files among virtual machines and the host computer. To use shared folders, you must have the current version of VMware Tools installed in the guest operating system and you must configure your virtual machine settings to specify which directories are to be shared.
VMware Workstation 5 includes new performance enhancements for shared folders.
You can use shared folders with virtual machines running the following guest operating systems:
  • Windows Server 2003
  • Windows XP
  • Windows 2000
  • Windows NT 4.0
  • Linux with a kernel version of 2.4 or higher
  • To set up one or more shared folders for a virtual machine, be sure the virtual machine is open in Workstation and click its tab to make it the active virtual machine. Choose VM > Settings > Options and click Shared folders.
    Link to w_vmset_opt_shareapl.png
    You can add one or more directories to the list. Those directories may be on the host computer or they may be network directories accessible from the host computer.

    Adding a Shared Folder on a Windows Host

    (To add a shared folder on a Linux host, see Adding a Shared Folder on a Linux Host.)
    1. Choose VM > Settings
    2. Select Options
    3. Click Shared Folders
    4. Click Add to open the Add Shared Folder Wizard and click Next
    Link to w_sharefolder_welcome.png
    5. Enter a name and location for the shared folder and click Next
    Link to w_sharefolder_name.png
  • Name — This is the name that appears inside the virtual machine.
  • Host folder — The path on the host to the directory you want to share. Type in the full path or browse to the directory.
  • 6. Enter attributes for the shared folder.
    Link to w_sharefolder_attributes.png
  • Enable this share — Select this option to enable the shared folder. Deselect this option to disable the shared folder without deleting it from the virtual machine configuration. You may want to add a folder to the list without enabling it immediately. You can then enable the folder at any time by clicking its name in this list, clicking Properties and enabling the folder in the Properties dialog box.
  • Read-only — Select this option to prevent the virtual machine from changing the contents of the shared folder in the host file system. Access to files in the shared folder is also governed by permission settings on the host computer.
  • Disable after this session — Select this option to disable the virtual machine's connection to the folder when the virtual machine is powered off or suspended. Leave this box unchecked to specify that the folder is always enabled.
  • 7. Click Finish.

    Adding a Shared Folder on a Linux Host

    (To add a shared folder on a Windows host, seeAdding a Shared Folder on a Windows Host.)
    1. Choose VM > Settings
    2. Select Options
    3. Click Shared Folders
    4. Click Add to open the Shared Folder Properties dialog box.
    Link to l_shared_folder.png
    5. Enter the following information for the shared folder.
  • Name — This is the name that appears inside the virtual machine.
  • Host folder — The path on the host to the directory you want to share. Type in the full path or browse to the directory.
  • Enable this share — Select this option to enable the shared folder. Deselect this option to disable the shared folder without deleting it from the virtual machine configuration. You may want to add a folder to the list without enabling it immediately. You can then enable the folder at any time by clicking its name in this list, clicking Properties and enabling the folder in the Properties dialog box.
  • Read-only — Select this option to prevent the virtual machine from changing the contents of the shared folder in the host file system. Access to files in the shared folder is also governed by permission settings on the host computer.
  • Disable after this session — Select this option to disable the virtual machine's connection to the folder when the virtual machine is powered off or suspended. Deselect this option to specify that the folder is always enabled.
  • 6. Click OK.

    Viewing a Shared Folder

    Shared folders appear differently, depending on the guest operating system. The following sections describe viewing shared folders in Windows and Linux guests.
    Note: You can use shared folders to share any type of file. However, Windows shortcuts and Linux symbolic links do not work correctly if you try to use them via shared folders.
    Caution: Do not open a file in a shared folder from more than one application at a time. For example, you should not open the same file using an application on the host operating system and another application in the guest operating system. In some circumstances, doing so could cause data corruption in the file.

    Viewing Shared Folders in a Windows Guest

    In a Windows guest operating system, you can view shared folders using Windows Explorer. Look in My Network Places (Network Neighborhood for a Windows NT guest) under VMware Shared Folders.
    Note: If you have trouble finding a shared folder when using the desktop icon for My Network Places (or Network Neighborhood in Windows NT), instead open Windows Explorer and look in My Network Places (Network Neighborhood). The Windows desktop icon does not display an option for Entire Network.
    For example, if you specify the name Test files for one of your shared folders, you can navigate to it by opening My Network Places > VMware Shared Folders > .host > Shared Folders > Test files.
    You can also go directly to the folder using the UNC path
    \\.host\Shared Folders\Test files.
    You can map a shared folder to a drive letter just as you would with a network share.
    Note: If your guest operating system has VMware Tools from Workstation 4.0, shared folders appear as folders on a designated drive letter.

    Viewing Shared Folders in a Linux Guest

    In a Linux virtual machine, shared folders appear under /mnt/hgfs.
    To change the settings for a shared folder on the list, click the folder's name to highlight it, then click Properties. The Properties dialog box appears.
    Change any settings you wish, then click OK.

    Thursday, December 13, 2012

    Installing wowza in Ubuntu

    Requiremnt:
    1) JDK 1.6 or latest
    *** Installing jdk in ubuntu
    sudo add-apt-repository "deb http://us.archive.ubuntu.com/ubuntu/ hardy multiverse"
    sudo add-apt-repository "deb http://us.archive.ubuntu.com/ubuntu/ hardy-updates multiverse"
    sudo apt-get update
    sudo apt-get install sun-java6-jdk
    sudo add-apt-repository ppa:ferramroberto/java
    sudo apt-get update
    sudo apt-get install sun-java6-jdk sun-java6-jre sun-java6-plugin sun-java6-fonts


    ** To Install wowza server in ubuntu
      ** go to the wowza .bin folder
       $ cd /newuser/installables/Wowza setup
       $ ./WowzaMediaServer-3.5.0.deb.bin

    ** To run the Wowza Media server
    $ cd /usr/local/WowzaMediaServer
    $ ./startup.sh
    -->  To Start Wowza Media Server as a background process
               $ ./WowzaMediaServer start
     --> To Stop Wowza Media Server
               $ ./WowzaMediaServer stop

    Tuesday, December 11, 2012

    Linux Helper

    cp Command Syntax:

    The syntax is as follows to copy files and directories using the cp command:
     
    cp SOURCE DEST
    cp SOURCE DIRECTORY
    cp SOURCE1 SOURCE2 SOURCE3 SOURCEn DIRECTORY
    cp [OPTION]  SOURCE DEST
    cp [OPTION]  SOURCE DIRECTORY
    
    

    chmod Command Syntax:

    The chmod command changes the access mode of one file or multiple files.
    The syntax for the chmod command is:
    chmod [option] mode files

    Options:

    Option Description
    -R Descend directory arguments recursively while setting modes.
    -f Suppress error messages if command fails.

    Mode:

    Mode Description
    Who u=user, g=group, o=other, a=all (default)
    Opcode + means add permission
    - means remove permission
    = means assign permission and remove the permission of unspecified fields
    Permission r=Read, w=write, x=Execute, s=set uid bit, t=sticky bit
    u=user, g=group, o=other, l=mandatory locking

    Examples

    chmod 751 tech chmod u=rwx, g=rx, o=x tech chmod =r tech
    Following are few examples on how to use the symbolic representation on chmod.

    1. Add single permission to a file/directory

    Changing permission to a single set. + symbol means adding permission. For example, do the following to give execute permission for the user irrespective of anything else:
    $ chmod u+x filename

    2. Add multiple permission to a file/directory

    Use comma to separate the multiple permission sets as shown below.
    $ chmod u+r,g+x filename

    3. Remove permission from a file/directory

    Following example removes read and write permission for the user.
    $ chmod u-rx filename

    4. Change permission for all roles on a file/directory

    Following example assigns execute privilege to user, group and others (basically anybody can execute this file).
    $ chmod a+x filename

    5. Make permission for a file same as another file (using reference)

    If you want to change a file permission same as another file, use the reference option as shown below. In this example, file2′s permission will be set exactly same as file1′s permission.
    $ chmod --reference=file1 file2

    6. Apply the permission to all the files under a directory recursively

    Use option -R to change the permission recursively as shown below.
    $ chmod -R 755 directory-name/

    7. Change execute permission only on the directories (files are not affected)

    On a particular directory if you have multiple sub-directories and files, the following command will assign execute permission only to all the sub-directories in the current directory (not the files in the current directory).
    $ chmod u+X *
    Note: If the files has execute permission already for either the group or others, the above command will assign the execute permission to the user


     

    Java Native Processing



    Native processing , is the way to invokes  the platform dependent process form the java code, Java provides the Native processing for Linux/Windows .
    Example Code :
     TestApp.java
    public class TestApp {
    public static void main(String[]args) {
    String line;
          try {
                Process process = Runtime.getRuntime().exec(“notepad.exe”);
    BufferedReader is = new BufferedReader(
     new InputStreamReader(process.getInputStream()));
    while ((line = is.readLine()) != null)
    System.out.println(line);
    System.out.println("In Main after EOF");
    System.out.flush();
    try {
       p.waitFor();  // wait for process to complete
     catch (InterruptedException e) {
      System.err.println(e);  // "Can'tHappen"
       return;
    }
    System.err.println("Process done, exit status was " + p.exitValue());
              } catch (Exception e) {
                e.printStackTrace(System.err);
              }
          }
    }
    Compile the above code
    Javac –d TestApp.java
    Run Application
    Java  TestApp
    It invokes the notepad application .
    But some time, we need to execute the heavy process they will take time, and we may run third party tools form the command prompt so we don’t have the control on them. To get the control on them Apache foundation providing an Apache Commons Exec  API  to achieve it. This is the best API for the java development to get the outcomes of the process.

    Example :
    ApacheCommonExec.java
    import org.apache.commons.exec.CommandLine;
    import org.apache.commons.exec.DefaultExecutor;
    Public class ApacheCommonExec {
    Public static void main(String args[]){
    try {
          CommandLine cmdLine = CommandLine.parse(filePath);
          DefaultExecutor executor = new DefaultExecutor();
          executor.execute(cmdLine);                     
          } catch (Exception ex) {
           ex.printStackTrace();
          }
    }
    }
    To download the library file please click Here
    For more Information please click  Here

    Call Servlet from normal java class

    We can call  the Servlet form the basic java code , it might be used, but some situations will force to do this.
    Some situations like, generate batch file in core java program and send the result 2 the servlet to  process the file as a native process

    Example :
    Step- I :  create a Dynamic web project web project

    Write your servlet for example :
    HelloServle.java
    package com.app;

    import java.io.IOException;
    import java.io.PrintWriter;

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

    /**
     * Servlet implementation class HelloServlet
     */
    public class HelloServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;

        /**
         * @see HttpServlet#HttpServlet()
         */
        public HelloServlet() {
            super();
            // TODO Auto-generated constructor stub
        }

        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
         *      response)
         */
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            /*
             * Get the value of form parameter
             */
            String value1 = request.getParameter("parameter1");
            response.setContentType("text/html");
            PrintWriter pw = response.getWriter();
            pw.println("<html>");
            pw.println("<head><title>Hello World</title></title>");
            pw.println("<body>");
            pw.println("<h1>Hello World</h1>");
            pw.println("<b> Dear ,"+value1 +"</b>");
            pw.println("</body></html>");
        }

        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
         *      response)
         */
        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            doGet(request,response);
        }

    }
     web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app id="WebApp_ID">
        <display-name>WebApp</display-name>
          <servlet>
            <servlet-name>hello</servlet-name>
            <display-name>HelloServlet</display-name>
             <servlet-class>com.app.HelloServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello.do</url-pattern>
        </servlet-mapping>
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

    Compile the code  and deploy in the tomcat

    Step- II :
    RemoteClass.java

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.URL;
     

    public class RemoteClass {

     public static void main(String args[]){
     String line;
      try {
            URL url = new URL("http://localhost:8080/WebApp/hello.do?parameter1="+value1 );
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            line = in.readLine();
            System.out.println( line );
            in.close();
          } catch (Exception e) {
              e.printStackTrace();
          }
       }
    }
    Compile the code and run above code from as JavaApplication.





    Friday, December 7, 2012

    FFMPEG : Video Editing Tool


    Ffmpeg is the one of the best tool available to us to perform operation on video and audio

    Installing ffmpeg in Linux
    --------------------------
    1. Open your terminal and login as root user 
    2. Update your repository
    3. FFMPEG is available in the ubuntu repository. so install it directly
    • apt-get update
    • sudo apt-get update
    • sudo apt-get install build-essential git-core checkinstall texi2html libopencore-amrnb-dev libopencore-amrwb-dev libsdl1.2-dev libtheora-dev libvorbis-dev libx11-dev libxfixes-dev zlib1g-dev automake autoconf libxvidcore-dev 
    • apt-get install ffmpeg
    
    
    Basics of FFMPEG-Options
    Command:
        ffmpeg
    
    Input file:
        -i yoursourcefile
    
    Optional rescaling
        -s 640x480
    
    Video conversion (choose one)
        -vcodec copy
        -vn (No Video)
    
    Audio conversion (choose one)
        -acodec libmp3lame -ab 64k
        -acodec copy
        -an (No audio)
    
    Output file (this name appears on the line without an option before it)
        youroutputfile

    Mixing two Audio files
    ffmpeg -i thelusa.mp3 -itsoffset 3.3 -i Fly-By-II.mp3  -filter_complex amix outputFile.mp3 

    To mix more than two files please repeat the above command  with replacing first input file with outcome of the above and second input file with newmp3 file . ie., 

    ffmpeg -i outputFile.mp3 -itsoffset 3.3 -i badBoys.mp3  -filter_complex amix outputFile2.mp3 
    Repeat this process to get the desired outcome from the n-files mixing .

    Cutting video file
     ffmpeg -i input.flv -ss 00:00:00 -t 00:10:00  -y output.flv  
     The above command will cut the video of 10 mins from the given input.flv file and generate the outcome as  output.flv

    Append Two Audio Files
     copy /b file1.mp3 + file2.mp3  out.mp3

     copy /b file1.flv + file2.flv  out.flv

    Extract Audio From video file 
     ffmpeg -i input.avi  -vn -acodec copy output.avi

    To record your screen withh FFMPEG, you can use this command:

    ffmpeg -f x11grab -follow_mouse 100 -r 25 -s vga -i :0.0 filename.avi
    To show the region that will be recorded while moving your mouse pointer, use this command:

    ffmpeg -f x11grab -follow_mouse centered -show_region 1 -r 25 -s vga -i :0.0 filename.avi

    If you want to record in fullscreen with better video quality (HD), you can use this command:

    ffmpeg -f x11grab -s wxga -r 25 -i :0.0 -sameq  video.mp4


    Add Image Watermarks to A Video 

    Picture Location: Top Left Corner
    ffmpeg -i input.avi -vf "movie=file.png [watermark]; [in][watermark] overlay=10:10 [out]" output.flv

    Picture Location: Top Right Corner

    ffmpeg –i input.avi -vf "movie=watermarklogo.png [watermark]; [in][watermark] overlay=main_w-overlay_w-10:10 [out]" output.flv

    Picture Location: Bottom Left Corner

    ffmpeg –i input.avi -vf "movie=watermarklogo.png [watermark]; [in][watermark] overlay=10:main_h-overlay_h-10 [out]" output.flv

    Picture Location: Bottom Right Corner

    ffmpeg –i input.avi -vf "movie=watermarklogo.png [watermark]; [in][watermark] overlay=main_w-overlay_w-10:main_h-overlay_h-10 [out]" output.flv

    Add Text as Watermarks to A Video 

    ffmpeg -i input.mp4 -vf drawtext="fontfile=/usr/share/fonts/truetype/freefont/FreeSans.ttf: text='YOUR TEXT HERE':fontcolor=red@1.0:fontsize=70:x=00: y=40" -y output.mp4

     


    Create Strtus2 Application Using Eclipse

    Initial Requirement to Start

    Before we starts with our first Hello World Struts 2 Example, we will need few tools.
    1. JDK 1.5 above (download)
    2. Tomcat 5.x above or any other container (Glassfish, JBoss, Websphere, Weblogic etc) (download)
    3. Eclipse 3.2.x above (download)
    4. Apache Struts2 JAR files:(download). Following are the list of JAR files required for this application.
      • commons-logging-1.0.4.jar
      • freemarker-2.3.8.jar
      • ognl-2.6.11.jar
      • struts2-core-2.0.12.jar
      • xwork-2.0.6.jar
      Note that depending on the current version of Struts2, the version number of above jar files may change.

    Getting Started

    Let us start with our first Struts2 based application.
    Open Eclipse and goto File -> New -> Project and select Dynamic Web Project in the New Project wizard screen.
    Dynamic Web Project in Eclipse
    After selecting Dynamic Web Project, press Next.
    Eclipse Struts2 Project
    Write the name of the project. For example StrutsHelloWorld. Once this is done, select the target runtime environment (e.g. Apache Tomcat v6.0). This is to run the project inside Eclipse environment. After this press Finish.
    Once the project is created, you can see its structure in Project Explorer.
    Eclipse Project Explorer: Struts2 Example
    Now copy all the required JAR files in WebContent -> WEB-INF -> lib folder. Create this folder if it does not exists.
    struts2-webinf-jars

    Login Application

    Our goal is to create a basic Struts2 application with a Login page. User will enter login credential and if authenticated successfully she will be redirected to a Welcome page which will display message ” Howdy, <username>…!“. If user is not authenticated, she will be redirected back to the login page.
    struts2-application-login-page

     

    Mapping Struts2 in WEB.xml

    As discussed in the previous article (Introduction to Struts2), the entry point of Struts2 application will be the Filter define in deployment descriptor (web.xml). Hence we will define an entry of org.apache.struts2.dispatcher.FilterDispatcher class in web.xml.
    Open web.xml file which is under WEB-INF folder and copy paste following code.
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_9" version="2.4"
        xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
        <display-name>Struts2 Application</display-name>
        <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>Login.jsp</welcome-file>
        </welcome-file-list>
    </web-app>
    The above code in web.xml will map Struts2 filter with url /*. The default url mapping for struts2 application will be /*.action. Also note that we have define Login.jsp as welcome file.
    Note: The FilterDispatcher filter is deprecated since Struts version 2.1.3. If you are using latest version of Struts2 ( > 2.1.3) use StrutsPrepareAndExecuteFilter class instead.
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
         org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    The Action Class

    We will need an Action class that will authenticate our user and holds the value for username and password. For this we will create a package net.viralpatel.struts2 in the source folder. This package will contain the action file.
    struts2-source-package
    Create a class called LoginAction in net.viralpatel.struts2 package with following content.
    package net.viralpatel.struts2;
    public class LoginAction {
        private String username;
        private String password;
        public String execute() {
            if (this.username.equals("admin")
                    && this.password.equals("admin123")) {
                return "success";
            } else {
                return "error";
            }
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
    }
    Note that, above action class contains two fields, username and password which will hold the values from form and also contains an execute() method that will authenticate the user. In this simple example, we are checking if username is admin and password is admin123.
    Also note that unlike Action class in Struts1, Struts2 action class is a simple POJO class with required attributes and method.
    The execute() method returns a String value which will determine the result page. Also, in Struts2 the name of the method is not fixed. In this example we have define method execute(). You may want to define a method authenticate() instead.

    The ResourceBundle

    ResourceBundle is very useful Java entity that helps in putting the static content away from the source file. Most of the application define a resource bundle file such as ApplicationResources.properties file which contains static messages such as Username or Password and include this with the application.
    ResourceBundle comes handy when we want to add Internationalization (I18N) support to an application.
    We will define an ApplicationResources.properties file for our application. This property file should be present in WEB-INF/classes folders when the source is compiled. Thus we will create a source folder called resources and put the ApplicationResources.properties file in it.
    To create a source folder, right click on your project in Project Explorer and select New -> Source Folder.
    struts2-resource-folder
    Specify folder name resources and press Finish.
    Create a file ApplicationResources.properties under resources folder.
    struts-2-application-resources-properties
    Copy following content in ApplicationResources.properties.
    label.username= Username
    label.password= Password
    label.login= Login

    The JSP

    We will create two JSP files to render the output to user. Login.jsp will be the starting point of our application which will contain a simple login form with username and password. On successful authentication, user will be redirected to Welcome.jsp which will display a simple welcome message.
    Create two JSP files Login.jsp and Welcome.jsp in WebContent folder of your project. Copy following content into it.

    Login.jsp

    <%@ page contentType="text/html; charset=UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags"%>
    <html>
    <head>
    <title>Struts 2 - Login Application | ViralPatel.net</title>
    </head>
    <body>
    <h2>Struts 2 - Login Application</h2>
    <s:actionerror />
    <s:form action="login.action" method="post">
        <s:textfield name="username" key="label.username" size="20" />
        <s:password name="password" key="label.password" size="20" />
        <s:submit method="execute" key="label.login" align="center" />
    </s:form>
    </body>
    </html>

    Welcome.jsp

    <%@ page contentType="text/html; charset=UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags"%>
    <html>
    <head>
    <title>Welcome</title>
    </head>
    <body>
        <h2>Howdy, <s:property value="username" />...!</h2>
    </body>
    </html>
    Note that we have used struts2 <s:> tag to render the textboxes and labels. Struts2 comes with a powerful built-in tag library to render UI elements more efficiently.

    The struts.xml file

    Struts2 reads the configuration and class definition from an xml file called struts.xml. This file is loaded from the classpath of the project. We will define struts.xml file in the resources folder. Create file struts.xml in resources folder.
    struts2-struts-xml
    Copy following content into struts.xml.
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
    <struts>
        <constant name="struts.enable.DynamicMethodInvocation"
            value="false" />
        <constant name="struts.devMode" value="false" />
        <constant name="struts.custom.i18n.resources"
            value="ApplicationResources" />
        <package name="default" extends="struts-default" namespace="/">
            <action name="login"
                class="net.viralpatel.struts2.LoginAction">
                <result name="success">Welcome.jsp</result>
                <result name="error">Login.jsp</result>
            </action>
        </package>
    </struts>
    Note that in above configuration file, we have defined Login action of our application. Two result paths are mapped with LoginAction depending on the outcome of execute() method. If execute() method returns success, user will be redirected to Welcome.jsp else to Login.jsp.
    Also note that a constant is specified with name struts.custom.i18n.resources. This constant specify the resource bundle file that we created in above steps. We just have to specify name of resource bundle file without extension (ApplicationResources without .properties).
    Our LoginAction contains the method execute() which is the default method getting called by Sturts2. If the name of method is different, e.g. authenticate(); then we should specify the method name in <action> tag.
    <action name="login" method="authenticate"
        class="net.viralpatel.struts2.LoginAction">

    Almost Done

    We are almost done with the application. You may want to run the application now and see the result yourself. I assume you have already configured Tomcat in eclipse. All you need to do:
    Open Server view from Windows -> Show View -> Server. Right click in this view and select New -> Server and add your server details.
    To run the project, right click on Project name from Project Explorer and select Run as -> Run on Server (Shortcut: Alt+Shift+X, R)
    But there is one small problem. Our application runs perfectly fine at this point. But when user enters wrong credential, she is redirected to Login page. But no error message is displayed. User does not know what just happened. A good application always show proper error messages to user. So we must display an error message Invalid Username/Password. Please try again when user authentication is failed.

    Final Touch

    To add this functionality first we will add the error message in our ResourceBundle file.
    Open ApplicationResources.properties and add an entry for error.login in it. The final ApplicationResources.properties will look like:
    label.username= Username
    label.password= Password
    label.login= Login
    error.login= Invalid Username/Password. Please try again.
    Also we need to add logic in LoginAction to add error message if user is not authenticated. But there is one problem. Our error message is specified in ApplicationResources.properties file. We must specify key error.login in LoginAction and the message should be displayed on JSP page.
    For this we must implement com.opensymphony.xwork2.TextProvider interface which provides method getText(). This method returns String value from resource bundle file. We just have to pass the key value as argument to getText() method. The TextProvider interface defines several method that we must implement in order to get hold on getText() method. But we don’t want to spoil our code by adding all those methods which we do not intend to use. There is a good way of dealing with this problem.
    Struts2 comes with a very useful class com.opensymphony.xwork2.ActionSupport. We just have to extend our LoginAction class with this class and directly use methods such as getText(), addActionErrors() etc. Thus we will extend the LoginAction class with ActionSupport class and add the logic for error reporting into it. The final code in LoginAction must look like:
    package net.viralpatel.struts2;
    import com.opensymphony.xwork2.ActionSupport;
    public class LoginAction extends ActionSupport {
        private String username;
        private String password;
        public String execute() {
            if (this.username.equals("admin")
                    && this.password.equals("admin123")) {
                return "success";
            } else {
                addActionError(getText("error.login"));
                return "error";
            }
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
    }
    And that’s it. Our first Hello World Struts2 Application is now ready.

    That’s All Folks

    Execute the application in Eclipse and run it in your favorite browser.
    Login page
    struts2-application-login-page
    Welcome page
    struts2-welcome-page
    Login page with error
    struts2-login-page-error

    Source of Article