List of usage examples for org.apache.commons.fileupload FileItem getContentType
String getContentType();
null
if not defined. 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) *///from ww w .j a va 2s .c om 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 {//www. j av a 2s . com 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 . ja v a2 s.c om 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.openanzo.binarystore.server.BinaryStoreServlet.java
@SuppressWarnings({ "unchecked", "null" }) private void createUpdate(AnzoClient ac, HttpServletRequest req, HttpServletResponse resp, boolean update) throws ServletException, AnzoException, IOException, JSONException { //check permissions before uploading the file. URI updateURI = null;/*w w w. j a va2 s . c o m*/ if (update) { String graphURI = req.getParameter(GRAPH); if (graphURI == null) { throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_NO_GRAPHURI_SPECIFIED); } updateURI = Constants.valueFactory.createURI(graphURI); if (!ac.namedGraphExists(updateURI)) { throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_UPDATE_FILEDOESNOTEXIST, updateURI.toString()); } else if (!ac.canAddToNamedGraph(updateURI) || (!ac.canRemoveFromNamedGraph(updateURI))) { throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_UPDATE_PERMISSION_DENIED, updateURI.toString()); } } else { if (!ac.canAddToNamedGraph(GRAPHS.GRAPHS_DATASET)) throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_UPDATE_PERMISSION_DENIED, GRAPHS.GRAPHS_DATASET.toString()); } String feedbackId = req.getParameter(FEEDBACK_ID); if (!ServletFileUpload.isMultipartContent(req)) throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_MULTIPART_FORM_REQUIRED); IStatementChannel scg = null; URI feedbackidURIg = null; ServletFileUpload upload = new ServletFileUpload(factory); if (feedbackId != null) { //Create a progress listener final URI feedbackURI = Constants.valueFactory.createURI(createFeedbackURI(ac)); final URI feedbackidURI = Constants.valueFactory.createURI(feedbackId); try { final IStatementChannel sc = ac.getStatementChannel(feedbackURI, AnzoClient.NON_REVISIONED_NAMED_GRAPH); scg = sc; feedbackidURIg = feedbackidURI; ac.updateRepository(); ProgressListener progressListener = new ProgressListener() { Date prevTime = null; public void update(long pBytesRead, long pContentLength, int pItems) { Date nowTime = new Date(); if ((pContentLength != pBytesRead) && (prevTime != null && (nowTime.getTime() < (prevTime.getTime() + progressUpdateFrequency)))) { return; } prevTime = nowTime; Map<String, Object> messageProperties = new HashMap<String, Object>(); Collection<Statement> statements = new HashSet<Statement>(); statements.add(Constants.valueFactory.createStatement(feedbackidURI, BINARYSTORE_ITEM_PROGRESS_JOB_URI, BINARYSTORE_ITEM_UPLOAD_JOB_URI, feedbackidURI)); statements.add(Constants.valueFactory.createStatement(feedbackidURI, BINARYSTORE_ITEM_PROGRESS_JOB_COMPLETE_URI, Constants.valueFactory.createLiteral(pContentLength), feedbackidURI)); statements.add(Constants.valueFactory.createStatement(feedbackidURI, BINARYSTORE_ITEM_PROGRESS_JOB_COMPLETED_URI, Constants.valueFactory.createLiteral(pBytesRead), feedbackidURI)); try { sc.sendMessage(messageProperties, statements); } catch (AnzoException e) { log.error(LogUtils.BINARY_MARKER, Messages.formatString( ExceptionConstants.BINARYSTORE.BINARYSTORE_ERROR_SENDING_PROGRESS), e); } } }; upload.setProgressListener(progressListener); } catch (AnzoException e) { log.error(LogUtils.BINARY_MARKER, Messages.formatString( ExceptionConstants.BINARYSTORE.BINARYSTORE_ERROR_FINDING_STATEMENT_CHANNEL), e); } } long revision = -1; BinaryStoreFile bsf = null; ClientGraph graph = null; File target = null; File lockFile = null; try { if (update) { graph = ac.getServerGraph(updateURI); revision = graph.getRevision(); if (!isRevisioned(graph)) revision = -1; //increase to the new revision; if (revision != -1) ++revision; bsf = getFileFromURI(updateURI, revision); target = new File(bsf.getFilename()); lockFile = getLock(target); if (lockFile == null) { graph.close(); throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_FILE_LOCKED, target.getAbsolutePath()); } } FileItem file = null; try { List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { if (!item.getFieldName().equals(FILENAME)) continue; file = item; break; } } catch (FileUploadException e) { throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_FILE_UPLOAD_ERROR, e); } catch (Exception e) { throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_FILE_UPLOAD_ERROR, e); } if (file == null || StringUtils.isEmpty(file.getName())) { throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_NO_FILE_SENT); } if (scg != null) { Map<String, Object> messageProperties = new HashMap<String, Object>(); Collection<Statement> statements = new HashSet<Statement>(); statements.add(Constants.valueFactory.createStatement(feedbackidURIg, BINARYSTORE_ITEM_PROGRESS_JOB_URI, BINARYSTORE_ITEM_CHECKSUM_JOB_URI, feedbackidURIg)); statements.add(Constants.valueFactory.createStatement(feedbackidURIg, BINARYSTORE_ITEM_PROGRESS_JOB_COMPLETE_URI, Constants.valueFactory.createLiteral(1), feedbackidURIg)); statements.add(Constants.valueFactory.createStatement(feedbackidURIg, BINARYSTORE_ITEM_PROGRESS_JOB_COMPLETED_URI, Constants.valueFactory.createLiteral(0), feedbackidURIg)); scg.sendMessage(messageProperties, statements); } String sha1sum = null; try { sha1sum = createChecksum(file.getInputStream()); } catch (IOException ioe) { throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_ERROR_CREATING_SHA1, file.getName()); } if (scg != null) { Map<String, Object> messageProperties = new HashMap<String, Object>(); Collection<Statement> statements = new HashSet<Statement>(); statements.add(Constants.valueFactory.createStatement(feedbackidURIg, BINARYSTORE_ITEM_PROGRESS_JOB_URI, BINARYSTORE_ITEM_CHECKSUM_JOB_URI, feedbackidURIg)); statements.add(Constants.valueFactory.createStatement(feedbackidURIg, BINARYSTORE_ITEM_PROGRESS_JOB_COMPLETE_URI, Constants.valueFactory.createLiteral(1), feedbackidURIg)); statements.add(Constants.valueFactory.createStatement(feedbackidURIg, BINARYSTORE_ITEM_PROGRESS_JOB_COMPLETED_URI, Constants.valueFactory.createLiteral(1), feedbackidURIg)); scg.sendMessage(messageProperties, statements); } String filename = new File(file.getName()).getName(); String contentType = file.getContentType(); long sizeInBytes = file.getSize(); if (update) { Collection<Statement> statements = graph.find(updateURI, BINARYSTORE_ITEM_SHA_1_URI, null); if (statements.size() > 0) { Statement s = statements.iterator().next(); String sum = ((Literal) s.getObject()).getLabel(); if (sum.equals(sha1sum)) { // no need to make a new revision as file is identical to currently stored file. if (revision != -1) --revision; bsf = getFileFromURI(updateURI, revision); sendSuccessMsg(req, resp, bsf.getURI(), revision); return; } } } else { revision = (req.getParameter(REVISIONED).equals("true")) ? 0 : -1; bsf = generateFilename(filename, revision); target = new File(bsf.getFilename()); //create the parent Directories File parentDir = target.getParentFile(); if (parentDir != null) parentDir.mkdirs(); } try { //its a new file if it is a create operation or the binary file is revisioned. if ((!update || (update && revision != -1)) && target.createNewFile() == false) { throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_FILE_ALREADY_EXISTS, target.getAbsolutePath()); } } catch (IOException ioe) { throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_ERROR_CREATING_FILE, target.getAbsolutePath()); } Resource fileURI = Constants.valueFactory.createResource(bsf.getURI().toString()); ac.begin(); if (!update) { if (revision == -1) { graph = ac.getServerGraph(bsf.getURI(), AnzoClient.NON_REVISIONED_NAMED_GRAPH); } else { graph = ac.getServerGraph(bsf.getURI(), AnzoClient.REVISIONED_NAMED_GRAPH); } graph.add(fileURI, RDF.TYPE, BINARYSTORE_ITEM_URI); } else { Collection<Statement> statements = graph.getStatements(); for (Statement s : statements) { if (s.getObject() != BINARYSTORE_ITEM_URI) { graph.remove(s); } } } //TODO: at this stage call out to any plugins which might want to add meta data to the graph. graph.add(fileURI, BINARYSTORE_ITEM_SIZE_URI, Constants.valueFactory.createLiteral(sizeInBytes)); graph.add(fileURI, CONTENT_TYPE_URI, Constants.valueFactory.createLiteral(contentType)); graph.add(fileURI, DC.TITLE, Constants.valueFactory.createLiteral(filename)); graph.add(fileURI, BINARYSTORE_ITEM_SHA_1_URI, Constants.valueFactory.createLiteral(sha1sum)); // copy the file to the correct place on the server. try { copy(file.getInputStream(), new FileOutputStream(target), scg); } catch (IOException ioe) { throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_ERROR_COPYING_FILE, file.getName(), target.getAbsolutePath()); } ac.commit(); ac.updateRepository(); } finally { if (graph != null) graph.close(); if (lockFile != null) lockFile.delete(); } if (scg != null) { scg.close(); try { //sleep so that the feedback events have enough time to send the final bytes complete event. Thread.sleep(200); } catch (InterruptedException e) { } } sendSuccessMsg(req, resp, bsf.getURI(), revision); }
From source file:org.opensingular.form.wicket.mapper.attachment.upload.FileUploadProcessor.java
public List<UploadResponseInfo> process(FileItem item, UploadInfo upInfo, FileUploadManager upManager) throws SingularException { final List<UploadResponseInfo> responses = new ArrayList<>(); if (!item.isFormField()) { // Garante que virar apenas o nome do arquivo sem path final String originalFilename = checkValidName(item); final String contentType = lowerCase(item.getContentType()); final String extension = lowerCase(substringAfterLast(originalFilename, ".")); if (item.getSize() == 0) { responses.add(new UploadResponseInfo(originalFilename, ARQUIVO_NAO_PODE_SER_DE_TAMANHO_0_ZERO)); } else if (!(upInfo.isFileTypeAllowed(contentType) || upInfo.isFileTypeAllowed(extension))) { responses.add(new UploadResponseInfo(originalFilename, TIPO_DE_ARQUIVO_NAO_PERMITIDO)); } else {// www . j a v a2 s .c o m try (InputStream in = item.getInputStream()) { final FileUploadInfo fileInfo = upManager.createFile(upInfo, originalFilename, in); responses.add(new UploadResponseInfo(fileInfo.getAttachmentRef())); } catch (Exception e) { throw SingularException.rethrow(e.getMessage(), e); } } } return responses; }
From source file:org.opensubsystems.core.util.servlet.WebUtils.java
/** * Create debug string containing all parameter names and their values from * the request, all attributes, all cookies and other data characterizing the * request./*from www .j a v a 2 s. co m*/ * * @param hsrqRequest - the servlet request. * @return String - debug string containing all parameter names and their * values from the request */ public static String debug(HttpServletRequest hsrqRequest) { Enumeration enumNames; Enumeration enumValues; Iterator iterValues; String strName; String[] arValues; Cookie[] arCookies; int iIndex; Map<String, String[]> mpParamMap; StringBuilder sbfReturn = new StringBuilder(); sbfReturn.append("HttpServletRequest=["); sbfReturn.append("\nRemoteAddress="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteAddr())); sbfReturn.append(";"); sbfReturn.append("\nRemotePort="); sbfReturn.append(hsrqRequest.getRemotePort()); sbfReturn.append(";"); sbfReturn.append("\nRemoteHost="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteHost())); sbfReturn.append(";"); sbfReturn.append("\nRemoteUser="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteUser())); sbfReturn.append(";"); sbfReturn.append("\nFullURL="); sbfReturn.append(getFullRequestURL(hsrqRequest)); sbfReturn.append(";"); sbfReturn.append("\nContextPath="); sbfReturn.append(hsrqRequest.getContextPath()); sbfReturn.append(";"); sbfReturn.append("\nServletPath="); sbfReturn.append(hsrqRequest.getServletPath()); sbfReturn.append(";"); sbfReturn.append("\nPathInfo ="); sbfReturn.append(hsrqRequest.getPathInfo()); sbfReturn.append(";"); sbfReturn.append("\nRequestURI="); sbfReturn.append(hsrqRequest.getRequestURI()); sbfReturn.append(";"); sbfReturn.append("\nRequestURL="); sbfReturn.append(hsrqRequest.getRequestURL()); sbfReturn.append(";"); sbfReturn.append("\nMethod="); sbfReturn.append(hsrqRequest.getMethod()); sbfReturn.append(";"); sbfReturn.append("\nAuthenticationType="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getAuthType())); sbfReturn.append(";"); sbfReturn.append("\nCharacterEncoding="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getCharacterEncoding())); sbfReturn.append(";"); sbfReturn.append("\nContentType="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getContentType())); sbfReturn.append(";"); sbfReturn.append("\nMultiPart="); sbfReturn.append(ServletFileUpload.isMultipartContent(hsrqRequest)); sbfReturn.append(";"); // Parameters //////////////////////////////////////////////////////////// try { Map.Entry<String, String[]> entry; // Use getParameterMap rather than request.getParameterNames since it // correctly handles multipart requests mpParamMap = WebParamUtils.getParameterMap("WebUtils: ", hsrqRequest); for (iterValues = mpParamMap.entrySet().iterator(); iterValues.hasNext();) { entry = (Map.Entry<String, String[]>) iterValues.next(); strName = entry.getKey(); arValues = entry.getValue(); sbfReturn.append("\nParam="); sbfReturn.append(strName); sbfReturn.append(" values="); for (iIndex = 0; iIndex < arValues.length; iIndex++) { sbfReturn.append(arValues[iIndex]); if (iIndex < (arValues.length - 1)) { sbfReturn.append(";"); } } if (iterValues.hasNext()) { sbfReturn.append(";"); } } } catch (OSSInvalidDataException ex) { sbfReturn.append("<Cannot access parameter map of the request>"); s_logger.log(Level.SEVERE, "Cannot access parameter map of the request", ex); } // Uploaded files //////////////////////////////////////////////////////// if (ServletFileUpload.isMultipartContent(hsrqRequest)) { try { FileItem item; Map<String, FileItem> mpFiles; TwoElementStruct<Map<String, Object>, Map<String, FileItem>> params; params = WebParamUtils.getMultipartParameters("WebUtils: ", hsrqRequest); mpFiles = params.getSecond(); for (iterValues = mpFiles.values().iterator(); iterValues.hasNext();) { item = (FileItem) iterValues.next(); sbfReturn.append("\nUpload="); sbfReturn.append(item.getName()); sbfReturn.append(" field="); sbfReturn.append(item.getFieldName()); sbfReturn.append(" contentType="); sbfReturn.append(item.getContentType()); sbfReturn.append(" isInMemory="); sbfReturn.append(item.isInMemory()); sbfReturn.append(" sizeInBytes="); sbfReturn.append(item.getSize()); if (iterValues.hasNext()) { sbfReturn.append(";"); } } } catch (OSSInvalidDataException ex) { sbfReturn.append("<Cannot access list of multipart parameters>"); s_logger.log(Level.SEVERE, "Cannot access list of multipart parameters", ex); } } // Headers /////////////////////////////////////////////////////////////// for (enumNames = hsrqRequest.getHeaderNames(); enumNames.hasMoreElements();) { strName = (String) enumNames.nextElement(); sbfReturn.append("\nHeader="); sbfReturn.append(strName); sbfReturn.append(" values="); for (enumValues = hsrqRequest.getHeaders(strName); enumValues.hasMoreElements();) { sbfReturn.append(enumValues.nextElement()); if (enumValues.hasMoreElements()) { sbfReturn.append(";"); } } if (enumNames.hasMoreElements()) { sbfReturn.append(";"); } } // Cookies /////////////////////////////////////////////////////////////// arCookies = hsrqRequest.getCookies(); if (arCookies != null) { Cookie cookie; for (iIndex = 0; iIndex < arCookies.length; iIndex++) { cookie = arCookies[iIndex]; sbfReturn.append("\nCookie="); sbfReturn.append(cookie.getName()); sbfReturn.append(" path="); sbfReturn.append(cookie.getPath()); sbfReturn.append(" path="); sbfReturn.append(cookie.getDomain()); sbfReturn.append(" maxage="); sbfReturn.append(cookie.getMaxAge()); sbfReturn.append(" version="); sbfReturn.append(cookie.getVersion()); sbfReturn.append(" secure="); sbfReturn.append(cookie.getSecure()); sbfReturn.append(" value="); sbfReturn.append(cookie.getValue()); sbfReturn.append(" comment="); sbfReturn.append(StringUtils.valueIfNotNull(cookie.getComment())); if (iIndex < (arCookies.length - 1)) { sbfReturn.append(";"); } } } if (enumNames.hasMoreElements()) { sbfReturn.append(";"); } // Attributes //////////////////////////////////////////////////////////// for (enumNames = hsrqRequest.getAttributeNames(); enumNames.hasMoreElements();) { strName = (String) enumNames.nextElement(); sbfReturn.append("\nAttribute="); sbfReturn.append(strName); sbfReturn.append(" value="); sbfReturn.append(hsrqRequest.getAttribute(strName)); if (enumNames.hasMoreElements()) { sbfReturn.append(";"); } } // Content /////////////////////////////////////////////////////////////// sbfReturn.append("\nContent="); try { sbfReturn.append(StringUtils.convertStreamToString(hsrqRequest.getInputStream(), true)); } catch (IOException ex) { sbfReturn.append("<Cannot access input stream of the request>"); s_logger.log(Level.SEVERE, "Cannot access input stream of the request", ex); } sbfReturn.append(";"); return sbfReturn.toString(); }
From source file:org.orbeon.oxf.processor.generator.RequestGenerator.java
protected static void addElements(Element requestElement, Map<String, ?> map, String name1, String name2) { if (map.size() >= 0) { final Element parametersElement = requestElement.addElement(name1); for (final String name : map.keySet()) { final Element parameterElement = parametersElement.addElement(name2); // Always create the name element parameterElement.addElement("name").addText(name); final Object entryValue = map.get(name); final Object[] values; if (entryValue instanceof Object[]) { values = (Object[]) entryValue; } else { values = new Object[] { entryValue }; }/*from ww w .j a va 2s . co m*/ for (int j = 0; j < values.length; j++) { final Object value = values[j]; if (value instanceof String) { // Simple String parameter parameterElement.addElement("value").addText((String) value); } else if (value instanceof FileItem) { // Retrieve the FileItem (only for parameters) final FileItem fileItem = (FileItem) value; // Set meta-information element if (fileItem.getName() != null) parameterElement.addElement("filename").addText(fileItem.getName()); if (fileItem.getContentType() != null) parameterElement.addElement(Headers.ContentTypeLower()) .addText(fileItem.getContentType()); parameterElement.addElement(Headers.ContentLengthLower()) .addText(Long.toString(fileItem.getSize())); if (!isFileItemEmpty(fileItem)) { // Create private placeholder element with parameter name as attribute final Element fileItemElement = parameterElement.addElement(FILE_ITEM_ELEMENT, REQUEST_PRIVATE_NAMESPACE_URI); fileItemElement.addAttribute(PARAMETER_NAME_ATTRIBUTE, name); fileItemElement.addAttribute(PARAMETER_POSITION_ATTRIBUTE, Integer.toString(j)); } else { // Just generate an empty "value" element parameterElement.addElement("value"); } } else { // ignore (needed in case of attributes, which can be any Java object) } } } } }
From source file:org.paxle.gui.impl.servlets.ParserTestServlet.java
protected void fillContext(Context context, HttpServletRequest request) { String cmdLocation = null;//from w ww . j a v a2 s .com String cDocCharset = "UTF-8"; File cDocContentFile = null; String cDocContentType = null; boolean mimeTypeDetection = false; boolean charsetDetection = false; try { context.put(CONTEXT_MIMETYPE_DETECTOR, this.mimeTypeDetector); context.put(CONTEXT_CHARSET_DETECTOR, this.charsetDetector); if (ServletFileUpload.isMultipartContent(request)) { // Create a factory for disk-based file items final FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler final ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request @SuppressWarnings("unchecked") final List<FileItem> items = upload.parseRequest(request); // Process the uploaded items final Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { final FileItem item = iter.next(); final String fieldName = item.getFieldName(); if (item.isFormField()) { if (fieldName.equals(PARAM_COMMAND_URI)) { cmdLocation = item.getString(); context.put(PARAM_COMMAND_URI, cmdLocation); } else if (fieldName.equals(PARAM_ENABLE_MIMETYPE_DETECTION)) { mimeTypeDetection = true; } else if (fieldName.equals(PARAM_ENABLE_CHARSET_DETECTION)) { charsetDetection = true; } } else { try { // ignore unknown items if (!fieldName.equals(PARAM_CRAWLERDOC_NAME)) continue; // getting the content type cDocContentType = item.getContentType(); // getting the file-Name String fileName = item.getName(); if (fileName != null) { context.put(PARAM_CRAWLERDOC_NAME, fileName); fileName = FilenameUtils.getName(fileName); } else { String errorMsg = String.format("Fileupload field '%s' has no valid filename '%s'.", PARAM_CRAWLERDOC_NAME, item.getFieldName()); this.logger.warn(errorMsg); context.put(CONTEXT_ERROR_MSG, errorMsg); continue; } // creating a temp-file cDocContentFile = this.tfm.createTempFile(); // getting the content item.write(cDocContentFile); } finally { // delete uploaded item item.delete(); } } } // detect the mime-type of the uploaded file if (this.mimeTypeDetector != null && mimeTypeDetection) { final String tempMimeType = this.mimeTypeDetector.getMimeType(cDocContentFile); if (tempMimeType != null) cDocContentType = tempMimeType; } // determine the charset of the uploaded file if (this.charsetDetector != null && charsetDetection) { final String tempCharset = this.charsetDetector.detectCharset(cDocContentFile); if (tempCharset != null) cDocCharset = tempCharset; } // creating a crawler-document final ICrawlerDocument cDoc = this.cDocFactory.createDocument(ICrawlerDocument.class); cDoc.setStatus(ICrawlerDocument.Status.OK); cDoc.setContent(cDocContentFile); cDoc.setMimeType(cDocContentType); cDoc.setCharset(cDocCharset); // creating a dummy command final ICommand cmd = this.cmdFactory.createDocument(ICommand.class); cmd.setLocation(URI.create(cmdLocation)); cmd.setCrawlerDocument(cDoc); // parsing the command this.parser.process(cmd); if (cmd.getResult() != Result.Passed) { context.put(CONTEXT_ERROR_MSG, String.format("Unable to parse the document: %s", cmd.getResultText())); return; } // trying to get the parsed content final IParserDocument pdoc = cmd.getParserDocument(); if (pdoc == null) { context.put("errorMsg", "Unable to parse the document: parser-document is null."); return; } else if (pdoc.getStatus() != Status.OK) { context.put(CONTEXT_ERROR_MSG, String.format("Unable to parse the document: %s", pdoc.getStatusText())); return; } /* * Remembering some object in the request-context * This is required for cleanup. See #requestCleanup(...) */ request.setAttribute(CONTEXT_CMD, cmd); request.setAttribute(REQ_ATTR_LINEITERS, new ArrayList<Reader>()); /* * Passing some properties to the rendering engine */ context.put(CONTEXT_CMD, cmd); context.put(CONTEXT_PROP_UTIL, new PropertyUtils()); context.put(CONTEXT_SERVLET, this); if (mimeTypeDetection && this.mimeTypeDetector != null) { context.put(PARAM_ENABLE_MIMETYPE_DETECTION, Boolean.TRUE); } if (charsetDetection && this.charsetDetector != null) { context.put(PARAM_ENABLE_CHARSET_DETECTION, Boolean.TRUE); } } } catch (Throwable e) { this.logger.error(e); // delete temp-file if (cDocContentFile != null) { try { this.tfm.releaseTempFile(cDocContentFile); } catch (IOException e2) { /* ignore this */} } } }
From source file:org.primeframework.mvc.parameter.RequestBodyWorkflow.java
/** * Handles parsing the multi-part body to pull out the files and the parameters. * * @return The files and the parameters. */// w w w. j ava2s .co m private FilesAndParameters handleFiles() { FilesAndParameters filesAndParameters = new FilesAndParameters(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { String name = item.getFieldName(); if (item.isFormField()) { String value = item.getString(); List<String> list = filesAndParameters.parameters.get(name); if (list == null) { list = new ArrayList<String>(); filesAndParameters.parameters.put(name, list); } list.add(value); } else { String fileName = item.getName(); // Handle lame ass IE issues with file names if (fileName.contains(":\\")) { int index = fileName.lastIndexOf("\\"); fileName = fileName.substring(index + 1); } String contentType = item.getContentType(); File file = File.createTempFile("prime", "fileupload"); item.write(file); // Handle when the user doesn't provide a file at all if (file.length() == 0 || fileName == null || contentType == null) { continue; } List<FileInfo> list = filesAndParameters.files.get(name); if (list == null) { list = new ArrayList<FileInfo>(); filesAndParameters.files.put(name, list); } list.add(new FileInfo(file, fileName, contentType)); } } } catch (Exception e) { throw new PrimeException("Unable to handle file uploads", e); } return filesAndParameters; }
From source file:org.purl.sword.client.ServletClient.java
/** * Process a deposit./*from w ww.j av a2 s .c om*/ * * @param request The request details. * @param response The response to output to. * * @throws ServletException * @throws IOException */ private void doDeposit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Do the deposit Client client = new Client(); try { PostMessage message = new PostMessage(); message.setUserAgent(ClientConstants.SERVICE_NAME); // Get the file FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); String u = null; String p = null; String contentDisposition = null; String filetype = null; boolean useMD5 = false; boolean errorMD5 = false; boolean verbose = false; boolean noOp = false; boolean login = false; while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); if (name.equals("url")) { message.setDestination(value); URL url = new URL(value); int port = url.getPort(); if (port == -1) { port = 80; } client.setServer(url.getHost(), port); } else if (name.equals("usemd5")) { useMD5 = true; } else if (name.equals("errormd5")) { errorMD5 = true; } else if (name.equals("verbose")) { verbose = true; } else if (name.equals("noop")) { noOp = true; } else if (name.equals("obo")) { message.setOnBehalfOf(value); } else if (name.equals("slug")) { if ((value != null) && (!value.trim().equals(""))) { message.setSlug(value); } } else if (name.equals("cd")) { contentDisposition = value; } else if (name.equals("filetype")) { filetype = value; } else if (name.equals("formatnamespace")) { if ((value != null) && (!value.trim().equals(""))) { message.setFormatNamespace(value); } } else if (name.equals("u")) { u = value; login = true; request.setAttribute("u", value); } else if (name.equals("p")) { p = value; login = true; } request.setAttribute(name, value); } else { String fname = tempDirectory + File.separator + "ServletClient-" + counter++; if ((contentDisposition != null) && (!contentDisposition.equals(""))) { fname = tempDirectory + File.separator + contentDisposition; } File uploadedFile = new File(fname); item.write(uploadedFile); message.setFilepath(fname); if ((filetype == null) || (filetype.trim().equals(""))) { message.setFiletype(item.getContentType()); } else { message.setFiletype(filetype); } } } if (login) { client.setCredentials(u, p); } if (useProxy) { client.setProxy(pHost, pPort); } message.setUseMD5(useMD5); message.setChecksumError(errorMD5); message.setVerbose(verbose); message.setNoOp(noOp); // Post the file DepositResponse resp = client.postFile(message); // Set the status Status status = client.getStatus(); request.setAttribute("status", status.toString()); if ((status.getCode() == 201) || (status.getCode() == 202)) { // Set the debug response String xml = resp.marshall(); String validateXml = xml; validateXml = validateXml.replaceAll("&", "&"); validateXml = validateXml.replaceAll("<", "<"); validateXml = validateXml.replaceAll(">", ">"); validateXml = validateXml.replaceAll("\"", """); validateXml = validateXml.replaceAll("'", "'"); request.setAttribute("xmlValidate", validateXml); // for passing to validation xml = xml.replaceAll("<", "<"); xml = xml.replaceAll(">", ">"); request.setAttribute("xml", xml); SWORDEntry se = resp.getEntry(); request.setAttribute("id", se.getId()); request.setAttribute("authors", se.getAuthors()); request.setAttribute("contributors", se.getContributors()); request.setAttribute("title", se.getTitle().getContent()); request.setAttribute("updated", se.getUpdated()); request.setAttribute("categories", se.getCategories()); request.setAttribute("treatment", se.getTreatment()); request.setAttribute("summary", se.getSummary().getContent()); request.setAttribute("generator", se.getGenerator().getContent()); request.setAttribute("userAgent", se.getUserAgent()); request.setAttribute("packaging", se.getPackaging()); request.setAttribute("links", se.getLinks()); request.setAttribute("location", resp.getLocation()); // Set the ServiceDocument and associated values request.getRequestDispatcher("deposit.jsp").forward(request, response); return; } else { String error = status.getCode() + " " + status.getMessage() + " - "; try { error += resp.getEntry().getSummary().getContent(); } catch (Exception e) { // Do nothing - we have default error message e.printStackTrace(); } request.setAttribute("error", error); // Try and get an error document in xml String xml = resp.marshall(); xml = xml.replaceAll("<", "<"); xml = xml.replaceAll(">", ">"); request.setAttribute("xml", xml); request.getRequestDispatcher("depositform.jsp").forward(request, response); return; } } catch (RuntimeException e) { e.printStackTrace(); request.setAttribute("error", "value: " + e.toString()); request.setAttribute("urls", urls); request.getRequestDispatcher("depositform.jsp").forward(request, response); } catch (Exception e) { e.printStackTrace(); request.setAttribute("error", "value: " + e.toString()); request.setAttribute("urls", urls); request.getRequestDispatcher("depositform.jsp").forward(request, response); } }