Example usage for org.apache.commons.fileupload.servlet ServletRequestContext ServletRequestContext

List of usage examples for org.apache.commons.fileupload.servlet ServletRequestContext ServletRequestContext

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletRequestContext ServletRequestContext.

Prototype

public ServletRequestContext(HttpServletRequest request) 

Source Link

Document

Construct a context for this request.

Usage

From source file:org.apache.felix.webconsole.WebConsoleUtil.java

/**
 * An utility method, that is used to filter out simple parameter from file
 * parameter when multipart transfer encoding is used.
 *
 * This method processes the request and sets a request attribute
 * {@link AbstractWebConsolePlugin#ATTR_FILEUPLOAD}. The attribute value is a {@link Map}
 * where the key is a String specifying the field name and the value
 * is a {@link org.apache.commons.fileupload.FileItem}.
 *
 * @param request the HTTP request coming from the user
 * @param name the name of the parameter
 * @return if not multipart transfer encoding is used - the value is the
 *  parameter value or <code>null</code> if not set. If multipart is used,
 *  and the specified parameter is field - then the value of the parameter
 *  is returned./* w  w w  . j  a va 2  s. c o  m*/
 */
public static final String getParameter(HttpServletRequest request, String name) {
    // just get the parameter if not a multipart/form-data POST
    if (!FileUploadBase.isMultipartContent(new ServletRequestContext(request))) {
        return request.getParameter(name);
    }

    // check, whether we already have the parameters
    Map params = (Map) request.getAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD);
    if (params == null) {
        // parameters not read yet, read now
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(256000);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(-1);

        // Parse the request
        params = new HashMap();
        try {
            List items = upload.parseRequest(request);
            for (Iterator fiter = items.iterator(); fiter.hasNext();) {
                FileItem fi = (FileItem) fiter.next();
                FileItem[] current = (FileItem[]) params.get(fi.getFieldName());
                if (current == null) {
                    current = new FileItem[] { fi };
                } else {
                    FileItem[] newCurrent = new FileItem[current.length + 1];
                    System.arraycopy(current, 0, newCurrent, 0, current.length);
                    newCurrent[current.length] = fi;
                    current = newCurrent;
                }
                params.put(fi.getFieldName(), current);
            }
        } catch (FileUploadException fue) {
            // TODO: log
        }
        request.setAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD, params);
    }

    FileItem[] param = (FileItem[]) params.get(name);
    if (param != null) {
        for (int i = 0; i < param.length; i++) {
            if (param[i].isFormField()) {
                return param[i].getString();
            }
        }
    }

    // no valid string parameter, fail
    return null;
}

From source file:org.apache.myfaces.webapp.filter.servlet.ServletChacheFileSizeErrorsFileUpload.java

/**
 * Similar to {@link ServletFileUpload#parseRequest(RequestContext)} but will
 * catch and swallow FileSizeLimitExceededExceptions in order to return as
 * many usable items as possible.//from w ww. j ava 2s . co  m
 * 
 * @param fileUpload
 * @return List of {@link FileItem} excluding any that exceed max size.  
 * @throws FileUploadException
 */
public List parseRequestCatchingFileSizeErrors(HttpServletRequest request, FileUpload fileUpload)
        throws FileUploadException {
    try {
        List items = new ArrayList();

        // The line below throws a SizeLimitExceededException (wrapped by a
        // FileUploadIOException) if the request is longer than the max size
        // allowed by fileupload requests (FileUpload.getSizeMax)
        // But note that if the request does not send proper headers this check
        // just will not do anything and we still have to check it again.
        FileItemIterator iter = fileUpload.getItemIterator(new ServletRequestContext(request));

        FileItemFactory fac = fileUpload.getFileItemFactory();
        if (fac == null) {
            throw new NullPointerException("No FileItemFactory has been set.");
        }

        long maxFileSize = this.getFileSizeMax();
        long maxSize = this.getSizeMax();
        boolean checkMaxSize = false;

        if (maxFileSize == -1L) {
            //The max allowed file size should be approximate to the maxSize
            maxFileSize = maxSize;
        }
        if (maxSize != -1L) {
            checkMaxSize = true;
        }

        while (iter.hasNext()) {
            final FileItemStream item = iter.next();
            FileItem fileItem = fac.createItem(item.getFieldName(), item.getContentType(), item.isFormField(),
                    item.getName());

            long allowedLimit = 0L;
            try {
                if (maxFileSize != -1L || checkMaxSize) {
                    if (checkMaxSize) {
                        allowedLimit = maxSize > maxFileSize ? maxFileSize : maxSize;
                    } else {
                        //Just put the limit
                        allowedLimit = maxFileSize;
                    }

                    long contentLength = getContentLength(item.getHeaders());

                    //If we have a content length in the header we can use it
                    if (contentLength != -1L && contentLength > allowedLimit) {
                        throw new FileUploadIOException(new FileSizeLimitExceededException(
                                "The field " + item.getFieldName() + " exceeds its maximum permitted "
                                        + " size of " + allowedLimit + " characters.",
                                contentLength, allowedLimit));
                    }

                    //Otherwise we must limit the input as it arrives (NOTE: we cannot rely
                    //on commons upload to throw this exception as it will close the 
                    //underlying stream
                    final InputStream itemInputStream = item.openStream();

                    InputStream limitedInputStream = new LimitedInputStream(itemInputStream, allowedLimit) {
                        protected void raiseError(long pSizeMax, long pCount) throws IOException {
                            throw new FileUploadIOException(new FileSizeLimitExceededException(
                                    "The field " + item.getFieldName() + " exceeds its maximum permitted "
                                            + " size of " + pSizeMax + " characters.",
                                    pCount, pSizeMax));
                        }
                    };

                    //Copy from the limited stream
                    long bytesCopied = Streams.copy(limitedInputStream, fileItem.getOutputStream(), true);

                    // Decrement the bytesCopied values from maxSize, so the next file copied 
                    // takes into account this value when allowedLimit var is calculated
                    // Note the invariant before the line is maxSize >= bytesCopied, since if this
                    // is not true a FileUploadIOException is thrown first.
                    maxSize -= bytesCopied;
                } else {
                    //We can just copy the data
                    Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
                }
            } catch (FileUploadIOException e) {
                try {
                    throw (FileUploadException) e.getCause();
                } catch (FileUploadBase.FileSizeLimitExceededException se) {
                    request.setAttribute("org.apache.myfaces.custom.fileupload.exception",
                            "fileSizeLimitExceeded");
                    String fieldName = fileItem.getFieldName();
                    request.setAttribute("org.apache.myfaces.custom.fileupload." + fieldName + ".maxSize",
                            new Integer((int) allowedLimit));
                }
            } catch (IOException e) {
                throw new IOFileUploadException("Processing of " + FileUploadBase.MULTIPART_FORM_DATA
                        + " request failed. " + e.getMessage(), e);
            }
            if (fileItem instanceof FileItemHeadersSupport) {
                final FileItemHeaders fih = item.getHeaders();
                ((FileItemHeadersSupport) fileItem).setHeaders(fih);
            }
            if (fileItem != null) {
                items.add(fileItem);
            }
        }
        return items;
    } catch (FileUploadIOException e) {
        throw (FileUploadException) e.getCause();
    } catch (IOException e) {
        throw new FileUploadException(e.getMessage(), e);
    }
}

From source file:org.apache.openejb.server.httpd.part.CommonsFileUploadPartFactory.java

public static Collection<Part> read(final HttpRequestImpl request) { // mainly for testing
    // Create a new file upload handler
    final DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(REPO);//w  w  w.  ja  va2s  . c o m

    final ServletFileUpload upload = new ServletFileUpload();
    upload.setFileItemFactory(factory);

    final List<Part> parts = new ArrayList<>();
    try {
        final List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));
        final String enc = request.getCharacterEncoding();
        for (final FileItem item : items) {
            final CommonsFileUploadPart part = new CommonsFileUploadPart(item, null);
            parts.add(part);
            if (part.getSubmittedFileName() == null) {
                String name = part.getName();
                String value = null;
                try {
                    String encoding = request.getCharacterEncoding();
                    if (encoding == null) {
                        if (enc == null) {
                            encoding = "UTF-8";
                        } else {
                            encoding = enc;
                        }
                    }
                    value = part.getString(encoding);
                } catch (final UnsupportedEncodingException uee) {
                    try {
                        value = part.getString("UTF-8");
                    } catch (final UnsupportedEncodingException e) {
                        // not possible
                    }
                }
                request.addInternalParameter(name, value);
            }
        }

        return parts;
    } catch (final FileUploadException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.apache.sling.engine.impl.parameters.ParameterSupport.java

private ParameterMap getRequestParameterMapInternal() {
    if (this.postParameterMap == null) {

        // SLING-508 Try to force servlet container to decode parameters
        // as ISO-8859-1 such that we can recode later
        String encoding = getServletRequest().getCharacterEncoding();
        if (encoding == null) {
            encoding = Util.ENCODING_DIRECT;
            try {
                getServletRequest().setCharacterEncoding(encoding);
            } catch (UnsupportedEncodingException uee) {
                throw new SlingUnsupportedEncodingException(uee);
            }//from ww w .  java2 s.c o m
        }

        // SLING-152 Get parameters from the servlet Container
        ParameterMap parameters = new ParameterMap();

        // fallback is only used if this request has been started by a service call
        boolean useFallback = getServletRequest().getAttribute(MARKER_IS_SERVICE_PROCESSING) != null;
        boolean addContainerParameters = false;
        // Query String
        final String query = getServletRequest().getQueryString();
        if (query != null) {
            try {
                InputStream input = Util.toInputStream(query);
                Util.parseQueryString(input, encoding, parameters, false);
                addContainerParameters = checkForAdditionalParameters;
            } catch (IllegalArgumentException e) {
                this.log.error("getRequestParameterMapInternal: Error parsing request", e);
            } catch (UnsupportedEncodingException e) {
                throw new SlingUnsupportedEncodingException(e);
            } catch (IOException e) {
                this.log.error("getRequestParameterMapInternal: Error parsing request", e);
            }
            useFallback = false;
        } else {
            addContainerParameters = checkForAdditionalParameters;
            useFallback = true;
        }

        // POST requests
        final boolean isPost = "POST".equals(this.getServletRequest().getMethod());
        if (isPost) {
            // WWW URL Form Encoded POST
            if (isWWWFormEncodedContent(this.getServletRequest())) {
                try {
                    InputStream input = this.getServletRequest().getInputStream();
                    Util.parseQueryString(input, encoding, parameters, false);
                    addContainerParameters = checkForAdditionalParameters;
                } catch (IllegalArgumentException e) {
                    this.log.error("getRequestParameterMapInternal: Error parsing request", e);
                } catch (UnsupportedEncodingException e) {
                    throw new SlingUnsupportedEncodingException(e);
                } catch (IOException e) {
                    this.log.error("getRequestParameterMapInternal: Error parsing request", e);
                }
                this.requestDataUsed = true;
                useFallback = false;
            }

            // Multipart POST
            if (ServletFileUpload.isMultipartContent(new ServletRequestContext(this.getServletRequest()))) {
                if (isStreamed(parameters, this.getServletRequest())) {
                    // special case, the request is Mutipart and streamed processing has been requested
                    try {
                        this.getServletRequest().setAttribute(REQUEST_PARTS_ITERATOR_ATTRIBUTE,
                                new RequestPartsIterator(this.getServletRequest()));
                        this.log.debug(
                                "getRequestParameterMapInternal: Iterator<javax.servlet.http.Part> available as request attribute  named request-parts-iterator");
                    } catch (IOException e) {
                        this.log.error(
                                "getRequestParameterMapInternal: Error parsing mulmultipart streamed requesttipart streamed request",
                                e);
                    } catch (FileUploadException e) {
                        this.log.error(
                                "getRequestParameterMapInternal: Error parsing mulmultipart streamed request",
                                e);
                    }
                    // The request data has been passed to the RequestPartsIterator, hence from a RequestParameter pov its been used, and must not be used again.
                    this.requestDataUsed = true;
                    // must not try and get anything from the request at this point so avoid jumping through the stream.
                    addContainerParameters = false;
                    useFallback = false;
                } else {
                    this.parseMultiPartPost(parameters);
                    this.requestDataUsed = true;
                    addContainerParameters = checkForAdditionalParameters;
                    useFallback = false;
                }
            }
        }
        if (useFallback) {
            getContainerParameters(parameters, encoding, true);
        } else if (addContainerParameters) {
            getContainerParameters(parameters, encoding, false);
        }
        // apply any form encoding (from '_charset_') in the parameter map
        Util.fixEncoding(parameters);

        this.postParameterMap = parameters;
    }
    return this.postParameterMap;
}

From source file:org.apache.sling.engine.impl.parameters.ParameterSupport.java

private void parseMultiPartPost(ParameterMap parameters) {

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setSizeMax(ParameterSupport.maxRequestSize);
    upload.setFileSizeMax(ParameterSupport.maxFileSize);
    upload.setFileItemFactory(/*from  ww  w .  j  a  va2 s  . c o m*/
            new DiskFileItemFactory(ParameterSupport.fileSizeThreshold, ParameterSupport.location));

    RequestContext rc = new ServletRequestContext(this.getServletRequest()) {
        @Override
        public String getCharacterEncoding() {
            String enc = super.getCharacterEncoding();
            return (enc != null) ? enc : Util.ENCODING_DIRECT;
        }
    };

    // Parse the request
    List<?> /* FileItem */ items = null;
    try {
        items = upload.parseRequest(rc);
    } catch (FileUploadException fue) {
        this.log.error("parseMultiPartPost: Error parsing request", fue);
    }

    if (items != null && items.size() > 0) {
        for (Iterator<?> ii = items.iterator(); ii.hasNext();) {
            FileItem fileItem = (FileItem) ii.next();
            RequestParameter pp = new MultipartRequestParameter(fileItem);
            parameters.addParameter(pp, false);
        }
    }
}

From source file:org.apache.sling.osgi.obr.OSGiBundleRepositoryServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // check whether dumping the repository is requested
    if (req.getRequestURI().endsWith("/repository.zip")) {
        this.dumpRepository(req.getParameterValues("bundle"), resp);
        resp.sendRedirect(req.getRequestURI());
        return;//  www  . j  a  v  a  2 s.  c  o m
    }

    if (!ServletFileUpload.isMultipartContent(new ServletRequestContext(req))) {
        resp.sendRedirect(req.getRequestURI());
        return;
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(256000);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(-1);

    // Parse the request
    boolean noRedirect = false;
    String bundleLocation = null;
    InputStream bundleStream = null;
    try {
        List /* FileItem */ items = upload.parseRequest(req);

        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                bundleStream = item.getInputStream();
                bundleLocation = item.getName();
            } else {
                noRedirect |= "_noredir_".equals(item.getFieldName());
            }
        }

        if (bundleStream != null && bundleLocation != null) {
            try {
                this.repository.addResource(bundleStream);
            } catch (IOException ioe) {
                resp.sendError(500, "Cannot register file " + bundleLocation + ". Reason: " + ioe.getMessage());
            }

        }
    } catch (FileUploadException fue) {
        throw new ServletException(fue.getMessage(), fue);
    } finally {
        if (bundleStream != null) {
            try {
                bundleStream.close();
            } catch (IOException ignore) {
            }
        }
    }

    // only redirect if not instructed otherwise
    if (noRedirect) {
        resp.setContentType("text/plain");
        if (bundleLocation != null) {
            resp.getWriter().print("Bundle " + bundleLocation + " uploaded");
        } else {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().print("No Bundle uploaded");
        }
    } else {
        resp.sendRedirect(req.getRequestURI());
    }
}

From source file:org.apache.wicket.protocol.http.servlet.MultipartServletWebRequestImpl.java

@Override
public void parseFileParts() throws FileUploadException {
    HttpServletRequest request = getContainerRequest();

    // The encoding that will be used to decode the string parameters
    // It should NOT be null at this point, but it may be
    // especially if the older Servlet API 2.2 is used
    String encoding = request.getCharacterEncoding();

    // The encoding can also be null when using multipart/form-data encoded forms.
    // In that case we use the [application-encoding] which we always demand using
    // the attribute 'accept-encoding' in wicket forms.
    if (encoding == null) {
        encoding = Application.get().getRequestCycleSettings().getResponseRequestEncoding();
    }//from   ww  w  . ja  v a  2s . c  om

    FileUploadBase fileUpload = newFileUpload(encoding);

    List<FileItem> items;

    if (wantUploadProgressUpdates()) {
        ServletRequestContext ctx = new ServletRequestContext(request) {
            @Override
            public InputStream getInputStream() throws IOException {
                return new CountingInputStream(super.getInputStream());
            }
        };
        totalBytes = request.getContentLength();

        onUploadStarted(totalBytes);
        try {
            items = fileUpload.parseRequest(ctx);
        } finally {
            onUploadCompleted();
        }
    } else {
        // try to parse the file uploads by using Apache Commons FileUpload APIs
        // because they are feature richer (e.g. progress updates, cleaner)
        items = fileUpload.parseRequest(new ServletRequestContext(request));
        if (items.isEmpty()) {
            // fallback to Servlet 3.0 APIs
            items = readServlet3Parts(request);
        }
    }

    // Loop through items
    for (final FileItem item : items) {
        // Get next item
        // If item is a form field
        if (item.isFormField()) {
            // Set parameter value
            final String value;
            if (encoding != null) {
                try {
                    value = item.getString(encoding);
                } catch (UnsupportedEncodingException e) {
                    throw new WicketRuntimeException(e);
                }
            } else {
                value = item.getString();
            }

            addParameter(item.getFieldName(), value);
        } else {
            List<FileItem> fileItems = files.get(item.getFieldName());
            if (fileItems == null) {
                fileItems = new ArrayList<>();
                files.put(item.getFieldName(), fileItems);
            }
            // Add to file list
            fileItems.add(item);
        }
    }
}

From source file:org.brutusin.rpc.http.RpcServlet.java

/**
 *
 * @param req/*from   w  w  w  .ja  v  a2s .  c om*/
 * @param rpcRequest
 * @param service
 * @return
 * @throws Exception
 */
private Map<String, InputStream> getStreams(HttpServletRequest req, RpcRequest rpcRequest, HttpAction service)
        throws Exception {
    if (!FileUploadBase.isMultipartContent(new ServletRequestContext(req))) {
        return null;
    }
    int streamsNumber = getInputStreamsNumber(rpcRequest, service);
    boolean isResponseStreamed = service.isBinaryResponse();
    FileItemIterator iter = (FileItemIterator) req.getAttribute(REQ_ATT_MULTIPART_ITERATOR);
    int count = 0;
    final Map<String, InputStream> map = new HashMap();
    final File tempDirectory;
    if (streamsNumber > 1 || streamsNumber == 1 && isResponseStreamed) {
        tempDirectory = createTempUploadDirectory();
        req.setAttribute(REQ_ATT_TEMPORARY_FOLDER, tempDirectory);
    } else {
        tempDirectory = null;
    }
    FileItemStream item = (FileItemStream) req.getAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM);
    long availableLength = RpcConfig.getInstance().getMaxRequestSize();
    while (item != null) {
        count++;
        long maxLength = Math.min(availableLength, RpcConfig.getInstance().getMaxFileSize());
        if (count < streamsNumber || isResponseStreamed) { // if response is streamed all inputstreams have to be readed first
            File file = new File(tempDirectory, item.getFieldName());
            FileOutputStream fos = new FileOutputStream(file);
            try {
                Miscellaneous.pipeSynchronously(new LimitedLengthInputStream(item.openStream(), maxLength),
                        fos);
            } catch (MaxLengthExceededException ex) {
                if (maxLength == RpcConfig.getInstance().getMaxFileSize()) {
                    throw new MaxLengthExceededException(
                            "Upload part '" + item.getFieldName() + "' exceeds maximum length ("
                                    + RpcConfig.getInstance().getMaxFileSize() + " bytes)",
                            RpcConfig.getInstance().getMaxFileSize());
                } else {
                    throw new MaxLengthExceededException("Request exceeds maximum length ("
                            + RpcConfig.getInstance().getMaxRequestSize() + " bytes)",
                            RpcConfig.getInstance().getMaxRequestSize());
                }
            }
            map.put(item.getFieldName(), new MetaDataInputStream(new FileInputStream(file), item.getName(),
                    item.getContentType(), file.length(), null));
            availableLength -= file.length();
        } else if (count == streamsNumber) {
            map.put(item.getFieldName(),
                    new MetaDataInputStream(new LimitedLengthInputStream(item.openStream(), maxLength),
                            item.getName(), item.getContentType(), null, null));
            break;
        }
        req.setAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM, item);
        if (iter.hasNext()) {
            item = iter.next();
        } else {
            item = null;
        }
    }
    if (count != streamsNumber) {
        throw new IllegalArgumentException("Invalid multipart request received. Number of uploaded files ("
                + count + ") does not match expected (" + streamsNumber + ")");
    }
    return map;
}

From source file:org.chiba.web.servlet._HttpRequestHandler.java

/**
 * Parses a HTTP request. Returns an array containing maps for upload
 * controls, other controls, repeat indices, and trigger. The individual
 * maps may be null in case no corresponding parameters appear in the
 * request./*  w  ww. j  av a  2 s  . com*/
 *
 * @param request a HTTP request.
 * @return an array of maps containing the parsed request parameters.
 * @throws FileUploadException if an error occurred during file upload.
 * @throws UnsupportedEncodingException if an error occurred during
 * parameter value decoding.
 */
protected Map[] parseRequest(HttpServletRequest request)
        throws FileUploadException, UnsupportedEncodingException {
    Map[] parameters = new Map[4];

    if (FileUploadBase.isMultipartContent(new ServletRequestContext(request))) {
        UploadListener uploadListener = new UploadListener(request, this.sessionKey);
        DiskFileItemFactory factory = new MonitoredDiskFileItemFactory(uploadListener);
        factory.setRepository(new File(this.uploadRoot));
        ServletFileUpload upload = new ServletFileUpload(factory);

        String encoding = request.getCharacterEncoding();
        if (encoding == null) {
            encoding = "UTF-8";
        }

        Iterator iterator = upload.parseRequest(request).iterator();
        FileItem item;
        while (iterator.hasNext()) {
            item = (FileItem) iterator.next();

            if (item.isFormField()) {
                LOGGER.info("request param: " + item.getFieldName() + " - value='" + item.getString() + "'");
            } else {
                LOGGER.info("file in request: " + item.getName());
            }

            parseMultiPartParameter(item, encoding, parameters);
        }
    } else {
        Enumeration enumeration = request.getParameterNames();
        String name;
        String[] values;
        while (enumeration.hasMoreElements()) {
            name = (String) enumeration.nextElement();
            values = request.getParameterValues(name);

            parseURLEncodedParameter(name, values, parameters);
        }
    }

    return parameters;
}

From source file:org.eclipse.vtp.framework.engine.http.HttpConnector.java

/**
 * invokeProcessEngine.//  w w  w  .  ja  v  a  2s  .c  om
 * 
 * @param req
 * @param res
 * @param httpSession
 * @param pathInfo
 * @param embeddedInvocation TODO
 * @throws IOException
 * @throws ServletException
 */
private void invokeProcessEngine(HttpServletRequest req, HttpServletResponse res, HttpSession httpSession,
        String pathInfo, Map<Object, Object> variableValues,
        @SuppressWarnings("rawtypes") Map<String, String[]> parameterValues, boolean embeddedInvocation)
        throws IOException, ServletException {
    boolean newSession = false;
    Integer depth = (Integer) httpSession.getAttribute("connector.depth");
    if (depth == null) {
        depth = new Integer(0);
    }
    String prefix = "connector.attributes.";
    String fullPrefix = prefix + depth.intValue() + ".";
    if (embeddedInvocation)
        httpSession.setAttribute(fullPrefix + "fragment", "true");
    Deployment deployment = null;
    String brand = null;
    String entryName = null;
    boolean subdialog = false;
    if (!pathInfo.startsWith(PATH_PREFIX)) {
        System.out.println("invoking process engine for new session: " + pathInfo);
        newSession = true;
        synchronized (this) {
            for (String path : deploymentsByPath.keySet()) {
                System.out.println("Comparing to deployment: " + path);
                if (pathInfo.equals(path) || pathInfo.startsWith(path) && pathInfo.length() > path.length()
                        && pathInfo.charAt(path.length()) == '/') {
                    deployment = deploymentsByPath.get(path);
                    System.out.println("Matching deployment found: " + deployment);
                    brand = req.getParameter("BRAND");
                    if (req.getParameter("SUBDIALOG") != null)
                        subdialog = Boolean.parseBoolean(req.getParameter("SUBDIALOG"));
                    if (pathInfo.length() > path.length() + 1) {
                        entryName = pathInfo.substring(path.length() + 1);
                        System.out.println("Entry point name: " + entryName);
                    }
                    break;
                }
            }
        }
        if (deployment == null) {
            res.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        if (entryName == null) {
            res.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
        pathInfo = NEXT_PATH;
        httpSession.setAttribute(fullPrefix + DEPLOYMENT_ID, deployment.getProcessID());
    } else if (pathInfo.equals(LOG_PATH)) {
        if (req.getParameter("cmd") != null && req.getParameter("cmd").equals("set")) {
            String level = req.getParameter("level");
            if (level == null || (!level.equalsIgnoreCase("ERROR") && !level.equalsIgnoreCase("WARN")
                    && !level.equalsIgnoreCase("INFO") && !level.equalsIgnoreCase("DEBUG")))
                level = "INFO";
            System.setProperty("org.eclipse.vtp.loglevel", level);
        }
        writeLogging(req, res);
        return;
    } else {
        String deploymentID = (String) httpSession.getAttribute(fullPrefix + DEPLOYMENT_ID);
        synchronized (this) {
            deployment = deploymentsByID.get(deploymentID);
        }
        if (deployment == null) {
            res.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
    }
    if (subdialog)
        httpSession.setAttribute(fullPrefix + "subdialog", "true");
    if (pathInfo.equals(INDEX_PATH)) {
        writeIndex(res, deployment);
        return;
    }
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    if (ServletFileUpload.isMultipartContent(new ServletRequestContext(req))) {
        System.out.println(
                "ServletFileUpload.isMultipartContent(new ServletRequestContext(httpRequest)) is true");
        try {
            List items = upload.parseRequest(req);
            for (int i = 0; i < items.size(); i++) {
                FileItem fui = (FileItem) items.get(i);
                if (fui.isFormField() || "text/plain".equals(fui.getContentType())) {
                    System.out.println("Form Field: " + fui.getFieldName() + " | " + fui.getString());
                    parameterValues.put(fui.getFieldName(), new String[] { fui.getString() });
                } else {
                    File temp = File.createTempFile(Guid.createGUID(), ".tmp");
                    fui.write(temp);
                    parameterValues.put(fui.getFieldName(), new String[] { temp.getAbsolutePath() });
                    fui.delete();
                    System.out.println("File Upload: " + fui.getFieldName());
                    System.out.println("\tTemp file name: " + temp.getAbsolutePath());
                    System.out.println("\tContent Type: " + fui.getContentType());
                    System.out.println("\tSize: " + fui.getSize());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) {
        String key = (String) e.nextElement();
        parameterValues.put(key, req.getParameterValues(key));
    }
    for (String key : parameterValues.keySet()) {
        String[] values = parameterValues.get(key);
        if (values == null || values.length == 0)
            System.out.println(key + " empty");
        else {
            System.out.println(key + " " + values[0]);
            for (int i = 1; i < values.length; i++)
                System.out.println("\t" + values[i]);
        }
    }
    IDocument document = null;
    if (pathInfo.equals(ABORT_PATH))
        document = deployment.abort(httpSession, req, res, prefix, depth.intValue(), variableValues,
                parameterValues);
    else if (pathInfo.equals(NEXT_PATH)) {
        if (brand == null && !newSession)
            document = deployment.next(httpSession, req, res, prefix, depth.intValue(), variableValues,
                    parameterValues);
        else
            document = deployment.start(httpSession, req, res, prefix, depth.intValue(), variableValues,
                    parameterValues, entryName, brand, subdialog);
    } else {
        res.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    if (document == null) {
        res.setStatus(HttpServletResponse.SC_NO_CONTENT);
        return;
    } else if (document instanceof ControllerDocument) {
        ControllerDocument cd = (ControllerDocument) document;
        if (cd.getTarget() == null) {
            @SuppressWarnings("unchecked")
            Map<String, Map<String, Object>> outgoing = (Map<String, Map<String, Object>>) httpSession
                    .getAttribute(fullPrefix + "outgoing-data");
            int newDepth = depth.intValue() - 1;
            if (newDepth == 0)
                httpSession.removeAttribute("connector.depth");
            else
                httpSession.setAttribute("connector.depth", new Integer(newDepth));
            String oldFullPrefix = fullPrefix;
            fullPrefix = prefix + newDepth + ".";
            Object[] params = (Object[]) httpSession.getAttribute(fullPrefix + "exitparams");
            if (params != null)
                for (int i = 0; i < params.length; i += 2)
                    parameterValues.put((String) params[i], (String[]) params[i + 1]);
            String[] paramNames = cd.getParameterNames();
            for (int i = 0; i < paramNames.length; ++i)
                parameterValues.put(paramNames[i], cd.getParameterValues(paramNames[i]));
            String[] variableNames = cd.getVariableNames();
            Map<Object, Object> variables = new HashMap<Object, Object>(variableNames.length);
            if (outgoing != null) {
                Map<String, Object> map = outgoing.get(cd.getParameterValues("exit")[0]);
                if (map != null) {
                    for (int i = 0; i < variableNames.length; ++i) {
                        Object mapping = map.get(variableNames[i]);
                        if (mapping != null)
                            variables.put(mapping, cd.getVariableValue(variableNames[i]));
                    }
                }
            }
            deployment.end(httpSession, prefix, depth.intValue());
            for (@SuppressWarnings("rawtypes")
            Enumeration e = httpSession.getAttributeNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                if (name.startsWith(oldFullPrefix))
                    httpSession.removeAttribute(name);
            }
            invokeProcessEngine(req, res, httpSession, NEXT_PATH, variables, parameterValues, newDepth > 0);
            return;
        } else {
            String[] paramNames = cd.getParameterNames();
            Object[] params = new Object[paramNames.length * 2];
            for (int i = 0; i < params.length; i += 2) {
                params[i] = paramNames[i / 2];
                params[i + 1] = cd.getParameterValues(paramNames[i / 2]);
            }
            httpSession.setAttribute(fullPrefix + "exitparams", params);
            String[] variableNames = cd.getVariableNames();
            Map<Object, Object> variables = new HashMap<Object, Object>(variableNames.length);
            for (int i = 0; i < variableNames.length; ++i)
                variables.put(variableNames[i], cd.getVariableValue(variableNames[i]));
            httpSession.setAttribute("connector.depth", new Integer(depth.intValue() + 1));
            fullPrefix = prefix + (depth.intValue() + 1) + ".";
            String deploymentId = cd.getTarget().substring(0, cd.getTarget().lastIndexOf('(') - 1);
            String entryPointName = cd.getTarget().substring(cd.getTarget().lastIndexOf('(') + 1,
                    cd.getTarget().length() - 1);
            httpSession.setAttribute(fullPrefix + DEPLOYMENT_ID, deploymentId);
            httpSession.setAttribute(fullPrefix + ENTRY_POINT_NAME, entryPointName);
            Map<String, Map<String, Object>> outgoing = new HashMap<String, Map<String, Object>>();
            String[] outPaths = cd.getOutgoingPaths();
            for (int i = 0; i < outPaths.length; ++i) {
                Map<String, Object> map = new HashMap<String, Object>();
                String[] names = cd.getOutgoingDataNames(outPaths[i]);
                for (int j = 0; j < names.length; ++j)
                    map.put(names[j], cd.getOutgoingDataValue(outPaths[i], names[j]));
                outgoing.put(outPaths[i], map);
            }
            httpSession.setAttribute(fullPrefix + "outgoing-data", outgoing);
            invokeProcessEngine(req, res, httpSession, "/" + deploymentId + "/" + entryPointName, variables,
                    parameterValues, true);
            return;
        }
    }
    res.setStatus(HttpServletResponse.SC_OK);
    if (!document.isCachable())
        res.setHeader("Cache-Control", "max-age=0, no-cache");
    res.setContentType(document.getContentType());
    OutputStream writer = res.getOutputStream();
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        XMLWriter xmlWriter = new XMLWriter(writer);
        xmlWriter.setCompactElements(true);
        transformer.transform(document.toXMLSource(), xmlWriter.toXMLResult());
        if (reporter.isSeverityEnabled(IReporter.SEVERITY_INFO) && !document.isSecured()) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            xmlWriter = new XMLWriter(baos);
            xmlWriter.setCompactElements(true);
            transformer.transform(document.toXMLSource(), xmlWriter.toXMLResult());
            System.out.println(new String(baos.toByteArray(), "UTF-8"));
        }
    } catch (TransformerException e) {
        throw new ServletException(e);
    }
    writer.flush();
    writer.close();
}