use of org.apache.commons.fileupload.FileUploadException in project iaf by ibissource.
the class StreamPipe method doPipe.
@Override
public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
Object result = input;
String inputString;
if (input instanceof String) {
inputString = (String) input;
} else {
inputString = "";
}
ParameterResolutionContext prc = new ParameterResolutionContext(inputString, session, isNamespaceAware());
Map parameters = null;
ParameterList parameterList = getParameterList();
if (parameterList != null) {
try {
parameters = prc.getValueMap(parameterList);
} catch (ParameterException e) {
throw new PipeRunException(this, "Could not resolve parameters", e);
}
}
InputStream inputStream = null;
OutputStream outputStream = null;
HttpServletRequest httpRequest = null;
HttpServletResponse httpResponse = null;
String contentType = null;
String contentDisposition = null;
if (parameters != null) {
if (parameters.get("inputStream") != null) {
inputStream = (InputStream) parameters.get("inputStream");
}
if (parameters.get("outputStream") != null) {
outputStream = (OutputStream) parameters.get("outputStream");
}
if (parameters.get("httpRequest") != null) {
httpRequest = (HttpServletRequest) parameters.get("httpRequest");
}
if (parameters.get("httpResponse") != null) {
httpResponse = (HttpServletResponse) parameters.get("httpResponse");
}
if (parameters.get("contentType") != null) {
contentType = (String) parameters.get("contentType");
}
if (parameters.get("contentDisposition") != null) {
contentDisposition = (String) parameters.get("contentDisposition");
}
}
if (inputStream == null && input instanceof InputStream) {
inputStream = (InputStream) input;
}
try {
if (httpResponse != null) {
HttpSender.streamResponseBody(inputStream, contentType, contentDisposition, httpResponse, log, getLogPrefix(session));
} else if (httpRequest != null) {
StringBuilder partsString = new StringBuilder("<parts>");
String firstStringPart = null;
List<AntiVirusObject> antiVirusObjects = new ArrayList<AntiVirusObject>();
if (ServletFileUpload.isMultipartContent(httpRequest)) {
log.debug(getLogPrefix(session) + "request with content type [" + httpRequest.getContentType() + "] and length [" + httpRequest.getContentLength() + "] contains multipart content");
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
List<FileItem> items = servletFileUpload.parseRequest(httpRequest);
int fileCounter = 0;
int stringCounter = 0;
log.debug(getLogPrefix(session) + "multipart request items size [" + items.size() + "]");
String lastFoundFileName = null;
String lastFoundAVStatus = null;
String lastFoundAVMessage = null;
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input
// type="text|radio|checkbox|etc", select, etc).
String fieldValue = item.getString();
String fieldName = item.getFieldName();
if (isCheckAntiVirus() && fieldName.equalsIgnoreCase(getAntiVirusPartName())) {
log.debug(getLogPrefix(session) + "found antivirus status part [" + fieldName + "] with value [" + fieldValue + "]");
lastFoundAVStatus = fieldValue;
} else if (isCheckAntiVirus() && fieldName.equalsIgnoreCase(getAntiVirusMessagePartName())) {
log.debug(getLogPrefix(session) + "found antivirus message part [" + fieldName + "] with value [" + fieldValue + "]");
lastFoundAVMessage = fieldValue;
} else {
log.debug(getLogPrefix(session) + "found string part [" + fieldName + "] with value [" + fieldValue + "]");
if (isExtractFirstStringPart() && firstStringPart == null) {
firstStringPart = fieldValue;
} else {
String sessionKeyName = "part_string" + (++stringCounter > 1 ? stringCounter : "");
addSessionKey(session, sessionKeyName, fieldValue);
partsString.append("<part type=\"string\" name=\"" + fieldName + "\" sessionKey=\"" + sessionKeyName + "\" size=\"" + fieldValue.length() + "\"/>");
}
}
} else {
// Process form file field (input type="file").
if (lastFoundFileName != null && lastFoundAVStatus != null) {
antiVirusObjects.add(new AntiVirusObject(lastFoundFileName, lastFoundAVStatus, lastFoundAVMessage));
lastFoundFileName = null;
lastFoundAVStatus = null;
lastFoundAVMessage = null;
}
log.debug(getLogPrefix(session) + "found file part [" + item.getName() + "]");
String sessionKeyName = "part_file" + (++fileCounter > 1 ? fileCounter : "");
String fileName = FilenameUtils.getName(item.getName());
InputStream is = item.getInputStream();
int size = is.available();
String mimeType = item.getContentType();
if (size > 0) {
addSessionKey(session, sessionKeyName, is, fileName);
} else {
addSessionKey(session, sessionKeyName, null);
}
partsString.append("<part type=\"file\" name=\"" + fileName + "\" sessionKey=\"" + sessionKeyName + "\" size=\"" + size + "\" mimeType=\"" + mimeType + "\"/>");
lastFoundFileName = fileName;
}
}
if (lastFoundFileName != null && lastFoundAVStatus != null) {
antiVirusObjects.add(new AntiVirusObject(lastFoundFileName, lastFoundAVStatus, lastFoundAVMessage));
}
} else {
log.debug(getLogPrefix(session) + "request with content type [" + httpRequest.getContentType() + "] and length [" + httpRequest.getContentLength() + "] does NOT contain multipart content");
}
partsString.append("</parts>");
if (isExtractFirstStringPart()) {
result = adjustFirstStringPart(firstStringPart, session);
session.put(getMultipartXmlSessionKey(), partsString.toString());
} else {
result = partsString.toString();
}
if (!antiVirusObjects.isEmpty()) {
for (AntiVirusObject antiVirusObject : antiVirusObjects) {
if (!antiVirusObject.getStatus().equalsIgnoreCase(getAntiVirusPassedMessage())) {
String errorMessage = "multipart contains file [" + antiVirusObject.getFileName() + "] with antivirus status [" + antiVirusObject.getStatus() + "] and message [" + StringUtils.defaultString(antiVirusObject.getMessage()) + "]";
PipeForward antiVirusFailedForward = findForward(ANTIVIRUS_FAILED_FORWARD);
if (antiVirusFailedForward == null) {
throw new PipeRunException(this, errorMessage);
} else {
if (antiVirusFailureAsSoapFault) {
errorMessage = createSoapFaultMessage(errorMessage);
}
if (StringUtils.isEmpty(getAntiVirusFailureReasonSessionKey())) {
return new PipeRunResult(antiVirusFailedForward, errorMessage);
} else {
session.put(getAntiVirusFailureReasonSessionKey(), errorMessage);
return new PipeRunResult(antiVirusFailedForward, result);
}
}
}
}
}
} else {
Misc.streamToStream(inputStream, outputStream);
}
} catch (IOException e) {
throw new PipeRunException(this, "IOException streaming input to output", e);
} catch (FileUploadException e) {
throw new PipeRunException(this, "FileUploadException getting multiparts from httpServletRequest", e);
}
return new PipeRunResult(getForward(), result);
}
use of org.apache.commons.fileupload.FileUploadException in project jspwiki by apache.
the class AttachmentServlet method upload.
/**
* Uploads a specific mime multipart input set, intercepts exceptions.
*
* @param req The servlet request
* @return The page to which we should go next.
* @throws RedirectException If there's an error and a redirection is needed
* @throws IOException If upload fails
* @throws FileUploadException
*/
protected String upload(HttpServletRequest req) throws RedirectException, IOException {
String msg = "";
String attName = "(unknown)";
// If something bad happened, Upload should be able to take care of most stuff
String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false);
String nextPage = errorPage;
String progressId = req.getParameter("progressid");
// Check that we have a file upload request
if (!ServletFileUpload.isMultipartContent(req)) {
throw new RedirectException("Not a file upload", errorPage);
}
try {
FileItemFactory factory = new DiskFileItemFactory();
// Create the context _before_ Multipart operations, otherwise
// strict servlet containers may fail when setting encoding.
WikiContext context = m_engine.createContext(req, WikiContext.ATTACH);
UploadListener pl = new UploadListener();
m_engine.getProgressManager().startProgress(pl, progressId);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
if (!context.hasAdminPermissions()) {
upload.setFileSizeMax(m_maxSize);
}
upload.setProgressListener(pl);
List<FileItem> items = upload.parseRequest(req);
String wikipage = null;
String changeNote = null;
// FileItem actualFile = null;
List<FileItem> fileItems = new java.util.ArrayList<FileItem>();
for (FileItem item : items) {
if (item.isFormField()) {
if (item.getFieldName().equals("page")) {
//
// FIXME: Kludge alert. We must end up with the parent page name,
// if this is an upload of a new revision
//
wikipage = item.getString("UTF-8");
int x = wikipage.indexOf("/");
if (x != -1)
wikipage = wikipage.substring(0, x);
} else if (item.getFieldName().equals("changenote")) {
changeNote = item.getString("UTF-8");
if (changeNote != null) {
changeNote = TextUtil.replaceEntities(changeNote);
}
} else if (item.getFieldName().equals("nextpage")) {
nextPage = validateNextPage(item.getString("UTF-8"), errorPage);
}
} else {
fileItems.add(item);
}
}
if (fileItems.size() == 0) {
throw new RedirectException("Broken file upload", errorPage);
} else {
for (FileItem actualFile : fileItems) {
String filename = actualFile.getName();
long fileSize = actualFile.getSize();
InputStream in = actualFile.getInputStream();
try {
executeUpload(context, in, filename, nextPage, wikipage, changeNote, fileSize);
} finally {
IOUtils.closeQuietly(in);
}
}
}
} catch (ProviderException e) {
msg = "Upload failed because the provider failed: " + e.getMessage();
log.warn(msg + " (attachment: " + attName + ")", e);
throw new IOException(msg);
} catch (IOException e) {
// Show the submit page again, but with a bit more
// intimidating output.
msg = "Upload failure: " + e.getMessage();
log.warn(msg + " (attachment: " + attName + ")", e);
throw e;
} catch (FileUploadException e) {
// Show the submit page again, but with a bit more
// intimidating output.
msg = "Upload failure: " + e.getMessage();
log.warn(msg + " (attachment: " + attName + ")", e);
throw new IOException(msg, e);
} finally {
m_engine.getProgressManager().stopProgress(progressId);
// FIXME: In case of exceptions should absolutely
// remove the uploaded file.
}
return nextPage;
}
use of org.apache.commons.fileupload.FileUploadException in project Gemma by PavlidisLab.
the class CommonsMultipartMonitoredResolver method resolveMultipart.
@Override
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
String enc = determineEncoding(request);
ServletFileUpload fileUpload = this.newFileUpload(request);
DiskFileItemFactory newFactory = (DiskFileItemFactory) fileUpload.getFileItemFactory();
fileUpload.setSizeMax(sizeMax);
newFactory.setRepository(this.uploadTempDir);
fileUpload.setHeaderEncoding(enc);
try {
MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<>();
Map<String, String[]> multipartParams = new HashMap<>();
// Extract multipart files and multipart parameters.
List<?> fileItems = fileUpload.parseRequest(request);
for (Object fileItem1 : fileItems) {
FileItem fileItem = (FileItem) fileItem1;
if (fileItem.isFormField()) {
String value;
String fieldName = fileItem.getFieldName();
try {
value = fileItem.getString(enc);
} catch (UnsupportedEncodingException ex) {
logger.warn("Could not decode multipart item '" + fieldName + "' with encoding '" + enc + "': using platform default");
value = fileItem.getString();
}
String[] curParam = multipartParams.get(fieldName);
if (curParam == null) {
// simple form field
multipartParams.put(fieldName, new String[] { value });
} else {
// array of simple form fields
String[] newParam = StringUtils.addStringToArray(curParam, value);
multipartParams.put(fieldName, newParam);
}
} else {
// multipart file field
MultipartFile file = new CommonsMultipartFile(fileItem);
multipartFiles.set(file.getName(), file);
if (logger.isDebugEnabled()) {
logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() + " bytes with original filename [" + file.getOriginalFilename() + "]");
}
}
}
return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParams, null);
} catch (FileUploadException ex) {
return new FailedMultipartHttpServletRequest(request, ex.getMessage());
}
}
use of org.apache.commons.fileupload.FileUploadException in project fabric8 by jboss-fuse.
the class ProxyServlet method handleMultipartPost.
/**
* Sets up the given {@link EntityEnclosingMethod} to send the same multipart
* data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
*
* @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are
* configuring to send a multipart request
* @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} that contains
* the mutlipart data to be sent via the {@link EntityEnclosingMethod}
*/
private void handleMultipartPost(EntityEnclosingMethod entityEnclosingMethod, HttpServletRequest httpServletRequest) throws ServletException {
// Create a factory for disk-based file items
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// Set factory constraints
diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
// Create a new file upload handler
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
// Parse the request
try {
// Get the multipart items as a list
List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
// Create a list to hold all of the parts
List<Part> listParts = new ArrayList<Part>();
// Iterate the multipart items list
for (FileItem fileItemCurrent : listFileItems) {
// If the current item is a form field, then create a string part
if (fileItemCurrent.isFormField()) {
StringPart stringPart = new StringPart(// The field name
fileItemCurrent.getFieldName(), // The field value
fileItemCurrent.getString());
// Add the part to the list
listParts.add(stringPart);
} else {
// The item is a file upload, so we create a FilePart
FilePart filePart = new FilePart(// The field name
fileItemCurrent.getFieldName(), new ByteArrayPartSource(// The uploaded file name
fileItemCurrent.getName(), // The uploaded file contents
fileItemCurrent.get()));
// Add the part to the list
listParts.add(filePart);
}
}
MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(listParts.toArray(new Part[] {}), entityEnclosingMethod.getParams());
entityEnclosingMethod.setRequestEntity(multipartRequestEntity);
// The current content-type header (received from the client) IS of
// type "multipart/form-data", but the content-type header also
// contains the chunk boundary string of the chunks. Currently, this
// header is using the boundary of the client request, since we
// blindly copied all headers from the client request to the proxy
// request. However, we are creating a new request with a new chunk
// boundary string, so it is necessary that we re-set the
// content-type string to reflect the new chunk boundary string
entityEnclosingMethod.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType());
} catch (FileUploadException fileUploadException) {
throw new ServletException(fileUploadException);
}
}
use of org.apache.commons.fileupload.FileUploadException in project webprotege by protegeproject.
the class FileUploadServlet method doPost.
@Override
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
WebProtegeSession webProtegeSession = new WebProtegeSessionImpl(req.getSession());
UserId userId = webProtegeSession.getUserInSession();
if (!accessManager.hasPermission(Subject.forUser(userId), ApplicationResource.get(), BuiltInAction.UPLOAD_PROJECT)) {
sendErrorMessage(resp, "You do not have permission to upload files to " + applicationNameSupplier.get());
}
logger.info("Received upload request from {} at {}", webProtegeSession.getUserInSession(), formatAddr(req));
resp.setHeader("Content-Type", RESPONSE_MIME_TYPE);
try {
if (ServletFileUpload.isMultipartContent(req)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(maxUploadSizeSupplier.get());
List<FileItem> items = upload.parseRequest(req);
for (FileItem item : items) {
if (!item.isFormField()) {
File uploadedFile = createServerSideFile();
item.write(uploadedFile);
long sizeInBytes = uploadedFile.length();
long computedFileSizeInBytes = computeFileSize(uploadedFile);
logger.info("File size is {} bytes. Computed file size is {} bytes.", sizeInBytes, computedFileSizeInBytes);
if (computedFileSizeInBytes > maxUploadSizeSupplier.get()) {
sendFileSizeTooLargeResponse(resp);
} else {
logger.info("Stored uploaded file with name {}", uploadedFile.getName());
resp.setStatus(HttpServletResponse.SC_CREATED);
sendSuccessMessage(resp, uploadedFile.getName());
}
return;
}
}
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not find form file item");
} else {
logger.info("Bad upload request: POST must be multipart encoding.");
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "POST must be multipart encoding.");
}
} catch (FileUploadBase.FileSizeLimitExceededException | FileUploadBase.SizeLimitExceededException e) {
sendFileSizeTooLargeResponse(resp);
} catch (FileUploadBase.FileUploadIOException | FileUploadBase.IOFileUploadException e) {
logger.info("File upload failed because an IOException occurred: {}", e.getMessage(), e);
sendErrorMessage(resp, "File upload failed because of an IOException");
} catch (FileUploadBase.InvalidContentTypeException e) {
logger.info("File upload failed because the content type was invalid: {}", e.getMessage());
sendErrorMessage(resp, "File upload failed because the content type is invalid");
} catch (FileUploadException e) {
logger.info("File upload failed: {}", e.getMessage());
sendErrorMessage(resp, "File upload failed");
} catch (Exception e) {
logger.info("File upload failed because of an error when trying to write the file item: {}", e.getMessage(), e);
sendErrorMessage(resp, "File upload failed");
}
}
Aggregations