Example usage for javax.servlet.http HttpServletRequest getCharacterEncoding

List of usage examples for javax.servlet.http HttpServletRequest getCharacterEncoding

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getCharacterEncoding.

Prototype

public String getCharacterEncoding();

Source Link

Document

Returns the name of the character encoding used in the body of this request.

Usage

From source file:org.apache.catalina.valves.ExtendedAccessLogValve.java

/**
 * Get app specific data.//  w  w  w  .j  a  v a 2  s.  com
 * @param fieldInfo The field to decode
 * @param request Where we will pull the data from.
 * @return The appropriate value
 */
private String getAppSpecific(FieldInfo fieldInfo, Request request) {

    ServletRequest sr = request.getRequest();
    HttpServletRequest hsr = null;
    if (sr instanceof HttpServletRequest)
        hsr = (HttpServletRequest) sr;

    switch (fieldInfo.xType) {
    case FieldInfo.X_PARAMETER:
        return wrap(urlEncode(sr.getParameter(fieldInfo.value)));
    case FieldInfo.X_REQUEST:
        return wrap(sr.getAttribute(fieldInfo.value));
    case FieldInfo.X_SESSION:
        HttpSession session = null;
        if (hsr != null) {
            session = hsr.getSession(false);
            if (session != null)
                return wrap(session.getAttribute(fieldInfo.value));
        }
        break;
    case FieldInfo.X_COOKIE:
        Cookie[] c = hsr.getCookies();
        for (int i = 0; c != null && i < c.length; i++) {
            if (fieldInfo.value.equals(c[i].getName())) {
                return wrap(c[i].getValue());
            }
        }
    case FieldInfo.X_APP:
        return wrap(request.getContext().getServletContext().getAttribute(fieldInfo.value));
    case FieldInfo.X_SERVLET_REQUEST:
        if (fieldInfo.location == FieldInfo.X_LOC_AUTHTYPE) {
            return wrap(hsr.getAuthType());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REMOTEUSER) {
            return wrap(hsr.getRemoteUser());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONID) {
            return wrap(hsr.getRequestedSessionId());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDFROMCOOKIE) {
            return wrap("" + hsr.isRequestedSessionIdFromCookie());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDVALID) {
            return wrap("" + hsr.isRequestedSessionIdValid());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CONTENTLENGTH) {
            return wrap("" + hsr.getContentLength());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CHARACTERENCODING) {
            return wrap(hsr.getCharacterEncoding());
        } else if (fieldInfo.location == FieldInfo.X_LOC_LOCALE) {
            return wrap(hsr.getLocale());
        } else if (fieldInfo.location == FieldInfo.X_LOC_PROTOCOL) {
            return wrap(hsr.getProtocol());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SCHEME) {
            return wrap(hsr.getScheme());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SECURE) {
            return wrap("" + hsr.isSecure());
        }
        break;
    default:
        ;
    }

    return "-";

}

From source file:org.wings.session.MultipartRequest.java

/**
 * Parses passed request and stores contained parameters.
 *
 * @throws IOException On unrecoverable parsing bugs due to old Tomcat version.
 *//*  www  .ja v  a2s. co m*/
protected void processRequest(HttpServletRequest req) throws IOException {
    String type = req.getContentType();
    if (type == null || !type.toLowerCase().startsWith("multipart/form-data")) {
        urlencodedRequest = true;
        return;
    }

    urlencodedRequest = false;
    parameters = new HashMap<String, List>();
    files = new HashMap<String, UploadedFile>();

    for (Iterator iterator = req.getParameterMap().entrySet().iterator(); iterator.hasNext(); /**/) {
        Map.Entry entry = (Map.Entry) iterator.next();
        parameters.put((String) entry.getKey(), new ArrayList(Arrays.asList((String[]) entry.getValue())));
    }

    String boundaryToken = extractBoundaryToken(type);
    if (boundaryToken == null) {
        /*
         * this could happen due to a bug in Tomcat 3.2.2 in combination
         * with Opera.
         * Opera sends the boundary on a separate line, which is perfectly
         * correct regarding the way header may be constructed 
         * (multiline headers). Alas, Tomcat fails to read the header in 
         * the content type line and thus we cannot read it.. haven't 
         * checked later versions of Tomcat, but upgrading is
         * definitly needed, since we cannot do anything about it here.
         * (JServ works fine, BTW.) (Henner)
         */
        throw new IOException("Separation boundary was not specified (BUG in Tomcat 3.* with Opera?)");
    }

    MultipartInputStream mimeStream = null;

    ByteArrayOutputStream headerByteArray;
    StringBuilder content = new StringBuilder();
    HashMap headers = null;
    int currentByte = 0;
    int currentPos = 0;
    int currentTransformByte = 0;
    String currentParam = null;
    File uploadFile = null;
    OutputStream fileStream = null;
    boolean done;
    int last = -1;

    try {
        mimeStream = new MultipartInputStream(req.getInputStream(), req.getContentLength(), maxSize);
        while (currentByte != -1) {
            // Read MIME part header line
            done = false;
            headerByteArray = new ByteArrayOutputStream();
            while ((currentByte = mimeStream.read()) != -1 && !done) {
                headerByteArray.write(currentByte);
                done = (last == '\n' && currentByte == '\r');
                last = currentByte;
            }
            if (currentByte == -1)
                break;

            headers = parseHeader(headerByteArray.toString(req.getCharacterEncoding()));
            headerByteArray.reset();
            currentParam = (String) headers.get("name");

            if (headers.size() == 1) { // .. it's not a file
                byte[] bytes = new byte[req.getContentLength()];
                currentPos = 0;
                while ((currentByte = mimeStream.read()) != -1) {
                    bytes[currentPos] = (byte) currentByte;
                    currentPos++;
                    if (currentPos >= boundaryToken.length()) {
                        int i;
                        for (i = 0; i < boundaryToken.length(); i++) {
                            if (boundaryToken
                                    .charAt(boundaryToken.length() - i - 1) != bytes[currentPos - i - 1]) {
                                i = 0;
                                break;
                            }
                        }
                        if (i == boundaryToken.length()) { // end of part ..
                            ByteArrayInputStream bais = new ByteArrayInputStream(bytes, 0,
                                    currentPos - boundaryToken.length() - 4);
                            InputStreamReader ir;
                            if (req.getCharacterEncoding() != null)
                                // It's common behaviour of browsers to encode their form input in the character
                                // encoding of the page, though they don't declare the used characterset explicetly
                                // for backward compatibility.
                                ir = new InputStreamReader(bais, req.getCharacterEncoding());
                            else
                                ir = new InputStreamReader(bais);
                            content.setLength(0);
                            while ((currentTransformByte = ir.read()) != -1) {
                                content.append((char) currentTransformByte);
                            }

                            putParameter(currentParam, content.toString());
                            break;
                        }
                    }
                }
            } else { // .. it's a file
                String filename = (String) headers.get("filename");
                if (filename != null && filename.length() != 0) {
                    // The filename may contain a full path.  Cut to just the filename.
                    int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
                    if (slash > -1) {
                        filename = filename.substring(slash + 1);
                    }
                    String name = (String) headers.get("name");

                    String contentType = (String) headers.get("content-type");
                    try {
                        uploadFile = File.createTempFile("wings_uploaded", "tmp");
                    } catch (IOException e) {
                        log.error("couldn't create temp file in '" + System.getProperty("java.io.tmpdir")
                                + "' (CATALINA_TMPDIR set correctly?)", e);
                        throw e;
                    }

                    UploadedFile upload = new UploadedFile(filename, contentType, uploadFile);
                    fileStream = new FileOutputStream(uploadFile);

                    fileStream = UploadFilterManager.createFilterInstance(name, fileStream);

                    AccessibleByteArrayOutputStream byteArray = new AccessibleByteArrayOutputStream();
                    byte[] bytes = null;

                    int blength = boundaryToken.length();
                    int i;
                    while ((currentByte = mimeStream.read()) != -1) {
                        byteArray.write(currentByte);
                        for (i = 0; i < blength; i++) {
                            if (boundaryToken.charAt(blength - i - 1) != byteArray.charAt(-i - 1)) {
                                i = 0;
                                if (byteArray.size() > 512 + blength + 2)
                                    byteArray.writeTo(fileStream, 512);
                                break;
                            }
                        }
                        if (i == blength) // end of part ..
                            break;
                    }
                    bytes = byteArray.toByteArray();
                    fileStream.write(bytes, 0, bytes.length - blength - 4);
                    fileStream.close();

                    files.put(name, upload);
                    putParameter(name, upload.toString());
                } else { // workaround for some netscape bug
                    int i;
                    int blength = boundaryToken.length();
                    while ((currentByte = mimeStream.read()) != -1) {
                        content.append((char) currentByte);
                        if (content.length() >= blength) {
                            for (i = 0; i < blength; i++) {
                                if (boundaryToken.charAt(blength - i - 1) != content
                                        .charAt(content.length() - i - 1)) {
                                    i = 0;
                                    break;
                                }
                            }
                            if (i == blength)
                                break;
                        }
                    }
                }
            }

            currentByte = mimeStream.read();
            if (currentByte == '\r' && mimeStream.read() != '\n')
                log.error("No line return char? " + currentByte);
            if (currentByte == '-' && mimeStream.read() != '-')
                log.error("?? No clue " + currentByte);
        }
    } catch (IOException ex) {
        // cleanup and store the exception for notification of SFileChooser
        log.warn("upload", ex);
        if (uploadFile != null)
            uploadFile.delete();
        setException(currentParam, ex);
    } finally {
        try {
            fileStream.close();
        } catch (Exception ign) {
        }
        try {
            mimeStream.close();
        } catch (Exception ign) {
        }
    }
}

From source file:org.deegree.services.wps.WPService.java

@Override
public void doSOAP(SOAPEnvelope soapDoc, HttpServletRequest request, HttpResponseBuffer response,
        List<FileItem> multiParts, SOAPFactory factory) throws ServletException, IOException {

    LOG.trace("doSOAP invoked");
    OMElement requestElement = soapDoc.getBody().getFirstElement();
    try {/*  w w w. j ava 2s. c o  m*/
        WPSRequestType requestType = getRequestTypeByName(requestElement.getLocalName());

        // check if requested version is supported and offered (except for GetCapabilities)
        Version requestVersion = getVersion(requestElement.getAttributeValue(new QName("version")));
        if (requestType != WPSRequestType.GetCapabilities) {
            checkVersion(requestVersion);
        }

        beginSOAPResponse(response);

        switch (requestType) {
        case GetCapabilities:
            GetCapabilitiesXMLAdapter getCapabilitiesAdapter = new GetCapabilitiesXMLAdapter();
            getCapabilitiesAdapter.setRootElement(requestElement);
            // getCapabilitiesAdapter.setSystemId( soapDoc.getSystemId() );
            GetCapabilities getCapabilitiesRequest = getCapabilitiesAdapter.parse100();
            doGetCapabilities(getCapabilitiesRequest, response);
            break;
        case DescribeProcess:
            DescribeProcessRequestXMLAdapter describeProcessAdapter = new DescribeProcessRequestXMLAdapter();
            describeProcessAdapter.setRootElement(requestElement);
            // describeProcessAdapter.setSystemId( soapDoc.getSystemId() );
            DescribeProcessRequest describeProcessRequest = describeProcessAdapter.parse100();
            doDescribeProcess(describeProcessRequest, response);
            break;
        case Execute:
            // TODO switch to StaX-based parsing
            ExecuteRequestXMLAdapter executeAdapter = new ExecuteRequestXMLAdapter(
                    processManager.getProcesses(), storageManager);
            executeAdapter.setRootElement(requestElement);
            // executeAdapter.setSystemId( soapDoc.getSystemId() );
            ExecuteRequest executeRequest = executeAdapter.parse100();
            ResponseForm responseForm = executeRequest.getResponseForm();
            if (responseForm != null && responseForm instanceof RawDataOutput) {
                String msg = "Response type RawDataOutput is not supported for SOAP requests.";
                throw new OWSException(msg, OWSException.OPTION_NOT_SUPPORTED);
            }

            doExecute(executeRequest, response);
            break;
        case GetOutput:
        case GetResponseDocument:
            String msg = "Request type '" + requestType.name() + "' is only support as KVP request.";
            throw new OWSException(msg, OWSException.OPERATION_NOT_SUPPORTED);
        }

        endSOAPResponse(response);

    } catch (OWSException e) {
        sendSOAPException(soapDoc.getHeader(), factory, response, e, null, null, null, request.getServerName(),
                request.getCharacterEncoding());
    } catch (XMLStreamException e) {
        LOG.debug(e.getMessage(), e);
    } catch (UnknownCRSException e) {
        LOG.debug(e.getMessage(), e);
    }
}

From source file:nl.nn.adapterframework.webcontrol.action.TestPipeLineExecute.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {

    // Initialize action
    initAction(request);/*from   w w w  . j  ava2 s  . com*/
    if (null == config) {
        return (mapping.findForward("noconfig"));
    }

    if (isCancelled(request)) {
        return (mapping.findForward("success"));
    }

    DynaActionForm pipeLineTestForm = (DynaActionForm) form;
    String form_adapterName = (String) pipeLineTestForm.get("adapterName");
    String form_message = (String) pipeLineTestForm.get("message");
    String form_resultText = "";
    String form_resultState = "";
    FormFile form_file = (FormFile) pipeLineTestForm.get("file");

    // if no message and no formfile, send an error
    if (StringUtils.isEmpty(form_message) && (form_file == null || form_file.getFileSize() == 0)) {

        storeFormData(null, null, null, pipeLineTestForm);
        warn("Nothing to send or test");
    }
    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        storeFormData(null, null, null, pipeLineTestForm);
        return (new ActionForward(mapping.getInput()));
    }
    if ((form_adapterName == null) || (form_adapterName.length() == 0)) {
        warn("No adapter selected");
    }
    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        storeFormData(null, null, form_message, pipeLineTestForm);
        return (new ActionForward(mapping.getInput()));
    }
    // Execute the request
    IAdapter adapter = config.getRegisteredAdapter(form_adapterName);
    if (adapter == null) {
        warn("Adapter with specified name [" + form_adapterName + "] could not be retrieved");
    }
    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        storeFormData(null, null, form_message, pipeLineTestForm);
        return (new ActionForward(mapping.getInput()));
    }

    // if upload is choosen, it prevails over the message
    if ((form_file != null) && (form_file.getFileSize() > 0)) {
        log.debug("Upload of file [" + form_file.getFileName() + "] ContentType[" + form_file.getContentType()
                + "]");
        if (FileUtils.extensionEqualsIgnoreCase(form_file.getFileName(), "zip")) {
            ZipInputStream archive = new ZipInputStream(new ByteArrayInputStream(form_file.getFileData()));
            for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) {
                String name = entry.getName();
                int size = (int) entry.getSize();
                if (size > 0) {
                    byte[] b = new byte[size];
                    int rb = 0;
                    int chunk = 0;
                    while (((int) size - rb) > 0) {
                        chunk = archive.read(b, rb, (int) size - rb);
                        if (chunk == -1) {
                            break;
                        }
                        rb += chunk;
                    }
                    String currentMessage = XmlUtils.readXml(b, 0, rb, request.getCharacterEncoding(), false);
                    //PipeLineResult pipeLineResult = adapter.processMessage(name+"_" + Misc.createSimpleUUID(), currentMessage);
                    PipeLineResult pipeLineResult = processMessage(adapter,
                            name + "_" + Misc.createSimpleUUID(), currentMessage);
                    form_resultText += name + ":" + pipeLineResult.getState() + "\n";
                    form_resultState = pipeLineResult.getState();
                }
                archive.closeEntry();
            }
            archive.close();
            form_message = null;
        } else {
            form_message = XmlUtils.readXml(form_file.getFileData(), request.getCharacterEncoding(), false);
        }
    } else {
        form_message = new String(form_message.getBytes(), Misc.DEFAULT_INPUT_STREAM_ENCODING);
    }

    if (form_message != null && form_message.length() > 0) {
        // Execute the request
        //PipeLineResult pipeLineResult = adapter.processMessage("testmessage" + Misc.createSimpleUUID(), form_message);
        PipeLineResult pipeLineResult = processMessage(adapter, "testmessage" + Misc.createSimpleUUID(),
                form_message);
        form_resultText = pipeLineResult.getResult();
        form_resultState = pipeLineResult.getState();
    }
    storeFormData(form_resultText, form_resultState, form_message, pipeLineTestForm);

    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        return (new ActionForward(mapping.getInput()));
    }

    // Forward control to the specified success URI
    log.debug("forward to success");
    return (mapping.findForward("success"));

}

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)
*//* www .j ava  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:net.ymate.module.webproxy.WebProxy.java

@SuppressWarnings("unchecked")
public void transmission(HttpServletRequest request, HttpServletResponse response, String url,
        Type.HttpMethod method) throws Exception {
    StopWatch _consumeTime = null;// w  w w .j  a  va  2  s  .c  om
    long _threadId = 0;
    if (_LOG.isDebugEnabled()) {
        _consumeTime = new StopWatch();
        _consumeTime.start();
        _threadId = Thread.currentThread().getId();
        _LOG.debug("-------------------------------------------------");
        _LOG.debug("--> [" + _threadId + "] URL: " + url);
    }
    //
    HttpURLConnection _conn = null;
    try {
        if (__moduleCfg.isUseProxy()) {
            _conn = (HttpURLConnection) new URL(url).openConnection(__moduleCfg.getProxy());
        } else {
            _conn = (HttpURLConnection) new URL(url).openConnection();
        }
        _conn.setUseCaches(__moduleCfg.isUseCaches());
        _conn.setInstanceFollowRedirects(__moduleCfg.isInstanceFollowRedirects());
        //
        boolean _postFlag = Type.HttpMethod.POST.equals(method);
        boolean _multipartFlag = _postFlag && StringUtils.contains(request.getContentType(), "multipart/");
        if (_postFlag) {
            _conn.setDoOutput(true);
            _conn.setDoInput(true);
            _conn.setRequestMethod(method.name());
        }
        if (__moduleCfg.getConnectTimeout() > 0) {
            _conn.setConnectTimeout(__moduleCfg.getConnectTimeout());
        }
        if (__moduleCfg.getReadTimeout() > 0) {
            _conn.setReadTimeout(__moduleCfg.getReadTimeout());
        }
        //
        if (_LOG.isDebugEnabled()) {
            _LOG.debug("--> [" + _threadId + "] Method: " + method.name());
            _LOG.debug("--> [" + _threadId + "] Request Headers: ");
        }
        //
        Enumeration _header = request.getHeaderNames();
        while (_header.hasMoreElements()) {
            String _name = (String) _header.nextElement();
            String _value = request.getHeader(_name);
            boolean _flag = false;
            if (_postFlag && StringUtils.equalsIgnoreCase(_name, "content-type")
                    || __moduleCfg.isTransferHeaderEnabled()
                            && (!__moduleCfg.getTransferHeaderBlackList().isEmpty()
                                    && !__moduleCfg.getTransferHeaderBlackList().contains(_name)
                                    || !__moduleCfg.getTransferHeaderWhiteList().isEmpty()
                                            && __moduleCfg.getTransferHeaderWhiteList().contains(_name))) {
                _conn.setRequestProperty(_name, _value);
                _flag = true;
            }
            //
            if (_LOG.isDebugEnabled()) {
                _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _name + ": " + _value);
            }
        }
        _conn.connect();
        //
        if (_postFlag) {
            DataOutputStream _output = new DataOutputStream(_conn.getOutputStream());
            try {
                if (_multipartFlag) {
                    if (_LOG.isDebugEnabled()) {
                        _LOG.debug("--> [" + _threadId + "] Multipart: TRUE");
                    }
                    IOUtils.copyLarge(request.getInputStream(), _output);
                } else {
                    String _charset = request.getCharacterEncoding();
                    String _queryStr = ParamUtils.buildQueryParamStr(request.getParameterMap(), true, _charset);
                    IOUtils.write(_queryStr, _output, _charset);
                    //
                    if (_LOG.isDebugEnabled()) {
                        _LOG.debug("--> [" + _threadId + "] Request Parameters: ");
                        Map<String, String> _paramsMap = ParamUtils.parseQueryParamStr(_queryStr, true,
                                _charset);
                        for (Map.Entry<String, String> _param : _paramsMap.entrySet()) {
                            _LOG.debug("--> [" + _threadId + "] \t - " + _param.getKey() + ": "
                                    + _param.getValue());
                        }
                    }
                }
                _output.flush();
            } finally {
                IOUtils.closeQuietly(_output);
            }
        }
        //
        int _code = _conn.getResponseCode();
        //
        if (_LOG.isDebugEnabled()) {
            _LOG.debug("--> [" + _threadId + "] Response Code: " + _code);
            _LOG.debug("--> [" + _threadId + "] Response Headers: ");
        }
        //
        Map<String, List<String>> _headers = _conn.getHeaderFields();
        for (Map.Entry<String, List<String>> _entry : _headers.entrySet()) {
            if (_entry.getKey() != null) {
                boolean _flag = false;
                String _values = StringUtils.join(_entry.getValue(), ",");
                if (StringUtils.equalsIgnoreCase(_entry.getKey(), "content-type")
                        || __moduleCfg.isTransferHeaderEnabled()
                                && !__moduleCfg.getResponseHeaderWhileList().isEmpty()
                                && __moduleCfg.getResponseHeaderWhileList().contains(_entry.getKey())) {
                    response.setHeader(_entry.getKey(), _values);
                    _flag = true;
                }
                if (_LOG.isDebugEnabled()) {
                    _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _entry.getKey() + ": "
                            + _values);
                }
            }
        }
        if (HttpURLConnection.HTTP_BAD_REQUEST <= _conn.getResponseCode()) {
            response.sendError(_code);
        } else {
            if (HttpURLConnection.HTTP_OK == _code) {
                InputStream _inputStream = _conn.getInputStream();
                if (_inputStream != null) {
                    if (!_multipartFlag) {
                        byte[] _content = IOUtils.toByteArray(_inputStream);
                        IOUtils.write(_content, response.getOutputStream());
                        //
                        if (_LOG.isDebugEnabled()) {
                            _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody(
                                    _conn, _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding()));
                        }
                    } else {
                        IOUtils.copyLarge(_conn.getInputStream(), response.getOutputStream());
                        //
                        if (_LOG.isDebugEnabled()) {
                            _LOG.debug("--> [" + _threadId + "] Response Content: MultipartBody");
                        }
                    }
                } else if (_LOG.isDebugEnabled()) {
                    _LOG.debug("--> [" + _threadId + "] Response Content: NULL");
                }
                response.flushBuffer();
            } else {
                InputStream _inputStream = _conn.getInputStream();
                if (_inputStream != null) {
                    byte[] _content = IOUtils.toByteArray(_inputStream);
                    IOUtils.write(_content, response.getOutputStream());
                    //
                    if (_LOG.isDebugEnabled()) {
                        _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody(_conn,
                                _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding()));
                    }
                } else if (_LOG.isDebugEnabled()) {
                    _LOG.debug("--> [" + _threadId + "] Response Content: NULL");
                }
                response.setStatus(_code);
                response.flushBuffer();
            }
        }
    } catch (Throwable e) {
        _LOG.warn("An exception occurred while processing request mapping '" + url + "': ",
                RuntimeUtils.unwrapThrow(e));
    } finally {
        IOUtils.close(_conn);
        //
        if (_LOG.isDebugEnabled()) {
            if (_consumeTime != null) {
                _consumeTime.stop();
                _LOG.debug("--> [" + _threadId + "] Total execution time: " + _consumeTime.getTime() + "ms");
            }
            _LOG.debug("-------------------------------------------------");
        }
    }
}

From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java

public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) {
    HttpServletRequest initialRequest = (HttpServletRequest) request;
    this.session = session;
    this.authorization = authorization;
    //Copy common data
    authType = initialRequest.getAuthType();
    contextPath = initialRequest.getContextPath();
    remoteUser = initialRequest.getRemoteUser();
    userPrincipal = initialRequest.getUserPrincipal();
    requestedSessionId = initialRequest.getRequestedSessionId();
    requestedSessionIdValid = initialRequest.isRequestedSessionIdValid();

    attributes = new HashMap();
    Enumeration attributeNames = initialRequest.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String name = (String) attributeNames.nextElement();
        Object attribute = initialRequest.getAttribute(name);
        if ((null != name) && (null != attribute)) {
            attributes.put(name, attribute);
        }/*from   w w  w  .  j a  v  a  2  s.  c o  m*/
    }

    // Warning:  For some reason, the various javax.include.* attributes are
    // not available via the getAttributeNames() call.  This may be limited
    // to a Liferay issue but when the MainPortlet dispatches the call to
    // the MainServlet, all of the javax.include.* attributes can be
    // retrieved using this.request.getAttribute() but they do NOT appear in
    // the Enumeration of names returned by getAttributeNames().  So here
    // we manually add them to our map to ensure we can find them later.
    String[] incAttrKeys = Constants.INC_CONSTANTS;
    for (int index = 0; index < incAttrKeys.length; index++) {
        String incAttrKey = incAttrKeys[index];
        Object incAttrVal = initialRequest.getAttribute(incAttrKey);
        if (incAttrVal != null) {
            attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey));
        }
    }

    headers = new HashMap();
    Enumeration headerNames = initialRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        Enumeration values = initialRequest.getHeaders(name);
        headers.put(name, Collections.list(values));
    }

    parameters = new HashMap();
    Enumeration parameterNames = initialRequest.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String name = (String) parameterNames.nextElement();
        parameters.put(name, initialRequest.getParameterValues(name));
    }

    scheme = initialRequest.getScheme();
    serverName = initialRequest.getServerName();
    serverPort = initialRequest.getServerPort();
    secure = initialRequest.isSecure();

    //Copy servlet specific data
    cookies = initialRequest.getCookies();
    method = initialRequest.getMethod();
    pathInfo = initialRequest.getPathInfo();
    pathTranslated = initialRequest.getPathTranslated();
    queryString = initialRequest.getQueryString();
    requestURI = initialRequest.getRequestURI();
    try {
        requestURL = initialRequest.getRequestURL();
    } catch (NullPointerException e) {
        //TODO remove this catch block when GlassFish bug is addressed
        if (log.isErrorEnabled()) {
            log.error("Null Protocol Scheme in request", e);
        }
        HttpServletRequest req = initialRequest;
        requestURL = new StringBuffer(
                "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI());
    }
    servletPath = initialRequest.getServletPath();
    servletSession = initialRequest.getSession();
    isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie();
    isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL();
    characterEncoding = initialRequest.getCharacterEncoding();
    contentLength = initialRequest.getContentLength();
    contentType = initialRequest.getContentType();
    protocol = initialRequest.getProtocol();
    remoteAddr = initialRequest.getRemoteAddr();
    remoteHost = initialRequest.getRemoteHost();
    initializeServlet2point4Properties(initialRequest);
}

From source file:jp.aegif.alfresco.online_webdav.WebDAVMethod.java

/**
 * Set the request/response details/*from  ww w .  j  a  va  2 s .c o m*/
 * 
 * @param req
 *            HttpServletRequest
 * @param resp
 *            HttpServletResponse
 * @param registry
 *            ServiceRegistry
 * @param rootNode
 *            NodeRef
 */
public void setDetails(final HttpServletRequest req, HttpServletResponse resp, WebDAVHelper davHelper,
        NodeRef rootNode) {
    // Wrap the request so that it is 'retryable'. Calls to getInputStream() and getReader() will result in the
    // request body being read into an intermediate file.
    this.m_request = new HttpServletRequestWrapper(req) {

        @Override
        public ServletInputStream getInputStream() throws IOException {
            if (WebDAVMethod.this.m_reader != null) {
                throw new IllegalStateException("Reader in use");
            }
            if (WebDAVMethod.this.m_inputStream == null) {
                final FileInputStream in = new FileInputStream(getRequestBodyAsFile(req));
                WebDAVMethod.this.m_inputStream = new ServletInputStream() {

                    @Override
                    public int read() throws IOException {
                        return in.read();
                    }

                    @Override
                    public int read(byte b[]) throws IOException {
                        return in.read(b);
                    }

                    @Override
                    public int read(byte b[], int off, int len) throws IOException {
                        return in.read(b, off, len);
                    }

                    @Override
                    public long skip(long n) throws IOException {
                        return in.skip(n);
                    }

                    @Override
                    public int available() throws IOException {
                        return in.available();
                    }

                    @Override
                    public void close() throws IOException {
                        in.close();
                    }

                    @Override
                    public void mark(int readlimit) {
                        in.mark(readlimit);
                    }

                    @Override
                    public void reset() throws IOException {
                        in.reset();
                    }

                    @Override
                    public boolean markSupported() {
                        return in.markSupported();
                    }
                };
            }

            return WebDAVMethod.this.m_inputStream;
        }

        @Override
        public BufferedReader getReader() throws IOException {
            if (WebDAVMethod.this.m_inputStream != null) {
                throw new IllegalStateException("Input Stream in use");
            }
            if (WebDAVMethod.this.m_reader == null) {
                String encoding = req.getCharacterEncoding();
                WebDAVMethod.this.m_reader = new BufferedReader(
                        new InputStreamReader(new FileInputStream(getRequestBodyAsFile(req)),
                                encoding == null ? "ISO-8859-1" : encoding));
            }

            return WebDAVMethod.this.m_reader;
        }

    };
    this.m_response = resp;
    this.m_davHelper = davHelper;
    this.m_rootNodeRef = rootNode;

    this.m_strPath = m_davHelper.getRepositoryPath(m_request);
}

From source file:net.openkoncept.vroom.VroomController.java

private void processRequestInvoke(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    String method = request.getParameter(METHOD);
    String beanClass = request.getParameter(BEAN_CLASS);
    String var = request.getParameter(VAR);
    if (var == null || var.trim().length() == 0) {
        var = beanClass;
    }//from   ww w  .j av  a  2  s.c o  m
    String scope = request.getParameter(SCOPE);
    if (scope == null || scope.trim().length() == 0) {
        if (var.equals(beanClass)) {
            scope = SCOPE_APPLICATION;
        } else {
            scope = SCOPE_SESSION;
        }
    }
    Object beanObject;
    Object object = null;
    try {
        Class clazz = Class.forName(beanClass);
        if (SCOPE_APPLICATION.equals(scope)) {
            beanObject = appBeanMap.get(var);
            if (beanObject == null) {
                beanObject = clazz.newInstance();
                appBeanMap.put(var, beanObject);
            }
        } else if (SCOPE_SESSION.equals(scope)) {
            beanObject = request.getSession().getAttribute(var);
            if (beanObject == null) {
                beanObject = clazz.newInstance();
                request.getSession().setAttribute(var, beanObject);
            }
        } else if (SCOPE_REQUEST.equals(scope)) {
            beanObject = request.getAttribute(var);
            if (beanObject == null) {
                beanObject = clazz.newInstance();
                request.setAttribute(var, beanObject);
            }
        } else {
            beanObject = clazz.newInstance();
        }
        String output;
        if ("getProperties".equals(method)) {
            object = beanObject;
        } else {
            Class[] signature = new Class[] { HttpServletRequest.class, HttpServletResponse.class };
            Method m;
            try {
                m = clazz.getMethod(method, signature);
                object = m.invoke(beanObject, new Object[] { request, response });
            } catch (Exception ex) {
                try {
                    m = clazz.getMethod(method, null);
                    object = m.invoke(beanObject, null);
                } catch (Exception ex2) {
                    try {
                        signature = new Class[] { HttpServletRequest.class };
                        m = clazz.getMethod(method, signature);
                        object = m.invoke(beanObject, new Object[] { request });
                    } catch (NoSuchMethodException ex3) {
                        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
                    } catch (InvocationTargetException ex3) {
                        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
                    }
                }
            }
            if (object == null) {
                object = "";
            }
        }
        JSONObject jo = VroomUtilities.convertObjectToJSONObject(object);
        jo.put("contextPath", request.getContextPath());
        jo.put("sessionId", request.getSession().getId());
        jo.put("locale", VroomUtilities.convertObjectToJSONObject(request.getLocale()));
        output = jo.toString();
        String encoding = request.getHeader("response-encoding");
        if (encoding == null || encoding.trim().length() == 0) {
            encoding = request.getCharacterEncoding();
        }
        response.setContentType(JSON_MIME_TYPE);
        if (encoding != null) {
            VroomUtilities.safeCall(response, "setCharacterEncoding", new Class[] { String.class },
                    new Object[] { encoding });
            //                response.setCharacterEncoding(encoding);
        }
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(output);
        } catch (IOException e) {
            throw new ServletException(e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    } catch (ClassNotFoundException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (InstantiationException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (IllegalAccessException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (JSONException ex) {
        throw new ServletException("Invalid JSON Object [" + object + "]", ex);
    }
}

From source file:org.apache.ofbiz.webapp.event.ServiceEventHandler.java

/**
 * @see org.apache.ofbiz.webapp.event.EventHandler#invoke(ConfigXMLReader.Event, ConfigXMLReader.RequestMap, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///  w w w . jav 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", "http.upload.max.size", "-1",
                dctx.getDelegator());
        long maxUploadSize = -1;
        try {
            maxUploadSize = Long.parseLong(maxSizeStr);
        } catch (NumberFormatException e) {
            Debug.logError(e, "Unable to obtain the max upload size from general.properties; using default -1",
                    module);
            maxUploadSize = -1;
        }
        // get the http size threshold configuration - files bigger than this will be
        // temporarly stored on disk during upload
        String sizeThresholdStr = EntityUtilProperties.getPropertyValue("general",
                "http.upload.max.sizethreshold", "10240", dctx.getDelegator());
        int sizeThreshold = 10240; // 10K
        try {
            sizeThreshold = Integer.parseInt(sizeThresholdStr);
        } catch (NumberFormatException e) {
            Debug.logError(e, "Unable to obtain the threshold size from general.properties; using default 10K",
                    module);
            sizeThreshold = -1;
        }
        // directory used to temporarily store files that are larger than the configured size threshold
        String tmpUploadRepository = EntityUtilProperties.getPropertyValue("general",
                "http.upload.tmprepository", "runtime/tmp", dctx.getDelegator());
        String encoding = request.getCharacterEncoding();
        // check for multipart content types which may have uploaded items

        ServletFileUpload upload = new ServletFileUpload(
                new DiskFileItemFactory(sizeThreshold, new File(tmpUploadRepository)));

        // create the progress listener and add it to the session
        FileUploadProgressListener listener = new FileUploadProgressListener();
        upload.setProgressListener(listener);
        session.setAttribute("uploadProgressListener", listener);

        if (encoding != null) {
            upload.setHeaderEncoding(encoding);
        }
        upload.setSizeMax(maxUploadSize);

        List<FileItem> uploadedItems = null;
        try {
            uploadedItems = UtilGenerics.<FileItem>checkList(upload.parseRequest(request));
        } catch (FileUploadException e) {
            throw new EventHandlerException("Problems reading uploaded data", e);
        }
        if (uploadedItems != null) {
            for (FileItem item : uploadedItems) {
                String fieldName = item.getFieldName();
                //byte[] itemBytes = item.get();
                /*
                Debug.logInfo("Item Info [" + fieldName + "] : " + item.getName() + " / " + item.getSize() + " / " +
                    item.getContentType() + " FF: " + item.isFormField(), module);
                */
                if (item.isFormField() || item.getName() == null) {
                    if (multiPartMap.containsKey(fieldName)) {
                        Object mapValue = multiPartMap.get(fieldName);
                        if (mapValue instanceof List<?>) {
                            checkList(mapValue, Object.class).add(item.getString());
                        } else if (mapValue instanceof String) {
                            List<String> newList = new LinkedList<String>();
                            newList.add((String) mapValue);
                            newList.add(item.getString());
                            multiPartMap.put(fieldName, newList);
                        } else {
                            Debug.logWarning("Form field found [" + fieldName + "] which was not handled!",
                                    module);
                        }
                    } else {
                        if (encoding != null) {
                            try {
                                multiPartMap.put(fieldName, item.getString(encoding));
                            } catch (java.io.UnsupportedEncodingException uee) {
                                Debug.logError(uee, "Unsupported Encoding, using deafault", module);
                                multiPartMap.put(fieldName, item.getString());
                            }
                        } else {
                            multiPartMap.put(fieldName, item.getString());
                        }
                    }
                } else {
                    String fileName = item.getName();
                    if (fileName.indexOf('\\') > -1 || fileName.indexOf('/') > -1) {
                        // get just the file name IE and other browsers also pass in the local path
                        int lastIndex = fileName.lastIndexOf('\\');
                        if (lastIndex == -1) {
                            lastIndex = fileName.lastIndexOf('/');
                        }
                        if (lastIndex > -1) {
                            fileName = fileName.substring(lastIndex + 1);
                        }
                    }
                    multiPartMap.put(fieldName, ByteBuffer.wrap(item.get()));
                    multiPartMap.put("_" + fieldName + "_size", Long.valueOf(item.getSize()));
                    multiPartMap.put("_" + fieldName + "_fileName", fileName);
                    multiPartMap.put("_" + fieldName + "_contentType", item.getContentType());
                }
            }
        }
    }

    // store the multi-part map as an attribute so we can access the parameters
    request.setAttribute("multiPartMap", multiPartMap);

    Map<String, Object> rawParametersMap = UtilHttp.getCombinedMap(request);
    Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet();

    // we have a service and the model; build the context
    Map<String, Object> serviceContext = new HashMap<String, Object>();
    for (ModelParam modelParam : model.getInModelParamList()) {
        String name = modelParam.name;

        // don't include userLogin, that's taken care of below
        if ("userLogin".equals(name))
            continue;
        // don't include locale, that is also taken care of below
        if ("locale".equals(name))
            continue;
        // don't include timeZone, that is also taken care of below
        if ("timeZone".equals(name))
            continue;

        Object value = null;
        if (UtilValidate.isNotEmpty(modelParam.stringMapPrefix)) {
            Map<String, Object> paramMap = UtilHttp.makeParamMapWithPrefix(request, multiPartMap,
                    modelParam.stringMapPrefix, null);
            value = paramMap;
            if (Debug.verboseOn())
                Debug.logVerbose("Set [" + modelParam.name + "]: " + paramMap, module);
        } else if (UtilValidate.isNotEmpty(modelParam.stringListSuffix)) {
            List<Object> paramList = UtilHttp.makeParamListWithSuffix(request, multiPartMap,
                    modelParam.stringListSuffix, null);
            value = paramList;
        } else {
            // first check the multi-part map
            value = multiPartMap.get(name);

            // next check attributes; do this before parameters so that attribute which can be changed by code can override parameters which can't
            if (UtilValidate.isEmpty(value)) {
                Object tempVal = request
                        .getAttribute(UtilValidate.isEmpty(modelParam.requestAttributeName) ? name
                                : modelParam.requestAttributeName);
                if (tempVal != null) {
                    value = tempVal;
                }
            }

            // check the request parameters
            if (UtilValidate.isEmpty(value)) {
                ServiceEventHandler.checkSecureParameter(requestMap, urlOnlyParameterNames, name, session,
                        serviceName, dctx.getDelegator());

                // if the service modelParam has allow-html="any" then get this direct from the request instead of in the parameters Map so there will be no canonicalization possibly messing things up
                if ("any".equals(modelParam.allowHtml)) {
                    value = request.getParameter(name);
                } else {
                    // use the rawParametersMap from UtilHttp in order to also get pathInfo parameters, do canonicalization, etc
                    value = rawParametersMap.get(name);
                }

                // make any composite parameter data (e.g., from a set of parameters {name_c_date, name_c_hour, name_c_minutes})
                if (value == null) {
                    value = UtilHttp.makeParamValueFromComposite(request, name, locale);
                }
            }

            // then session
            if (UtilValidate.isEmpty(value)) {
                Object tempVal = request.getSession()
                        .getAttribute(UtilValidate.isEmpty(modelParam.sessionAttributeName) ? name
                                : modelParam.sessionAttributeName);
                if (tempVal != null) {
                    value = tempVal;
                }
            }

            // no field found
            if (value == null) {
                //still null, give up for this one
                continue;
            }

            if (value instanceof String && ((String) value).length() == 0) {
                // interpreting empty fields as null values for each in back end handling...
                value = null;
            }
        }
        // set even if null so that values will get nulled in the db later on
        serviceContext.put(name, value);
    }

    // get only the parameters for this service - converted to proper type
    // TODO: pass in a list for error messages, like could not convert type or not a proper X, return immediately with messages if there are any
    List<Object> errorMessages = new LinkedList<Object>();
    serviceContext = model.makeValid(serviceContext, ModelService.IN_PARAM, true, errorMessages, timeZone,
            locale);
    if (errorMessages.size() > 0) {
        // uh-oh, had some problems...
        request.setAttribute("_ERROR_MESSAGE_LIST_", errorMessages);
        return "error";
    }

    // include the UserLogin value object
    if (userLogin != null) {
        serviceContext.put("userLogin", userLogin);
    }

    // include the Locale object
    if (locale != null) {
        serviceContext.put("locale", locale);
    }

    // include the TimeZone object
    if (timeZone != null) {
        serviceContext.put("timeZone", timeZone);
    }

    // invoke the service
    Map<String, Object> result = null;
    try {
        if (ASYNC.equalsIgnoreCase(mode)) {
            dispatcher.runAsync(serviceName, serviceContext);
        } else {
            result = dispatcher.runSync(serviceName, serviceContext);
        }
    } catch (ServiceAuthException e) {
        // not logging since the service engine already did
        request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
        return "error";
    } catch (ServiceValidationException e) {
        // not logging since the service engine already did
        request.setAttribute("serviceValidationException", e);
        if (e.getMessageList() != null) {
            request.setAttribute("_ERROR_MESSAGE_LIST_", e.getMessageList());
        } else {
            request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
        }
        return "error";
    } catch (GenericServiceException e) {
        Debug.logError(e, "Service invocation error", module);
        throw new EventHandlerException("Service invocation error", e.getNested());
    }

    String responseString = null;

    if (result == null) {
        responseString = ModelService.RESPOND_SUCCESS;
    } else {

        if (!result.containsKey(ModelService.RESPONSE_MESSAGE)) {
            responseString = ModelService.RESPOND_SUCCESS;
        } else {
            responseString = (String) result.get(ModelService.RESPONSE_MESSAGE);
        }

        // set the messages in the request; this will be picked up by messages.ftl and displayed
        request.setAttribute("_ERROR_MESSAGE_LIST_", result.get(ModelService.ERROR_MESSAGE_LIST));
        request.setAttribute("_ERROR_MESSAGE_MAP_", result.get(ModelService.ERROR_MESSAGE_MAP));
        request.setAttribute("_ERROR_MESSAGE_", result.get(ModelService.ERROR_MESSAGE));

        request.setAttribute("_EVENT_MESSAGE_LIST_", result.get(ModelService.SUCCESS_MESSAGE_LIST));
        request.setAttribute("_EVENT_MESSAGE_", result.get(ModelService.SUCCESS_MESSAGE));

        // set the results in the request
        for (Map.Entry<String, Object> rme : result.entrySet()) {
            String resultKey = rme.getKey();
            Object resultValue = rme.getValue();

            if (resultKey != null && !ModelService.RESPONSE_MESSAGE.equals(resultKey)
                    && !ModelService.ERROR_MESSAGE.equals(resultKey)
                    && !ModelService.ERROR_MESSAGE_LIST.equals(resultKey)
                    && !ModelService.ERROR_MESSAGE_MAP.equals(resultKey)
                    && !ModelService.SUCCESS_MESSAGE.equals(resultKey)
                    && !ModelService.SUCCESS_MESSAGE_LIST.equals(resultKey)) {
                request.setAttribute(resultKey, resultValue);
            }
        }
    }

    if (Debug.verboseOn())
        Debug.logVerbose("[Event Return]: " + responseString, module);
    return responseString;
}