use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project cerberus-source by cerberustesting.
the class UpdateTestDataLib method processRequest.
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject jsonResponse = new JSONObject();
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
Answer ans = new Answer();
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
ans.setResultMessage(msg);
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
String charset = request.getCharacterEncoding();
IFactoryTestDataLibData tdldFactory = appContext.getBean(IFactoryTestDataLibData.class);
ITestDataLibDataService tdldService = appContext.getBean(ITestDataLibDataService.class);
IParameterService parameterService = appContext.getBean(IParameterService.class);
response.setContentType("application/json");
Map<String, String> fileData = new HashMap<String, String>();
FileItem file = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> fields = upload.parseRequest(request);
Iterator<FileItem> it = fields.iterator();
if (!it.hasNext()) {
return;
}
while (it.hasNext()) {
FileItem fileItem = it.next();
boolean isFormField = fileItem.isFormField();
if (isFormField) {
fileData.put(fileItem.getFieldName(), ParameterParserUtil.parseStringParamAndDecode(fileItem.getString("UTF-8"), "", charset));
} else {
file = fileItem;
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
/**
* Parsing and securing all required parameters.
*/
// Parameter that are already controled by GUI (no need to decode) --> We SECURE them
String type = policy.sanitize(fileData.get("type"));
String system = policy.sanitize(fileData.get("system"));
String environment = policy.sanitize(fileData.get("environment"));
String country = policy.sanitize(fileData.get("country"));
String database = policy.sanitize(fileData.get("database"));
String databaseUrl = policy.sanitize(fileData.get("databaseUrl"));
String databaseCsv = policy.sanitize(fileData.get("databaseCsv"));
// Parameter that needs to be secured --> We SECURE+DECODE them
// this is mandatory
String name = fileData.get("name");
String group = fileData.get("group");
String description = fileData.get("libdescription");
String service = fileData.get("service");
// Parameter that we cannot secure as we need the html --> We DECODE them
String script = fileData.get("script");
String servicePath = fileData.get("servicepath");
String method = fileData.get("method");
String envelope = fileData.get("envelope");
String csvUrl = fileData.get("csvUrl");
String separator = fileData.get("separator");
String activateAutoSubdata = fileData.get("subdataCheck");
Integer testdatalibid = 0;
boolean testdatalibid_error = true;
try {
if (fileData.get("testdatalibid") != null && !fileData.get("testdatalibid").isEmpty()) {
testdatalibid = Integer.valueOf(fileData.get("testdatalibid"));
testdatalibid_error = false;
}
} catch (NumberFormatException ex) {
testdatalibid_error = true;
LOG.warn(ex);
}
try {
// Prepare the final answer.
MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
Answer finalAnswer = new Answer(msg1);
/**
* Checking all constrains before calling the services.
*/
if (StringUtil.isNullOrEmpty(name)) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Test data library").replace("%OPERATION%", "Update").replace("%REASON%", "Test data library name is missing."));
finalAnswer.setResultMessage(msg);
} else if (testdatalibid_error) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Test data library").replace("%OPERATION%", "Update").replace("%REASON%", "Could not manage to convert testdatalibid to an integer value or testdatalibid is missing."));
finalAnswer.setResultMessage(msg);
} else {
/**
* All data seems cleans so we can call the services.
*/
// specific attributes
ITestDataLibService libService = appContext.getBean(ITestDataLibService.class);
AnswerItem resp = libService.readByKey(testdatalibid);
if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
/**
* Object could not be found. We stop here and report the
* error.
*/
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) resp);
} else {
/**
* The service was able to perform the query and confirm the
* object exist, then we can update it.
*/
TestDataLib lib = (TestDataLib) resp.getItem();
String fileName = lib.getCsvUrl();
if (file != null) {
ans = libService.uploadFile(lib.getTestDataLibID(), file);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
fileName = file.getName();
}
}
lib.setName(name);
lib.setType(type);
lib.setGroup(group);
lib.setDescription(description);
lib.setSystem(system);
lib.setEnvironment(environment);
lib.setCountry(country);
lib.setDatabase(database);
lib.setScript(script);
lib.setDatabaseUrl(databaseUrl);
lib.setServicePath(servicePath);
lib.setService(service);
lib.setMethod(method);
lib.setEnvelope(envelope);
lib.setDatabaseCsv(databaseCsv);
if (file == null) {
lib.setCsvUrl(csvUrl);
} else {
lib.setCsvUrl(File.separator + lib.getTestDataLibID() + File.separator + fileName);
}
lib.setSeparator(separator);
lib.setLastModifier(request.getRemoteUser());
ans = libService.update(lib);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Update operation finished with success, then the
* logging entry must be added.
*/
ILogEventService logEventService = appContext.getBean(LogEventService.class);
logEventService.createForPrivateCalls("/UpdateTestDataLib", "UPDATE", "Update TestDataLib - id: " + testdatalibid + " name: " + name + " system: " + system + " environment: " + environment + " country: " + country, request);
}
List<TestDataLibData> tdldList = new ArrayList();
// Getting list of SubData from JSON Call
if (fileData.get("subDataList") != null) {
JSONArray objSubDataArray = new JSONArray(fileData.get("subDataList"));
tdldList = getSubDataFromParameter(request, appContext, testdatalibid, objSubDataArray);
}
// When File has just been uploaded to servlet and flag to load the subdata value has been checked, we will parse it in order to automatically feed the subdata.
if (file != null && activateAutoSubdata.equals("1")) {
String str = "";
try (BufferedReader reader = new BufferedReader(new FileReader(parameterService.getParameterStringByKey("cerberus_testdatalibcsv_path", "", null) + lib.getCsvUrl()))) {
// First line of the file is split by separator.
str = reader.readLine();
String[] subData = (!lib.getSeparator().isEmpty()) ? str.split(lib.getSeparator()) : str.split(",");
// We take the subdata from the servlet input.
TestDataLibData firstLine = tdldList.get(0);
tdldList = new ArrayList();
firstLine.setColumnPosition("1");
tdldList.add(firstLine);
int i = 1;
for (String item : subData) {
String subdataName = "SUBDATA" + i;
TestDataLibData tdld = tdldFactory.create(null, testdatalibid, subdataName, item, null, null, Integer.toString(i), null);
tdldList.add(tdld);
i++;
}
// Update the Database with the new list.
} finally {
try {
file.getInputStream().close();
} catch (Throwable ignore) {
}
}
}
ans = tdldService.compareListAndUpdateInsertDeleteElements(testdatalibid, tdldList);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
}
}
jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
response.getWriter().print(jsonResponse);
response.getWriter().flush();
} catch (JSONException ex) {
LOG.warn(ex);
// returns a default error message with the json format that is able to be parsed by the client-side
response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
}
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project cerberus-source by cerberustesting.
the class UpdateApplicationObject method processRequest.
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
JSONObject jsonResponse = new JSONObject();
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
Answer ans = new Answer();
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
ans.setResultMessage(msg);
String charset = request.getCharacterEncoding();
response.setContentType("application/json");
// Calling Servlet Transversal Util.
ServletUtil.servletStart(request);
Map<String, String> fileData = new HashMap<String, String>();
FileItem file = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> fields = upload.parseRequest(request);
Iterator<FileItem> it = fields.iterator();
if (!it.hasNext()) {
return;
}
while (it.hasNext()) {
FileItem fileItem = it.next();
boolean isFormField = fileItem.isFormField();
if (isFormField) {
fileData.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
} else {
file = fileItem;
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
/**
* Parsing and securing all required parameters.
*/
// Parameter that are already controled by GUI (no need to decode) --> We SECURE them
// Parameter that needs to be secured --> We SECURE+DECODE them
String application = ParameterParserUtil.parseStringParamAndDecode(fileData.get("application"), null, charset);
String object = ParameterParserUtil.parseStringParamAndDecode(fileData.get("object"), null, charset);
String value = ParameterParserUtil.parseStringParam(fileData.get("value"), null);
String usrmodif = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getRemoteUser(), "", charset);
String datemodif = new Timestamp(new java.util.Date().getTime()).toString();
// Parameter that we cannot secure as we need the html --> We DECODE them
// Getting list of application from JSON Call
// Prepare the final answer.
MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
Answer finalAnswer = new Answer(msg1);
/**
* Checking all constrains before calling the services.
*/
if (StringUtil.isNullOrEmpty(application)) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "ApplicationObject").replace("%OPERATION%", "Update").replace("%REASON%", "Application name (applicationobject) is missing."));
ans.setResultMessage(msg);
} else if (StringUtil.isNullOrEmpty(object)) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "ApplicationObject").replace("%OPERATION%", "Update").replace("%REASON%", "Object name (applicationobject) is missing."));
ans.setResultMessage(msg);
} else {
/**
* All data seems cleans so we can call the services.
*/
IApplicationObjectService applicationObjectService = appContext.getBean(IApplicationObjectService.class);
AnswerItem resp = applicationObjectService.readByKey(application, object);
if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
/**
* Object could not be found. We stop here and report the error.
*/
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) resp);
} else {
/**
* The service was able to perform the query and confirm the
* object exist, then we can update it.
*/
ApplicationObject applicationData = (ApplicationObject) resp.getItem();
String fileName = applicationData.getScreenShotFileName();
if (file != null) {
ans = applicationObjectService.uploadFile(applicationData.getID(), file);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
fileName = file.getName();
}
}
applicationData.setValue(value);
applicationData.setScreenShotFileName(fileName);
applicationData.setUsrModif(usrmodif);
applicationData.setDateModif(datemodif);
ans = applicationObjectService.update(applicationData.getApplication(), applicationData.getObject(), applicationData);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Update was successful. Adding Log entry.
*/
ILogEventService logEventService = appContext.getBean(LogEventService.class);
logEventService.createForPrivateCalls("/UpdateApplication", "UPDATE", "Updated Application : ['" + application + "']", request);
}
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
}
}
/**
* Formating and returning the json result.
*/
jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
response.getWriter().print(jsonResponse);
response.getWriter().flush();
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project cerberus-source by cerberustesting.
the class ImportTestCaseFromJson method processRequest.
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String test = "";
String testcase = "";
JSONObject jo = null;
FileItem item = null;
if (ServletFileUpload.isMultipartContent(request)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
item = (FileItem) iterator.next();
if (item.isFormField()) {
String name = item.getFieldName();
if (name.equals("test")) {
test = item.getString("UTF-8");
}
if (name.equals("testcase")) {
testcase = item.getString("UTF-8");
}
} else {
InputStream inputStream = item.getInputStream();
BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null) {
responseStrBuilder.append(inputStr);
}
inputStream.close();
streamReader.close();
jo = new JSONObject(responseStrBuilder.toString());
}
}
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
ITestCaseService tcService = appContext.getBean(ITestCaseService.class);
TestCase tcInfo = new TestCase();
tcInfo.setTest(test);
tcInfo.setTestCase(testcase);
tcInfo.setOrigine(jo.getString("origin") == null ? "" : jo.getString("origin"));
tcInfo.setImplementer(jo.getString("implementer") == null ? "123TOTO" : "1234TOTO");
tcInfo.setBehaviorOrValueExpected(jo.getString("description") == null ? "1293TOTO" : "12394TOTO");
tcService.updateTestCaseInformation(tcInfo);
response.sendRedirect("TestCase.jsp");
} catch (FileUploadException e) {
e.printStackTrace();
} catch (JSONException ex) {
LOG.warn(ex);
} catch (Exception e) {
e.printStackTrace();
}
}
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project tephra by heisedebaise.
the class UploadHelperImpl method getUpload.
private synchronized ServletFileUpload getUpload(HttpServletRequest request) {
if (upload == null) {
synchronized (this) {
if (upload == null) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository((File) request.getServletContext().getAttribute("javax.servlet.context.tempdir"));
upload = new ServletFileUpload(factory);
upload.setSizeMax(converter.toBitSize(maxSize));
}
if (uploaders == null) {
uploaders = new HashMap<>();
BeanFactory.getBeans(Uploader.class).forEach(uploader -> uploaders.put(uploader.getName(), uploader));
}
}
}
return upload;
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project ofbiz-framework by apache.
the class ServiceEventHandler method invoke.
/**
* @see org.apache.ofbiz.webapp.event.EventHandler#invoke(ConfigXMLReader.Event, ConfigXMLReader.RequestMap, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
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);
VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
// get the service model to generate context
ModelService model = null;
try {
model = dctx.getModelService(serviceName);
} catch (GenericServiceException e) {
throw new EventHandlerException("Problems getting the service model", e);
}
if (model == null) {
throw new EventHandlerException("Problems getting the service model");
}
if (Debug.verboseOn()) {
Debug.logVerbose("[Processing]: SERVICE Event", module);
Debug.logVerbose("[Using delegator]: " + dispatcher.getDelegator().getDelegatorName(), module);
}
boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
Map<String, Object> multiPartMap = new HashMap<String, Object>();
if (isMultiPart) {
// get the http upload configuration
String maxSizeStr = EntityUtilProperties.getPropertyValue("general", "http.upload.max.size", "-1", dctx.getDelegator());
long maxUploadSize = -1;
try {
maxUploadSize = Long.parseLong(maxSizeStr);
} catch (NumberFormatException e) {
Debug.logError(e, "Unable to obtain the max upload size from general.properties; using default -1", module);
maxUploadSize = -1;
}
// get the http size threshold configuration - files bigger than this will be
// temporarly stored on disk during upload
String sizeThresholdStr = EntityUtilProperties.getPropertyValue("general", "http.upload.max.sizethreshold", "10240", dctx.getDelegator());
// 10K
int sizeThreshold = 10240;
try {
sizeThreshold = Integer.parseInt(sizeThresholdStr);
} catch (NumberFormatException e) {
Debug.logError(e, "Unable to obtain the threshold size from general.properties; using default 10K", module);
sizeThreshold = -1;
}
// directory used to temporarily store files that are larger than the configured size threshold
String tmpUploadRepository = EntityUtilProperties.getPropertyValue("general", "http.upload.tmprepository", "runtime/tmp", dctx.getDelegator());
String encoding = request.getCharacterEncoding();
// check for multipart content types which may have uploaded items
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory(sizeThreshold, new File(tmpUploadRepository)));
// create the progress listener and add it to the session
FileUploadProgressListener listener = new FileUploadProgressListener();
upload.setProgressListener(listener);
session.setAttribute("uploadProgressListener", listener);
if (encoding != null) {
upload.setHeaderEncoding(encoding);
}
upload.setSizeMax(maxUploadSize);
List<FileItem> uploadedItems = null;
try {
uploadedItems = UtilGenerics.<FileItem>checkList(upload.parseRequest(request));
} catch (FileUploadException e) {
throw new EventHandlerException("Problems reading uploaded data", e);
}
if (uploadedItems != null) {
for (FileItem item : uploadedItems) {
String fieldName = item.getFieldName();
/*
Debug.logInfo("Item Info [" + fieldName + "] : " + item.getName() + " / " + item.getSize() + " / " +
item.getContentType() + " FF: " + item.isFormField(), module);
*/
if (item.isFormField() || item.getName() == null) {
if (multiPartMap.containsKey(fieldName)) {
Object mapValue = multiPartMap.get(fieldName);
if (mapValue instanceof List<?>) {
checkList(mapValue, Object.class).add(item.getString());
} else if (mapValue instanceof String) {
List<String> newList = new LinkedList<String>();
newList.add((String) mapValue);
newList.add(item.getString());
multiPartMap.put(fieldName, newList);
} else {
Debug.logWarning("Form field found [" + fieldName + "] which was not handled!", module);
}
} else {
if (encoding != null) {
try {
multiPartMap.put(fieldName, item.getString(encoding));
} catch (java.io.UnsupportedEncodingException uee) {
Debug.logError(uee, "Unsupported Encoding, using deafault", module);
multiPartMap.put(fieldName, item.getString());
}
} else {
multiPartMap.put(fieldName, item.getString());
}
}
} else {
String fileName = item.getName();
if (fileName.indexOf('\\') > -1 || fileName.indexOf('/') > -1) {
// get just the file name IE and other browsers also pass in the local path
int lastIndex = fileName.lastIndexOf('\\');
if (lastIndex == -1) {
lastIndex = fileName.lastIndexOf('/');
}
if (lastIndex > -1) {
fileName = fileName.substring(lastIndex + 1);
}
}
multiPartMap.put(fieldName, ByteBuffer.wrap(item.get()));
multiPartMap.put("_" + fieldName + "_size", Long.valueOf(item.getSize()));
multiPartMap.put("_" + fieldName + "_fileName", fileName);
multiPartMap.put("_" + fieldName + "_contentType", item.getContentType());
}
}
}
}
// store the multi-part map as an attribute so we can access the parameters
request.setAttribute("multiPartMap", multiPartMap);
Map<String, Object> rawParametersMap = UtilHttp.getCombinedMap(request);
Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet();
// we have a service and the model; build the context
Map<String, Object> serviceContext = new HashMap<String, Object>();
for (ModelParam modelParam : model.getInModelParamList()) {
String name = modelParam.name;
// don't include userLogin, that's taken care of below
if ("userLogin".equals(name))
continue;
// don't include locale, that is also taken care of below
if ("locale".equals(name))
continue;
// don't include timeZone, that is also taken care of below
if ("timeZone".equals(name))
continue;
// don't include theme, that is also taken care of below
if ("visualTheme".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);
}
// include the Theme object
if (visualTheme != null) {
serviceContext.put("visualTheme", visualTheme);
}
// invoke the service
Map<String, Object> result = null;
try {
if (ASYNC.equalsIgnoreCase(mode)) {
dispatcher.runAsync(serviceName, serviceContext);
} else {
result = dispatcher.runSync(serviceName, serviceContext);
}
} catch (ServiceAuthException e) {
// not logging since the service engine already did
request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
return "error";
} catch (ServiceValidationException e) {
// not logging since the service engine already did
request.setAttribute("serviceValidationException", e);
if (e.getMessageList() != null) {
request.setAttribute("_ERROR_MESSAGE_LIST_", e.getMessageList());
} else {
request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
}
return "error";
} catch (GenericServiceException e) {
Debug.logError(e, "Service invocation error", module);
throw new EventHandlerException("Service invocation error", e.getNested());
}
String responseString = null;
if (result == null) {
responseString = ModelService.RESPOND_SUCCESS;
} else {
if (!result.containsKey(ModelService.RESPONSE_MESSAGE)) {
responseString = ModelService.RESPOND_SUCCESS;
} else {
responseString = (String) result.get(ModelService.RESPONSE_MESSAGE);
}
// set the messages in the request; this will be picked up by messages.ftl and displayed
request.setAttribute("_ERROR_MESSAGE_LIST_", result.get(ModelService.ERROR_MESSAGE_LIST));
request.setAttribute("_ERROR_MESSAGE_MAP_", result.get(ModelService.ERROR_MESSAGE_MAP));
request.setAttribute("_ERROR_MESSAGE_", result.get(ModelService.ERROR_MESSAGE));
request.setAttribute("_EVENT_MESSAGE_LIST_", result.get(ModelService.SUCCESS_MESSAGE_LIST));
request.setAttribute("_EVENT_MESSAGE_", result.get(ModelService.SUCCESS_MESSAGE));
// set the results in the request
for (Map.Entry<String, Object> rme : result.entrySet()) {
String resultKey = rme.getKey();
Object resultValue = rme.getValue();
if (resultKey != null && !ModelService.RESPONSE_MESSAGE.equals(resultKey) && !ModelService.ERROR_MESSAGE.equals(resultKey) && !ModelService.ERROR_MESSAGE_LIST.equals(resultKey) && !ModelService.ERROR_MESSAGE_MAP.equals(resultKey) && !ModelService.SUCCESS_MESSAGE.equals(resultKey) && !ModelService.SUCCESS_MESSAGE_LIST.equals(resultKey)) {
request.setAttribute(resultKey, resultValue);
}
}
}
if (Debug.verboseOn())
Debug.logVerbose("[Event Return]: " + responseString, module);
return responseString;
}
Aggregations