use of org.apache.commons.fileupload.servlet.ServletRequestContext in project MassBank-web by MassBank.
the class AdminActions method doUpload.
@Action(name = "doUpload", post = true)
public Redirect doUpload(HttpServletRequest req) throws ServletException {
RequestContext reqContext = new ServletRequestContext(req);
boolean isMultipart = ServletFileUpload.isMultipartContent(reqContext);
if (isMultipart) {
try {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
List<?> items = upload.parseRequest(req);
// Process the uploaded items
Iterator<?> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String fileName = item.getName();
String fileExtesion = fileName;
fileExtesion = fileExtesion.toLowerCase();
if (!(fileExtesion.endsWith(".jar") || fileExtesion.endsWith(".aar"))) {
return new Redirect(UPLOAD).withStatus(false, "Unsupported file type " + fileExtesion);
} else {
String fileNameOnly;
if (fileName.indexOf("\\") < 0) {
fileNameOnly = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
} else {
fileNameOnly = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
}
File uploadedFile = new File(serviceDir, fileNameOnly);
item.write(uploadedFile);
return new Redirect(UPLOAD).withStatus(true, "File " + fileNameOnly + " successfully uploaded");
}
}
}
} catch (Exception e) {
return new Redirect(UPLOAD).withStatus(false, "The following error occurred: " + e.getMessage());
}
}
throw new ServletException("Invalid request");
}
use of org.apache.commons.fileupload.servlet.ServletRequestContext in project sling by apache.
the class ParameterSupport method getRequestParameterMapInternal.
private ParameterMap getRequestParameterMapInternal() {
if (this.postParameterMap == null) {
// SLING-508 Try to force servlet container to decode parameters
// as ISO-8859-1 such that we can recode later
String encoding = getServletRequest().getCharacterEncoding();
if (encoding == null) {
encoding = Util.ENCODING_DIRECT;
try {
getServletRequest().setCharacterEncoding(encoding);
} catch (UnsupportedEncodingException uee) {
throw new SlingUnsupportedEncodingException(uee);
}
}
// SLING-152 Get parameters from the servlet Container
ParameterMap parameters = new ParameterMap();
// fallback is only used if this request has been started by a service call
boolean useFallback = getServletRequest().getAttribute(MARKER_IS_SERVICE_PROCESSING) != null;
boolean addContainerParameters = false;
// Query String
final String query = getServletRequest().getQueryString();
if (query != null) {
try {
InputStream input = Util.toInputStream(query);
Util.parseQueryString(input, encoding, parameters, false);
addContainerParameters = checkForAdditionalParameters;
} catch (IllegalArgumentException e) {
this.log.error("getRequestParameterMapInternal: Error parsing request", e);
} catch (UnsupportedEncodingException e) {
throw new SlingUnsupportedEncodingException(e);
} catch (IOException e) {
this.log.error("getRequestParameterMapInternal: Error parsing request", e);
}
useFallback = false;
} else {
addContainerParameters = checkForAdditionalParameters;
useFallback = true;
}
// POST requests
final boolean isPost = "POST".equals(this.getServletRequest().getMethod());
if (isPost) {
// WWW URL Form Encoded POST
if (isWWWFormEncodedContent(this.getServletRequest())) {
try {
InputStream input = this.getServletRequest().getInputStream();
Util.parseQueryString(input, encoding, parameters, false);
addContainerParameters = checkForAdditionalParameters;
} catch (IllegalArgumentException e) {
this.log.error("getRequestParameterMapInternal: Error parsing request", e);
} catch (UnsupportedEncodingException e) {
throw new SlingUnsupportedEncodingException(e);
} catch (IOException e) {
this.log.error("getRequestParameterMapInternal: Error parsing request", e);
}
this.requestDataUsed = true;
useFallback = false;
}
// Multipart POST
if (ServletFileUpload.isMultipartContent(new ServletRequestContext(this.getServletRequest()))) {
if (isStreamed(parameters, this.getServletRequest())) {
// special case, the request is Multipart and streamed processing has been requested
try {
this.getServletRequest().setAttribute(REQUEST_PARTS_ITERATOR_ATTRIBUTE, new RequestPartsIterator(this.getServletRequest()));
this.log.debug("getRequestParameterMapInternal: Iterator<javax.servlet.http.Part> available as request attribute named request-parts-iterator");
} catch (IOException e) {
this.log.error("getRequestParameterMapInternal: Error parsing multipart streamed request", e);
} catch (FileUploadException e) {
this.log.error("getRequestParameterMapInternal: Error parsing multipart streamed request", e);
}
// The request data has been passed to the RequestPartsIterator, hence from a RequestParameter pov its been used, and must not be used again.
this.requestDataUsed = true;
// must not try and get anything from the request at this point so avoid jumping through the stream.
addContainerParameters = false;
useFallback = false;
} else {
this.parseMultiPartPost(parameters);
this.requestDataUsed = true;
addContainerParameters = checkForAdditionalParameters;
useFallback = false;
}
}
}
if (useFallback) {
getContainerParameters(parameters, encoding, true);
} else if (addContainerParameters) {
getContainerParameters(parameters, encoding, false);
}
// apply any form encoding (from '_charset_') in the parameter map
Util.fixEncoding(parameters);
this.postParameterMap = parameters;
}
return this.postParameterMap;
}
use of org.apache.commons.fileupload.servlet.ServletRequestContext in project sling by apache.
the class ParameterSupport method parseMultiPartPost.
private void parseMultiPartPost(ParameterMap parameters) {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
upload.setSizeMax(ParameterSupport.maxRequestSize);
upload.setFileSizeMax(ParameterSupport.maxFileSize);
upload.setFileItemFactory(new DiskFileItemFactory(ParameterSupport.fileSizeThreshold, ParameterSupport.location));
RequestContext rc = new ServletRequestContext(this.getServletRequest()) {
@Override
public String getCharacterEncoding() {
String enc = super.getCharacterEncoding();
return (enc != null) ? enc : Util.ENCODING_DIRECT;
}
};
// Parse the request
List<?> /* FileItem */
items = null;
try {
items = upload.parseRequest(rc);
} catch (FileUploadException fue) {
this.log.error("parseMultiPartPost: Error parsing request", fue);
}
if (items != null && items.size() > 0) {
for (Iterator<?> ii = items.iterator(); ii.hasNext(); ) {
FileItem fileItem = (FileItem) ii.next();
RequestParameter pp = new MultipartRequestParameter(fileItem);
parameters.addParameter(pp, false);
}
}
}
use of org.apache.commons.fileupload.servlet.ServletRequestContext in project felix by apache.
the class WebConsoleUtil method getParameter.
/**
* An utility method, that is used to filter out simple parameter from file
* parameter when multipart transfer encoding is used.
*
* This method processes the request and sets a request attribute
* {@link AbstractWebConsolePlugin#ATTR_FILEUPLOAD}. The attribute value is a {@link Map}
* where the key is a String specifying the field name and the value
* is a {@link org.apache.commons.fileupload.FileItem}.
*
* @param request the HTTP request coming from the user
* @param name the name of the parameter
* @return if not multipart transfer encoding is used - the value is the
* parameter value or <code>null</code> if not set. If multipart is used,
* and the specified parameter is field - then the value of the parameter
* is returned.
*/
public static final String getParameter(HttpServletRequest request, String name) {
// just get the parameter if not a multipart/form-data POST
if (!FileUploadBase.isMultipartContent(new ServletRequestContext(request))) {
return request.getParameter(name);
}
// check, whether we already have the parameters
Map params = (Map) request.getAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD);
if (params == null) {
// parameters not read yet, read now
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(256000);
// See https://issues.apache.org/jira/browse/FELIX-4660
final Object repo = request.getAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD_REPO);
if (repo instanceof File) {
factory.setRepository((File) repo);
}
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(-1);
// Parse the request
params = new HashMap();
try {
List items = upload.parseRequest(request);
for (Iterator fiter = items.iterator(); fiter.hasNext(); ) {
FileItem fi = (FileItem) fiter.next();
FileItem[] current = (FileItem[]) params.get(fi.getFieldName());
if (current == null) {
current = new FileItem[] { fi };
} else {
FileItem[] newCurrent = new FileItem[current.length + 1];
System.arraycopy(current, 0, newCurrent, 0, current.length);
newCurrent[current.length] = fi;
current = newCurrent;
}
params.put(fi.getFieldName(), current);
}
} catch (FileUploadException fue) {
// TODO: log
}
request.setAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD, params);
}
FileItem[] param = (FileItem[]) params.get(name);
if (param != null) {
for (int i = 0; i < param.length; i++) {
if (param[i].isFormField()) {
return param[i].getString();
}
}
}
// no valid string parameter, fail
return null;
}
use of org.apache.commons.fileupload.servlet.ServletRequestContext in project xwiki-platform by xwiki.
the class FileUploadPlugin method loadFileList.
/**
* Loads the list of uploaded files in the context if there are any uploaded files.
*
* @param uploadMaxSize Maximum size of the uploaded files.
* @param uploadSizeThreashold Threashold over which the file data should be stored on disk, and not in memory.
* @param tempdir Temporary directory to store the uploaded files that are not kept in memory.
* @param context Context of the request.
* @throws XWikiException if the request could not be parsed, or the maximum file size was reached.
* @see FileUploadPluginApi#loadFileList(long, int, String)
*/
public void loadFileList(long uploadMaxSize, int uploadSizeThreashold, String tempdir, XWikiContext context) throws XWikiException {
LOGGER.debug("Loading uploaded files");
// Continuing would empty the list.. We need to stop.
if (context.get(FILE_LIST_KEY) != null) {
LOGGER.debug("Called loadFileList twice");
return;
}
// Get the FileUpload Data
// Make sure the factory only ever creates file items which will be deleted when the jvm is stopped.
DiskFileItemFactory factory = new DiskFileItemFactory() {
@Override
public FileItem createItem(String fieldName, String contentType, boolean isFormField, String fileName) {
try {
final DiskFileItem item = (DiskFileItem) super.createItem(fieldName, contentType, isFormField, fileName);
// Needed to make sure the File object is created.
item.getOutputStream();
return item;
} catch (IOException e) {
String path = System.getProperty("java.io.tmpdir");
if (super.getRepository() != null) {
path = super.getRepository().getPath();
}
throw new RuntimeException("Unable to create a temporary file for saving the attachment. " + "Do you have write access on " + path + "?");
}
}
};
factory.setSizeThreshold(uploadSizeThreashold);
if (tempdir != null) {
File tempdirFile = new File(tempdir);
if (tempdirFile.mkdirs() && tempdirFile.canWrite()) {
factory.setRepository(tempdirFile);
}
}
// TODO: Does this work in portlet mode, or we must use PortletFileUpload?
FileUpload fileupload = new ServletFileUpload(factory);
RequestContext reqContext = new ServletRequestContext(context.getRequest().getHttpServletRequest());
fileupload.setSizeMax(uploadMaxSize);
try {
@SuppressWarnings("unchecked") List<FileItem> list = fileupload.parseRequest(reqContext);
if (list.size() > 0) {
LOGGER.info("Loaded " + list.size() + " uploaded files");
}
// We store the file list in the context
context.put(FILE_LIST_KEY, list);
} catch (FileUploadBase.SizeLimitExceededException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_FILE_EXCEPTION_MAXSIZE, "Exception uploaded file");
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_UPLOAD_PARSE_EXCEPTION, "Exception while parsing uploaded file", e);
}
}
Aggregations