List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setHeaderEncoding
public void setHeaderEncoding(String encoding)
From source file:nl.b3p.commons.uploadProgress.ExtendedMultipartRequestHandler.java
/** * Parses the input stream and partitions the parsed items into a set of * form fields and a set of file items. In the process, the parsed items * are translated from Commons FileUpload <code>FileItem</code> instances * to Struts <code>FormFile</code> instances. * * @param request The multipart request to be processed. * * @throws ServletException if an unrecoverable error occurs. */// w ww . ja v a2 s . co m public void handleRequest(HttpServletRequest request) throws ServletException { // Get the app config for the current request. ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY); // Create and configure a DIskFileUpload instance. //everything thats added: UploadListener listener = new UploadListener(request, 1); FileItemFactory factory = new MonitoredDiskFileItemFactory(listener); ServletFileUpload upload = new ServletFileUpload(factory); // The following line is to support an "EncodingFilter" // see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=23255 upload.setHeaderEncoding(request.getCharacterEncoding()); // Set the maximum size before a FileUploadException will be thrown. upload.setSizeMax(getSizeMax(ac)); // Set the maximum size that will be stored in memory. //upload.setSizeThreshold((int) getSizeThreshold(ac)); // Set the the location for saving data on disk. //upload.setRepositoryPath(getRepositoryPath(ac)); // Create the hash tables to be populated. elementsText = new Hashtable(); elementsFile = new Hashtable(); elementsAll = new Hashtable(); // Parse the request into file items. List items = null; try { items = upload.parseRequest(request); } catch (DiskFileUpload.SizeLimitExceededException e) { // Special handling for uploads that are too big. request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE); return; } catch (FileUploadException e) { log.error("Failed to parse multipart request", e); throw new ServletException(e); } // Partition the items into form fields and files. Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { addTextParameter(request, item); } else { addFileParameter(item); } } }
From source file:org.alfresco.web.app.servlet.UploadFileServlet.java
/** * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from w w w. j av a2 s .co m @SuppressWarnings("unchecked") protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uploadId = null; String returnPage = null; final RequestContext requestContext = new ServletRequestContext(request); boolean isMultipart = ServletFileUpload.isMultipartContent(requestContext); try { AuthenticationStatus status = servletAuthenticate(request, response); if (status == AuthenticationStatus.Failure) { return; } if (!isMultipart) { throw new AlfrescoRuntimeException( "This servlet can only be used to handle file upload requests, make" + "sure you have set the enctype attribute on your form to multipart/form-data"); } if (logger.isDebugEnabled()) logger.debug("Uploading servlet servicing..."); FacesContext context = FacesContext.getCurrentInstance(); Map<Object, Object> session = context.getExternalContext().getSessionMap(); ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); // ensure that the encoding is handled correctly upload.setHeaderEncoding("UTF-8"); List<FileItem> fileItems = upload.parseRequest(request); FileUploadBean bean = new FileUploadBean(); for (FileItem item : fileItems) { if (item.isFormField()) { if (item.getFieldName().equalsIgnoreCase("return-page")) { returnPage = item.getString(); } else if (item.getFieldName().equalsIgnoreCase("upload-id")) { uploadId = item.getString(); } } else { String filename = item.getName(); if (filename != null && filename.length() != 0) { if (logger.isDebugEnabled()) { logger.debug("Processing uploaded file: " + filename); } // ADB-41: Ignore non-existent files i.e. 0 byte streams. if (allowZeroByteFiles() == true || item.getSize() > 0) { // 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 filename = FilenameUtils.getName(filename); final File tempFile = TempFileProvider.createTempFile("alfresco", ".upload"); item.write(tempFile); bean.setFile(tempFile); bean.setFileName(filename); bean.setFilePath(tempFile.getAbsolutePath()); if (logger.isDebugEnabled()) { logger.debug("Temp file: " + tempFile.getAbsolutePath() + " size " + tempFile.length() + " bytes created from upload filename: " + filename); } } else { if (logger.isWarnEnabled()) logger.warn("Ignored file '" + filename + "' as there was no content, this is either " + "caused by uploading an empty file or a file path that does not exist on the client."); } } } } session.put(FileUploadBean.getKey(uploadId), bean); if (bean.getFile() == null && uploadId != null && logger.isWarnEnabled()) { logger.warn("no file uploaded for upload id: " + uploadId); } if (returnPage == null || returnPage.length() == 0) { throw new AlfrescoRuntimeException("return-page parameter has not been supplied"); } JSONObject json; try { json = new JSONObject(returnPage); if (json.has("id") && json.has("args")) { // finally redirect if (logger.isDebugEnabled()) { logger.debug("Sending back javascript response " + returnPage); } response.setContentType(MimetypeMap.MIMETYPE_HTML); response.setCharacterEncoding("utf-8"); // work-around for WebKit protection against embedded javascript on POST body response response.setHeader("X-XSS-Protection", "0"); final PrintWriter out = response.getWriter(); out.println("<html><body><script type=\"text/javascript\">"); out.println("window.parent.upload_complete_helper("); out.println("'" + json.getString("id") + "'"); out.println(", "); out.println(json.getJSONObject("args")); out.println(");"); out.println("</script></body></html>"); out.close(); } } catch (JSONException e) { // finally redirect if (logger.isDebugEnabled()) logger.debug("redirecting to: " + returnPage); response.sendRedirect(returnPage); } if (logger.isDebugEnabled()) logger.debug("upload complete"); } catch (Throwable error) { handleUploadException(request, response, error, returnPage); } }
From source file:org.alfresco.web.bean.ajax.ContentUpdateBean.java
/** * Ajax method to update file content. A multi-part form is required as the input. * //from ww w . java 2 s. c om * "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); }
From source file:org.alfresco.web.bean.ajax.FileUploadBean.java
/** * Ajax method to upload file content. A multi-part form is required as the input. * //from www. j av a 2 s . c o m * "return-page" = javascript to execute on return from the upload request * "currentPath" = the cm:name based server path to upload the content into * and the file item content. * * @throws Exception */ @InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML) public void uploadFile() 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); FileUploadBean bean = new FileUploadBean(); String currentPath = null; String filename = null; String returnPage = null; File file = null; for (FileItem item : fileItems) { if (item.isFormField() && item.getFieldName().equals("return-page")) { returnPage = item.getString(); } else if (item.isFormField() && item.getFieldName().equals("currentPath")) { currentPath = URLDecoder.decode(item.getString()); } else { filename = FilenameUtils.getName(item.getName()); file = TempFileProvider.createTempFile("alfresco", ".upload"); item.write(file); } } if (logger.isDebugEnabled()) logger.debug("Ajax file upload request: " + filename + " to path: " + currentPath + " return page: " + returnPage); try { if (file != null && currentPath != null && currentPath.length() != 0) { NodeRef containerRef = pathToNodeRef(fc, currentPath); if (containerRef != null) { // Guess the mimetype String mimetype = Repository.getMimeTypeForFileName(fc, filename); // Now guess the encoding String encoding = "UTF-8"; InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); encoding = Repository.guessEncoding(fc, is, mimetype); } catch (Throwable e) { // Bad as it is, it's not terminal logger.error("Failed to guess character encoding of file: " + file, e); } finally { if (is != null) { try { is.close(); } catch (Throwable e) { } } } // Try and extract metadata from the file ContentReader cr = new FileContentReader(file); cr.setMimetype(mimetype); // create properties for content type String author = null; String title = null; String description = null; Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>(5, 1.0f); if (Repository.extractMetadata(fc, cr, contentProps)) { author = (String) (contentProps.get(ContentModel.PROP_AUTHOR)); title = DefaultTypeConverter.INSTANCE.convert(String.class, contentProps.get(ContentModel.PROP_TITLE)); description = DefaultTypeConverter.INSTANCE.convert(String.class, contentProps.get(ContentModel.PROP_DESCRIPTION)); } // default the title to the file name if not set if (title == null) { title = filename; } ServiceRegistry services = Repository.getServiceRegistry(fc); FileInfo fileInfo = services.getFileFolderService().create(containerRef, filename, ContentModel.TYPE_CONTENT); NodeRef fileNodeRef = fileInfo.getNodeRef(); // set the author aspect if (author != null) { Map<QName, Serializable> authorProps = new HashMap<QName, Serializable>(1, 1.0f); authorProps.put(ContentModel.PROP_AUTHOR, author); services.getNodeService().addAspect(fileNodeRef, ContentModel.ASPECT_AUTHOR, authorProps); } // apply the titled aspect - title and description Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>(2, 1.0f); titledProps.put(ContentModel.PROP_TITLE, title); titledProps.put(ContentModel.PROP_DESCRIPTION, description); services.getNodeService().addAspect(fileNodeRef, ContentModel.ASPECT_TITLED, titledProps); // get a writer for the content and put the file ContentWriter writer = services.getContentService().getWriter(fileNodeRef, ContentModel.PROP_CONTENT, true); writer.setMimetype(mimetype); writer.setEncoding(encoding); writer.putContent(file); } } } catch (Exception e) { returnPage = returnPage.replace("${UPLOAD_ERROR}", e.getMessage()); } finally { if (file != null) { logger.debug("delete temporary file:" + file.getPath()); // Delete the temporary file file.delete(); } } 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(returnPage); scriptEl.appendChild(scriptText); if (logger.isDebugEnabled()) { logger.debug("File upload request complete."); } ResponseWriter out = fc.getResponseWriter(); XMLUtil.print(result, out); }
From source file:org.alfresco.web.bean.wcm.FilePickerBean.java
@InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML) public void uploadFile() throws Exception { LOGGER.debug(this + ".uploadFile()"); final FacesContext facesContext = FacesContext.getCurrentInstance(); final ExternalContext externalContext = facesContext.getExternalContext(); final HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); final ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); upload.setHeaderEncoding("UTF-8"); final List<FileItem> fileItems = upload.parseRequest(request); final FileUploadBean bean = new FileUploadBean(); String uploadId = null;//from w w w .ja v a 2 s . co m String currentPath = null; String filename = null; String returnPage = null; InputStream fileInputStream = null; for (FileItem item : fileItems) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("item = " + item); } if (item.isFormField() && item.getFieldName().equals("upload-id")) { uploadId = item.getString(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("uploadId is " + uploadId); } } if (item.isFormField() && item.getFieldName().equals("return-page")) { returnPage = item.getString(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("returnPage is " + returnPage); } } else if (item.isFormField() && item.getFieldName().equals("currentPath")) { final String previewStorePath = AVMUtil .getCorrespondingPathInPreviewStore(this.getCurrentAVMPath()); currentPath = AVMUtil.buildPath(previewStorePath, item.getString(), AVMUtil.PathRelation.WEBAPP_RELATIVE); if (LOGGER.isDebugEnabled()) { LOGGER.debug("currentPath is " + currentPath); } } else { filename = FilenameUtils.getName(item.getName()); fileInputStream = item.getInputStream(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("uploading file " + filename); } } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("saving file " + filename + " to " + currentPath); } try { FileCopyUtils.copy(fileInputStream, this.getAvmService().createFile(currentPath, filename)); final Map<QName, PropertyValue> props = new HashMap<QName, PropertyValue>(1, 1.0f); props.put(ContentModel.PROP_TITLE, new PropertyValue(DataTypeDefinition.TEXT, filename)); // props.put(ContentModel.PROP_DESCRIPTION, // new PropertyValue(DataTypeDefinition.TEXT, // "Uploaded for form " + this.xformsSession.getForm().getName())); this.getAvmService().setNodeProperties(currentPath + "/" + filename, props); this.getAvmService().addAspect(currentPath + "/" + filename, ContentModel.ASPECT_TITLED); this.uploads.add(AVMNodeConverter.ToNodeRef(-1, currentPath + "/" + filename)); returnPage = returnPage.replace("${_FILE_TYPE_IMAGE}", org.alfresco.repo.web.scripts.FileTypeImageUtils .getFileTypeImage(facesContext, filename, true)); } catch (Exception e) { LOGGER.debug(e.getMessage(), e); returnPage = returnPage.replace("${_UPLOAD_ERROR}", e.getMessage()); } LOGGER.debug("upload complete. sending response: " + returnPage); final org.w3c.dom.Document result = XMLUtil.newDocument(); final org.w3c.dom.Element htmlEl = result.createElement("html"); result.appendChild(htmlEl); final org.w3c.dom.Element bodyEl = result.createElement("body"); htmlEl.appendChild(bodyEl); final org.w3c.dom.Element scriptEl = result.createElement("script"); bodyEl.appendChild(scriptEl); scriptEl.setAttribute("type", "text/javascript"); final org.w3c.dom.Node scriptText = result.createTextNode(returnPage); scriptEl.appendChild(scriptText); final ResponseWriter out = facesContext.getResponseWriter(); XMLUtil.print(result, out); }
From source file:org.apache.jackrabbit.server.util.HttpMultipartPost.java
/** * //from www .j a v a2s .com * @param request * @param tmpDir * @throws IOException */ private void extractMultipart(HttpServletRequest request, File tmpDir) throws IOException { if (!ServletFileUpload.isMultipartContent(request)) { log.debug("Request does not contain multipart content -> ignoring."); return; } ServletFileUpload upload = new ServletFileUpload(getFileItemFactory(tmpDir)); // make sure the content disposition headers are read with the charset // specified in the request content type (or UTF-8 if no charset is specified). // see JCR if (request.getCharacterEncoding() == null) { upload.setHeaderEncoding("UTF-8"); } try { @SuppressWarnings("unchecked") List<FileItem> fileItems = upload.parseRequest(request); for (FileItem fileItem : fileItems) { addItem(fileItem); } } catch (FileUploadException e) { log.error("Error while processing multipart.", e); throw new IOException(e.toString()); } }
From source file:org.apache.ofbiz.webapp.event.ServiceEventHandler.java
/** * @see org.apache.ofbiz.webapp.event.EventHandler#invoke(ConfigXMLReader.Event, ConfigXMLReader.RequestMap, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//*from www . j a v a 2 s . co m*/ public String invoke(Event event, RequestMap requestMap, HttpServletRequest request, HttpServletResponse response) throws EventHandlerException { // make sure we have a valid reference to the Service Engine LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); if (dispatcher == null) { throw new EventHandlerException("The local service dispatcher is null"); } DispatchContext dctx = dispatcher.getDispatchContext(); if (dctx == null) { throw new EventHandlerException("Dispatch context cannot be found"); } // get the details for the service(s) to call String mode = SYNC; String serviceName = null; if (UtilValidate.isEmpty(event.path)) { mode = SYNC; } else { mode = event.path; } // make sure we have a defined service to call serviceName = event.invoke; if (serviceName == null) { throw new EventHandlerException("Service name (eventMethod) cannot be null"); } if (Debug.verboseOn()) Debug.logVerbose("[Set mode/service]: " + mode + "/" + serviceName, module); // some needed info for when running the service Locale locale = UtilHttp.getLocale(request); TimeZone timeZone = UtilHttp.getTimeZone(request); HttpSession session = request.getSession(); GenericValue userLogin = (GenericValue) session.getAttribute("userLogin"); // get the service model to generate context ModelService model = null; try { model = dctx.getModelService(serviceName); } catch (GenericServiceException e) { throw new EventHandlerException("Problems getting the service model", e); } if (model == null) { throw new EventHandlerException("Problems getting the service model"); } if (Debug.verboseOn()) { Debug.logVerbose("[Processing]: SERVICE Event", module); Debug.logVerbose("[Using delegator]: " + dispatcher.getDelegator().getDelegatorName(), module); } boolean isMultiPart = ServletFileUpload.isMultipartContent(request); Map<String, Object> multiPartMap = new HashMap<String, Object>(); if (isMultiPart) { // get the http upload configuration String maxSizeStr = EntityUtilProperties.getPropertyValue("general", "http.upload.max.size", "-1", dctx.getDelegator()); long maxUploadSize = -1; try { maxUploadSize = Long.parseLong(maxSizeStr); } catch (NumberFormatException e) { Debug.logError(e, "Unable to obtain the max upload size from general.properties; using default -1", module); maxUploadSize = -1; } // get the http size threshold configuration - files bigger than this will be // temporarly stored on disk during upload String sizeThresholdStr = EntityUtilProperties.getPropertyValue("general", "http.upload.max.sizethreshold", "10240", dctx.getDelegator()); int sizeThreshold = 10240; // 10K try { sizeThreshold = Integer.parseInt(sizeThresholdStr); } catch (NumberFormatException e) { Debug.logError(e, "Unable to obtain the threshold size from general.properties; using default 10K", module); sizeThreshold = -1; } // directory used to temporarily store files that are larger than the configured size threshold String tmpUploadRepository = EntityUtilProperties.getPropertyValue("general", "http.upload.tmprepository", "runtime/tmp", dctx.getDelegator()); String encoding = request.getCharacterEncoding(); // check for multipart content types which may have uploaded items ServletFileUpload upload = new ServletFileUpload( new DiskFileItemFactory(sizeThreshold, new File(tmpUploadRepository))); // create the progress listener and add it to the session FileUploadProgressListener listener = new FileUploadProgressListener(); upload.setProgressListener(listener); session.setAttribute("uploadProgressListener", listener); if (encoding != null) { upload.setHeaderEncoding(encoding); } upload.setSizeMax(maxUploadSize); List<FileItem> uploadedItems = null; try { uploadedItems = UtilGenerics.<FileItem>checkList(upload.parseRequest(request)); } catch (FileUploadException e) { throw new EventHandlerException("Problems reading uploaded data", e); } if (uploadedItems != null) { for (FileItem item : uploadedItems) { String fieldName = item.getFieldName(); //byte[] itemBytes = item.get(); /* Debug.logInfo("Item Info [" + fieldName + "] : " + item.getName() + " / " + item.getSize() + " / " + item.getContentType() + " FF: " + item.isFormField(), module); */ if (item.isFormField() || item.getName() == null) { if (multiPartMap.containsKey(fieldName)) { Object mapValue = multiPartMap.get(fieldName); if (mapValue instanceof List<?>) { checkList(mapValue, Object.class).add(item.getString()); } else if (mapValue instanceof String) { List<String> newList = new LinkedList<String>(); newList.add((String) mapValue); newList.add(item.getString()); multiPartMap.put(fieldName, newList); } else { Debug.logWarning("Form field found [" + fieldName + "] which was not handled!", module); } } else { if (encoding != null) { try { multiPartMap.put(fieldName, item.getString(encoding)); } catch (java.io.UnsupportedEncodingException uee) { Debug.logError(uee, "Unsupported Encoding, using deafault", module); multiPartMap.put(fieldName, item.getString()); } } else { multiPartMap.put(fieldName, item.getString()); } } } else { String fileName = item.getName(); if (fileName.indexOf('\\') > -1 || fileName.indexOf('/') > -1) { // get just the file name IE and other browsers also pass in the local path int lastIndex = fileName.lastIndexOf('\\'); if (lastIndex == -1) { lastIndex = fileName.lastIndexOf('/'); } if (lastIndex > -1) { fileName = fileName.substring(lastIndex + 1); } } multiPartMap.put(fieldName, ByteBuffer.wrap(item.get())); multiPartMap.put("_" + fieldName + "_size", Long.valueOf(item.getSize())); multiPartMap.put("_" + fieldName + "_fileName", fileName); multiPartMap.put("_" + fieldName + "_contentType", item.getContentType()); } } } } // store the multi-part map as an attribute so we can access the parameters request.setAttribute("multiPartMap", multiPartMap); Map<String, Object> rawParametersMap = UtilHttp.getCombinedMap(request); Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet(); // we have a service and the model; build the context Map<String, Object> serviceContext = new HashMap<String, Object>(); for (ModelParam modelParam : model.getInModelParamList()) { String name = modelParam.name; // don't include userLogin, that's taken care of below if ("userLogin".equals(name)) continue; // don't include locale, that is also taken care of below if ("locale".equals(name)) continue; // don't include timeZone, that is also taken care of below if ("timeZone".equals(name)) continue; Object value = null; if (UtilValidate.isNotEmpty(modelParam.stringMapPrefix)) { Map<String, Object> paramMap = UtilHttp.makeParamMapWithPrefix(request, multiPartMap, modelParam.stringMapPrefix, null); value = paramMap; if (Debug.verboseOn()) Debug.logVerbose("Set [" + modelParam.name + "]: " + paramMap, module); } else if (UtilValidate.isNotEmpty(modelParam.stringListSuffix)) { List<Object> paramList = UtilHttp.makeParamListWithSuffix(request, multiPartMap, modelParam.stringListSuffix, null); value = paramList; } else { // first check the multi-part map value = multiPartMap.get(name); // next check attributes; do this before parameters so that attribute which can be changed by code can override parameters which can't if (UtilValidate.isEmpty(value)) { Object tempVal = request .getAttribute(UtilValidate.isEmpty(modelParam.requestAttributeName) ? name : modelParam.requestAttributeName); if (tempVal != null) { value = tempVal; } } // check the request parameters if (UtilValidate.isEmpty(value)) { ServiceEventHandler.checkSecureParameter(requestMap, urlOnlyParameterNames, name, session, serviceName, dctx.getDelegator()); // if the service modelParam has allow-html="any" then get this direct from the request instead of in the parameters Map so there will be no canonicalization possibly messing things up if ("any".equals(modelParam.allowHtml)) { value = request.getParameter(name); } else { // use the rawParametersMap from UtilHttp in order to also get pathInfo parameters, do canonicalization, etc value = rawParametersMap.get(name); } // make any composite parameter data (e.g., from a set of parameters {name_c_date, name_c_hour, name_c_minutes}) if (value == null) { value = UtilHttp.makeParamValueFromComposite(request, name, locale); } } // then session if (UtilValidate.isEmpty(value)) { Object tempVal = request.getSession() .getAttribute(UtilValidate.isEmpty(modelParam.sessionAttributeName) ? name : modelParam.sessionAttributeName); if (tempVal != null) { value = tempVal; } } // no field found if (value == null) { //still null, give up for this one continue; } if (value instanceof String && ((String) value).length() == 0) { // interpreting empty fields as null values for each in back end handling... value = null; } } // set even if null so that values will get nulled in the db later on serviceContext.put(name, value); } // get only the parameters for this service - converted to proper type // TODO: pass in a list for error messages, like could not convert type or not a proper X, return immediately with messages if there are any List<Object> errorMessages = new LinkedList<Object>(); serviceContext = model.makeValid(serviceContext, ModelService.IN_PARAM, true, errorMessages, timeZone, locale); if (errorMessages.size() > 0) { // uh-oh, had some problems... request.setAttribute("_ERROR_MESSAGE_LIST_", errorMessages); return "error"; } // include the UserLogin value object if (userLogin != null) { serviceContext.put("userLogin", userLogin); } // include the Locale object if (locale != null) { serviceContext.put("locale", locale); } // include the TimeZone object if (timeZone != null) { serviceContext.put("timeZone", timeZone); } // invoke the service Map<String, Object> result = null; try { if (ASYNC.equalsIgnoreCase(mode)) { dispatcher.runAsync(serviceName, serviceContext); } else { result = dispatcher.runSync(serviceName, serviceContext); } } catch (ServiceAuthException e) { // not logging since the service engine already did request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage()); return "error"; } catch (ServiceValidationException e) { // not logging since the service engine already did request.setAttribute("serviceValidationException", e); if (e.getMessageList() != null) { request.setAttribute("_ERROR_MESSAGE_LIST_", e.getMessageList()); } else { request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage()); } return "error"; } catch (GenericServiceException e) { Debug.logError(e, "Service invocation error", module); throw new EventHandlerException("Service invocation error", e.getNested()); } String responseString = null; if (result == null) { responseString = ModelService.RESPOND_SUCCESS; } else { if (!result.containsKey(ModelService.RESPONSE_MESSAGE)) { responseString = ModelService.RESPOND_SUCCESS; } else { responseString = (String) result.get(ModelService.RESPONSE_MESSAGE); } // set the messages in the request; this will be picked up by messages.ftl and displayed request.setAttribute("_ERROR_MESSAGE_LIST_", result.get(ModelService.ERROR_MESSAGE_LIST)); request.setAttribute("_ERROR_MESSAGE_MAP_", result.get(ModelService.ERROR_MESSAGE_MAP)); request.setAttribute("_ERROR_MESSAGE_", result.get(ModelService.ERROR_MESSAGE)); request.setAttribute("_EVENT_MESSAGE_LIST_", result.get(ModelService.SUCCESS_MESSAGE_LIST)); request.setAttribute("_EVENT_MESSAGE_", result.get(ModelService.SUCCESS_MESSAGE)); // set the results in the request for (Map.Entry<String, Object> rme : result.entrySet()) { String resultKey = rme.getKey(); Object resultValue = rme.getValue(); if (resultKey != null && !ModelService.RESPONSE_MESSAGE.equals(resultKey) && !ModelService.ERROR_MESSAGE.equals(resultKey) && !ModelService.ERROR_MESSAGE_LIST.equals(resultKey) && !ModelService.ERROR_MESSAGE_MAP.equals(resultKey) && !ModelService.SUCCESS_MESSAGE.equals(resultKey) && !ModelService.SUCCESS_MESSAGE_LIST.equals(resultKey)) { request.setAttribute(resultKey, resultValue); } } } if (Debug.verboseOn()) Debug.logVerbose("[Event Return]: " + responseString, module); return responseString; }
From source file:org.apache.wicket.protocol.http.servlet.MultipartServletWebRequestImpl.java
/** * Factory method for creating new instances of FileUploadBase * * @param encoding// w ww . ja va 2 s .c o m * The encoding to use while reading the data * @return A new instance of FileUploadBase */ protected FileUploadBase newFileUpload(String encoding) { // Configure the factory here, if desired. ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory); // set encoding specifically when we found it if (encoding != null) { fileUpload.setHeaderEncoding(encoding); } fileUpload.setSizeMax(getMaxSize().bytes()); Bytes fileMaxSize = getFileMaxSize(); if (fileMaxSize != null) { fileUpload.setFileSizeMax(fileMaxSize.bytes()); } return fileUpload; }
From source file:org.azkfw.web.purser.HttpServletMultipartPurser.java
@Override protected Map<String, Object> doPurse(final HttpServletRequest aReq, final HttpServletResponse aRes) throws WebServiceException { Map<String, Object> parameter = new HashMap<String, Object>(); if (ServletFileUpload.isMultipartContent(aReq)) { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); factory.setSizeThreshold(1024);/*from w ww . ja va 2s . co m*/ upload.setSizeMax(-1); upload.setHeaderEncoding(encoding); try { List<FileItem> list = upload.parseRequest(aReq); Iterator<FileItem> iterator = list.iterator(); while (iterator.hasNext()) { FileItem fItem = (FileItem) iterator.next(); if (fItem.isFormField()) { parameter.put(fItem.getFieldName(), fItem.getString(encoding)); } else { String fileName = fItem.getName(); if ((fileName != null) && (!fileName.equals(""))) { fileName = (new File(fileName)).getName(); String filePath = PathUtility.cat(temporaryDirectory, fileName); File file = new File(filePath); fItem.write(file); parameter.put(fItem.getFieldName(), file); } } } } catch (FileUploadException ex) { throw new WebServiceException(ex); } catch (Exception ex) { throw new WebServiceException(ex); } } else { for (String key : (Set<String>) aReq.getParameterMap().keySet()) { String[] values = aReq.getParameterValues(key); if (1 == values.length) { parameter.put(key, values[0]); } else { parameter.put(key, values); } } } return parameter; }
From source file:org.codelabor.system.file.web.controller.xplatform.FileController.java
@RequestMapping("/upload-test") public String upload(Model model, HttpServletRequest request, ServletContext context) throws Exception { logger.debug("upload-teset"); DataSetList outputDataSetList = new DataSetList(); VariableList outputVariableList = new VariableList(); try {/*from ww w.j a va2s .co m*/ boolean isMultipart = ServletFileUpload.isMultipartContent(request); Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug("paramMap: {}", paramMap.toString()); String mapId = (String) paramMap.get("mapId"); RepositoryType acceptedRepositoryType = repositoryType; String requestedRepositoryType = (String) paramMap.get("repositoryType"); if (StringUtils.isNotEmpty(requestedRepositoryType)) { acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType); } if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(sizeThreshold); factory.setRepository(new File(tempRepositoryPath)); factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(context)); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(fileSizeMax); upload.setSizeMax(requestSizeMax); upload.setHeaderEncoding(characterEncoding); upload.setProgressListener(new FileUploadProgressListener()); List<FileItem> fileItemList = upload.parseRequest(request); Iterator<FileItem> iter = fileItemList.iterator(); while (iter.hasNext()) { FileItem fileItem = iter.next(); logger.debug("fileItem: {}", fileItem.toString()); FileDTO fileDTO = null; if (fileItem.isFormField()) { paramMap.put(fileItem.getFieldName(), fileItem.getString(characterEncoding)); } else { if (fileItem.getName() == null || fileItem.getName().length() == 0) continue; // set DTO fileDTO = new FileDTO(); fileDTO.setMapId(mapId); fileDTO.setRealFilename(FilenameUtils.getName(fileItem.getName())); if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) { fileDTO.setUniqueFilename(uniqueFilenameGenerationService.getNextStringId()); } fileDTO.setContentType(fileItem.getContentType()); fileDTO.setRepositoryPath(realRepositoryPath); logger.debug("fileDTO: {}", fileDTO.toString()); UploadUtils.processFile(acceptedRepositoryType, fileItem.getInputStream(), fileDTO); } if (fileDTO != null) fileManager.insertFile(fileDTO); } } else { } XplatformUtils.setSuccessMessage( messageSource.getMessage("info.success", new Object[] {}, forcedLocale), outputVariableList); logger.debug("success"); } catch (Exception e) { logger.error("fail"); e.printStackTrace(); logger.error(e.getMessage()); throw new XplatformException(messageSource.getMessage("error.failure", new Object[] {}, forcedLocale), e); } model.addAttribute(OUTPUT_DATA_SET_LIST, outputDataSetList); model.addAttribute(OUTPUT_VARIABLE_LIST, outputVariableList); return VIEW_NAME; }