List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setHeaderEncoding
public void setHeaderEncoding(String encoding)
From source file:org.mycore.frontend.editor.MCRRequestParameters.java
public MCRRequestParameters(HttpServletRequest req) { if (ServletFileUpload.isMultipartContent(req)) { ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxSize);//w w w .ja v a 2 s . c o m upload.setHeaderEncoding("UTF-8"); List<FileItem> items = null; try { items = upload.parseRequest(req); } catch (FileUploadException ex) { String msg = "Error while parsing http multipart/form-data request from file upload webpage"; throw new MCRException(msg, ex); } for (Object item1 : items) { FileItem item = (FileItem) item1; String name = item.getFieldName(); String value = null; if (item.isFormField()) { try { value = item.getString("UTF-8"); } catch (UnsupportedEncodingException ex) { throw new MCRConfigurationException("UTF-8 is unsupported encoding !?", ex); } } else { value = item.getName(); } if (!item.isFormField()) filelist.add(item); if (value != null && value.trim().length() > 0 && !files.containsKey(name)) { if (!item.isFormField()) { files.put(name, item); } String[] values = new String[1]; values[0] = value; parameters.put(name, values); } } } else { for (Enumeration<String> e = req.getParameterNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); String[] values = req.getParameterValues(name); if (values != null && values.length > 0) { parameters.put(name, values); } } } }
From source file:org.ofbiz.webapp.event.RestEventHandler.java
/** * @see org.ofbiz.webapp.event.EventHandler#invoke(ConfigXMLReader.Event, ConfigXMLReader.RequestMap, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */// w w w.ja va 2 s .c o m public String invoke(Event event, RequestMap requestMap, HttpServletRequest request, HttpServletResponse response) throws EventHandlerException { LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); Delegator delegator = (GenericDelegator) request.getAttribute("delegator"); DispatchContext dctx = dispatcher.getDispatchContext(); HttpSession session = request.getSession(); Map<String, Object> serviceContext = FastMap.newInstance(); Map<String, Object> parameterMap = null; List uploadedFileList = new ArrayList(); String method = request.getMethod(); if ("POST".equals(method) || "PUT".equals(method)) { // get the service name and parameters BufferedReader reader = null; StringBuilder buf = new StringBuilder(); boolean isMultiPart = ServletFileUpload.isMultipartContent(request); try { Map<String, Object> multiPartMap = new HashMap<String, Object>(); if (isMultiPart) { // get the http upload configuration String maxSizeStr = EntityUtilProperties.getPropertyValue("general.properties", "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.properties", "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.properties", "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(); 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 { Map<String, Object> uploadedMap = FastMap.newInstance(); 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); } } uploadedMap.put("uploadedFile", ByteBuffer.wrap(item.get())); uploadedMap.put("_uploadedFile_size", Long.valueOf(item.getSize())); uploadedMap.put("_uploadedFile_fileName", fileName); uploadedMap.put("_uploadedFile_contentType", item.getContentType()); uploadedFileList.add(uploadedMap); } } } request.setAttribute("multiPartMap", multiPartMap); Map<String, Object> rawParametersMap = UtilHttp.getParameterMap(request, null, null); Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet(); Map<String, Object> requestBodyMap = null; try { requestBodyMap = RequestBodyMapHandlerFactory.extractMapFromRequestBody(request); } catch (IOException ioe) { Debug.logWarning(ioe, module); } if (requestBodyMap != null) { rawParametersMap.putAll(requestBodyMap); } } else { // parameterMap = requestByMap(request, response); // read the inputstream buffer String line; // reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8")); reader = new BufferedReader(new InputStreamReader(request.getInputStream())); while ((line = reader.readLine()) != null) { buf.append(line).append("\n"); } } } catch (Exception e) { throw new EventHandlerException(e.getMessage(), e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { throw new EventHandlerException(e.getMessage(), e); } } } Debug.logInfo("json: " + buf.toString(), module); Map<String, Object> rawParametersMap = UtilHttp.getParameterMap(request, null, null); serviceContext.putAll(rawParametersMap); if (UtilValidate.isNotEmpty(rawParametersMap)) { serviceContext.putAll(rawParametersMap); } else if (buf.toString().length() > 0) { JSONObject json = JSONObject.fromObject(buf.toString()); serviceContext.putAll(json); } } if ("GET".equals(method) || "DELETE".equals(method)) { Map<String, Object> rawParametersMap = UtilHttp.getParameterMap(request, null, null); serviceContext.putAll(rawParametersMap); } String serviceName = getOverrideViewUri(request.getPathInfo()); String restIdValue = ""; List<String> pathItemList = StringUtil.split(serviceName, "/"); if (pathItemList.size() > 1) { serviceName = pathItemList.get(0); restIdValue = pathItemList.get(1); } Debug.log("serviceName:\n" + serviceName + "\n", module); GenericValue userLogin = null; try { ModelService model = dctx.getModelService(serviceName); if (model == null) { sendError(response, "Problem processing the service", serviceName); Debug.logError("Could not find Service [" + serviceName + "].", module); return null; } // if (!model.export) { // sendError(response, "Problem processing the service", serviceName); // Debug.logError("Trying to call Service [" + serviceName + "] that is not exported.", module); // return null; // } if (model.auth) { String username = request.getHeader("USERNAME"); String password = request.getHeader("PASSWORD"); if (UtilValidate.isNotEmpty(username) && UtilValidate.isNotEmpty(password)) { serviceContext.remove("USERNAME"); serviceContext.remove("PASSWORD"); } else { username = request.getParameter("USERNAME"); password = request.getParameter("PASSWORD"); } // GenericValue yuemeiUser = delegator.findOne("YuemeiUser", UtilMisc.toMap("userLoginId", username), true); // if(UtilValidate.isNotEmpty(yuemeiUser)){ // String tenantId = yuemeiUser.getString("tenantId"); // if(UtilValidate.isNotEmpty(tenantId)){ // delegator = DelegatorFactory.getDelegator(delegator.getDelegatorBaseName() + "#" + tenantId); // dispatcher = GenericDispatcher.getLocalDispatcher(dispatcher.getName(), delegator); // } // } Map<String, Object> loginResult = dispatcher.runSync("userLogin", UtilMisc.toMap("login.username", username, "login.password", password));//, "locale", Locale.CHINESE Debug.log(loginResult.toString(), module); if (ServiceUtil.isSuccess(loginResult)) { userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", username), false); } if (UtilValidate.isEmpty(userLogin)) { sendError(response, "Problem processing the service, check your USERNAME and PASSWORD.", "serviceName"); } } Locale locale = UtilHttp.getLocale(request); TimeZone timeZone = UtilHttp.getTimeZone(request); // 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 = FastList.newInstance(); // serviceContext = model.makeValid(serviceContext, ModelService.IN_PARAM, true, errorMessages, timeZone, locale); if (errorMessages.size() > 0) { sendError(response, "Problem processing the serviceContext Valid," + errorMessages, serviceName); } // 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); } if (UtilValidate.isNotEmpty(model.defaultEntityName)) { ModelEntity modelEntity = delegator.getModelEntity(model.defaultEntityName); if (UtilValidate.isNotEmpty(restIdValue) && modelEntity.getPksSize() == 1) { String pkFieldName = modelEntity.getPkFieldNames().get(0); serviceContext.put(pkFieldName, restIdValue); } } } catch (GenericServiceException e) { Debug.logError(e.getMessage(), module); sendError(response, "Problem processing the service, check ." + e.getMessage(), serviceName); } catch (GenericEntityException e) { Debug.logError(e.getMessage(), module); sendError(response, "Problem processing the service, check your ." + e.getMessage(), serviceName); } //response.setContentType("text/xml"); response.setContentType("application/json"); Debug.logVerbose("[Processing]: REST Event", module); try { if (UtilValidate.isNotEmpty(uploadedFileList)) serviceContext.put("uploadedFileList", uploadedFileList); if (UtilValidate.isNotEmpty(serviceName) && !"updateOutsideExperts".equals(serviceName) && !"saveTgAndItemAndDse".equals(serviceName) && !"getMyFriends".equals(serviceName)) { serviceContext.remove("json"); } Map<String, Object> serviceResults = dispatcher.runSync(serviceName, serviceContext); Debug.logVerbose("[EventHandler] : Service invoked", module); createAndSendRESTResponse(serviceResults, serviceName, response); } catch (GenericServiceException e) { if (e.getMessageList() == null) { sendError(response, e.getMessage(), serviceName); } else { sendError(response, e.getMessageList(), serviceName); } Debug.logError(e, module); return null; } return null; }
From source file:org.ofbiz.webapp.event.RestEventHandler.java
private Map getServiceContext(HttpServletRequest request, DispatchContext dctx, ModelService model, Locale locale) throws EventHandlerException { // get the http upload configuration String maxSizeStr = EntityUtilProperties.getPropertyValue("general.properties", "http.upload.max.size", "-1", dctx.getDelegator()); long maxUploadSize = -1; try {// w w w. ja v a 2s . c o m 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.properties", "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.properties", "http.upload.tmprepository", "runtime/tmp", dctx.getDelegator()); String encoding = request.getCharacterEncoding(); // check for multipart content types which may have uploaded items boolean isMultiPart = ServletFileUpload.isMultipartContent(request); Map<String, Object> multiPartMap = FastMap.newInstance(); if (isMultiPart) { 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 = FastList.newInstance(); 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.getParameterMap(request, null, null); Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet(); // we have a service and the model; build the context Map<String, Object> serviceContext = FastMap.newInstance(); 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(name); 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(name); // 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); } return serviceContext; }
From source file:org.ofbiz.webapp.event.ServiceEventHandler.java
/** * @see org.ofbiz.webapp.event.EventHandler#invoke(ConfigXMLReader.Event, ConfigXMLReader.RequestMap, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//*from ww w . j a v a2 s.com*/ 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.properties", "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.properties", "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.properties", "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.getParameterMap(request, null, null); Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet(); Map<String, Object> requestBodyMap = null; try { requestBodyMap = RequestBodyMapHandlerFactory.extractMapFromRequestBody(request); } catch (IOException ioe) { Debug.logWarning(ioe, module); } if (requestBodyMap != null) { rawParametersMap.putAll(requestBodyMap); } // 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); if (("Y").equals(request.getParameter("json"))) { JSONObject json = JSONObject.fromObject(result); String jsonStr = json.toString(); Debug.log(jsonStr); if (jsonStr == null) { // Debug.logError("JSON Object was empty; fatal error!", // module); } // set the X-JSON content type response.setContentType("textml"); // jsonStr.length is not reliable for unicode characters try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-type", "text/html;charset=UTF-8"); response.setContentLength(jsonStr.getBytes("UTF8").length); } catch (UnsupportedEncodingException e) { // Debug.logError("Problems with Json encoding"); } // return the JSON String Writer out; try { out = response.getWriter(); out.write(jsonStr); out.flush(); } catch (IOException e) { // Debug.logError("Unable to get response writer", // module); } return null; } else { return responseString; } }
From source file:org.opencms.ade.upload.CmsUploadBean.java
/** * Parses a request of the form <code>multipart/form-data</code>.<p> * // ww w . ja v a2 s . c o m * The result list will contain items of type <code>{@link FileItem}</code>. * If the request has no file items, then <code>null</code> is returned.<p> * * @param listener the upload listener * * @return the list of <code>{@link FileItem}</code> extracted from the multipart request, * or <code>null</code> if the request has no file items * * @throws Exception if anything goes wrong */ private List<FileItem> readMultipartFileItems(CmsUploadListener listener) throws Exception { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(4096); // the location for saving data that is larger than the threshold factory.setRepository(new File(OpenCms.getSystemInfo().getPackagesRfsPath())); // create a file upload servlet ServletFileUpload fu = new ServletFileUpload(factory); // set the listener fu.setProgressListener(listener); // set encoding to correctly handle special chars (e.g. in filenames) fu.setHeaderEncoding(getRequest().getCharacterEncoding()); // set the maximum size for a single file (value is in bytes) long maxFileSizeBytes = OpenCms.getWorkplaceManager().getFileBytesMaxUploadSize(getCmsObject()); if (maxFileSizeBytes > 0) { fu.setFileSizeMax(maxFileSizeBytes); } // try to parse the request try { return CmsCollectionsGenericWrapper.list(fu.parseRequest(getRequest())); } catch (SizeLimitExceededException e) { // request size is larger than maximum allowed request size, throw an error Integer actualSize = new Integer((int) (e.getActualSize() / 1024)); Integer maxSize = new Integer((int) (e.getPermittedSize() / 1024)); throw new CmsUploadException(m_bundle .key(org.opencms.ade.upload.Messages.ERR_UPLOAD_REQUEST_SIZE_LIMIT_2, actualSize, maxSize), e); } catch (FileSizeLimitExceededException e) { // file size is larger than maximum allowed file size, throw an error Integer actualSize = new Integer((int) (e.getActualSize() / 1024)); Integer maxSize = new Integer((int) (e.getPermittedSize() / 1024)); throw new CmsUploadException(m_bundle.key(org.opencms.ade.upload.Messages.ERR_UPLOAD_FILE_SIZE_LIMIT_3, actualSize, e.getFileName(), maxSize), e); } }
From source file:org.opencms.util.CmsRequestUtil.java
/** * Parses a request of the form <code>multipart/form-data</code>. * /*from ww w .jav a 2 s . c om*/ * The result list will contain items of type <code>{@link FileItem}</code>. * If the request is not of type <code>multipart/form-data</code>, then <code>null</code> is returned.<p> * * @param request the HTTP servlet request to parse * * @return the list of <code>{@link FileItem}</code> extracted from the multipart request, * or <code>null</code> if the request was not of type <code>multipart/form-data</code> */ public static List<FileItem> readMultipartFileItems(HttpServletRequest request) { if (!ServletFileUpload.isMultipartContent(request)) { return null; } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(4096); // the location for saving data that is larger than getSizeThreshold() factory.setRepository(new File(OpenCms.getSystemInfo().getPackagesRfsPath())); ServletFileUpload fu = new ServletFileUpload(factory); // set encoding to correctly handle special chars (e.g. in filenames) fu.setHeaderEncoding(request.getCharacterEncoding()); List<FileItem> result = new ArrayList<FileItem>(); try { List<FileItem> items = CmsCollectionsGenericWrapper.list(fu.parseRequest(request)); if (items != null) { result = items; } } catch (FileUploadException e) { LOG.error(Messages.get().getBundle().key(Messages.LOG_PARSE_MULIPART_REQ_FAILED_0), e); } return result; }
From source file:org.sakaiproject.util.RequestFilter.java
/** * if the filter is configured to parse file uploads, AND the request is multipart (typically a file upload), then parse the * request.//from w w w . j a va2 s . co m * * @return If there is a file upload, and the filter handles it, return the wrapped request that has the results of the parsed * file upload. Parses the files using Apache commons-fileuplaod. Exposes the results through a wrapped request. Files * are available like: fileItem = (FileItem) request.getAttribute("myHtmlFileUploadId"); */ protected HttpServletRequest handleFileUpload(HttpServletRequest req, HttpServletResponse resp, List<FileItem> tempFiles) throws ServletException, UnsupportedEncodingException { if (!m_uploadEnabled || !ServletFileUpload.isMultipartContent(req) || req.getAttribute(ATTR_UPLOADS_DONE) != null) { return req; } // mark that the uploads have been parsed, so they aren't parsed again on this request req.setAttribute(ATTR_UPLOADS_DONE, ATTR_UPLOADS_DONE); // Result - map that will be created of request parameters, // parsed parameters, and uploaded files Map map = new HashMap(); // parse using commons-fileupload // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // set the factory parameters: the temp dir and the keep-in-memory-if-smaller threshold if (m_uploadTempDir != null) factory.setRepository(new File(m_uploadTempDir)); if (m_uploadThreshold > 0) factory.setSizeThreshold(m_uploadThreshold); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // set the encoding String encoding = req.getCharacterEncoding(); if (encoding != null && encoding.length() > 0) upload.setHeaderEncoding(encoding); // set the max upload size long uploadMax = -1; if (m_uploadMaxSize > 0) uploadMax = m_uploadMaxSize; // check for request-scoped override to upload.max (value in megs) String override = req.getParameter(CONFIG_UPLOAD_MAX); if (override != null) { try { // get the max in bytes uploadMax = Long.parseLong(override) * 1024L * 1024L; } catch (NumberFormatException e) { M_log.warn(CONFIG_UPLOAD_MAX + " set to non-numeric: " + override); } } // limit to the ceiling if (uploadMax > m_uploadCeiling) { /** * KNL-602 This is the expected behaviour of the request filter honouring the globaly configured * value -DH */ M_log.debug("Upload size exceeds ceiling: " + ((uploadMax / 1024L) / 1024L) + " > " + ((m_uploadCeiling / 1024L) / 1024L) + " megs"); uploadMax = m_uploadCeiling; } // to let commons-fileupload throw the exception on over-max, and also halt full processing of input fields if (!m_uploadContinue) { // TODO: when we switch to commons-fileupload 1.2 // // either per file or overall request, as configured // if (m_uploadMaxPerFile) // { // upload.setFileSizeMax(uploadMax); // } // else // { // upload.setSizeMax(uploadMax); // } upload.setSizeMax(uploadMax); } try { // parse multipart encoded parameters boolean uploadOk = true; List list = upload.parseRequest(req); for (int i = 0; i < list.size(); i++) { FileItem item = (FileItem) list.get(i); if (item.isFormField()) { String str = item.getString(encoding); Object obj = map.get(item.getFieldName()); if (obj == null) { map.put(item.getFieldName(), new String[] { str }); } else if (obj instanceof String[]) { String[] old_vals = (String[]) obj; String[] values = new String[old_vals.length + 1]; for (int i1 = 0; i1 < old_vals.length; i1++) { values[i1] = old_vals[i1]; } values[values.length - 1] = str; map.put(item.getFieldName(), values); } else if (obj instanceof String) { String[] values = new String[2]; values[0] = (String) obj; values[1] = str; map.put(item.getFieldName(), values); } } else { // collect it for delete at the end of the request tempFiles.add(item); // check the max, unless we are letting commons-fileupload throw exception on max exceeded // Note: the continue option assumes the max is per-file, not overall. if (m_uploadContinue && (item.getSize() > uploadMax)) { uploadOk = false; M_log.info("Upload size limit exceeded: " + ((uploadMax / 1024L) / 1024L)); req.setAttribute("upload.status", "size_limit_exceeded"); // TODO: for 1.2 commons-fileupload, switch this to a FileSizeLimitExceededException req.setAttribute("upload.exception", new FileUploadBase.SizeLimitExceededException("", item.getSize(), uploadMax)); req.setAttribute("upload.limit", Long.valueOf((uploadMax / 1024L) / 1024L)); } else { req.setAttribute(item.getFieldName(), item); } } } // unless we had an upload file that exceeded max, set the upload status to "ok" if (uploadOk) { req.setAttribute("upload.status", "ok"); } } catch (FileUploadBase.SizeLimitExceededException ex) { M_log.info("Upload size limit exceeded: " + ((upload.getSizeMax() / 1024L) / 1024L)); // DON'T throw an exception, instead note the exception // so that the tool down-the-line can handle the problem req.setAttribute("upload.status", "size_limit_exceeded"); req.setAttribute("upload.exception", ex); req.setAttribute("upload.limit", Long.valueOf((upload.getSizeMax() / 1024L) / 1024L)); } // TODO: put in for commons-fileupload 1.2 // catch (FileUploadBase.FileSizeLimitExceededException ex) // { // M_log.info("Upload size limit exceeded: " + ((upload.getFileSizeMax() / 1024L) / 1024L)); // // // DON'T throw an exception, instead note the exception // // so that the tool down-the-line can handle the problem // req.setAttribute("upload.status", "size_limit_exceeded"); // req.setAttribute("upload.exception", ex); // req.setAttribute("upload.limit", new Long((upload.getFileSizeMax() / 1024L) / 1024L)); // } catch (FileUploadException ex) { M_log.info("Unexpected exception in upload parsing", ex); req.setAttribute("upload.status", "exception"); req.setAttribute("upload.exception", ex); } // add any parameters that were in the URL - make sure to get multiples for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); String[] values = req.getParameterValues(name); map.put(name, values); } // return a wrapped response that exposes the parsed parameters and files return new WrappedRequestFileUpload(req, map); }
From source file:org.seasar.struts.upload.S2MultipartRequestHandler.java
@SuppressWarnings("unchecked") @Override/*from w w w . j a va 2s . c o m*/ public void handleRequest(HttpServletRequest request) throws ServletException { ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY); ServletFileUpload upload = new ServletFileUpload( new DiskFileItemFactory((int) getSizeThreshold(ac), new File(getRepositoryPath(ac)))); upload.setHeaderEncoding(request.getCharacterEncoding()); upload.setSizeMax(getSizeMax(ac)); elementsText = new Hashtable(); elementsFile = new Hashtable(); elementsAll = new Hashtable(); List items = null; try { items = upload.parseRequest(request); } catch (SizeLimitExceededException e) { request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE); request.setAttribute(SIZE_EXCEPTION_KEY, e); try { InputStream is = request.getInputStream(); try { byte[] buf = new byte[1024]; @SuppressWarnings("unused") int len = 0; while ((len = is.read(buf)) != -1) { } } catch (Exception ignore) { } finally { try { is.close(); } catch (Exception ignore) { } } } catch (Exception ignore) { } 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.vosao.servlet.FileUploadServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //logger.info("File upload..."); ServletFileUpload upload = new ServletFileUpload(); upload.setFileSizeMax(MAX_SIZE);//from ww w .jav a2 s. c om upload.setHeaderEncoding("UTF-8"); String message = null; Map<String, String> parameters = new HashMap<String, String>(); List<UploadItem> uploadItems = new ArrayList<UploadItem>(); try { FileItemIterator iter; try { iter = upload.getItemIterator(request); FileItemStream imageFileItem = null; String folder = null; InputStream stream = null; InputStream filestream = null; byte[] fileData = null; parameters.put(IMAGE_UPLOAD_PAGE_ID, VosaoContext.getInstance().getSession().getString(IMAGE_UPLOAD_PAGE_ID)); if (request.getParameter("CKEditorFuncNum") != null) { ckeditorFuncNum = request.getParameter("CKEditorFuncNum"); } while (iter.hasNext()) { FileItemStream item = iter.next(); stream = item.openStream(); if (item.isFormField()) { parameters.put(item.getFieldName(), Streams.asString(stream, "UTF-8")); } else { UploadItem uploadItem = new UploadItem(); uploadItem.item = item; uploadItem.data = StreamUtil.readFileStream(stream); uploadItems.add(uploadItem); } } //logger.info(parameters.toString()); for (UploadItem item : uploadItems) { message = processFile(item.item, item.data, parameters); } } catch (FileUploadException e) { logger.error(Messages.get("request_parsing_error")); throw new UploadException(Messages.get("request_parsing_error")); } } catch (UploadException e) { message = createMessage("error", e.getMessage()); logger.error(message); } if (isCKeditorUpload(parameters)) { response.setContentType("text/html"); } else { response.setContentType("text/plain"); } response.setStatus(200); response.getWriter().write(message); }
From source file:org.vosao.servlet.FormSendServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String message = null;//from www.jav a2 s. c om Map<String, String> parameters = new HashMap<String, String>(); List<FileItem> files = new ArrayList<FileItem>(); try { if (request.getContentType().startsWith("multipart/form-data")) { ServletFileUpload upload = new ServletFileUpload(); upload.setFileSizeMax(MAX_SIZE); upload.setHeaderEncoding("UTF-8"); FileItemIterator iter; try { iter = upload.getItemIterator(request); InputStream stream = null; while (iter.hasNext()) { FileItemStream item = iter.next(); stream = item.openStream(); if (item.isFormField()) { parameters.put(item.getFieldName(), Streams.asString(stream, "UTF-8")); } else { files.add(new FileItem(item, StreamUtil.readFileStream(stream))); } } } catch (FileUploadException e) { logger.error(e.getMessage()); throw new UploadException(Messages.get("request_parsing_error")); } } else { for (Object key : request.getParameterMap().keySet()) { String paramName = (String) key; parameters.put(paramName, request.getParameter(paramName)); } } message = processForm(parameters, files, request); } catch (UploadException e) { message = createMessage("error", e.getMessage()); logger.error(message); } catch (Exception e) { message = createMessage("error", e.getMessage()); logger.error(message); e.printStackTrace(); } response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.setStatus(200); response.getWriter().write(message); }