import javax.servlet.*;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletInputStream.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import org.apache.commons.fileupload.*;
import java.text.*;
public class UploadTest2 extends AbstractPage {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
doRequest(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
doRequest(request, response);
}
public void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
[COLOR=red]
// Check that we have a file upload request
System.err.println("Testing multipart request");
boolean isMultipart = FileUpload.isMultipartContent(request);
[/color]
if (!isMultipart == true ) {
AbstractItem[] outItems = {};
Document outDOM = this.createDom(outItems, "", "");
MyXSLProc xslProc = new MyXSLProc();
xslProc.process(request, response, "UploadTest2.xsl", outDOM);
return;
}
[COLOR=red]
System.err.println("Message is multipart");
// Create a new file upload handler
DiskFileUpload upload = new DiskFileUpload();
// Parse the request
try {
List items = upload.parseRequest(request);
// Set upload parameters
upload.setSizeThreshold(0); //All files more than 0 bytes are written direct to disk
upload.setSizeMax(-1); //-1 = there is no maximum size for files being uploaded
upload.setRepositoryPath("../../../docs/");
// Process the uploaded items one by one
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
boolean formChecker = processFormField(item);
[/color]
}
}
}
}
catch(Exception e) {
System.err.println("Error Parsing Request: "+e);
}
// ALL CORRECT PROCESSING FINISHED - LOAD HTML PAGE
AbstractItem[] outItems = {};
String reason = ("File has been saved.");
Document outDOM = createDom(outItems, "", reason);
MyXSLProc xslProc = new MyXSLProc();
xslProc.process(request, response, "UploadTest2.xsl", outDOM);
return;
}
[COLOR=red]
public boolean processFormField(FileItem item){
field ++;
String name = item.getFieldName();
String value = item.getString();
[/color]
System.err.println("Found Form Field for Upload: ("+name+", "+value+")");
if (name.equals("filename")) {
docTitle = value;
return true;
}
if (name.equals("synopsis")) {
synopsis = value;
return true;
}
if (name.equals("category") && value == "new") {
newCat = true;
System.err.println("A new category has been selected");
return true;
}
if (name.equals("catName") && value.equals("") && newCat == true) {
System.err.println("Error Category Check #1");
return false;
}
if (name.equals("catName") && !value.equals("") && newCat == true) {
// SAVE NEW CATEGORY TO DATABASE
System.err.println("Error Category Check #2");
con = getConnection();
newCatID = Category.saveCategory(value, con);
return true;
}
if (name.equals("category") && !value.equals("Please Select")) {
catID = Integer.parseInt(value);
System.err.println("catID set to "+catID);
return true;
}
if (name.equals("category") && value.equals("Please Select")){
catIDcheck = false;
return false;
}
if (name.equals("group") && !value.equals("Please Select")) {
gID = Integer.parseInt(value);
System.err.println("catID set to "+gID);
return true;
}
if (name.equals("group") && value.equals("Please Select")) {
gIDcheck = false;
return false;
}
if (name.equals("public")) {
isPublic = value;
if (isPublic.equals("on")){
isPublicInt = 1;
}else {
isPublicInt = 0;
}
return true;
}
return false;
}
[COLOR=red]
public boolean processUploadedFile(FileItem item){
String fileName = item.getName();
sizeInBytes = item.getSize();
StringTokenizer tok = new StringTokenizer(fileName, "\\");
int count = tok.countTokens();
for (int i = 1; i < count ; i++) {
tok.nextToken();
}
fileNameOnly = tok.nextToken();
System.err.println("processing file upload: "+fileNameOnly);
File uploadedFile = new File("../../../docs/"+fileNameOnly);
if (!uploadedFile.exists()){
try {
// UPLOAD FILE
item.write(uploadedFile);
[/color]
System.err.println("Uploading the file "+fileNameOnly+" has been successful");
// CREATE ZIP VERSION OF THE FILE:
// These are the files to include in the ZIP file
//String[] filenames = new String[]{"filename1", "filename2"};
// Create a buffer for reading the files
byte[] buf = new byte[((int)sizeInBytes)+1];
try {
// Create the ZIP file
String pathCheck = uploadedFile.getAbsolutePath();
System.err.println(pathCheck+" Path check");
String outFilename = "../../../impactdev/docs/"+fileNameOnly+".zip";
String inFilename = "C:\\impactdev\\docs\\"+fileNameOnly;
System.err.println("Attempting to Zip file: "+inFilename);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
// Compress the files
FileInputStream in = new FileInputStream(inFilename);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(inFilename));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
// Complete the ZIP file
out.close();
} catch (IOException e) {
}
//***************** SAVE DOCUMENT DETAILS TO DATABASE *******************//
con = getConnection();
LibraryDoc.saveDocument(gID, docTitle, synopsis, fileNameOnly, catID, this.getFormattedDate(), isPublicInt, fileNameOnly+".zip", con);
}
//creates nodes for the XML document.
public Document createDom(AbstractItem[] inItem, String title, String reason) throws ServletException {
Document doc = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
doc = docBuilder.newDocument();
}
catch(Exception e) {
throw new ServletException(e.toString());
}
Element root = doc.createElement("page");
doc.appendChild(root);
Element titleElement = doc.createElement("title");
titleElement.appendChild(doc.createTextNode(title));
root.appendChild(titleElement);
Element menuEl = doc.createElement("menu");
Element loginEl = doc.createElement("login");
Element mainpageEl = doc.createElement("mainpage");
root.appendChild(menuEl);
root.appendChild(loginEl);
root.appendChild(mainpageEl);
Element reasonEl = doc.createElement("reason");
reasonEl.appendChild(doc.createTextNode(reason));
root.appendChild(reasonEl);
return doc;
}
public String getFormattedDate() {
Date today;
String dateOutFormatted;
SimpleDateFormat formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd");
today = new Date();
dateOutFormatted = formatter.format(today);
System.err.println("######## "+dateOutFormatted);
return dateOutFormatted;
}
}