/**
* This is an utility method to get value of private instance variable of a class.
*
* @param classInstance
* @param fieldName
* @return
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static Object getPrivateInstanceFieldValue(Object classInstance, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field field = classInstance.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(classInstance);
}
/**
* This is an utility method to invoke/execute private instance method of a class.
*
* Note: Make sure you pass the correct method arguments in order to invoke the correct method.
*
* @param classInstance
* @param methodName = name of the private instance method of the class whose instance is passed
* @param methodArguments = arguments of the private instance method whose name is passed
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static Object invokePrivateInstanceMethod(Object classInstance, String methodName, Object... methodArguments) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Method[] classMethods = classInstance.getClass().getDeclaredMethods();
for (Method method : classMethods) {
if(method.getName().equals(methodName) && method.getParameterTypes().length == methodArguments.length) {
method.setAccessible(true);
return method.invoke(classInstance, methodArguments);
}
}
Assert.fail ("Method - '" + methodName +"' with passed parameters not found in class - " + classInstance.getClass().getCanonicalName());
return null;
}
This is a place where you can find some hard searched, some regularly used, some fundoo - innovative, and some my own RnD utility stuff.
Visitor's questions, suggestions, comments are welcome.
Friday, July 13, 2012
Utility methods for calling private instance methods and variables
Monday, November 28, 2011
Send Mail with Attachments
[1] Mail.java
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
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;
/**
* @author Paresh
*
* Mail class is an email sending utility class.
*
*/
public class Mail {
private static Logger logger = Logger.getLogger(Mail.class.getName());
private Session session = null;
private String SMTP_SERVER = null;
private int SMTP_PORT = 25; // or 587 if your ISP blocks port 25
private String FROM_ADDRESS = null;
private String USER_NAME = null;
private String USER_PASS = null;
private String SMTP_AUTH = null;
private boolean startTLS = false;
public Mail() throws Exception {
Properties p = new Properties();
try {
p.load(new FileInputStream("mail.properties"));
this.SMTP_SERVER = p.getProperty("smtp.host");
this.SMTP_PORT = Integer.parseInt(p.getProperty("smtp.port"));
this.FROM_ADDRESS = p.getProperty("from.address");
this.USER_NAME = p.getProperty("smtp.user");
this.USER_PASS = p.getProperty("smtp.pass");
this.SMTP_AUTH = p.getProperty("smtp.auth");
String startTLS = p.getProperty("smtp.starttls");
if(startTLS != null) {
// Set mail.smtp.starttls.enable = true for gmail
this.startTLS = Boolean.valueOf(startTLS);
}
} catch (Exception e) {
// e.printStackTrace();
logger.error(e.getMessage(), e);
throw e;
}
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", SMTP_SERVER);
props.setProperty("mail.smtp.port", String.valueOf(SMTP_PORT));
props.setProperty("mail.smtp.auth", SMTP_AUTH);
if(this.startTLS)
props.put("mail.smtp.starttls.enable","true");
session = Session.getInstance(props, null);
}
/**
*
* @param emailToList - Compulsory - Minimum 1 recipient is required
* @param emailCcList - Pass null when there is no cc recipient
* @param emailBccList - Pass null when there is no bcc recipient
* @param subject
* @param body
* @param attachmentList - Pass null when there is no attachment
*/
public boolean send(List
Transport trans = null;
try {
if (SMTP_SERVER == null) {
throw new Exception("smtp server not provided.");
}
if(logger.isDebugEnabled())
logger.debug("Sending Email...");
// System.out.println("Email sending...");
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(FROM_ADDRESS));
msg.setSubject(subject);
msg.setSentDate(new Date());
if(emailToList == null || emailToList.isEmpty()) {
throw new Exception("emailToList is empty. Minimum 1 recipient is required...");
}
for (String emailTo : emailToList) {
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo, true));
}
if(emailCcList != null) {
for (String emailCc : emailCcList) {
msg.addRecipient(Message.RecipientType.CC, new InternetAddress(emailCc, true));
}
}
if(emailBccList != null) {
for (String emailBcc : emailBccList) {
msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(emailBcc, true));
}
}
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setText(body);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyPart);
if(logger.isDebugEnabled())
logger.debug("Attachment File Names:");
if(attachmentPathList != null) {
for (String attachment : attachmentPathList) {
bodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachment);
bodyPart.setDataHandler(new DataHandler(source));
String fileName = attachment.substring(attachment.lastIndexOf("\\") + 1);
if(logger.isDebugEnabled())
logger.debug(fileName);
bodyPart.setFileName(fileName);
multipart.addBodyPart(bodyPart);
}
}
msg.setContent(multipart);
trans = session.getTransport("smtp");
trans.connect(SMTP_SERVER, SMTP_PORT, USER_NAME, USER_PASS);
trans.sendMessage(msg, msg.getAllRecipients());
if(logger.isDebugEnabled())
logger.debug("Email sent successfully...");
// System.out.println("Email sent successfully...");
return true;
} catch (Exception ex) {
// ex.printStackTrace();
logger.error("Email sending failed.", ex);
} finally {
try {
if(trans != null) {
trans.close();
trans = null;
}
} catch(Exception e) {
// ignore
}
}
return false;
}
}
**activation package is now part of Java.
Sunday, November 27, 2011
Note:
With above values of properties file, program will execute keys repetitively after every 4 min for total 20 min. keys are "ALT+TAB" followed by "ALT+SHIFT+TAB".
Wednesday, September 14, 2011
JUnit Testcase for private method and variable
// ClassA.java
public class ClassA {
private int privateInteger = -1;
private String privateString;
private void methodA(String s, int a, int b) {
this.privateString = s;
this.privateInteger = a * b;
}
}
//ClassATest.java
@org.junit.Test
public void testMethodA() {
ClassA classA = new ClassA();
java.lang.reflect.Method methodA;
try {
methodA = ClassA.class.getDeclaredMethod("methodA", String.class, int.class, int.class);
java.lang.reflect.Field privateIntField = ClassA.class.getDeclaredField("privateInteger");
methodA.setAccessible(true);
privateIntField.setAccessible(true);
methodA.invoke(classA, "Hi", 2, 3);
org.junit.Assert.assertEquals(6, privateIntField.getInt(classA));
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (java.lang.reflect.InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Sunday, September 04, 2011
Eclipse Custom Templates
For that, eclipse provides inbuilt templates for writing for loops, iterator loops, main method, try/catch blocks, and many more which saves hail lot of time.
Not only that but eclipse also provides a facility to write our own customized templates.
So here I am adding my custom templates.. I will keep on adding here as whenever I find repetitive code and also get chance to write new ones.
Starting with DAO Insert method:
public int insert(${DTO} dto) throws java.sql.SQLException {
java.sql.Connection con = null;
java.sql.PreparedStatement ps = null;
String sql = "insert into ${table}(${col1},${col2}) values (?,?)";
try {
con = DBManager.getConnection();
ps = con.prepareStatement(sql);
ps.set${Type1}(1, dto.get${col1Value});
ps.set${Type2}(2, dto.get${col2Value});
return ps.executeUpdate();
} catch (java.sql.SQLException e) {
StringBuilder sb = new StringBuilder(${100});
sb = sb.append("${enclosing_type}.insert()").append(" :: ");
sb = sb.append("Database insertion failed.").append(System.getProperty("line.separator"));
sb = sb.append(" Table = ${table}").append(" :: ");
sb = sb.append(" ${col1} = ").append(dto.get${col1Value});
sb = sb.append(",").append(" ${col2} = ").append(dto.get${col2Value});
logger.error(sb.toString());
throw e;
} finally {
try {
if(ps != null) {
ps.close();
ps = null;
}
if(con != null) {
con.close();
}
} catch(java.sql.SQLException e) {
// ignore
}
}
}
Connection Pooling - Apache DBCP
Properties File: db.properties
#PostgreSQL Database - http://jdbc.postgresql.org/download.html
#db.connection.driver = org.postgresql..Driver
#db.connection.url = jdbc:postgresql://localhost:5432/[database]
db.connection.username = [username]
db.connection.password = [password]
db.connection.defaultpool = dbpool
db.connection.max.active = 5
db.connection.max.idle = 5
db.connection.max.wait = 10000
class: DBManager.java
package com.pd.db;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDriver;
import org.apache.commons.pool.impl.GenericObjectPool;
/**
* @author PD
*
*/
public class DBManager {
private static ConnectionFactory connectionFactory = null;
private static int DEFAULT_MAX_ACTIVE = 30;
private static int DEFAULT_MAX_IDLE = 30;
private static int DEFAULT_MAX_WAIT = 10000;
private static Properties props = null;
public static void load(Properties props) throws Exception {
DBManager.props = props;
//
// Load JDBC Driver class.
//
String driverName = getProperty("db.connection.driver");
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new Exception(
"Could not find suitable classes to load driver "
+ driverName, e);
}
//
// First, we'll need a ObjectPool that serves as the
// actual pool of connections.
//
// We'll use a GenericObjectPool instance, although
// any ObjectPool implementation will suffice.
//
GenericObjectPool connectionPool = new GenericObjectPool(null);
connectionPool.setMaxActive(Integer.parseInt(getProperty("db.connection.max.active", String.valueOf(DEFAULT_MAX_ACTIVE))));
connectionPool.setMaxIdle(Integer.parseInt(getProperty("db.connection.max.idle", String.valueOf(DEFAULT_MAX_IDLE))));
connectionPool.setMaxWait(Integer.parseInt(getProperty("db.connection.max.wait", String.valueOf(DEFAULT_MAX_WAIT))));
//
// Next, we'll create a ConnectionFactory that the
// pool will use to create Connections.
// We'll use the DriverManagerConnectionFactory,
// using the connect string passed in the command line
// arguments.
//
connectionFactory = new DriverManagerConnectionFactory(getProperty("db.connection.url"), getProperty("db.connection.username"), getProperty("db.connection.password"));
PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true);
//
// Finally, we create the PoolingDriver itself...
//
Class.forName("org.apache.commons.dbcp.PoolingDriver");
PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
driver.registerPool(getProperty("db.connection.defaultpool", "dbpool"), connectionPool);
fireTestQuery();
}
/**
* Call this to get the Connection objects in each DAO
*
* @return java.sql.Connection
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
Connection conn = null;
try {
if (connectionFactory != null) {
conn = connectionFactory.createConnection();
}
} catch (SQLException e) {
System.out.println("Connection already in use. Close connection and creat new Connection");
e.printStackTrace();
throw e;
}
return conn;
}
private static void fireTestQuery() throws Exception {
Connection conn = null;
PreparedStatement statement = null;
ResultSet results = null;
try {
conn = getConnection();
statement = conn.prepareStatement(getProperty("db.connection.query.test", "SELECT now()"));
results = statement.executeQuery();
if (!results.next())
throw new Exception("Not connected ...");
else {
System.out.println("TEST QUERY RESULTS No of rows :: "
+ results.getRow());
}
} catch (SQLException sqle) {
throw new Exception(
"Test Query failed during start up because of SQLException ",
sqle);
} finally {
try {
if (results != null) {
results.close();
results = null;
}
if (statement != null) {
statement.close();
statement = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException ignore) {
}
}
}
private static String getProperty(String key) throws Exception {
return getProperty(key, null);
}
private static String getProperty(String key, String defaultValue) throws Exception {
String str = props.getProperty(key);
if (str == null || str.trim().length() == 0) {
if(defaultValue != null) {
System.out.println("Using default value " + defaultValue + " due to missing entry - " + key);
return defaultValue;
} else {
System.err.println("DBManager :: Could not load driver :: Missing Entry - " + key);
throw new Exception("DBManager :: Could not load driver :: Missing Entry - " + key);
}
}
return str;
}
public static void main(String[] args) {
Properties props = new Properties();
try {
props.load(new FileInputStream("db.properties"));
load(props);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Thursday, June 09, 2011
Switch JAVA_HOME environment variable with just a double click
Why I decided to write a (VB)script ?
Recently I had to work in environment where I had to set JAVA_HOME environment variable very frequently and I really got bored by the lengthy steps we usually follow to set an environment variable like open file explorer then right click My Computer -> select Properties -> Advanced Tab -> Environment Varibles -> choose ur variable and edit it and then again copy required path. So I searched on internet a bit and by spending few hours I could mange to write a successful vb script to do what was required.
Surprisingly, writing a registry file did not work..
To save the search effort, I am writing this blog..
Steps / Procedure to write the script:
[1] Create two VB Script files as shown below.
| File Name: set_jdk6.vbs |
|---|
Set WSHShell = WScript.CreateObject("WScript.Shell") Set WshEnv = WshShell.Environment("USER") WshEnv("JAVA_HOME") = "C:\Program Files\Java\jdk1.6" |
| File Name: set_jdk5.vbs |
|---|
Set WSHShell = WScript.CreateObject("WScript.Shell") Set WshEnv = WshShell.Environment("USER") WshEnv("JAVA_HOME") = "C:\Program Files\Java\jdk1.5" |
[2] Now simply double click above files to switch JAVA_HOME environment variable on your windows machine.
That's it. Cheers...
Wednesday, June 01, 2011
Java Robot Example - Program to keep your computer away from Idle mode
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* This program will keep your computer alive i.e. it does not let computer go in Idle mode.
* Default wake up time = 1 min
*/
public class KeepAliveRobot{
private static boolean pause = true;
private static final int DEFAULT_SLEEP_TIME = 60000; // 60000 miliseconds = 1 min
public static void main(String[] args)
throws AWTException,IOException {
Robot robot = new Robot();
Properties p = new Properties();
int sleepTime = DEFAULT_SLEEP_TIME;
try {
p.load(new FileInputStream("live.properties"));
sleepTime = Integer.parseInt(p.getProperty("wakeup.time"));
} catch (Exception e) {
e.printStackTrace();
}
while (pause) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e1) {
break;
}
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_ALT);
}
}
}
Java program to test whether server is reachable ?
import java.net.InetAddress;
public class PingExample
{
public static void main(String[] args)
{
try
{
InetAddress address = InetAddress.getByName("127.0.0.1");
/**
* FROM JAVADOC
*
* Test whether that address is reachable. Best effort is made by the
* implementation to try to reach the host, but firewalls and server
* configuration may block requests resulting in a unreachable status
* while some specific ports may be accessible.
* A typical implementation will use ICMP ECHO REQUESTs if the
* privilege can be obtained, otherwise it will try to establish
* a TCP connection on port 7 (Echo) of the destination host.
* <p>
* The timeout value, in milliseconds, indicates the maximum amount of time
* the try should take. If the operation times out before getting an
* answer, the host is deemed unreachable. A negative value will result
* in an IllegalArgumentException being thrown.
*
* @param timeout the time, in milliseconds, before the call aborts
* @return a <code>boolean</code> indicating if the address is reachable.
* @throws IOException if a network error occurs
* @throws IllegalArgumentException if <code>timeout</code> is negative.
* @since 1.5
*/
boolean reachable = address.isReachable(10000);
System.out.println("Is host reachable? " + reachable);
} catch (Exception e)
{
e.printStackTrace();
}
}
}
Wednesday, December 29, 2010
ANT - sample build.xml & build.properties files for creating WAR
<project name="TestProject" default="war" basedir=".">
<property file="build.properties"/>
<property name="src.home" value="${basedir}/src"></property>
<property name="dist.home" value="${basedir}/dist"/>
<property name="web.home" value="${basedir}/WebRoot"></property>
<property name="build.home" value="${web.home}/WEB-INF/classes"/>
<property name="lib.home" value="${web.home}/WEB-INF/lib"/>
<property name="lib.ext.home" value="${basedir}/lib"/>
<path id="compile.classpath">
<fileset dir="${lib.home}">
<include name="*.jar"/>
</fileset>
<fileset dir="${lib.ext.home}">
<include name="*.jar"/>
</fileset>
</path>
<target name="init">
<mkdir dir="${dist.home}" />
</target>
<target name="compile" depends="init" >
<javac destdir="${build.home}" debug="true" srcdir="${src.home}">
<classpath refid="compile.classpath"/>
</javac>
<copy todir="${build.home}">
<fileset dir="${src.home}" includes="**/*.properties,**/*.xml"/>
</copy>
</target>
<target name="war" depends="compile">
<war destfile="${dist.home}/${app.name}.war" webxml="${web.home}/WEB-INF/web.xml">
<fileset dir="${web.home}"/>
</war>
</target>
<target name="clean">
<delete dir="${dist.home}" />
<delete includeemptydirs="true">
<fileset dir="${build.home}" includes="**/*"/>
</delete>
</target>
<target name="deploy2Tomcat">
<copy todir="${tomcat.webapps.dir}">
<fileset dir="${dist.home}" includes="${app.name}.war" />
</copy>
</target>
</project>
<copy todir="${build.home}">
<fileset dir="${src.home}" includes="**/*.properties,**/*.xml"/>
</copy>
</target>
<target name="war" depends="compile">
<war destfile="${dist.home}/${app.name}.war" webxml="${web.home}/WEB-INF/web.xml">
<fileset dir="${web.home}"/>
</war>
</target>
<target name="clean">
<delete dir="${dist.home}" />
<delete includeemptydirs="true">
<fileset dir="${build.home}" includes="**/*"/>
</delete>
</target>
<target name="deploy2Tomcat">
<copy todir="${tomcat.webapps.dir}">
<fileset dir="${dist.home}" includes="${app.name}.war" />
</copy>
</target>
</project>
build.properties
app.name=TestProject
catalina.home=D:/apache-tomcat-6.0.20
tomcat.webapps.dir=${catalina.home}/webapps
Tuesday, September 07, 2010
Macintosh - Run jar files by double clicking
This page assumes you want to run a .jar file directly, on your Macintosh, without splitting it up in any way.
First you have to have the "MRJ", the Macintosh Java Runtime. Then you have to find "JBindery".
In the Command Menu, where it says Class, you enter the name of the main program. For example, "jdrill", "CFclient", or some other classname.
Then pull down the 'ClassPath' submenu, click on 'Add .zip file', and select the .jar file you want. Then click "Run".
You can create an application by selecting the 'FILE' menu, then 'Save As...'. Once you've done that, you can double click on the icon to execute the java crossfire client.
Saturday, July 31, 2010
Command Prompt option on Right Click Menu
How to add command prompt option to right click ?
Most of us often need to open the command prompt which opens at User's Home directory and we had to change the path manually every time we open the command prompt.
For making this much easier, I am providing here a simple way which you will be glad to use instead of irritating/time consuming way.
With below steps, you can open the command prompt and find yourself at the location you want to reach with just a single click of mouse.
[1] Create a new file and save it with any name but with the extension ".reg" i.e. registry file extension.
filename ezample:= abc.reg
[2] Now copy paste below code inside that file and again save it.
Windows Registry Editor Version 5.00
@="Command Prompt"
[HKEY_CLASSES_ROOT\Directory\shell\Command\Command]
@="cmd.exe /k cd %1"
[3] Execute this file by simply double-clicking over it.
[4] Command Prompt option is added whenever you do a right-click on a folder.
This is one time procedure.
[5] Now onwards whenever you want to open the command prompt and reach out to a particular location, you can just browse through windows file explorer and right click on that particular folder and select command prompt option.
Friday, July 30, 2010
Eclipse - Debug Web Application running on Tomcat/JBoss
How to debug a web application, running on Tomcat/JBoss server, in Eclipse ?
Here are the simple steps to follow:
Tomcat
set JPDA_ADDRESS=8000
set JPDA_TRANSPORT=dt_socket
catalina.bat jpda start
[2] Start eclipse -> Run menu -> debug configuration -> Remote Java Application -> New launch configuration -> Make sure port is 8000 in connection properties.
[1] Edit the run.bat file of JBoss to use the following debug options (note the suspend=n option, this tells the server not to wait till the debugger attaches itself to the server
set JAVA_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n %JAVA_OPTS%
2) Start the server from the command line, using the run.bat file.
3) Once the server has completely started, i go to my (plain) Eclipse project and create a new "Remote Java Application" debug session (if it's not already created). In the "Port" text box i specify 8787 (the same as what i have in the run.bat). Then click on Debug.
The steps will be the same for NetBeans too (expect for the part where you have to configure NetBeans to listen to the debug port).
Sunday, October 29, 2006
File Upload - JSP
[1] Add a form tag in your jsp file as shown below:
<input type="file" name="theFile"></form>
[2] Add snippet code as below in the jsp file mentioned for the attribute action of form tag above i.e. upload.jsp:
<%
String contentType = request.getContentType();
if ((contentType != null) && (contentType.indexOf ("multipart/form-data") >= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < byteread =" in.read(dataBytes," file =" new">
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
String savePath = request.getRealPath ("documents");
saveFile = savePath + "/" + saveFile;
FileOutputStream fileOut = new FileOutputStream(saveFile);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
out.println("File saved as " +saveFile);
}
%>