use of org.apache.commons.fileupload.disk.DiskFileItemFactory 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.disk.DiskFileItemFactory in project acs-community-packaging by Alfresco.
the class ContentUpdateBean method updateFile.
/**
* Ajax method to update file content. A multi-part form is required as the input.
*
* "return-page" = javascript to execute on return from the upload request
* "nodeRef" = the nodeRef of the item to update the content of
*
* @throws Exception
*/
@InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML)
public void updateFile() throws Exception {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext externalContext = fc.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
upload.setHeaderEncoding("UTF-8");
List<FileItem> fileItems = upload.parseRequest(request);
String strNodeRef = null;
String strFilename = null;
String strReturnPage = null;
File file = null;
for (FileItem item : fileItems) {
if (item.isFormField() && item.getFieldName().equals("return-page")) {
strReturnPage = item.getString();
} else if (item.isFormField() && item.getFieldName().equals("nodeRef")) {
strNodeRef = item.getString();
} else {
strFilename = FilenameUtils.getName(item.getName());
file = TempFileProvider.createTempFile("alfresco", ".upload");
item.write(file);
}
}
if (logger.isDebugEnabled())
logger.debug("Ajax content update request: " + strFilename + " to nodeRef: " + strNodeRef + " return page: " + strReturnPage);
try {
if (file != null && strNodeRef != null && strNodeRef.length() != 0) {
NodeRef nodeRef = new NodeRef(strNodeRef);
if (nodeRef != null) {
ServiceRegistry services = Repository.getServiceRegistry(fc);
// get a writer for the content and put the file
ContentWriter writer = services.getContentService().getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
writer.putContent(file);
}
}
} catch (Exception e) {
strReturnPage = strReturnPage.replace("${UPLOAD_ERROR}", e.getMessage());
}
Document result = XMLUtil.newDocument();
Element htmlEl = result.createElement("html");
result.appendChild(htmlEl);
Element bodyEl = result.createElement("body");
htmlEl.appendChild(bodyEl);
Element scriptEl = result.createElement("script");
bodyEl.appendChild(scriptEl);
scriptEl.setAttribute("type", "text/javascript");
Node scriptText = result.createTextNode(strReturnPage);
scriptEl.appendChild(scriptText);
if (logger.isDebugEnabled())
logger.debug("Content update request complete.");
ResponseWriter out = fc.getResponseWriter();
XMLUtil.print(result, out);
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project acs-community-packaging by Alfresco.
the class AlfrescoFacesPortlet method processAction.
/**
* Called by the portlet container to allow the portlet to process an action request.
*/
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
Application.setInPortalServer(true);
try {
// Set the current locale
I18NUtil.setLocale(getLanguage(request.getPortletSession()));
boolean isMultipart = PortletFileUpload.isMultipartContent(request);
if (isMultipart) {
if (logger.isDebugEnabled())
logger.debug("Handling multipart request...");
PortletSession session = request.getPortletSession();
// get the file from the request and put it in the session
DiskFileItemFactory factory = new DiskFileItemFactory();
PortletFileUpload upload = new PortletFileUpload(factory);
List<FileItem> fileItems = upload.parseRequest(request);
Iterator<FileItem> iter = fileItems.iterator();
FileUploadBean bean = new FileUploadBean();
while (iter.hasNext()) {
FileItem item = iter.next();
String filename = item.getName();
if (item.isFormField() == false) {
if (logger.isDebugEnabled())
logger.debug("Processing uploaded file: " + filename);
// workaround a bug in IE where the full path is returned
// IE is only available for Windows so only check for the Windows path separator
int idx = filename.lastIndexOf('\\');
if (idx == -1) {
// if there is no windows path separator check for *nix
idx = filename.lastIndexOf('/');
}
if (idx != -1) {
filename = filename.substring(idx + File.separator.length());
}
File tempFile = TempFileProvider.createTempFile("alfresco", ".upload");
item.write(tempFile);
bean.setFile(tempFile);
bean.setFileName(filename);
bean.setFilePath(tempFile.getAbsolutePath());
session.setAttribute(FileUploadBean.FILE_UPLOAD_BEAN_NAME, bean, PortletSession.PORTLET_SCOPE);
}
}
// Set the VIEW_ID parameter to tell the faces portlet bridge to treat the request
// as a JSF request, this will send us back to the previous page we came from.
String lastViewId = (String) request.getPortletSession().getAttribute(SESSION_LAST_VIEW_ID);
if (lastViewId != null) {
response.setRenderParameter(VIEW_ID, lastViewId);
}
} else {
SessionUser sessionUser = (SessionUser) request.getPortletSession().getAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE);
User user = sessionUser instanceof User ? (User) sessionUser : null;
if (user != null) {
// setup the authentication context
try {
WebApplicationContext ctx = (WebApplicationContext) getPortletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
AuthenticationService auth = (AuthenticationService) ctx.getBean("AuthenticationService");
auth.validate(user.getTicket());
// save last username into portlet preferences, get from LoginBean state
LoginBean loginBean = (LoginBean) request.getPortletSession().getAttribute(AuthenticationHelper.LOGIN_BEAN);
if (loginBean != null) {
// TODO: Need to login to the Portal to get a user here to store prefs against
// so not really a suitable solution as they get thrown away at present!
// Also would need to store prefs PER user - so auto login for each...?
String oldValue = request.getPreferences().getValue(PREF_ALF_USERNAME, null);
if (oldValue == null || oldValue.equals(loginBean.getUsernameInternal()) == false) {
if (request.getPreferences().isReadOnly(PREF_ALF_USERNAME) == false) {
request.getPreferences().setValue(PREF_ALF_USERNAME, loginBean.getUsernameInternal());
request.getPreferences().store();
}
}
}
// do the normal JSF processing
super.processAction(request, response);
} catch (AuthenticationException authErr) {
// remove User object as it's now useless
request.getPortletSession().removeAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE);
}
} else {
// do the normal JSF processing as we may be on the login page
super.processAction(request, response);
}
}
} catch (Throwable e) {
if (getErrorPage() != null) {
handleError(request, response, e);
} else {
logger.warn("No error page configured, re-throwing exception");
if (e instanceof PortletException) {
throw (PortletException) e;
} else if (e instanceof IOException) {
throw (IOException) e;
} else {
throw new PortletException(e);
}
}
} finally {
Application.setInPortalServer(false);
}
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project OpenClinica by OpenClinica.
the class OpenRosaSubmissionController method doFieldSubmission.
/**
* @api {post} /pages/api/v2/editform/:studyOid/fieldsubmission Submit form data
* @apiName doSubmission
* @apiPermission admin
* @apiVersion 3.8.0
* @apiParam {String} studyOid Study Oid.
* @apiParam {String} ecid Key that will be used to look up subject context information while processing submission.
* @apiGroup Form
* @apiDescription Submits the data from a completed form.
*/
@RequestMapping(value = "/{studyOID}/fieldsubmission", method = RequestMethod.POST)
public ResponseEntity<String> doFieldSubmission(HttpServletRequest request, HttpServletResponse response, @PathVariable("studyOID") String studyOID, @RequestParam(FORM_CONTEXT) String ecid) {
long millis = System.currentTimeMillis();
logger.info("Processing xform field submission.");
HashMap<String, String> subjectContext = null;
Locale locale = LocaleResolver.getLocale(request);
DataBinder dataBinder = new DataBinder(null);
Errors errors = dataBinder.getBindingResult();
Study study = studyDao.findByOcOID(studyOID);
String requestBody = null;
String instanceId = null;
HashMap<String, String> map = new HashMap();
ArrayList<HashMap> listOfUploadFilePaths = new ArrayList();
try {
// Verify Study is allowed to submit
if (!mayProceed(study)) {
logger.info("Field Submissions to the study not allowed. Aborting field submission.");
return new ResponseEntity<String>(HttpStatus.NOT_ACCEPTABLE);
}
if (ServletFileUpload.isMultipartContent(request)) {
String dir = getAttachedFilePath(studyOID);
FileProperties fileProperties = new FileProperties();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(fileProperties.getFileSizeMax());
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.getFieldName().equals("instance_id")) {
instanceId = item.getString();
} else if (item.getFieldName().equals("xml_submission_fragment_file")) {
requestBody = item.getString("UTF-8");
} else if (item.getContentType() != null) {
if (!new File(dir).exists())
new File(dir).mkdirs();
File file = processUploadedFile(item, dir);
map.put(item.getFieldName(), file.getPath());
}
}
listOfUploadFilePaths.add(map);
}
if (instanceId == null) {
logger.info("Field Submissions to the study not allowed without a valid instanceId. Aborting field submission.");
return new ResponseEntity<String>(HttpStatus.NOT_ACCEPTABLE);
}
// Load user context from ecid
PFormCache cache = PFormCache.getInstance(context);
subjectContext = cache.getSubjectContext(ecid);
// Execute save as Hibernate transaction to avoid partial imports
openRosaSubmissionService.processFieldSubmissionRequest(study, subjectContext, instanceId, requestBody, errors, locale, listOfUploadFilePaths, SubmissionContainer.FieldRequestTypeEnum.FORM_FIELD);
} catch (Exception e) {
logger.error("Exception while processing xform submission.");
logger.error(e.getMessage());
logger.error(ExceptionUtils.getStackTrace(e));
if (!errors.hasErrors()) {
// Send a failure response
logger.info("Submission caused internal error. Sending error response.");
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
if (!errors.hasErrors()) {
// JsonLog submission with Participate
if (isParticipantSubmission(subjectContext))
notifier.notify(studyOID, subjectContext);
logger.info("Completed xform field submission. Sending successful response");
String responseMessage = "<OpenRosaResponse xmlns=\"http://openrosa.org/http/response\">" + "<message>success</message>" + "</OpenRosaResponse>";
long endMillis = System.currentTimeMillis();
logger.info("Total time *********** " + (endMillis - millis));
return new ResponseEntity<String>(responseMessage, HttpStatus.CREATED);
} else {
logger.info("Field Submission contained errors. Sending error response");
return new ResponseEntity<String>(HttpStatus.NOT_ACCEPTABLE);
}
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory 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;
}
Aggregations