struts2 download file
Here’s a scenario:
1. User select a directory, and you show him all the files in that directory as ‘downloadable’
2. User select a file to download and gets it.
First, you need to write a Action class, that sends back a list of files in that directory.
public class MyAction extends ActionSupport{ private List FilesList; public List getFilesList() { return FilesList; } public void setFilesList(List FilesList) { this.FilesList = FilesList; } public String files() throws Exception { String dirPath = (String) getGlobal(Constants.DIRPATH); File dir = new File(dirPath); ArrayList filesList = new ArrayList(); String[] children = dir.list(); if (children == null) { // Either dir does not exist or is not a directory } else { for (int i = 0; i < children.length; i++) { // Get filename of file or directory String filename = children[i]; File file = new File(dirPath + File.separator + filename); Files files= new Files(); files.setFileSize(readableFileSize(file.length())); files.setFileName(filename); filesList.add(files); } } setFilesList(filesList); return Constants.SUCCESS; } }
Your JSP needs to have this listing:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <s:if test="%{filesList!=null && filesList.size > 0}"> <table border=0 cellspacing=1 cellpadding=1 width=60% align=center class=tablebody> <s:iterator value="filesList" status="rownum"> <tr height=25> <td align=left style='font-family: verdana; font-size: 11pt' nowrap> <s:url id="fileDownload" action="download"> <s:param name="downloadFileName" value="{fileName}" /> </s:url> <s:a href="%{fileDownload}"><s:property value="fileName" /></s:a> <span style="font-family: verdana; font-size: 9pt"><s:property value="fileSize" /></span> </td> </tr> </s:iterator> </table> </s:if> <s:else test="%{filesList!=null && filesList.size == 0}"> No files found </s:else>
Couple of interesting things in the struts tags above:
<s:url id="fileDownload" action="download"> <s:param name="downloadFileName" value="{fileName}" /> </s:url> <s:a href="%{fileDownload}"><s:property value="fileName" /></s:a>
This specifying a URL with the parameter as the selected filename. If you want to see the filename being apprended to the URL,You can specify includeParams="get"
to s:url.
Now, lets map the ‘download’ action in 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.devMode" value="true" /> <package name="basicstruts2" extends="struts-default"> <interceptors> <interceptor-stack name="appDefaultStack"> <interceptor-ref name="defaultStack"> <param name="exception.logEnabled">true</param> <param name="exception.logLevel">ERROR</param> </interceptor-ref> </interceptor-stack> </interceptors> <default-interceptor-ref name="appDefaultStack" /> <default-action-ref name="input" /> <global-results> <result name="error">/error.jsp</result> </global-results> <global-exception-mappings> <exception-mapping exception="java.lang.Exception" result="error" /> </global-exception-mappings> <action name="input" class="com......" method="prepare"> <result name="success">/....jsp</result> </action> <action name="*Filter" class="com......" method="{1}"> <result name="success">/.....jsp</result> <result name="error">/error.jsp</result> <result name="input">/mdt_viewer.jsp</result> </action> <action name="download" class="com.action.DownloadAction" method="download"> <result name="success" type="stream"> <param name="contentType">application/zip</param> <param name="inputName">fileInputStream</param> <!--param name="contentDisposition">attachment;filename="fileABC.txt"</param --> <param name="bufferSize">1024</param> </result> </action> </package> </struts>
Lets check out the DownloadAction class,
public class DownloadAction extends ActionSupport{ private InputStream fileInputStream; private String downloadFileName; /** * Will override the default in struts.xml. * * @return */ public String getContentDisposition() { return "attachment;filename=" + getDownloadFileName(); } public InputStream getFileInputStream() { return fileInputStream; } public void setFileInputStream(InputStream fileInputStream) { this.fileInputStream = fileInputStream; } public String getDownloadFileName() { return downloadFileName; } public void setDownloadFileName(String downloadFileName) { this.downloadFileName = downloadFileName; } public String download() throws Exception { log.debug("Fetching for download:" + getDownloadFileName()); String filesPath = (String) getGlobal(Constants.DIR_PATH); try { String file = filesPath + File.separator + getDownloadFileName(); setFileInputStream(new FileInputStream(file)); return Constants.SUCCESS; } catch (Exception e) { log.error(e); throw e; } } }
Thats about it! Happy downloading.
Quick copy/paste for Java connecting to Oracle
package com.xerox.remsvcs.utils; import java.sql.Array; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Types; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import oracle.jdbc.driver.OracleCallableStatement; import oracle.jdbc.driver.OracleTypes; import oracle.sql.ARRAY; public class Connecttooracle { private static Connection getConn() { Connection connection = null; try { // Load the JDBC driver String driverName = "oracle.jdbc.OracleDriver"; Class.forName(driverName); // Create a connection to the database String serverName = "127.0.0.1"; String portNumber = "1521"; String sid = "mydatabase"; String url = "jdbc:oracle:thin:@<IP>:1521:<DB>"; String username = ""; String password = "1234"; connection = DriverManager.getConnection(url, username, password); } catch (Exception e) { e.printStackTrace(); } return connection; } public static void mai(String[] args) { String sql = ""; Connection connection = getConn(); PreparedStatement cstmt = null; ResultSet rs = null; List<String> serialNoList = new ArrayList<String>(); long start = System.currentTimeMillis(); try { cstmt = connection.prepareCall(sql); rs = cstmt.executeQuery(); System.out.println("execute=" + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); while (rs.next()) { } System.out.println("snolist=" + (System.currentTimeMillis() - start)); System.out.println(serialNoList); System.out.println(serialNoList.size()); } catch (Exception e) { e.printStackTrace(); } finally { closeConnections(connection, cstmt, null); } } public static void main(String[] args) { String sql = "{call ABC.XX_lib.GetName(?,?,?,?)}"; Connection connection = getConn(); CallableStatement cstmt = null; ResultSet rs = null; List<String> serialNoList = new ArrayList<String>(); long start = System.currentTimeMillis(); try { cstmt = (CallableStatement) connection.prepareCall(sql); cstmt.setString(1, "121332"); cstmt.setString(2, "2232222"); cstmt.setString(3, "www"); cstmt.registerOutParameter(4, OracleTypes.CURSOR); cstmt.execute(); System.out.println("execute=" + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); rs = (ResultSet) cstmt.getObject(4); while (rs.next()) { serialNoList.add((String) (rs.getString("timestamp"))); } System.out.println("snolist=" + (System.currentTimeMillis() - start) + "," + serialNoList.size()); System.out.println(serialNoList); } catch (Exception e) { e.printStackTrace(); } finally { closeConnections(connection, cstmt, null); } } public static void closeConnections(Connection conn, Statement stmt, ResultSet rs) { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (Exception e) { e.printStackTrace(); } } }
Ant script to create a WAR file
<?xml version="1.0"?> <project name="MyWebPortal" default="deploy" basedir="."> <description> MyWeb Portal </description> <property name="src.dir" value="src/main/java" /> <property name="test.dir" value="src/test/java" /> <property name="lib.dir" value="src/main/lib" /> <property name="resources.dir" value="src/main/resources" /> <property name="build.dir" value="build" /> <property name="dist.dir" value="dist" /> <property name="webapps.dir" value="src/main/webapps" /> <property name="app.name" value="MyWebPortal" /> <property name="deploy.dir" value="\\jboss-5.1.0.GA\\server\\default\\deploy" /> <target name="clean" description="Delete old build and dist directories"> <delete dir="${dist.dir}" /> <delete dir="${build.dir}" /> </target> <target name="init" depends="clean" description="Create build directory"> <mkdir dir="${build.dir}" /> <mkdir dir="${dist.dir}" /> </target> <target name="compile" depends="init" description="Compile Java sources"> <mkdir dir="${build.dir}/WEB-INF/classes" /> <echo message="Using Java version ${ant.java.version}."/> <javac srcdir="${src.dir}" destdir="${build.dir}/WEB-INF/classes" debug="true" source="1.6" target="1.6"> <classpath> <path> <fileset dir="${lib.dir}" /> </path> </classpath> </javac> </target> <target name="build" depends="compile" description="Copies all non Java classes to build directoy"> <copy todir="${build.dir}/WEB-INF/classes"> <fileset dir="${resources.dir}" includes="struts.xml,struts.properties" /> </copy> <copy todir="${build.dir}"> <fileset dir="${resources.dir}" excludes="struts.xml,log4j.*,*-ds.xml" /> </copy> <copy todir="${build.dir}/WEB-INF/lib"> <fileset dir="${lib.dir}" excludes="jboss-common-jdbc-wrapper.jar,ojdbc*.jar"/> </copy> <copy todir="${build.dir}/WEB-INF"> <fileset dir="${webapps.dir}/WEB-INF" excludes="SVN,**/*.class" /> </copy> <copy todir="${build.dir}/META-INF"> <fileset dir="${webapps.dir}/META-INF" /> </copy> <copy todir="${build.dir}"> <fileset dir="${webapps.dir}" includes="**/*.jsp,**/*.htm" /> </copy> </target> <target name="archive" depends="build" description="Create binary archive of all files in dist.home"> <!-- Create application WAR file --> <jar jarfile="${dist.dir}/${app.name}.war" basedir="${build.dir}" /> </target> <target name="deploy" depends="archive"> <copy todir="${deploy.dir}"> <fileset dir="${dist.dir}" includes="${app.name}.war" /> </copy> </target> </project>
Java calling PL/SQL proc returning a TYPE
Take this piece of code:
Connection connection = getConn(); CallableStatement cstmt = null; List serialList = new ArrayList(); try { cstmt = (CallableStatement) connection.prepareCall(sql); cstmt.registerOutParameter(1, Types.ARRAY, "tblXYZNum".toUpperCase()); cstmt.execute(); Array arr = cstmt.getArray(1); String[] serialNumbers = (String[])arr.getArray(); System.out.println(serialNumbers); System.out.println(serialNoList);
Few things that need notice:
1. The TYPE name has to be in upper case.
2. The TYPE shouldnt be declared inside a PL/SQL package. It should have been created as ‘CREATE TYPE’. Java does not have access to TYPE’s inside a package. You will get an invalid name pattern error if you refer a TYPE inside a package.
Kill multiple unix processes
ps -ef | grep <process_name> | cut -d' ' -f3 | awk '{x=x" "$1} END {print x}'
Kill multiple oracle sessions
SELECT 'alter system kill session '''||sess.SID||','|| sess.serial# ||''';' FROM v$session sess, v$sql SQL WHERE sql.sql_id(+) = sess.sql_id AND sess.type = 'USER' AND sql.sql_text like 'XYZ%';
I didnt find any other way. Executing the above SQL, will give a bunch of Alter statements.