Example usage for javax.servlet.http HttpServletRequest getInputStream

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

Introduction

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

Prototype

public ServletInputStream getInputStream() throws IOException;

Source Link

Document

Retrieves the body of the request as binary data using a ServletInputStream .

Usage

From source file:com.concursive.connect.web.modules.documents.utils.HttpMultiPartParser.java

/**
 * Description of the Method/*from   w w w  .  j  a va  2  s.co  m*/
 *
 * @param saveInDir Description of Parameter
 * @param request   Description of the Parameter
 * @return Description of the Returned Value
 * @throws IllegalArgumentException Description of Exception
 * @throws IOException              Description of Exception
 */
private HashMap processData(HttpServletRequest request, String saveInDir)
        throws IllegalArgumentException, IOException {
    String contentType = request.getHeader("Content-type");
    //TODO: use the contentLength for a progress bar
    int contentLength = request.getContentLength();
    LOG.debug("HttpMultiPartParser Length: " + contentLength);
    if ((contentType == null) || (!contentType.startsWith("multipart/"))) {
        throw new IllegalArgumentException("Not a multipart message");
    }
    int boundaryIndex = contentType.indexOf("boundary=");
    String boundary = contentType.substring(boundaryIndex + 9);
    LOG.debug("Request boundary: " + boundary);
    ServletInputStream is = request.getInputStream();
    if (is == null) {
        throw new IllegalArgumentException("InputStream");
    }
    if (boundary == null || boundary.trim().length() < 1) {
        throw new IllegalArgumentException("boundary");
    }
    //Each content will begin with two dashes "--" plus the actual boundary string
    boundary = "--" + boundary;
    //Prepare to read in from request
    StringTokenizer stLine = null;
    StringTokenizer stFields = null;
    FileInfo fileInfo = null;
    HashMap dataTable = new HashMap(5);
    String line = null;
    String field = null;
    String paramName = null;
    boolean saveFiles = (saveInDir != null && saveInDir.trim().length() > 0);
    boolean isFile = false;
    boolean validFile = false;
    int fileCount = 0;
    //First line should be the boundary
    line = getLine(is);
    if (line == null || !line.startsWith(boundary)) {
        throw new IOException("Boundary not found;" + " boundary = " + boundary + ", line = " + line);
    }
    //Continue with the rest of the lines
    while (line != null) {
        LOG.trace(line);
        // Process boundary line  ----------------------------------------
        if (line == null || !line.startsWith(boundary)) {
            return dataTable;
        }
        // Process "Content-Disposition: " line --------------------------
        line = getLine(is);
        if (line == null) {
            return dataTable;
        }
        // Split line into the following 3 tokens (or 2 if not a file):
        // 1. Content-Disposition: form-data
        // 2. name="LocalFile1"
        // 3. filename="C:\autoexec.bat"  (only present if this is part of a HTML file INPUT tag) */
        stLine = new StringTokenizer(line, ";\r\n");
        if (stLine.countTokens() < 2) {
            throw new IllegalArgumentException("Bad data in second line");
        }
        // Confirm that this is "form-data"
        line = stLine.nextToken().toLowerCase();
        if (line.indexOf("form-data") < 0) {
            throw new IllegalArgumentException("Bad data in second line");
        }
        // Now split token 2 from above into field "name" and it's "value"
        // e.g. name="LocalFile1"
        stFields = new StringTokenizer(stLine.nextToken(), "=\"");
        if (stFields.countTokens() < 2) {
            throw new IllegalArgumentException("Bad data in second line");
        }
        // Get field name
        fileInfo = new FileInfo();
        fileInfo.setVersion(version);
        fileInfo.setExtensionId(extensionId);
        stFields.nextToken();
        paramName = stFields.nextToken();
        // Now split token 3 from above into file "name" and it's "value"
        // e.g. filename="C:\autoexec.bat"
        isFile = false;
        if (stLine.hasMoreTokens()) {
            field = stLine.nextToken();
            stFields = new StringTokenizer(field, "=\"");
            if (stFields.countTokens() > 1) {
                if (stFields.nextToken().trim().equalsIgnoreCase("filename")) {
                    fileInfo.setName(paramName);
                    String value = stFields.nextToken();
                    if (value != null && value.trim().length() > 0) {
                        fileInfo.setClientFileName(value);
                        isFile = true;
                        ++fileCount;
                    } else {
                        // An error condition occurred, skip to next boundary
                        line = getLine(is);
                        // Skip "Content-Type:" line
                        line = getLine(is);
                        // Skip blank line
                        line = getLine(is);
                        // Skip blank line
                        line = getLine(is);
                        // Position to boundary line
                        continue;
                    }
                }
            } else if (field.toLowerCase().indexOf("filename") >= 0) {
                // An error condition occurred, skip to next boundary
                line = getLine(is);
                // Skip "Content-Type:" line
                line = getLine(is);
                // Skip blank line
                line = getLine(is);
                // Skip blank line
                line = getLine(is);
                // Position to boundary line
                continue;
            }
        }
        // Process "Content-Type: " line ----------------------------------
        // e.g. Content-Type: text/plain
        boolean skipBlankLine = true;
        if (isFile) {
            line = getLine(is);
            if (line == null) {
                return dataTable;
            }
            // "Content-type" line not guaranteed to be sent by the browser
            if (line.trim().length() < 1) {
                skipBlankLine = false;
            } else {
                // Prevent re-skipping below
                stLine = new StringTokenizer(line, ": ");
                if (stLine.countTokens() < 2) {
                    throw new IllegalArgumentException("Bad data in third line");
                }
                stLine.nextToken();
                // Content-Type
                fileInfo.setFileContentType(stLine.nextToken());
            }
        }
        // Skip blank line  -----------------------------------------------
        if (skipBlankLine) {
            // Blank line already skipped above?
            line = getLine(is);
            if (line == null) {
                return dataTable;
            }
        }
        // Process data: If not a file, add to hashmap and continue
        if (!isFile) {
            line = getLine(is);
            if (line == null) {
                return dataTable;
            }
            StringBuffer sb = new StringBuffer();
            sb.append(line);
            while (line != null && !line.startsWith(boundary)) {
                line = getLine(is);
                if (line != null && !line.startsWith(boundary)) {
                    sb.append(System.getProperty("line.separator"));
                    sb.append(line);
                }
            }
            LOG.debug(" HttpMultiPartParser ->Adding param: " + paramName);
            dataTable.put(paramName, sb.toString());
            continue;
        }
        // Either save contents in memory or to a local file
        OutputStream os = null;
        String path = null;
        try {
            String tmpPath = null;
            String filenameToUse = null;
            if (saveFiles) {
                if (usePathParam) {
                    tmpPath = saveInDir + fileInfo.getName() + fs;
                } else {
                    tmpPath = saveInDir;
                }
                if (useDateForFolder) {
                    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy");
                    String datePathToUse1 = formatter1.format(new java.util.Date());
                    SimpleDateFormat formatter2 = new SimpleDateFormat("MMdd");
                    String datePathToUse2 = formatter2.format(new java.util.Date());
                    tmpPath += datePathToUse1 + fs + datePathToUse2 + fs;
                }
                // Create output directory in case it doesn't exist
                File f = new File(tmpPath);
                f.mkdirs();
                //If specified, store files using a unique name, based on date
                if (useUniqueName) {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
                    filenameToUse = formatter.format(new java.util.Date());
                    if (fileCount > 1) {
                        filenameToUse += String.valueOf(fileCount);
                    }
                } else {
                    filenameToUse = fileInfo.getClientFileName();
                }
                fileInfo.setClientFileName(getFileName(fileInfo.getClientFileName()));
                //Append a version id for record keeping and uniqueness, prevents
                //multiple uploads from overwriting each other
                filenameToUse += (version == -1 ? "" : "^" + version)
                        + (extensionId == -1 ? "" : "-" + extensionId);
                //Create the file to a file
                os = new FileOutputStream(path = getFileName(tmpPath, filenameToUse));
            } else {
                //Store the file in memory
                os = new ByteArrayOutputStream(ONE_MB);
            }
            //Begin reading in the request
            boolean readingContent = true;
            byte previousLine[] = new byte[2 * ONE_MB];
            byte temp[] = null;
            byte currentLine[] = new byte[2 * ONE_MB];
            int read;
            int read3;
            //read in the first line, break out if eof
            if ((read = is.readLine(previousLine, 0, previousLine.length)) == -1) {
                line = null;
                break;
            }
            //read until next boundary and write the contents to OutputStream
            while (readingContent) {
                if ((read3 = is.readLine(currentLine, 0, currentLine.length)) == -1) {
                    line = null;
                    break;
                }
                //check if current line is a boundary
                if (compareBoundary(boundary, currentLine)) {
                    if (read - 2 > 0) {
                        validFile = true;
                    }
                    os.write(previousLine, 0, read - 2);
                    os.flush();
                    line = new String(currentLine, 0, read3);
                    break;
                } else {
                    //current line is not a boundary, write previous line
                    os.write(previousLine, 0, read);
                    validFile = true;
                    os.flush();
                    //reposition previousLine to be currentLine
                    temp = currentLine;
                    currentLine = previousLine;
                    previousLine = temp;
                    read = read3;
                }
            }
            os.close();
            temp = null;
            previousLine = null;
            currentLine = null;
            //Store the completed file somewhere
            if (!saveFiles) {
                ByteArrayOutputStream baos = (ByteArrayOutputStream) os;
                fileInfo.setFileContents(baos.toByteArray());
            } else {
                File thisFile = new File(path);
                if (validFile) {
                    fileInfo.setLocalFile(thisFile);
                    fileInfo.setSize((int) thisFile.length());
                    os = null;
                } else {
                    thisFile.delete();
                }
            }
            if (validFile) {
                LOG.debug("Adding file param: " + fileInfo.getName());
                dataTable.put(paramName, fileInfo);
            }
        } catch (Exception e) {
            LOG.error("HttpMultiPartParser-> error: " + e.getMessage(), e);
            if (os != null) {
                os.close();
            }
            if (saveFiles && path != null) {
                File thisFile = new File(path);
                if (thisFile.exists()) {
                    thisFile.delete();
                    LOG.warn("HttpMultiPartParser-> Temporary file deleted");
                }
            }
        }
    }
    return dataTable;
}

From source file:org.overlord.sramp.server.mvn.services.MavenRepositoryService.java

private void uploadArtifact(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {
    // Get the URL request and prepare it to obtain the maven metadata
    // information
    String url = req.getRequestURI();
    String maven_url = ""; //$NON-NLS-1$
    if (url.contains(URL_CONTEXT_STR)) {
        maven_url = url.substring(url.indexOf(URL_CONTEXT_STR) + URL_CONTEXT_STR.length());
    } else {/* w  w w.j av  a  2 s  . c  o  m*/
        maven_url = url;
    }

    if (maven_url.startsWith("/")) { //$NON-NLS-1$
        maven_url = maven_url.substring(1);
    }

    // Extract the relevant content from the POST'd form
    Map<String, String> responseMap = new HashMap<String, String>();

    InputStream content = null;
    // Parse the request
    content = req.getInputStream();

    // Builder class that converts the url into a Maven MetaData Object
    MavenMetaData metadata = MavenMetaDataBuilder.build(maven_url);
    try {
        if (metadata.isArtifact()) {
            if (SNAPSHOT_ALLOWED || !metadata.isSnapshotVersion()) {
                String uuid = uploadArtifact(metadata, content);
                responseMap.put("uuid", uuid); //$NON-NLS-1$
            } else {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        Messages.i18n.format("maven.servlet.put.snapshot.not.allowed")); //$NON-NLS-1$
            }

        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    Messages.i18n.format("maven.servlet.put.url.without.artifact")); //$NON-NLS-1$
        }

    } catch (Throwable e) {
        logger.error(Messages.i18n.format("maven.servlet.artifact.content.put.exception"), e); //$NON-NLS-1$
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                Messages.i18n.format("maven.servlet.put.exception")); //$NON-NLS-1$
    } finally {
        if (content != null) {
            IOUtils.closeQuietly(content);
        }

    }
}

From source file:net.naijatek.myalumni.util.fileupload.FileUpload.java

/**
 * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
 * compliant <code>multipart/form-data</code> stream. If files are stored
 * on disk, the path is given by <code>getRepositoryPath()</code>.
 * //from www.ja v a 2s.  co m
 * @param req The servlet request to_email be parsed.
 * @param sizeThreshold The max size in bytes to_email be stored in memory.
 * @param sizeMax The maximum allowed upload size, in bytes.
 * @param path The location where the files should be stored.
 * 
 * @return A list of <code>FileItem</code> instances parsed from_email the
 * request, in the order that they were transmitted.
 * 
 * @exception FileUploadException if there are problems reading/parsing
 * the request or storing files.
 */
public List /* FileItem */ parseRequest(final HttpServletRequest req, final int sizeThreshold,
        final int sizeMax, final String path) throws FileUploadException {
    ArrayList items = new ArrayList();
    String contentType = req.getHeader(CONTENT_TYPE);

    if (!contentType.startsWith(MULTIPART)) {
        throw new FileUploadException(
                "the request doesn't contain a " + MULTIPART_FORM_DATA + " or " + MULTIPART_MIXED + " stream");
    }
    int requestSize = req.getContentLength();

    if (requestSize == -1) {
        throw new FileUploadException("the request was rejected because " + "it's size is unknown");
    }

    if (sizeMax >= 0 && requestSize > sizeMax) {
        throw new FileUploadException("the request was rejected because " + "it's size exceeds allowed range");
    }

    try {
        byte[] boundary = contentType.substring(contentType.indexOf("boundary=") + 9).getBytes();

        InputStream input = req.getInputStream();

        MultipartStream multi = new MultipartStream(input, boundary);
        boolean nextPart = multi.skipPreamble();
        while (nextPart) {
            Map headers = parseHeaders(multi.readHeaders());
            String fieldName = getFieldName(headers);
            if (fieldName != null) {
                String subContentType = getHeader(headers, CONTENT_TYPE);
                if (subContentType != null && subContentType.startsWith(MULTIPART_MIXED)) {
                    // Multiple files.
                    byte[] subBoundary = subContentType.substring(subContentType.indexOf("boundary=") + 9)
                            .getBytes();
                    multi.setBoundary(subBoundary);
                    boolean nextSubPart = multi.skipPreamble();
                    while (nextSubPart) {
                        headers = parseHeaders(multi.readHeaders());
                        if (getFileName(headers) != null) {
                            FileItem item = createItem(sizeThreshold, path, headers, requestSize);
                            OutputStream os = ((DefaultFileItem) item).getOutputStream();
                            try {
                                multi.readBodyData(os);
                            } finally {
                                os.close();
                            }
                            item.setFieldName(getFieldName(headers));
                            items.add(item);
                        } else {
                            // Ignore anything but files inside
                            // multipart/mixed.
                            multi.discardBodyData();
                        }
                        nextSubPart = multi.readBoundary();
                    }
                    multi.setBoundary(boundary);
                } else {
                    if (getFileName(headers) != null) {
                        // A single file.
                        FileItem item = createItem(sizeThreshold, path, headers, requestSize);
                        OutputStream os = ((DefaultFileItem) item).getOutputStream();
                        try {
                            multi.readBodyData(os);
                        } finally {
                            os.close();
                        }
                        item.setFieldName(getFieldName(headers));
                        items.add(item);
                    } else {
                        // A form field.
                        FileItem item = createItem(sizeThreshold, path, headers, requestSize);
                        OutputStream os = ((DefaultFileItem) item).getOutputStream();
                        try {
                            multi.readBodyData(os);
                        } finally {
                            os.close();
                        }
                        item.setFieldName(getFieldName(headers));
                        item.setIsFormField(true);
                        items.add(item);
                    }
                }
            } else {
                // Skip this part.
                multi.discardBodyData();
            }
            nextPart = multi.readBoundary();
        }
    } catch (IOException e) {
        throw new FileUploadException(
                "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage());
    }

    return items;
}

From source file:com.googlecode.noweco.calendar.CaldavServlet.java

@Override
public void doPut(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    String requestURI = req.getRequestURI();
    String[] split = requestURI.split("/");
    MemoryFile memoryFile = ROOT;//w  w  w  . j  a  va  2s  .  c om
    for (int i = 0; i < split.length - 1; i++) {
        String name = split[i];
        MemoryFile locate = MemoryFileUtils.locate(memoryFile, name);
        if (locate == null) {
            memoryFile = new MemoryFile(memoryFile, name, true);
        } else {
            memoryFile = locate;
        }
    }
    String name = split[split.length - 1];
    MemoryFile locate = MemoryFileUtils.locate(memoryFile, name);
    if (locate == null) {
        memoryFile = new MemoryFile(memoryFile, name, false);
    } else {
        memoryFile = locate;
    }
    CalendarBuilder builder = new CalendarBuilder();
    net.fortuna.ical4j.model.Calendar calendar;
    try {
        calendar = builder.build(req.getInputStream());
    } catch (ParserException e) {
        throw new RuntimeException(e);
    }
    for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) {
        Component component = (Component) i.next();
        System.out.println("Component [" + component.getName() + "]");

        if (component instanceof VEvent) {
            VEvent event = (VEvent) component;
            LOGGER.info("Create event " + event.getSummary().getValue() + " in "
                    + event.getLocation().getValue() + " from " + event.getStartDate().getDate() + " to "
                    + event.getEndDate().getDate());

        }
    }
    CalendarOutputter outputter = new CalendarOutputter();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        outputter.output(calendar, out);
    } catch (ValidationException e) {
        throw new RuntimeException(e);
    }
    memoryFile.setContent(out.toByteArray());
    Getcontenttype getcontenttype = new Getcontenttype();
    getcontenttype.getContent().add(req.getHeader("Content-Type"));
    memoryFile.getProp().setGetcontenttype(getcontenttype);
    Prop prop = memoryFile.getProp();
    prop.setResourcetype(new Resourcetype());
    Getetag getetag = new Getetag();
    getetag.getContent().add("\"" + System.currentTimeMillis() + "\"");
    prop.setGetetag(getetag);
    resp.setHeader("ETag", prop.getGetetag().getContent().get(0));
    resp.setStatus(HttpServletResponse.SC_CREATED);
}

From source file:org.iff.infra.util.servlet.ProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    // Make the Request
    //note: we won't transfer the protocol version because I'm not sure it would truly be compatible
    String method = servletRequest.getMethod();
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);
    HttpRequest proxyRequest;//from www  .j  a  v  a2 s.c  o  m
    //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        // Add the input entity (streamed)
        //  note: we don't bother ensuring we close the servletInputStream since the container handles it
        eProxyRequest.setEntity(
                new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        proxyRequest = eProxyRequest;
    } else {
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }

    copyRequestHeaders(servletRequest, proxyRequest);

    setXForwardedForHeader(servletRequest, proxyRequest);

    {//add by tylerchen
        String header = initParameterMap.get("header");
        if (header != null) {
            String[] split = header.split("@@@");
            for (String s : split) {
                String[] headerPaire = s.split("=");
                if (headerPaire.length == 2) {
                    proxyRequest.addHeader(headerPaire[0], headerPaire[1]);
                }
            }
        }
    }

    HttpResponse proxyResponse = null;
    try {
        // Execute the request
        if (doLog) {
            log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }
        proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUriObj), proxyRequest);

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            //the response is already "committed" now without any body to send
            //TODO copy response headers?
            return;
        }

        // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the
        //  reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletResponse);

        if ("true".equals(initParameterMap.get("cached"))) {//add cache by tylerchen
            //servlet??
            //?????20
            //20????servlet
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            Date date = new Date();
            response.setDateHeader("Last-Modified", date.getTime()); //Last-Modified:??? 
            response.setDateHeader("Expires", date.getTime() * 100); //Expires:? 
            response.setHeader("Cache-Control", "public"); //Cache-Control???,public:?????
            response.setHeader("Cache-Control", "max-age=" + date.getTime() * 100);
            response.setHeader("Pragma", "Pragma"); //Pragma:??Pragmano-cache?

            //???????
            /*response.setHeader( "Pragma", "no-cache" );   
            response.setDateHeader("Expires", 0);   
            response.addHeader( "Cache-Control", "no-cache" );//?????
            response.addHeader( "Cache-Control", "no-store" );//????    
            response.addHeader( "Cache-Control", "must-revalidate" );*///??????
        }

        // Send the content to the client
        copyResponseEntity(proxyResponse, servletResponse);

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        if (e instanceof ServletException)
            throw (ServletException) e;
        //noinspection ConstantConditions
        if (e instanceof IOException)
            throw (IOException) e;
        throw new RuntimeException(e);

    } finally {
        // make sure the entire entity was consumed, so the connection is released
        if (proxyResponse != null)
            consumeQuietly(proxyResponse.getEntity());
        //Note: Don't need to close servlet outputStream:
        // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
    }
}

From source file:org.mitre.dsmiley.httpproxy.DynamicProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    // Make the Request
    //note: we won't transfer the protocol version because I'm not sure it would truly be compatible
    String method = servletRequest.getMethod();
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);
    HttpRequest proxyRequest;//from  w ww.ja va2  s.c om
    //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        // Add the input entity (streamed)
        //  note: we don't bother ensuring we close the servletInputStream since the container handles it
        eProxyRequest.setEntity(
                new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        proxyRequest = eProxyRequest;
    } else
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);

    copyRequestHeaders(servletRequest, proxyRequest);

    setXForwardedForHeader(servletRequest, proxyRequest);

    HttpResponse proxyResponse = null;
    try {
        // Execute the request
        if (doLog) {
            LOG.info("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }
        proxyResponse = proxyClient.execute(getTargetHost(servletRequest), proxyRequest);

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();

        // copying response headers to make sure SESSIONID or other Cookie which comes from remote server
        // will be saved in client when the proxied url was redirected to another one.
        // see issue [#51](https://github.com/mitre/HTTP-Proxy-Servlet/issues/51)
        copyResponseHeaders(proxyResponse, servletRequest, servletResponse);

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            //the response is already "committed" now without any body to send
            return;
        }

        // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the
        //  reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        // Send the content to the client
        copyResponseEntity(proxyResponse, servletResponse);

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        if (e instanceof ServletException)
            throw (ServletException) e;
        //noinspection ConstantConditions
        if (e instanceof IOException)
            throw (IOException) e;
        throw new RuntimeException(e);

    } finally {
        // make sure the entire entity was consumed, so the connection is released
        if (proxyResponse != null)
            consumeQuietly(proxyResponse.getEntity());
        //Note: Don't need to close servlet outputStream:
        // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
    }
}

From source file:it.greenvulcano.gvesb.adapter.http.mapping.RESTHttpServletMapping.java

/**
 * @param req/*www.  j  av  a  2s .  c  o  m*/
 * @param request
 * @throws GVException
 */
private void parseRequest(HttpServletRequest req, String methodName, PatternResolver pr, GVBuffer request)
        throws GVException {
    try {
        Map<String, String[]> params = req.getParameterMap();
        Iterator<String> i = params.keySet().iterator();
        while (i.hasNext()) {
            String n = i.next();
            String v = params.get(n)[0];

            request.setProperty(n, ((v != null) && !"".equals(v)) ? v : "NULL");
        }

        String ct = Optional.ofNullable(req.getContentType()).orElse("");
        request.setProperty("HTTP_REQ_CONTENT_TYPE", ct.isEmpty() ? ct : "NULL");
        String acc = req.getHeader("Accept");
        request.setProperty("HTTP_REQ_ACCEPT", (acc != null) ? acc : "NULL");

        if (methodName.equals("POST") || methodName.equals("PUT")) {
            if (!ct.startsWith(AdapterHttpConstants.URLENCODED_MIMETYPE_NAME)) {
                Object requestContent = IOUtils.toByteArray(req.getInputStream());
                if (ct.startsWith(AdapterHttpConstants.APPXML_MIMETYPE_NAME)
                        || ct.startsWith(AdapterHttpConstants.APPJSON_MIMETYPE_NAME)
                        || ct.startsWith("text/")) {
                    /* GESTIRE ENCODING!!! */
                    requestContent = new String((byte[]) requestContent);
                }
                request.setObject(requestContent);
            }
        }

        if (pr.isExtractHdr()) {
            XMLUtils parser = null;
            try {
                parser = XMLUtils.getParserInstance();
                Document doc = parser.newDocument("Hdr");
                Element root = doc.getDocumentElement();

                Enumeration<?> hn = req.getHeaderNames();
                while (hn.hasMoreElements()) {
                    Element h = parser.insertElement(root, "h");
                    String name = (String) hn.nextElement();
                    String val = req.getHeader(name);
                    parser.setAttribute(h, "n", name);
                    parser.setAttribute(h, "v", val);
                }
                request.setProperty("HTTP_REQ_HEADERS", parser.serializeDOM(doc, true, false));
            } finally {
                XMLUtils.releaseParserInstance(parser);
            }
        }

    } catch (Exception exc) {
        throw new AdapterHttpExecutionException("RESTHttpServletMapping - Error parsing request data", exc);
    }
}

From source file:be.integrationarchitects.web.dragdrop.servlet.impl.DragDropServlet.java

protected void doPrepare(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    Map<String, Map<String, String>> p = utils.getHeadersParams(request, false);
    String ddropId = getRandom();
    p.get("params").put(DragDropContext.CTX_ID, ddropId);
    DragDropContext ctx = new DragDropContext(cfg.getHandler().getUserForRequest(request), p.get("params"),
            p.get("headers"));
    if (!ctx.validateContext()) {
        logger.logError("ERROR:context params missing");
        setServerError(request, response, "ERROR:context params missing");
        return;/*w w w  .j  ava 2  s. co  m*/
    }

    DragDropMimeHandlerRequest mimeRequest = new DragDropMimeHandlerRequest(p.get("params"), p.get("headers"),
            ctx);

    //mimeRequest.getCtx().setDropID(getRandom());

    //test server side functional error
    //      if(1==1){
    //         setServerError(request,response,"test server errorrrr");
    //       return;
    //}

    File f = null;
    //String user=cfg.getHandler().getUserForRequest(request);
    try {
        f = utils.serialize(mimeRequest.getCtx(), request.getInputStream(), cfg.getFileUploadSpeed());
    } catch (IllegalArgumentException e) {
        logger.logError("ERROR:" + e.getMessage(), e);
        setServerError(request, response, "Error saving prepare request");
        return;
    }

    cleanUpOldFiles();

    if (cfg.getMaxFileSizeTotal() > 0) {
        if (f.length() > cfg.getMaxFileSizeTotal()) {
            //total prepare size for all files check size
            logger.logError("File too big:" + f.length() + ":" + f.getName());
            f.delete();
            setServerError(request, response, "File prepare too big");
            return;
        }
    }

    //http header
    //content-type=multipart/form-data; boundary=----WebKitFormBoundaryoPekYfIk57uBF67C

    String boundary = null;
    String sb = request.getHeader("content-type");
    int i = sb.indexOf("boundary=");
    if (i > 0) {
        boundary = sb.substring(i + 9);
        logger.logTrace("Boundary::" + boundary);
    }
    mimeRequest.setMimeBoundary(boundary);
    // mimeRequest.getCtx().setUser(cfg.getHandler().getUserForRequest(request));
    try {
        prepareMultiPartFile(mimeRequest, f, response);
    } catch (Throwable e) {
        logger.logError("ERROR:" + e.getMessage(), e);
        setServerError(request, response, "Error prepareMultiPartFile");
        throw new RuntimeException(e);
    }
    logger.logTrace(("------------------"));
    logger.logTrace((new String("" + f.getName() + ":" + f.length())));
    logger.logTrace(("------------------"));
    logger.logDebug("...Post done #bytes:" + f.length());
}

From source file:com.buglabs.bug.ws.program.ProgramServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = req.getPathInfo();

    if (path == null) {
        log.log(LogService.LOG_WARNING, "Error: null program path.");
        resp.sendError(665, "Error: invalid program path.");
        return;//ww  w.  j  a v a  2  s.  c  o  m
    }

    String[] toks = path.split("/");

    String jarName = toks[toks.length - 1];

    File bundleDir = new File(incomingBundleDir);

    if (!bundleDir.exists()) {
        log.log(LogService.LOG_ERROR, "Unable to save bundle; can't create file.");
        resp.sendError(0, "Unable to save bundle; can't create file.");
    }

    Bundle existingBundle = findBundleByName(jarName);
    if (existingBundle != null) {
        try {
            uninstallBundle(existingBundle);
        } catch (BundleException e) {
            log.log(LogService.LOG_ERROR, "Unable to uninstall existing bundle.  Aborting install.", e);
        }
    }

    File jarFile = new File(bundleDir.getAbsolutePath() + File.separator + jarName + ".jar");
    FileOutputStream fos = new FileOutputStream(jarFile);
    IOUtils.copy(req.getInputStream(), fos);
    fos.flush();
    fos.close();
    //Tell knapsack to start the bundle.
    jarFile.setExecutable(true);

    initService.updateBundles();

    resp.getWriter().println(HTTP_OK_RESPONSE);
    req.getInputStream().close();
}

From source file:eionet.rpcserver.servlets.XmlRpcRouter.java

/**
 * Standard doPost implementation.// ww w . ja v  a2 s .com
 *
 */
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    /*
    System.out.println("=============================");
    System.out.println("============POST ============");
    System.out.println("=============================");
            
    */
    byte[] result = null;
    //authorization here!

    String encoding = null;
    try {
        Hashtable<Object, Object> props = UITServiceRoster.loadProperties();

        encoding = (String) props.get(UITServiceRoster.PROP_XMLRPC_ENCODING);
    } catch (Exception e) {
    }

    if (encoding != null) {
        req.setCharacterEncoding(encoding);
        XmlRpc.setEncoding(encoding);
    }

    //get authorization header from request
    String auth = req.getHeader("Authorization");
    if (auth != null) {

        if (!auth.toUpperCase().startsWith("BASIC")) {
            throw new ServletException("wrong kind of authorization!");
        }

        //get encoded username and password
        String userPassEncoded = auth.substring(6);

        String userPassDecoded = new String(Base64.decodeBase64(userPassEncoded));

        //split decoded username and password
        StringTokenizer userAndPass = new StringTokenizer(userPassDecoded, ":");
        String username = userAndPass.nextToken();
        String password = userAndPass.nextToken();

        result = xmlrpc.execute(req.getInputStream(), username, password);
    } else {
        //log("================ 2 ");
        result = xmlrpc.execute(req.getInputStream());
    }

    res.setContentType("text/xml");
    res.setContentLength(result.length);
    OutputStream output = res.getOutputStream();
    output.write(result);
    output.flush();

    //req.getSession().invalidate(); //???????????????
}