Friday, March 6, 2009

Multiple File Upload using JAVA Applet or Multiart Handler And Form Submission



NewUploader.java Main Class



package com.joshi.upload;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URLConnection;
import java.util.Properties;
/**
* @author Shirin Joshi
**/
public class NewUploader {

private String url;
Properties mimeTypesProperties;
public NewUploader(String url) {
this.url = url;
mimeTypesProperties = new Properties();
final String mimetypePropertiesFilename = "/conf/mimetypes.properties";
try {
/*
* mimeTypesProperties.load(getClass().getResourceAsStream(
* mimetypePropertiesFilename));
*/
mimeTypesProperties.load(Class.forName("com.joshi.upload.NewUploader").getResourceAsStream(
mimetypePropertiesFilename));

} catch (Exception e) {
}
}

public void publish(File[] allfiles) {
// URL url = new URL("http://www.domain.com/webems/upload.do");
// create a boundary string
try {
String boundary = MultiPartFormOutputStream.createBoundary();
URLConnection urlConn = MultiPartFormOutputStream
.createConnection(url);
urlConn.setRequestProperty("Accept", "*/*");
urlConn.setRequestProperty("Content-Type",
MultiPartFormOutputStream.getContentType(boundary));
// set some other request headers...
urlConn.setRequestProperty("Connection", "Keep-Alive");
urlConn.setRequestProperty("Cache-Control", "no-cache");

// no need to connect cuz getOutputStream() does it
MultiPartFormOutputStream out = new MultiPartFormOutputStream(
urlConn.getOutputStream(), boundary);

// write a text field element
out.writeField("myText", "text field text data..............");
// upload a file
//out.writeFile("myFile", "text/plain", new File("C:\\test.txt"));
for(File f : allfiles) {
// Let
String mimeType = mimeTypesProperties.getProperty(getExtension(f).toLowerCase());
if (mimeType == null) {
mimeType = "application/octet-stream";
}
System.out.println("mimeType :: " + mimeType);
out.writeFile(f.getName(), mimeType, f);
}
// can also write bytes directly
// out.writeFile("myFile", "text/plain", "C:\\test.txt",
// "This is some file text.".getBytes("ASCII"));
out.close();
// read response from server
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConn.getInputStream()));
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();

} catch (Exception e) {
System.out.println("Exception -----------");
e.printStackTrace();
}
}

public static String getExtension(File file) {
String name = file.getName();
return name.substring(name.lastIndexOf('.') + 1);
}

public static void main(String args[]) {
try {
File[] fileList = new File("c:\\tmp\\").listFiles();

// Your Server name and directory....
new NewUploader("http://127.0.0.1:8080/test/UploadServlet").publish(fileList);
} catch (Exception e) {
e.printStackTrace();
}

}
}




MultiPartFormOutputStream.java Required to generate Header for Form and Files



package com.joshi.upload;

import java.io.*;
import java.net.*;

/**
* @author Shirin Joshi
*
* http://forums.sun.com/thread.jspa?threadID=451245&forumID=31
*
* MultiPartFormOutputStream is used to write
* "multipart/form-data" to a java.net.URLConnection for
* POSTing. This is primarily for file uploading to HTTP servers.
*
**/
public class MultiPartFormOutputStream {
/**
* The line end characters.
*/
private static final String NEWLINE = "\r\n";

/**
* The boundary prefix.
*/
private static final String PREFIX = "--";

/**
* The output stream to write to.
*/
private DataOutputStream out = null;

/**
* The multipart boundary string.
*/
private String boundary = null;

/**
* Creates a new MultiPartFormOutputStream object using
* the specified output stream and boundary. The boundary is required
* to be created before using this method, as described in the
* description for the getContentType(String) method.
* The boundary is only checked for null or empty string,
* but it is recommended to be at least 6 characters. (Or use the
* static createBoundary() method to create one.)
*
* @param os the output stream
* @param boundary the boundary
* @see #createBoundary()
* @see #getContentType(String)
*/
public MultiPartFormOutputStream(OutputStream os, String boundary) {
if(os == null) {
throw new IllegalArgumentException("Output stream is required.");
}
if(boundary == null || boundary.length() == 0) {
throw new IllegalArgumentException("Boundary stream is required.");
}
this.out = new DataOutputStream(os);
this.boundary = boundary;
}

/**
* Writes an boolean field value.
*
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
*/
public void writeField(String name, boolean value)
throws java.io.IOException {
writeField(name, new Boolean(value).toString());
}

/**
* Writes an double field value.
*
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
*/
public void writeField(String name, double value)
throws java.io.IOException {
writeField(name, Double.toString(value));
}

/**
* Writes an float field value.
*
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
*/
public void writeField(String name, float value)
throws java.io.IOException {
writeField(name, Float.toString(value));
}

/**
* Writes an long field value.
*
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
*/
public void writeField(String name, long value)
throws java.io.IOException {
writeField(name, Long.toString(value));
}

/**
* Writes an int field value.
*
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
*/
public void writeField(String name, int value)
throws java.io.IOException {
writeField(name, Integer.toString(value));
}

/**
* Writes an short field value.
*
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
*/
public void writeField(String name, short value)
throws java.io.IOException {
writeField(name, Short.toString(value));
}

/**
* Writes an char field value.
*
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
*/
public void writeField(String name, char value)
throws java.io.IOException {
writeField(name, new Character(value).toString());
}

/**
* Writes an string field value. If the value is null, an empty string
* is sent ("").
*
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
*/
public void writeField(String name, String value)
throws java.io.IOException {
if(name == null) {
throw new IllegalArgumentException("Name cannot be null or empty.");
}
if(value == null) {
value = "";
}
/*
--boundary\r\n
Content-Disposition: form-data; name=""\r\n
\r\n
\r\n
*/
// write boundary
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(NEWLINE);
// write content header
out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"");
out.writeBytes(NEWLINE);
out.writeBytes(NEWLINE);
// write content
out.writeBytes(value);
out.writeBytes(NEWLINE);
out.flush();
}

/**
* Writes a file's contents. If the file is null, does not exists, or
* is a directory, a java.lang.IllegalArgumentException
* will be thrown.
*
* @param name the field name
* @param mimeType the file content type (optional, recommended)
* @param file the file (the file must exist)
* @throws java.io.IOException on input/output errors
*/
public void writeFile(String name, String mimeType, File file)
throws java.io.IOException {
if(file == null) {
throw new IllegalArgumentException("File cannot be null.");
}
if(!file.exists()) {
throw new IllegalArgumentException("File does not exist.");
}
if(file.isDirectory()) {
throw new IllegalArgumentException("File cannot be a directory.");
}
writeFile(name, mimeType, file.getCanonicalPath(), new FileInputStream(file));
}

/**
* Writes a input stream's contents. If the input stream is null, a
* java.lang.IllegalArgumentException will be thrown.
*
* @param name the field name
* @param mimeType the file content type (optional, recommended)
* @param fileName the file name (required)
* @param is the input stream
* @throws java.io.IOException on input/output errors
*/
public void writeFile(String name, String mimeType,
String fileName, InputStream is)
throws java.io.IOException {
if(is == null) {
throw new IllegalArgumentException("Input stream cannot be null.");
}
if(fileName == null || fileName.length() == 0) {
throw new IllegalArgumentException("File name cannot be null or empty.");
}
/*
--boundary\r\n
Content-Disposition: form-data; name=""; filename=""\r\n
Content-Type: \r\n
\r\n
\r\n
*/
// write boundary
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(NEWLINE);
// write content header
out.writeBytes("Content-Disposition: form-data; name=\"" + name +
"\"; filename=\"" + fileName + "\"");
out.writeBytes(NEWLINE);
if(mimeType != null) {
out.writeBytes("Content-Type: " + mimeType);
out.writeBytes(NEWLINE);
}
out.writeBytes(NEWLINE);
// write content
byte[] data = new byte[1024];
int r = 0;
while((r = is.read(data, 0, data.length)) != -1) {
out.write(data, 0, r);
}
// close input stream, but ignore any possible exception for it
try {
is.close();
} catch(Exception e) {}
out.writeBytes(NEWLINE);
out.flush();
}

/**
* Writes the given bytes. The bytes are assumed to be the contents
* of a file, and will be sent as such. If the data is null, a
* java.lang.IllegalArgumentException will be thrown.
*
* @param name the field name
* @param mimeType the file content type (optional, recommended)
* @param fileName the file name (required)
* @param data the file data
* @throws java.io.IOException on input/output errors
*/
public void writeFile(String name, String mimeType,
String fileName, byte[] data)
throws java.io.IOException {
if(data == null) {
throw new IllegalArgumentException("Data cannot be null.");
}
if(fileName == null || fileName.length() == 0) {
throw new IllegalArgumentException("File name cannot be null or empty.");
}
/*
--boundary\r\n
Content-Disposition: form-data; name=""; filename=""\r\n
Content-Type: \r\n
\r\n
\r\n
*/
// write boundary
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(NEWLINE);
// write content header
out.writeBytes("Content-Disposition: form-data; name=\"" + name +
"\"; filename=\"" + fileName + "\"");
out.writeBytes(NEWLINE);
if(mimeType != null) {
out.writeBytes("Content-Type: " + mimeType);
out.writeBytes(NEWLINE);
}
out.writeBytes(NEWLINE);
// write content
out.write(data, 0, data.length);
out.writeBytes(NEWLINE);
out.flush();
}

/**
* Flushes the stream. Actually, this method does nothing, as the only
* write methods are highly specialized and automatically flush.
*
* @throws java.io.IOException on input/output errors
*/
public void flush() throws java.io.IOException {
// out.flush();
}

/**
* Closes the stream.

*

* NOTE: This method MUST be called to finalize the
* multipart stream.
*
* @throws java.io.IOException on input/output errors
*/
public void close() throws java.io.IOException {
// write final boundary
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(PREFIX);
out.writeBytes(NEWLINE);
out.flush();
out.close();
}

/**
* Gets the multipart boundary string being used by this stream.
*
* @return the boundary
*/
public String getBoundary() {
return this.boundary;
}

/**
* Creates a new java.net.URLConnection object from the
* specified java.net.URL. This is a convenience method
* which will set the doInput, doOutput,
* useCaches and defaultUseCaches fields to
* the appropriate settings in the correct order.
*
* @return a java.net.URLConnection object for the URL
* @throws java.io.IOException on input/output errors
*/
public static URLConnection createConnection(URL url)
throws java.io.IOException {
URLConnection urlConn = url.openConnection();
if(urlConn instanceof HttpURLConnection) {
HttpURLConnection httpConn = (HttpURLConnection)urlConn;
httpConn.setRequestMethod("POST");
}
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setDefaultUseCaches(false);
return urlConn;
}

/**
* Creates a new java.net.URLConnection object from the
* specified java.net.URL. This is a convenience method
* which will set the doInput, doOutput,
* useCaches and defaultUseCaches fields to
* the appropriate settings in the correct order.
*
* @return a java.net.URLConnection object for the URL
* @throws java.io.IOException on input/output errors
*/
public static URLConnection createConnection(String strUrl)
throws java.io.IOException {
URL url = new URL(strUrl);
return createConnection(url);
}

/**
* Creates a multipart boundary string by concatenating 20 hyphens (-)
* and the hexadecimal (base-16) representation of the current time in
* milliseconds.
*
* @return a multipart boundary string
* @see #getContentType(String)
*/
public static String createBoundary() {
return "--------------------" +
Long.toString(System.currentTimeMillis(), 16);
}

/**
* Gets the content type string suitable for the
* java.net.URLConnection which includes the multipart
* boundary string.

*

* This method is static because, due to the nature of the
* java.net.URLConnection class, once the output stream
* for the connection is acquired, it's too late to set the content
* type (or any other request parameter). So one has to create a
* multipart boundary string first before using this class, such as
* with the createBoundary() method.
*
* @param boundary the boundary string
* @return the content type string
* @see #createBoundary()
*/
public static String getContentType(String boundary) {
return "multipart/form-data; boundary=" + boundary;
}
}





NewUploader.java Main Class



package com.servlet;

import java.io.File;
import java.util.Enumeration;

import javax.servlet.http.HttpServlet;

import org.apache.struts.upload.MultipartElement;
import org.apache.struts.upload.MultipartIterator;

/**
* @author Shirin Joshi
*
* servelet URL is UploadServlet
* http://127.0.0.1:8080/test/UploadServlet
**/

public class UploadServlet extends HttpServlet {

private static final long serialVersionUID = 1791025251610442056L;

public void doPost(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)
throws javax.servlet.ServletException, java.io.IOException {
doGet(request, response);
}

public void doGet(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)
throws javax.servlet.ServletException, java.io.IOException {

String text = null;
try {

/**/

Enumeration enum1 = request.getHeaderNames();
while (enum1.hasMoreElements()) {
String key = (String) enum1.nextElement();
System.out.println(key + " === " + request.getHeader(key));
}
MultipartIterator iterator = new MultipartIterator(request, request
.getContentLength(), 500000, "c:\\outputs\\");
MultipartElement mpElement = iterator.getNextElement();

while (mpElement != null) {
System.out.println("Name MM :: " + mpElement.getName());
if (mpElement.isFile()) {

File tempFile = mpElement.getFile();
System.out.println("tempFile -------- " + tempFile.getName());
// controleer of er wel informatie in de file zit
if (tempFile.length() != 0) {
System.out.println("Length:: 0");
File resultFile = new File("c:\\outputs\\"
+ mpElement.getFileName());
if (resultFile.exists()) {
resultFile.delete();
}

tempFile.renameTo(resultFile);
} else {
// wis de file er zit toch geen informatie in.
System.out.println("Temp File Deleted :: 0");
tempFile.delete();
}

} else {
text = mpElement.getValue();
System.out.println(mpElement.getName() + " ---> "
+ mpElement.getValue());
}

mpElement = iterator.getNextElement();
}
/**/
response
.getOutputStream()
.write(
("<html><head><title>succes</title></head><body>Uploaded Successfully"
+ text + "</body></html>").getBytes());

} catch (Exception e) {
e.printStackTrace();
}

}
}

JTable with JProgressBar and JCheckBox



package com.joshi.jprogress;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.EventObject;
import java.util.Hashtable;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.CellEditorListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

public class TableTest extends JFrame {

class CheckBoxRenderer extends JCheckBox implements TableCellRenderer {

CheckBoxRenderer() {
setHorizontalAlignment(JLabel.CENTER);
}

public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setSelected((value != null && ((Boolean) value).booleanValue()));
return this;
}
}

Action action = new AbstractAction("CheckBox") {

public void actionPerformed(ActionEvent evt) {

JCheckBox cb = (JCheckBox) evt.getSource();

boolean isSel = cb.isSelected();
if (isSel) {
System.out.println("true");
} else {
System.out.println("false");
}
}
};

public TableTest() {
super("MultiComponent Table");

DefaultTableModel dm = new DefaultTableModel() {
public boolean isCellEditable(int row, int column) {
if (column == 0) {
return true;
}
return false;
}
};

// Table Data

JProgressBar p1 = createBar(50, "50%");
JProgressBar p2 = createBar(70, "70%");
dm.setDataVector(new Object[][] {
{ new Boolean(false), "Franky", "50%", p1 },
{ new Boolean(false), "Joe", "60%", p2 } }, new Object[] {
"CheckBox", "String", "Percentage", "Progress" });

CheckBoxRenderer checkBoxRenderer = new CheckBoxRenderer();
EachRowRenderer rowRenderer = new EachRowRenderer();

rowRenderer.add(0, checkBoxRenderer);
rowRenderer.add(1, checkBoxRenderer);

JCheckBox checkBox = new JCheckBox(action);
checkBox.setHorizontalAlignment(JLabel.CENTER);

DefaultCellEditor checkBoxEditor = new DefaultCellEditor(checkBox);
JTable table = new JTable(dm);

EachRowEditor rowEditor = new EachRowEditor(table);

rowEditor.setEditorAt(0, checkBoxEditor);
rowEditor.setEditorAt(1, checkBoxEditor);

table.getColumn("CheckBox").setCellRenderer(rowRenderer);
table.getColumn("CheckBox").setCellEditor(rowEditor);

JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll);
setSize(400, 160);
setVisible(true);

System.out.println(dm.getValueAt(0, 3));
table.getColumn("Progress").setCellRenderer(new ProgRenderer());
try {
for (int row = 0; row < dm.getRowCount(); row++) {
JProgressBar jp = (JProgressBar) dm.getValueAt(row, 3);
for (int i = 0; i <= 100; i++) {
jp.setValue(i);
jp.setString(i + "%");
// p1.set
Thread.sleep(100);
table.repaint();
}
}
} catch (Exception e) {
e.printStackTrace();
}

}

public static void main(String[] args) {
TableTest frame = new TableTest();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public JProgressBar createBar(int percentDone, String text) {
JProgressBar progressBar = new JProgressBar(0, 100);

progressBar.setStringPainted(true);
progressBar.setValue(percentDone);
progressBar.setString(text);

return progressBar;
}
}

class ProgRenderer implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
return (JProgressBar) value;
}

}

class EachRowRenderer implements TableCellRenderer {
protected Hashtable renderers;

protected TableCellRenderer renderer, defaultRenderer;

public EachRowRenderer() {
renderers = new Hashtable();
defaultRenderer = new DefaultTableCellRenderer();
}

public void add(int row, TableCellRenderer renderer) {
renderers.put(new Integer(row), renderer);
}

public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {

renderer = (TableCellRenderer) renderers.get(new Integer(row));
if (renderer == null) {
renderer = defaultRenderer;
}
return renderer.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
}
}

class EachRowEditor implements TableCellEditor {
protected Hashtable editors;

protected TableCellEditor editor, defaultEditor;

JTable table;

public EachRowEditor(JTable table) {
this.table = table;
editors = new Hashtable();
defaultEditor = new DefaultCellEditor(new JTextField());
}

public void setEditorAt(int row, TableCellEditor editor) {
editors.put(new Integer(row), editor);
}

public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
// editor = (TableCellEditor)editors.get(new Integer(row));
// if (editor == null) {
// editor = defaultEditor;
// }
return editor.getTableCellEditorComponent(table, value, isSelected,
row, column);
}

public Object getCellEditorValue() {
return editor.getCellEditorValue();
}

public boolean stopCellEditing() {
return editor.stopCellEditing();
}

public void cancelCellEditing() {
editor.cancelCellEditing();
}

public boolean isCellEditable(EventObject anEvent) {
selectEditor((MouseEvent) anEvent);
return editor.isCellEditable(anEvent);
}

public void addCellEditorListener(CellEditorListener l) {
editor.addCellEditorListener(l);
}

public void removeCellEditorListener(CellEditorListener l) {
editor.removeCellEditorListener(l);
}

public boolean shouldSelectCell(EventObject anEvent) {
selectEditor((MouseEvent) anEvent);
return editor.shouldSelectCell(anEvent);
}

protected void selectEditor(MouseEvent e) {
int row;
if (e == null) {
row = table.getSelectionModel().getAnchorSelectionIndex();
} else {
row = table.rowAtPoint(e.getPoint());
}
editor = (TableCellEditor) editors.get(new Integer(row));
if (editor == null) {
editor = defaultEditor;
}
}
}


Contributors