Struts 2 Hello-World Example


index.jsp
---------
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Hello World</title>
    </head>
    <body>
        <s:form action="test" >
            <s:textfield name="userName" label="User Name" />
            <s:submit />
        </s:form>
    </body>
</html>


success.jsp
------------

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Hello World</title>
    </head>
    <body>
        <h1><s:property value="msg" /></h1>
    </body>
</html>

struts.xml
-----------

<struts>
 <package extends="struts-default" name="default">
        <action class="com.anil.HelloWorld" name="test">
            <result name="SUCCESS">/success.jsp</result>
        </action>
    </package>
</struts>   

web.xml
----------

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <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>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>



HelloWorld.java
----------------

package com.anil;

public class HelloWorld {

    private String msg;
    private String userName;

    public HelloWorld() {}

    public String execute() {
        setMsg("Hello -" + getUserName());
        return "SUCCESS";
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

}


jar files required
------------------------------
struts2-core-2.1.8.jar
xwork-2.1.3.jar
ognl-2.6.11.jar
freemarker-2.3.8.jar
commons-logging-1.0.4.jar
commons-fileupload-1.2.1.jar





Sending Email in java


jar files required to execute this file : mail.jar,activation.jar,log4j .jar


import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;

public class EmailClient {
       private static Logger logger = Logger.getLogger(EmailClient.class);

       public static boolean sendEmail(String fromAddress, String[] toAddress,
                       String[] ccAddress, String[] bccAddress, String subject,
                       String message, String htmlMessage, String outgoingHost) {
               MimeMultipart mimemultipart = null;
               InternetAddress toaddress[] = new InternetAddress[toAddress.length];
               InternetAddress ccaddress[] = null;
               if (ccAddress != null && ccAddress.length > 0) {
                       ccaddress = new InternetAddress[ccAddress.length];
               }
               InternetAddress bccaddress[] = null;
               if (bccAddress != null && bccAddress.length > 0) {
                       bccaddress = new InternetAddress[bccAddress.length];
               }

               java.util.Properties properties = System.getProperties();
// outgoingHost-is ur smtp host ip
               properties.put("mail.smtp.host", outgoingHost);
               Session session = Session.getDefaultInstance(properties, null);
               session.setDebug(false);
               try {
                       if (message != null && htmlMessage != null)
                               mimemultipart = new MimeMultipart("alternative");
                       else
                               mimemultipart = new MimeMultipart();
                       logger.info("Forming MimeMessage");
                       MimeMessage mimemessage = new MimeMessage(session);
                       mimemessage.setFrom(new InternetAddress(fromAddress));
                       for (int i = 0; i < toAddress.length; i++) {
                               toaddress[i] = new InternetAddress(toAddress[i]);
                       }
                       mimemessage.setRecipients(RecipientType.TO, toaddress);
                       logger.info("Set the to address");
                       if (ccAddress != null && ccAddress.length > 0) {
                               for (int i = 0; i < ccAddress.length; i++) {
                                       ccaddress[i] = new InternetAddress(ccAddress[i]);
                               }
                               mimemessage.setRecipients(RecipientType.CC, ccaddress);
                               logger.info("Set the cc address");
                       }
                       if (bccAddress != null && bccAddress.length > 0) {
                               for (int i = 0; i < bccAddress.length; i++) {
                                       bccaddress[i] = new InternetAddress(bccAddress[i]);
                               }
                               mimemessage.setRecipients(RecipientType.BCC, bccaddress);
                               logger.info("Set the bcc address");
                       }
                       mimemessage.setSubject(subject);
                       MimeBodyPart mimebodypart = new MimeBodyPart();
                       MimeBodyPart htmlmimebodypart = new MimeBodyPart();
                       if (message != null) {
                               mimebodypart.setText(message);
                               mimemultipart.addBodyPart(mimebodypart);
                       }
                       if (htmlMessage != null) {
                               htmlmimebodypart.setContent(htmlMessage, "text/html");
                               mimemultipart.addBodyPart(htmlmimebodypart);
                       }
                       logger.info("Set the subject and the message");
                       mimemessage.setContent(mimemultipart);
                       mimemessage.setSentDate(new java.util.Date());
                       logger.info("Set the content and the sent date");
                       Transport.send(mimemessage);
                       logger.info("Email sent");
               } catch (AddressException e) {
                       e.printStackTrace();
                       logger.error("AddressException " + e.toString());
                       return false;
               } catch (MessagingException e) {
                       e.printStackTrace();
                       logger.error("MessagingException " + e.getMessage());
                       return false;
               }
               return true;
       }
}

Folder/File Zipping in java

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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

               try {
                       BufferedInputStream bi = null;
                       FileOutputStream fileOutputStream = new FileOutputStream(
                                       "sample.zip");
                       ZipOutputStream outputStream = new ZipOutputStream(
fileOutputStream);
                       outputStream.setMethod(ZipOutputStream.DEFLATED);
                        byte data[]=new byte[2048];
                       File file = new File("C://anil");
                       File files[] = file.listFiles();

                       for (File f : files) {

                               System.out.println(f);

                               FileInputStream fileInputStream = new FileInputStream(f);

                               bi = new BufferedInputStream(fileInputStream,2048);

                               ZipEntry entry = new ZipEntry(f.getAbsolutePath());

                               outputStream.putNextEntry(entry);
                               int count;
                               while ((count =bi.read(data,0,2048))!= -1) {
                                       outputStream.write(2048);
                               }
                               bi.close();
                       }
                       outputStream.close();
                       System.out.println("zip created");
               } catch (Exception e) {
                       e.printStackTrace();
               }

       }
}

set Log4j file name at runtime in clustered environment

In a clustered environment if you use the same file name in all the clusters .you will get only one node logs and other nods logs goes missing.

for resolving the above issue change the logfile name from cluster to cluster.in my code i added the node name before the file name so that each cluster will have its own logs so that you wont miss any logs in cluster environment

in the blow class i extended DailyRollingFileAppender class and overriden the serFile Method where the file name changes for each cluster.

 and also you need to change your log4j.properties change the appender from "org.apache.log4j.DailyRollingFileAppender"      to CustomFileAppender

CustomFileAppender.java
--------------------------

import org.apache.log4j.DailyRollingFileAppender;

public class CustomFileAppender extends DailyRollingFileAppender {

       @Override
       public void setFile(String file) {
               String hostname = "";
               try {
                       InetAddress addr = InetAddress.getLocalHost();
                       hostname = addr.getHostName();
               } catch (Exception e) {
                       e.printStackTrace();
               }

               if (file.contains("//")) {
                       //System.out.println("File Name Before Changing : "+file);
                       file = file.replace("//", "//" + hostname + "-");
                       //System.out.println(" Chnaged File Name " + file);
               }
               super.setFile(file);
       }

}

ant Task to Copy specified files from Sub directories


The below class defines a custom ant task which is used to copy specified extension files from source sub directories to destination directory
package com.vz.ant.task;

import java.io.File;
import java.io.IOException;

import org.apache.tools.ant.BuildException;

public class CopyFromSubDir extends org.apache.tools.ant.Task {

 private String fromDir;
 private String toDir;
 private String fileExt;

 public void setFromDir(String fromDir) {
  this.fromDir = fromDir;
 }

 public void setToDir(String toDir) {
  this.toDir = toDir;
 }

 public void setFileExt(String fileExt) {
  this.fileExt = fileExt;
 }

 public void execute() throws BuildException {
  File srcDir = null;
  File destDir = null;

  if (fromDir != null && fromDir.trim() != "") {
   srcDir = new File(fromDir);
   if (!srcDir.isDirectory()) {
    System.err.print("fromDir is a File");
    throw new BuildException("fromDir is a File");
   }
  } else {
   System.err.print("fromDir attribute is not given");
   throw new BuildException("fromDir attribute is not given");
  }

  if (toDir != null && toDir.trim() != "") {
   destDir = new File(toDir);
   if (!destDir.exists()) {
    destDir.mkdirs();
   }
  } else {
   System.err.print("toDir attribute is not given");
   throw new BuildException("toDir attribute is not given");
  }

  if (!(fileExt != null && fileExt.trim() != "")) {
   System.err.print("fileExt attribute is not given");
   throw new BuildException("fileExt attribute is not given");
  }

  if (!srcDir.exists()) {
   throw new BuildException("from Directory doesnot exist");
  }

  File files[] = srcDir.listFiles();
  for (File f : files) {
   if (f.isDirectory()) {
    findExtensionFiles(f, fileExt);
   } else {

   }
  }
 }

 private boolean findExtensionFiles(File f, String exten) {

  for (File sf : f.listFiles()) {
   if (sf.getName().contains("." + exten.trim())) {
    try {
     System.out.println(sf.getAbsolutePath());
     System.out.println(toDir + "//" + sf.getName());
     FileCopy.copy(sf.getAbsolutePath(),
       toDir + "//" + sf.getName());
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  return false;
 }

 public static void main(String[] args) {
  CopyFromSubDir cd = new CopyFromSubDir();
  cd.setFromDir("C:\\Program Files\\Adobe\\Reader 10.0\\");
  cd.setToDir("c:\\anttest");
  cd.setFileExt("dll");
  cd.execute();
 }

}

package com.vz.ant.task;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileCopy {
 public static void main(String[] args) {
   if (args.length != 2)    // Check arguments
     System.err.println("Usage: java FileCopy  ");
   else {
     try { copy(args[0], args[1]); }
     catch (IOException e) { System.err.println(e.getMessage()); }
   }
 }

 public static void copy(String from_name, String to_name) throws IOException{
   File from_file = new File(from_name);  // Get File objects from Strings
   File to_file = new File(to_name);
   if (!from_file.exists())
     abort("FileCopy: no such source file: " + from_name);
   if (!from_file.isFile())
     abort("FileCopy: can't copy directory: " + from_name);
   if (!from_file.canRead())
     abort("FileCopy: source file is unreadable: " + from_name);

   if (to_file.isDirectory())
     to_file = new File(to_file, from_file.getName());

   if (to_file.exists()) {
     if (!to_file.canWrite())
       abort("FileCopy: destination file is unwriteable: " + to_name);
     System.out.print("Overwrite existing file " + to_name + "? (Y/N): ");
     System.out.flush();
     BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
     String response = in.readLine();
     if (!response.equals("Y") && !response.equals("y"))
       abort("FileCopy: existing file was not overwritten.");
   }
   else {
     String parent = to_file.getParent();  // Get the destination directory
     if (parent == null) parent = System.getProperty("user.dir"); // or CWD
     File dir = new File(parent);          // Convert it to a file.
     if (!dir.exists())
       abort("FileCopy: destination directory doesn't exist: " + parent);
     if (dir.isFile())
       abort("FileCopy: destination is not a directory: " + parent);
     if (!dir.canWrite())
       abort("FileCopy: destination directory is unwriteable: " + parent);
   }

   FileInputStream from = null;  // Stream to read from source
   FileOutputStream to = null;   // Stream to write to destination
   try {
     from = new FileInputStream(from_file);  // Create input stream
     to = new FileOutputStream(to_file);     // Create output stream
     byte[] buffer = new byte[4096];         // A buffer to hold file contents
     int bytes_read;                         // How many bytes in buffer
     while((bytes_read = from.read(buffer)) != -1) // Read bytes until EOF
       to.write(buffer, 0, bytes_read);            //   write bytes
   }
   finally {
     if (from != null) try { from.close(); } catch (IOException e) { ; }
     if (to != null) try { to.close(); } catch (IOException e) { ; }
   }
 }

 private static void abort(String msg) throws IOException {
   throw new IOException(msg);
 }
}

After creating a jar using above classes use the jar file in ur class path and add the below lines in ur build.xml 1.creating a type def
2. use the above typedef to copy jar files from subdirectories
<typedef name="copySubDirectoryFiles" class="com.vz.ant.task.CopyFromSubDir" 
  classpath="${path}"/>

<copySubDirectoryFiles  fromDir="${srcDir}" toDir="${destDir}"  fileExt="jar" />

File Copy In Java



package com.vz.ant.task;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileCopy {
 public static void main(String[] args) {
   if (args.length != 2)    // Check arguments
     System.err.println("Usage: java FileCopy  ");
   else {
     try { copy(args[0], args[1]); }
     catch (IOException e) { System.err.println(e.getMessage()); }
   }
 }

 public static void copy(String from_name, String to_name) throws IOException{
   File from_file = new File(from_name);  // Get File objects from Strings
   File to_file = new File(to_name);
   if (!from_file.exists())
     abort("FileCopy: no such source file: " + from_name);
   if (!from_file.isFile())
     abort("FileCopy: can't copy directory: " + from_name);
   if (!from_file.canRead())
     abort("FileCopy: source file is unreadable: " + from_name);

   if (to_file.isDirectory())
     to_file = new File(to_file, from_file.getName());

   if (to_file.exists()) {
     if (!to_file.canWrite())
       abort("FileCopy: destination file is unwriteable: " + to_name);
     System.out.print("Overwrite existing file " + to_name + "? (Y/N): ");
     System.out.flush();
     BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
     String response = in.readLine();
     if (!response.equals("Y") && !response.equals("y"))
       abort("FileCopy: existing file was not overwritten.");
   }
   else {
     String parent = to_file.getParent();  // Get the destination directory
     if (parent == null) parent = System.getProperty("user.dir"); // or CWD
     File dir = new File(parent);          // Convert it to a file.
     if (!dir.exists())
       abort("FileCopy: destination directory doesn't exist: " + parent);
     if (dir.isFile())
       abort("FileCopy: destination is not a directory: " + parent);
     if (!dir.canWrite())
       abort("FileCopy: destination directory is unwriteable: " + parent);
   }

   FileInputStream from = null;  // Stream to read from source
   FileOutputStream to = null;   // Stream to write to destination
   try {
     from = new FileInputStream(from_file);  // Create input stream
     to = new FileOutputStream(to_file);     // Create output stream
     byte[] buffer = new byte[4096];         // A buffer to hold file contents
     int bytes_read;                         // How many bytes in buffer
     while((bytes_read = from.read(buffer)) != -1) // Read bytes until EOF
       to.write(buffer, 0, bytes_read);            //   write bytes
   }
   finally {
     if (from != null) try { from.close(); } catch (IOException e) { ; }
     if (to != null) try { to.close(); } catch (IOException e) { ; }
   }
 }

 private static void abort(String msg) throws IOException {
   throw new IOException(msg);
 }
}

String to formatted XML conversion



import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class StringToXML {
 public static String strT0XML(String xmlString) {
  try {
   DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes());
   Document document = documentBuilder.parse(inputStream);
   TransformerFactory tfactory = TransformerFactory.newInstance();
   DOMSource xmlSource = new DOMSource(document);
   java.io.StringWriter writer = new StringWriter();
   javax.xml.transform.Result result = new javax.xml.transform.stream.StreamResult(writer);
   Transformer serializer = tfactory.newTransformer();
   serializer.setOutputProperty(OutputKeys.INDENT, "yes");
   serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
   serializer.transform(xmlSource, result);
   return writer.toString();
  } catch (TransformerException e) {
   e.printStackTrace();
   throw new RuntimeException(e);
  } catch (ParserConfigurationException e) {
   e.printStackTrace();
  } catch (SAXException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return "";
 }
}


AspectJ Example
------------------

TestAspect.java
----------------

package com.aspectj;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.JoinPoint;

@Aspect
public class TestAspect {

    @Before("execution (* com.aspectj.TestTarget.test*(..))")
    public void advice(JoinPoint joinPoint) {
        System.out.printf("TestAspect.advice() called on '%s'%n", joinPoint);
    }
}


TestTarget.java
-----------------

package com.aspectj;

public class TestTarget {

    public static void main(String[] args) {
        System.out.println("----------------------->--------- Start test -----------<---------------------");
        new TestTarget().test();
        System.out.println("----------------------->--------- End test -----------<---------------------");
    }

    public void test() {
        System.out.println("TestTarget.test()");
    }
}



aop.xml   - keep this file in META-INF 
----------------------------------------

<aspectj>
    <aspects>
        <aspect name="com.aspectj.TestAspect"/>
    </aspects>

    <weaver options="-verbose">
        <include within="com.aspectj.*"/>
    </weaver>
</aspectj>



build.xml
---------

<?xml version="1.0"?>
<project name="aspectj-example" xmlns:aspectj="antlib:org.aspectj">

    <property name="src.dir" value="src/main/java"/>
    <property name="resource.dir" value="src/main/resources"/>
    <property name="target.dir" value="target"/>
    <property name="classes.dir" value="${target.dir}/classes"/>

    <taskdef uri="antlib:org.aspectj"
            resource="org/aspectj/antlib.xml"
            classpath="${resource.dir}/aspectjtools.jar"/>

    <path id="aspectj.libs">
        <fileset dir="${resource.dir}"/>
    </path>

    <target name="clean">
        <delete dir="${target.dir}"/>
        <mkdir dir="${target.dir}"/>
        <mkdir dir="${classes.dir}"/>
    </target>

    <target name="compiletime" depends="clean">
        <aspectj:iajc source="1.5" srcdir="${src.dir}" classpathref="aspectj.libs" destDir="${classes.dir}"/>
        <java classname="com.aspectj.TestTarget" fork="true">
            <classpath>
                <path refid="aspectj.libs"/>
                <pathelement path="${classes.dir}"/>
            </classpath>
        </java>
    </target>

    <target name="postcompile" depends="clean">

        <echo message="Compiling..."/>
        <javac debug="true" srcdir="${src.dir}" classpathref="aspectj.libs" destdir="${classes.dir}"/>

        <echo message="Weaving..."/>
        <aspectj:iajc classpathref="aspectj.libs" inpath="${classes.dir}" aspectpath="${src.dir}" outJar="${classes.dir}/test.jar"/>

        <echo message="Running..."/>
        <java classname="com.aspectj.TestTarget" fork="true">
            <classpath>
                <path refid="aspectj.libs"/>
                <pathelement path="${classes.dir}/test.jar"/>
            </classpath>
        </java>

    </target>

    <target name="loadtime" depends="clean">

        <echo message="Compiling..."/>
        <javac debug="true" srcdir="${src.dir}" classpathref="aspectj.libs" destdir="${classes.dir}"/>

        <echo message="Running..."/>
        <java classname="com.aspectj.TestTarget" fork="true">
            <jvmarg value="-javaagent:${resource.dir}/aspectjweaver.jar"/>
            <classpath>
                <path refid="aspectj.libs"/>
                <pathelement path="${classes.dir}"/>
                <pathelement path="${resource.dir}"/>
            </classpath>
        </java>

    </target>

</project>



pom.xml
-----------

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test.aspectj</groupId>
    <artifactId>test</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>test</name>
    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.6.5</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>aspectj-maven-plugin</artifactId>
                <version>1.2</version>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.1</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>java</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <mainClass>com.aspectj.TestTarget</mainClass>
                </configuration>
            </plugin>
        </plugins>    </build>
</project>

and keep the below jar files under classpath and resource dir for build to run
aspectjrt.jar,aspectjtools.jar,aspectjweaver.jar

thanks
Anil.E