Java Examples for com.oreilly.servlet.multipart.Part
The following java examples will help you to understand the usage of com.oreilly.servlet.multipart.Part. These source code samples are taken from different open source projects.
Example 1
Project: crezoo-master File: MultipartHelper.java View source code |
// public String getParam(Part p) // { // try // { // if (p.isParam()) // { // ParamPart pp = (ParamPart)p; // // return pp.getStringValue(); // } // } // catch (Exception e) // { // e.printStackTrace(); // } // return null; // } /** * Parse parameters and store files in this request. * * Parameters can be collected with getAttributes. * FileIds can be collected with getFileIds * */ public void parse() { logger.debug("---------------------------------------->MultipartHelper#parse: Parsing file"); try { Part p = null; while ((p = mp.readNextPart()) != null) { if (p.isParam()) { ParamPart pp = (ParamPart) p; String id = pp.getName(); String val = pp.getStringValue(); bas.put(id, val); } else if (p.isFile()) { logger.debug("---------------------------------------->MultipartHelper#parse: It's a file"); FilePart fp1 = (FilePart) p; InputStream is = fp1.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int c; while ((c = is.read()) != -1) { out.write(c); } System.out.flush(); out.flush(); out.close(); byte[] data = out.toByteArray(); logger.debug("---------------------------------------->MultipartHelper#parse: Data " + data.length + " bytes"); logger.debug("---------------------------------------->MultipartHelper#parse: Content " + fp1.getContentType()); int fileid = resourceManager.saveFile(fp1.getFileName(), fp1.getContentType(), data, caller); fileIds.add(new Integer(fileid)); // GC data. data = null; } else { logger.warn("---------------------------------------->MultipartHelper#parse: No parameter and no file"); } } } catch (Exception e) { logger.error("---------------------------------------->MultipartHelper#parse: Error while parsing files and attributes", e); } }
Example 2
Project: JavaQA-master File: MultipartFormRequestEncodingFilter.java View source code |
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
File file = null;
HttpServletRequest httpRequest = (HttpServletRequest) request;
String contentType = httpRequest.getContentType();
if (contentType != null && contentType.startsWith("multipart/form-data")) {
try {
String charset = "utf-8";
String msS = ApplicationState.getApplicationSetting(SystemConstants.UPLOAD_MAX_SIZE);
int sizeInMB = 20;
if (JSP.ex(msS)) {
try {
sizeInMB = Integer.parseInt(msS);
} catch (NumberFormatException e) {
Tracer.platformLogger.error(e);
}
}
// 20MB
int maxSize = sizeInMB * 1024 * 1024;
MultipartParser mp = new MultipartParser(httpRequest, maxSize);
mp.setEncoding(charset);
com.oreilly.servlet.multipart.Part part;
MultiPartFormServletRequest servletRequest = new MultiPartFormServletRequest(httpRequest);
while ((part = mp.readNextPart()) != null) {
String name = part.getName();
if (part.isParam()) {
// it's a parameter part
ParamPart paramPart = (ParamPart) part;
String value = paramPart.getStringValue();
servletRequest.updateMap(name, value, null);
} else if (part.isFile()) {
// it's a file part
FilePart filePart = (FilePart) part;
String fileName = filePart.getFileName();
if (fileName != null) {
// the part actually contained a file
file = File.createTempFile("formTW_TEMP_FILE", ".tmp", ZipServe.getTempFolder(httpRequest));
long size = filePart.writeTo(file);
String mimeType = filePart.getContentType();
if (mimeType == null)
mimeType = "";
// remove the original path in order to fix difference between explorer and mozilla: mozilla cut automatically the path, explorer no
fileName = FileUtilities.getFileNameWithExtension(fileName);
servletRequest.updateMap(name, fileName, null);
servletRequest.updateMap(name + TEMPORARY_FILENAME, file.getAbsolutePath(), null);
servletRequest.updateMap(name + CONTENT_TYPE, mimeType, null);
} else {
//this is NECESSARY as it means that the file should be reset
servletRequest.updateMap(name, "", null);
}
}
}
chain.doFilter(servletRequest, response);
} catch (IOException lEx) {
Tracer.platformLogger.error("MultipartFormRequestEncodingFilter: error reading or saving file: " + lEx.getMessage());
throw new PlatformRuntimeException("MultipartFormRequestEncodingFilter: error reading or saving file: " + lEx.getMessage(), lEx);
} finally {
if (file != null && file.exists() && !FileUtilities.tryHardToDeleteFile(file))
file.deleteOnExit();
}
} else {
chain.doFilter(request, response);
}
}
Example 3
Project: dhcalc-master File: FileLoadServlet.java View source code |
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { MultipartParser parser = new MultipartParser(req, Integer.MAX_VALUE); Part part = parser.readNextPart(); if (part == null) { log.severe("No First Part"); } else { String client = null; FormData data = null; while (part != null) { if (part instanceof FilePart) { FilePart file = ((FilePart) part); InputStream stream = file.getInputStream(); ObjectMapper mapper = new ObjectMapper(); try { data = mapper.reader(FormData.class).readValue(stream); } catch (Exception e) { log.log(Level.WARNING, "Exception parsing FormData", e); } } else if (part instanceof ParamPart) { client = ((ParamPart) part).getStringValue(); } else { log.info("Skipping part of shooter " + part.getClass().getName()); } part = parser.readNextPart(); } // log.info("Done with parts"); String key = client + ".FormData"; if (client == null) { log.severe("No client Key"); } else if (data == null) { log.severe("No FormData"); ClientBuffer.getInstance().put(key, new FormData()); } else { // log.info("Created Client Buffer " + key + " = " + data); ClientBuffer.getInstance().put(key, data); } } } catch (Exception e) { log.log(Level.SEVERE, "Exception", e); } }
Example 4
Project: Pangolin-master File: LoadSRXDoc.java View source code |
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Set character encoding
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
SRXDocument srxDoc = null;
String error = null;
//wrap the request to handle multipart form type
MultipartParser parser = new MultipartParser(request, 65535, false, false, "UTF-8");
LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
Part nextPart = null;
while ((nextPart = parser.readNextPart()) != null) {
if (nextPart.isParam()) {
ParamPart p = (ParamPart) nextPart;
params.put(p.getName(), p.getStringValue());
} else if (nextPart.isFile()) {
FilePart f = (FilePart) nextPart;
String fileName = f.getFileName();
if (fileName != null) {
//load the file
SRXDocument newSRX = SRXDocumentService.buildBlankSRXDoc();
try {
newSRX.loadRules(f.getInputStream());
} catch (OkapiIOException e) {
newSRX = null;
error = "invalid-file";
}
if (newSRX != null) {
srxDoc = newSRX;
//set the filename session attribute
request.getSession().setAttribute("file-name", extractDocName(fileName));
}
}
}
}
boolean loadNew = params.get("load-new") != null;
boolean loadTest = params.get("load-test") != null;
boolean loadLocal = params.get("load-local") != null;
boolean loadUrl = params.get("load-url") != null;
boolean loadRepositoryDoc = params.get("load-repository") != null;
String urlString = params.get("file-url");
String repositoryDoc = params.get("selected-document");
boolean refreshDocs = params.get("refresh-repository") != null;
if (refreshDocs) {
request.getSession().setAttribute("repository-docs", RepositoryService.getDocList());
response.sendRedirect("chooseFile.jsp");
return;
}
if (loadRepositoryDoc) {
try {
srxDoc = loadFromURL(RepositoryService.getDocURL(repositoryDoc), request);
} catch (MalformedURLException e) {
srxDoc = null;
error = "invalid-url";
} catch (IOException e) {
srxDoc = null;
} catch (OkapiIOException e) {
srxDoc = null;
error = "invalid-file";
}
} else if (loadNew) {
srxDoc = SRXDocumentService.buildBlankSRXDoc();
request.getSession().removeAttribute("file-name");
} else if (loadTest) {
srxDoc = SRXDocumentService.buildTestSRXDoc();
request.getSession().setAttribute("file-name", "test_doc.srx");
} else if (loadLocal) {
if (srxDoc == null && error == null) {
error = "local-file-load-error";
}
//else it loaded successfully
} else if (loadUrl) {
try {
srxDoc = loadFromURL(urlString, request);
} catch (MalformedURLException e) {
srxDoc = null;
error = "invalid-url";
} catch (IOException e) {
srxDoc = null;
} catch (OkapiIOException e) {
srxDoc = null;
error = "invalid-file";
}
} else {
//no valid option selected
error = "no-load-option";
}
if (error == null && srxDoc == null) {
error = "document-load-error";
}
if (error != null) {
response.sendRedirect("chooseFile.jsp?error=" + error);
} else {
//clear session attributes from previous document
request.getSession().removeAttribute("languageRuleName");
request.getSession().removeAttribute("selectedRuleIndex");
request.getSession().setAttribute("srxDoc", srxDoc);
response.sendRedirect("editor.jsp");
//TODO success message when loading a file
}
}
Example 5
Project: vox-mail-master File: LeaveMessageAction.java View source code |
/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/
protected String processAndSendRecording(HttpServletRequest request, HttpServletResponse response, boolean isImap) throws ServletException, java.io.IOException {
//size of file, if saved
long savedFileSize = 0;
String mailboxId = "";
String cmd = "";
System.out.println("#---------------------------------------------------#");
System.out.println("LeaveMessageAction - Attempting to parse stream...");
String platform = null;
try {
// 25MB
MultipartParser mp = new MultipartParser(request, 25 * 1024 * 1024);
Part part;
String callerId = null;
String recordingType = "voicemail";
FilePart filePart = null;
ByteArrayOutputStream bout = null;
String audioFileName = null;
while ((part = mp.readNextPart()) != null) {
String name = part.getName();
if (part.isParam()) {
// it's a parameter part
ParamPart paramPart = (ParamPart) part;
String value = paramPart.getStringValue();
//get important params
if ("mailboxId".equals(name))
mailboxId = value;
else if ("callerId".equals(name))
callerId = value;
else if ("cmd".equals(name))
cmd = value;
System.out.println("name=" + name + ", value=" + value);
} else if (part.isFile()) {
//put the file into a ByteArrayOutputStream. We'll save it when we finish parsing
filePart = (FilePart) part;
audioFileName = filePart.getFileName();
System.out.println("filename=" + audioFileName);
bout = new ByteArrayOutputStream();
filePart.writeTo(bout);
}
}
//if we got a file, try to save it
if (filePart != null && bout != null) {
try {
if (audioFileName != null) {
//we really do have a file!
System.out.println("File is not null");
String timeStamp = new SimpleDateFormat("yyyy-MM-dd_kk,mm,S").format(new Date());
String myPath = filePath_Messages + File.separator;
String myFileName = mailboxId + "." + audioFileName + "." + timeStamp;
//test directory
File dir = new File(myPath);
if (!dir.exists()) {
System.out.println("Directory does not exist: " + myPath);
}
File file = new File(myPath + myFileName);
//write data to temp file
FileOutputStream fos = new FileOutputStream(file);
bout.writeTo(fos);
fos.close();
savedFileSize = file.length();
if (savedFileSize > 0) {
//send to mail
sendMail(mailboxId, file.getAbsolutePath(), callerId, isImap);
System.out.println("SAVED VM: " + file.getAbsolutePath());
}
} else {
System.out.println("LeaveMessageAction - Empty or missing file part");
}
} catch (Exception e) {
System.out.println("Unable to save file: " + e.getMessage());
}
} else {
System.out.println("null file");
}
System.out.println("LeaveMessageAction: mailboxId=" + mailboxId + "*");
} catch (Exception e) {
System.out.println("Parsing failed: " + e.getMessage());
System.out.println("We're still going to try and redirect to nextpage.");
}
return cmd;
}
Example 6
Project: RestFixture-master File: ResourcesServlet.java View source code |
private void processMultiPart(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
resp.setContentType("text/plain");
MultipartParser mp = new MultipartParser(req, 2048);
Part part = null;
while ((part = mp.readNextPart()) != null) {
String name = part.getName().trim();
if (part.isParam()) {
// it's a parameter part
ParamPart paramPart = (ParamPart) part;
String value = paramPart.getStringValue().trim();
LOG.info("param; name=" + name + ", value=" + value);
out.print("param; name=" + name + ", value=" + value);
} else if (part.isFile()) {
// it's a file part
FilePart filePart = (FilePart) part;
String fileName = filePart.getFileName();
if (fileName != null) {
// the part actually contained a file
// StringWriter sw = new StringWriter();
// long size = filePart.writeTo(new File(System
// .getProperty("java.io.tmpdir")));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
long size = filePart.writeTo(baos);
LOG.info("file; name=" + name + "; filename=" + fileName + ", filePath=" + filePart.getFilePath() + ", content type=" + filePart.getContentType() + ", size=" + size);
out.print(String.format("%s: %s", name, new String(baos.toByteArray()).trim()));
} else {
// the field did not contain a file
LOG.info("file; name=" + name + "; EMPTY");
}
out.flush();
}
}
resp.setStatus(HttpServletResponse.SC_OK);
}
Example 7
Project: platform2-master File: PaymentBooker.java View source code |
private void doUploadFile(IWContext modinfo) {
modinfo.getSession().removeAttribute(sParameterPrefix + "action");
String fileSeperator = System.getProperty("file.separator");
String sMessage = "";
Table MainTable = makeMainTable();
MainTable.add(makeLinkTable(5), 1, 1);
/*
* try{ File f = FileSaver.FileToDir(modinfo); FileReader reader = new
* FileReader(fileName); LineNumberReader lineReader = new
* LineNumberReader(reader); Payment P; String line; lineReader.mark(1);
* while (lineReader.read() != -1) { lineReader.reset(); line =
* lineReader.readLine(); if(line.startsWith("G2")){ int PID =
* line.substring(45,53); } lineReader.mark(1); } } catch
* (FileNotFoundException f) { sMessage ="File not
* found";e.printStackTrace(); } catch(IOException e){sMessage ="IO
* Error";e.printStackTrace();}
*/
try {
MultipartParser mp = new MultipartParser(modinfo.getRequest(), // 10MB
10 * 1024 * // 10MB
1024);
Part part;
File dir = null;
String value = null;
while ((part = mp.readNextPart()) != null) {
String name = part.getName();
if (part.isParam() && part.getName().equalsIgnoreCase(FileSaver.getUploadDirParameterName())) {
ParamPart paramPart = (ParamPart) part;
dir = new File(paramPart.getStringValue());
value = paramPart.getStringValue();
//add("<br>");
//add("\nparam; name=" + name + ", value=" + value);
}
if (part.isFile() && dir != null) {
// it's a file part
FilePart filePart = (FilePart) part;
String fileName = filePart.getFileName();
if (fileName != null) {
//dir = new File(value+fileSeperator+fileName);
// the part actually contained a file
long size = filePart.writeTo(dir);
//add("<br>");
//add("\nfile; name=" + name + "; filename=" + fileName +", content
// type=" + filePart.getContentType() + " size=" + size);
String l = fileSeperator + this.sUnionAbbrev.toLowerCase() + fileSeperator;
if (filePart.getContentType().equalsIgnoreCase("image/pjpeg")) {
MainTable.add(new Image(l + fileName), 1, 3);
} else
MainTable.add(new Link(l + fileName), 1, 3);
}
}
}
} catch (IOException lEx) {
System.err.print("error reading or saving file");
}
MainTable.add(sMessage, 1, 2);
MainTable.add("<br><br>", 1, 3);
add(MainTable);
}
Example 8
Project: com.idega.core-master File: IWEventProcessor.java View source code |
public void handleMultipartFormData(IWContext iwc) throws Exception {
String sep = FileUtil.getFileSeparator();
StringBuffer pathToFile = new StringBuffer();
pathToFile.append(iwc.getIWMainApplication().getApplicationRealPath());
pathToFile.append(IWCacheManager.IW_ROOT_CACHE_DIRECTORY);
pathToFile.append(sep);
pathToFile.append("upload");
pathToFile.append(sep);
FileUtil.createFolder(pathToFile.toString());
int maxSize = iwc.getRequest().getContentLength();
Logger.getLogger(getClass().getName()).info("content length of request is " + maxSize + ", max size of multipart data is " + (maxSize *= 1.3));
if (iwc.getRequest() instanceof MultipartWrapper) {
//oreilly This ONLY supports one file
// Cast the request to a MultipartWrapper
MultipartWrapper multi = (MultipartWrapper) iwc.getRequest();
// Show which files we received
Enumeration files = multi.getFileNames();
while (files.hasMoreElements()) {
String name = (String) files.nextElement();
String fileName = multi.getFilesystemName(name);
String mimetype = multi.getContentType(name);
File f = multi.getFile(name);
if (fileName != null) {
pathToFile.append(fileName);
String filePath = pathToFile.toString();
StringBuffer webPath = new StringBuffer();
webPath.append('/');
webPath.append(IWCacheManager.IW_ROOT_CACHE_DIRECTORY);
webPath.append('/');
webPath.append("upload");
webPath.append('/');
webPath.append(fileName);
// Opera mimetype fix ( aron@idega.is )
if (mimetype != null) {
StringTokenizer tokenizer = new StringTokenizer(mimetype, " ;:");
if (tokenizer.hasMoreTokens()) {
mimetype = tokenizer.nextToken();
}
}
UploadFile file = new UploadFile(fileName, filePath, iwc.getIWMainApplication().getTranslatedURIWithContext(webPath.toString()), mimetype, -1);
FileUtil.copyFile(f, file);
long size = f.length();
file.setSize(size);
iwc.setUploadedFile(file);
}
}
} else if (IWMainApplication.useJSF) {
//This is a hack so we don't have to add the myfaces dependency yet
FileUploadUtil.handleMyFacesMultiPartRequest(iwc);
} else {
MultipartParser mp = new MultipartParser(iwc.getRequest(), maxSize);
/**@todo the maximum size should be flexible could just match the filesiz we have? or don't we**/
Part part;
while ((part = mp.readNextPart()) != null) {
if (part.isParam()) {
ParamPart paramPart = (ParamPart) part;
iwc.setMultipartParameter(paramPart.getName(), paramPart.getStringValue());
//System.out.println(" PARAMETERS "+paramPart.getName()+" : "+paramPart.getStringValue());
} else if (part.isFile()) {
// it's a file part
FilePart filePart = (FilePart) part;
String fileName = filePart.getFileName();
if (fileName != null) {
pathToFile.append(fileName);
String filePath = pathToFile.toString();
StringBuffer webPath = new StringBuffer();
webPath.append('/');
webPath.append(IWCacheManager.IW_ROOT_CACHE_DIRECTORY);
webPath.append('/');
webPath.append("upload");
webPath.append('/');
webPath.append(fileName);
// Opera mimetype fix ( aron@idega.is )
String mimetype = filePart.getContentType();
if (mimetype != null) {
StringTokenizer tokenizer = new StringTokenizer(mimetype, " ;:");
if (tokenizer.hasMoreTokens()) {
mimetype = tokenizer.nextToken();
}
}
UploadFile file = new UploadFile(fileName, filePath, iwc.getIWMainApplication().getTranslatedURIWithContext(webPath.toString()), mimetype, -1);
long size = filePart.writeTo(file);
file.setSize(size);
iwc.setUploadedFile(file);
}
}
}
}
}
Example 9
Project: rest-fixture-master File: ResourcesServlet.java View source code |
private void processMultiPart(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
resp.setContentType("text/plain");
MultipartParser mp = new MultipartParser(req, 2048);
Part part = null;
while ((part = mp.readNextPart()) != null) {
String name = part.getName();
if (part.isParam()) {
// it's a parameter part
ParamPart paramPart = (ParamPart) part;
String value = paramPart.getStringValue();
log.info("param; name=" + name + ", value=" + value);
out.print("param; name=" + name + ", value=" + value);
} else if (part.isFile()) {
// it's a file part
FilePart filePart = (FilePart) part;
String fileName = filePart.getFileName();
if (fileName != null) {
// the part actually contained a file
// StringWriter sw = new StringWriter();
// long size = filePart.writeTo(new File(System
// .getProperty("java.io.tmpdir")));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
long size = filePart.writeTo(baos);
log.info("file; name=" + name + "; filename=" + fileName + ", filePath=" + filePart.getFilePath() + ", content type=" + filePart.getContentType() + ", size=" + size);
out.print(String.format("%s: %s", name, new String(baos.toByteArray())));
} else {
// the field did not contain a file
log.info("file; name=" + name + "; EMPTY");
}
out.flush();
}
}
resp.setStatus(HttpServletResponse.SC_OK);
}