Example usage for javax.servlet.http HttpServletRequest getContentLength

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

Introduction

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

Prototype

public int getContentLength();

Source Link

Document

Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known ir is greater than Integer.MAX_VALUE.

Usage

From source file:org.apache.solr.servlet.SolrRequestParserTest.java

License:asdf

public void doAutoDetect(String userAgent, String method, final String body, String expectedContentType,
        String expectedKey, String expectedValue) throws Exception {
    String uri = "/solr/select";
    String contentType = "application/x-www-form-urlencoded";
    int contentLength = -1; // does this mean auto-detect?

    HttpServletRequest request = createMock(HttpServletRequest.class);
    expect(request.getHeader("User-Agent")).andReturn(userAgent).anyTimes();
    expect(request.getHeader("Content-Length")).andReturn(null).anyTimes();
    expect(request.getRequestURI()).andReturn(uri).anyTimes();
    expect(request.getContentType()).andReturn(contentType).anyTimes();
    expect(request.getContentLength()).andReturn(contentLength).anyTimes();
    expect(request.getAttribute(SolrRequestParsers.REQUEST_TIMER_SERVLET_ATTRIBUTE)).andReturn(null).anyTimes();

    expect(request.getMethod()).andReturn(method).anyTimes();
    // we dont pass a content-length to let the security mechanism limit it:
    expect(request.getQueryString()).andReturn("foo=1&bar=2").anyTimes();
    expect(request.getInputStream())/*from w w  w.  ja  v  a2  s . com*/
            .andReturn(new ByteServletInputStream(body.getBytes(StandardCharsets.US_ASCII)));
    expect(request.getAttribute(EasyMock.anyObject(String.class))).andReturn(null).anyTimes();
    replay(request);

    SolrRequestParsers parsers = new SolrRequestParsers(h.getCore().getSolrConfig());
    SolrQueryRequest req = parsers.parse(h.getCore(), "/select", request);
    int num = 0;
    if (expectedContentType != null) {
        for (ContentStream cs : req.getContentStreams()) {
            num++;
            assertTrue(cs.getContentType().startsWith(expectedContentType));
            String returnedBody = IOUtils.toString(cs.getReader());
            assertEquals(body, returnedBody);
        }
        assertEquals(1, num);
    }

    assertEquals("1", req.getParams().get("foo"));
    assertEquals("2", req.getParams().get("bar"));

    if (expectedKey != null) {
        assertEquals(expectedValue, req.getParams().get(expectedKey));
    }

    req.close();
}

From source file:presentation.webgui.vitroappservlet.uploadService.UploadServlet.java

private void doFileUpload(HttpSession session, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    String fname = "";
    HashMap<String, String> myFileRequestParamsHM = new HashMap<String, String>();

    try {/*from   w w w  . java  2  s  . c o m*/
        FileUploadListener listener = new FileUploadListener(request.getContentLength());
        FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);

        ServletFileUpload upload = new ServletFileUpload(factory);
        //        upload.setSizeMax(83886080); /* the unit is bytes */

        FileItem fileItem = null;
        fileItem = myrequestGetParameter(upload, request, myFileRequestParamsHM);

        String mode = myFileRequestParamsHM.get("mode");

        session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats());

        boolean hasError = false;

        if (fileItem != null) {
            /**
             * (for KML only files) ( not prefabs (collada) or icons or images)
             */
            WstxInputFactory f = null;
            XMLStreamReader2 sr = null;
            SMInputCursor iroot = null;
            if (mode.equals("3dFile") || mode.equals("LinePlaceMarksFile")
                    || mode.equals("RoomCenterPointsFile")) {
                f = new WstxInputFactory();
                f.configureForConvenience();
                // Let's configure factory 'optimally'...
                f.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);
                f.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);

                sr = (XMLStreamReader2) f.createXMLStreamReader(fileItem.getInputStream());
                iroot = SMInputFactory.rootElementCursor(sr);
                // If we needed to store some information about preceding siblings,
                // we should enable tracking. (we need it for  mygetElementValueStaxMultiple method)
                iroot.setElementTracking(SMInputCursor.Tracking.PARENTS);

                iroot.getNext();
                if (!"kml".equals(iroot.getLocalName().toLowerCase())) {
                    hasError = true;
                    listener.getFileUploadStats().setCurrentStatus("finito");
                    session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats());
                    sendCompleteResponse(myFileRequestParamsHM, response, hasError,
                            "Root element not kml, as expected, but " + iroot.getLocalName());
                    return;
                }
            }

            fname = "";
            if (mode.equals("3dFile")) {
                if ((fileItem.getSize() / 1024) > 25096) { // with woodstox stax, file size should not be a problem. Let's put some limit however!
                    hasError = true;
                    listener.getFileUploadStats().setCurrentStatus("finito");
                    session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats());
                    sendCompleteResponse(myFileRequestParamsHM, response, hasError,
                            "File is very large for XML handler to process!");
                    return;
                }

                fname = "";
                String[] elementsToFollow = { "document", "name" };
                Vector<String> resultValues = SMTools.mygetElementValueStax(iroot, elementsToFollow, 0);
                if (resultValues != null && !resultValues.isEmpty()) {
                    fname = resultValues.elementAt(0);
                }

                if (!fname.equals("")) {
                    // check for kml extension and Add it if necessary!!
                    int lastdot = fname.lastIndexOf('.');
                    if (lastdot != -1) {
                        if (lastdot == 0) // if it is the first char then ignore it and add an extension anyway
                        {
                            fname += ".kml";
                        } else if (lastdot < fname.length() - 1) {
                            if (!(fname.substring(lastdot + 1).toLowerCase().equals("kml"))) {
                                fname += ".kml";
                            }
                        } else if (lastdot == fname.length() - 1) {
                            fname += "kml";
                        }
                    } else {
                        fname += ".kml";
                    }

                    String realPath = this.getServletContext().getRealPath("/");
                    int lastslash = realPath.lastIndexOf(File.separator);
                    realPath = realPath.substring(0, lastslash);
                    // too slow
                    //FileWriter out = new FileWriter(realPath+File.separator+"KML"+File.separator+fname);
                    //document.sendToWriter(out);
                    // too slow
                    //StringWriter outString = new StringWriter();
                    //document.sendToWriter(outString);
                    //out.close();

                    // fast - do not process and store xml file, just store it.
                    File outFile = new File(realPath + File.separator + "Models" + File.separator + "Large"
                            + File.separator + fname);
                    outFile.createNewFile();
                    FileWriter tmpoutWriter = new FileWriter(outFile);
                    BufferedWriter buffWriter = new BufferedWriter(tmpoutWriter);
                    buffWriter.write(new String(fileItem.get()));
                    buffWriter.flush();
                    buffWriter.close();
                    tmpoutWriter.close();
                } else {
                    hasError = true;
                    listener.getFileUploadStats().setCurrentStatus("finito");
                    session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats());
                    sendCompleteResponse(myFileRequestParamsHM, response, hasError,
                            "No name tag found inside the KML file!");
                    return;
                }
            } else if (mode.equals("LinePlaceMarksFile")) {
                fname = "";
                String[] elementsToFollow = { "document", "folder", "placemark", "point", "coordinates" };
                Vector<String> resultValues = SMTools.mygetElementValueStax(iroot, elementsToFollow, 0);
                if (resultValues != null && resultValues.size() < 2) {
                    hasError = true;
                    listener.getFileUploadStats().setCurrentStatus("finito");
                    session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats());
                    sendCompleteResponse(myFileRequestParamsHM, response, hasError,
                            "File does not contain 2 placemarks!");
                    return;
                }

                for (int i = 0; (i < resultValues.size()) && (i < 2); i++) {
                    fname = fname + ":" + resultValues.elementAt(i);
                }
            } else if (mode.equals("RoomCenterPointsFile")) {
                fname = "";
                // here: process PlaceMarks for rooms (centerpoints) in the building
                String[] elementsToFollow0 = { "document", "folder", "placemark", "point", "coordinates" };
                String[] elementsToFollow1 = { "document", "folder", "placemark", "name" };
                // add elements to follow for room names and coordinates        
                Vector<String[]> elementsToFollow = new Vector<String[]>();
                elementsToFollow.add(elementsToFollow0);
                elementsToFollow.add(elementsToFollow1);
                Vector<Vector<String>> resultValues = new Vector<Vector<String>>();
                SMTools.mygetMultipleElementValuesStax(iroot, elementsToFollow, resultValues);

                Vector<String> resultValuesForCoords = resultValues.elementAt(0);
                Vector<String> resultValuesForNames = resultValues.elementAt(1);

                if (resultValuesForCoords == null || resultValuesForCoords.size() == 0
                        || resultValuesForNames == null || resultValuesForCoords.size() == 0
                        || resultValuesForCoords.size() != resultValuesForNames.size()) {
                    hasError = true;
                    listener.getFileUploadStats().setCurrentStatus("finito");
                    session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats());
                    sendCompleteResponse(myFileRequestParamsHM, response, hasError,
                            "File does not contain valid data for rooms!");
                    return;
                }

                for (int i = 0; i < resultValuesForNames.size(); i++) {
                    // since we use ;  and ':' to seperate rooms, we replace the comma's in the rooms' names.
                    if (resultValuesForNames.elementAt(i).indexOf(';') >= 0
                            || resultValuesForNames.elementAt(i).indexOf(':') >= 0) {
                        String tmp = new String(resultValuesForNames.elementAt(i));
                        tmp.replace(';', ' ');
                        tmp.replace(':', ' ');
                        resultValuesForNames.set(i, tmp);
                    }
                    fname = fname + ";" + resultValuesForNames.elementAt(i) + ":"
                            + resultValuesForCoords.elementAt(i);
                }

            } else if (mode.equals("DefaultIconfile") || mode.equals("DefaultPrefabfile")
                    || mode.equals("SpecialValueIconfile") || mode.equals("SpecialValuePrefabfile")
                    || mode.equals("NumericRangeIconfile") || mode.equals("NumericRangePrefabfile")) {
                fname = "";
                if ((fileItem.getSize() / 1024) > 10096) { // no more than 10 Mbs of size for small prefabs or icons
                    hasError = true;
                    listener.getFileUploadStats().setCurrentStatus("finito");
                    session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats());
                    sendCompleteResponse(myFileRequestParamsHM, response, hasError, "File is very large!");
                    return;
                }
                fname = fileItem.getName();
                if (!fname.equals("")) {
                    String realPath = this.getServletContext().getRealPath("/");
                    int lastslash = realPath.lastIndexOf(File.separator);
                    realPath = realPath.substring(0, lastslash);

                    File outFile = new File(realPath + File.separator + "Models" + File.separator + "Media"
                            + File.separator + fname);
                    outFile.createNewFile();
                    /*
                    FileWriter tmpoutWriter = new FileWriter(outFile);
                    BufferedWriter buffWriter = new BufferedWriter(tmpoutWriter);                      
                    buffWriter.write(new String(fileItem.get()));
                    buffWriter.flush();
                    buffWriter.close();
                    tmpoutWriter.close();
                    */
                    fileItem.write(outFile);
                } else {
                    hasError = true;
                    listener.getFileUploadStats().setCurrentStatus("finito");
                    session.setAttribute("FILE_UPLOAD_STATS" + mode, listener.getFileUploadStats());
                    sendCompleteResponse(myFileRequestParamsHM, response, hasError,
                            "No valid name for uploaded file!");
                    return;
                }
            }

            fileItem.delete();
        }

        if (!hasError) {
            sendCompleteResponse(myFileRequestParamsHM, response, hasError, fname);
        } else {
            hasError = true;
            sendCompleteResponse(myFileRequestParamsHM, response, hasError,
                    "Could not process uploaded file. Please see log for details.");
        }
    } catch (Exception e) {
        boolean hasError = true;
        sendCompleteResponse(myFileRequestParamsHM, response, hasError, "::" + fname + "::" + e.getMessage());
    }
}

From source file:eionet.gdem.utils.FileUpload.java

/**
 * Uploads file from client to the server. Parses HttpRequestInputstream and writes bytes to the specified folder in the same
 * computer, where servlet runs/* w w w  . j a va  2 s .c o  m*/
 *
 * @param req request
 * @throws GDEMException If an error occurs.
 */
public File uploadFile(HttpServletRequest req) throws GDEMException {

    // helper arrays
    byte[] bt1 = new byte[4096];
    byte[] bt2 = new byte[4096];

    int[] int1 = new int[1];
    int[] int2 = new int[1];
    ServletInputStream si = null;

    try {
        si = req.getInputStream();
        String contentType = req.getContentType();
        String charEncoding = req.getCharacterEncoding();
        // +RV020508
        int contentLength = req.getContentLength();
        lenRcvd = 0;
        if (contentLength == -1) {
            throw new GDEMException("Invalid HTTP POST. Content length is unknown.");
        }
        //
        int boundaryPos;
        if ((boundaryPos = contentType.indexOf("boundary=")) != -1) {
            contentType = contentType.substring(boundaryPos + 9);
            contentType = "--" + contentType;
        } // end if

        // Find filename
        String fileName;
        while ((fileName = readLine(bt1, int1, si, charEncoding)) != null) {
            int i = fileName.indexOf("filename=");
            if (i >= 0) {
                fileName = fileName.substring(i + 10);
                i = fileName.indexOf("\"");
                if (i > 0) {
                    FileOutputStream fileOut = null;
                    boolean fWrite = false;
                    File tmpFile = new File(_folderName, getSessionId());
                    try {

                        fileName = fileName.substring(0, i);

                        fileName = getFileName(fileName);

                        // _fileName is returned by getFileName() method
                        _fileName = fileName;

                        String line2 = readLine(bt1, int1, si, charEncoding);
                        if (line2.indexOf("Content-Type") >= 0) {
                            readLine(bt1, int1, si, charEncoding);
                        }

                        fileOut = new FileOutputStream(tmpFile);

                        String helpStr = null;
                        long l = 0L;

                        // changes to true, if something is written to the output file
                        // remains false, if user has entered a wrong filename or the file's size is 0kB

                        // parse the file in the MIME message
                        while ((line2 = readLine(bt1, int1, si, charEncoding)) != null) {
                            if (line2.indexOf(contentType) == 0 && bt1[0] == 45) {
                                break;
                            }
                            if (helpStr != null && l <= 75L) {
                                fWrite = true;
                                fileOut.write(bt2, 0, int2[0]);
                                fileOut.flush();
                            } // endif
                            helpStr = readLine(bt2, int2, si, charEncoding);
                            if (helpStr == null || helpStr.indexOf(contentType) == 0 && bt2[0] == 45) {
                                break;
                            }

                            fWrite = true;
                            fileOut.write(bt1, 0, int1[0]);
                            fileOut.flush();
                        } // end while

                        byte bt0;

                        if (lineSep.length() == 1) {
                            bt0 = 2;
                        } else {
                            bt0 = 1;
                        }

                        if (helpStr != null && bt2[0] != 45 && int2[0] > lineSep.length() * bt0) {
                            fileOut.write(bt2, 0, int2[0] - lineSep.length() * bt0);
                            fWrite = true;
                        }
                        if (line2 != null && bt1[0] != 45 && int1[0] > lineSep.length() * bt0) {
                            fileOut.write(bt1, 0, int1[0] - lineSep.length() * bt0);
                            fWrite = true;
                        }
                    } finally {
                        IOUtils.closeQuietly(fileOut);
                    }
                    if (fWrite) {
                        try {
                            synchronized (fileLock) {
                                File file = new File(_folderName, fileName);
                                int n = 0;
                                while (file.exists()) {
                                    n++;
                                    fileName = genFileName(fileName, n);
                                    file = new File(_folderName, fileName);
                                }
                                setFileName(fileName);
                                try {
                                    file.delete();
                                } catch (Exception _ex) {
                                    throw new GDEMException("Error deleting temporary file: " + _ex.toString());
                                }
                                tmpFile.renameTo(file);
                                return file;
                            } // sync
                        } catch (Exception _ex) {
                            throw new GDEMException("Error renaming temporary file: " + _ex.toString());
                        }

                    } else { // end-if file = 0kb or does not exist
                        tmpFile.delete();
                        throw new GDEMException("File: " + fileName + " does not exist or contains no data.");
                    }

                }
                // break;
            } // end if (filename found)
        } // end while
          // +RV020508
        if (contentLength != lenRcvd) {
            throw new GDEMException(
                    "Canceled upload: expected " + contentLength + " bytes, received " + lenRcvd + " bytes.");
        }
    } catch (IOException e) {
        throw new GDEMException("Error uploading file: " + e.toString());
    } finally {
        IOUtils.closeQuietly(si);
    }

    return null;
}

From source file:com.dp.bigdata.taurus.web.servlet.CreateTaskServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    // Determine final URL
    StringBuffer uri = new StringBuffer();

    if (req.getParameter("update") != null) {
        uri.append(targetUri).append("/").append(req.getParameter("update"));
    } else {/*from   w  w w  . jav a  2s .  c  om*/
        uri.append(targetUri);
    }
    LOG.info("Access URI : " + uri.toString());
    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    // Unknown content length ...
    // if (contentLength == -1)
    // throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };
        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);
        request = tmpRequest;
    }

    // Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    // Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<?> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        String headerValue = req.getHeader(headerName);
        //LOG.info("header: " + headerName + " value: " + headerValue);
        // Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-type")) {
            request.addHeader(headerName, headerValue + ";charset=\"utf-8\"");
        } else if (!lowerHeader.equals("content-length") && !lowerHeader.equals("host")) {
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);
    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        if (!header.getName().equals("Transfer-Encoding"))
            resp.addHeader(header.getName(), header.getValue());
    }

    // Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();
    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();

    byte buffer[] = new byte[50];
    while (input.read(buffer) != -1) {
        output.write(buffer);
    }
    //        int b = input.read();
    //        while (b != -1) {
    //            output.write(b);
    //            b = input.read();
    //        }
    // Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}

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

/**
 * this method references to//from w w w  . j av a  2s  .c o  m
 * {@link #doGet(HttpServletRequest, HttpServletResponse)}
 */
public final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
    //value chosen to limit denial of service
    if (req.getContentLength() > getSession().getMaxContentLength() * 1024) {
        res.setContentType("text/html");
        ServletOutputStream out = res.getOutputStream();
        // WingS-Portlet-Bridge: removed unsupported tags
        out.println("<div><h1>Error - content length &gt; " + getSession().getMaxContentLength() + "k");
        out.println("</h1></div>");
    } else {
        doGet(req, res);
    }
    // sollte man den obigen Block nicht durch folgende Zeile ersetzen?
    //throw new RuntimeException("this method must never be called!");
    // bsc: Wieso?
}

From source file:com.dien.upload.server.UploadServlet.java

/**
 * Create a new listener for this session.
 * //from  w w w. j  a v  a2 s  .c o  m
 * @param request
 * @return the appropriate listener 
 */
protected AbstractUploadListener createNewListener(HttpServletRequest request) {
    if (isAppEngine()) {
        return new MemoryUploadListener(uploadDelay, request.getContentLength());
    } else {
        return new UploadListener(uploadDelay, request.getContentLength());
    }
}

From source file:org.ngrinder.script.controller.SvnDavController.java

@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
private void logRequest(HttpServletRequest request) {
    StringBuilder logBuffer = new StringBuilder();
    logBuffer.append('\n');
    logBuffer.append("request.getAuthType(): " + request.getAuthType());
    logBuffer.append('\n');
    logBuffer.append("request.getCharacterEncoding(): " + request.getCharacterEncoding());
    logBuffer.append('\n');
    logBuffer.append("request.getContentType(): " + request.getContentType());
    logBuffer.append('\n');
    logBuffer.append("request.getContextPath(): " + request.getContextPath());
    logBuffer.append('\n');
    logBuffer.append("request.getContentLength(): " + request.getContentLength());
    logBuffer.append('\n');
    logBuffer.append("request.getMethod(): " + request.getMethod());
    logBuffer.append('\n');
    logBuffer.append("request.getPathInfo(): " + request.getPathInfo());
    logBuffer.append('\n');
    logBuffer.append("request.getPathTranslated(): " + request.getPathTranslated());
    logBuffer.append('\n');
    logBuffer.append("request.getQueryString(): " + request.getQueryString());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteAddr(): " + request.getRemoteAddr());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteHost(): " + request.getRemoteHost());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteUser(): " + request.getRemoteUser());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURI(): " + request.getRequestURI());
    logBuffer.append('\n');
    logBuffer.append("request.getServerName(): " + request.getServerName());
    logBuffer.append('\n');
    logBuffer.append("request.getServerPort(): " + request.getServerPort());
    logBuffer.append('\n');
    logBuffer.append("request.getServletPath(): " + request.getServletPath());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURL(): " + request.getRequestURL());
    LOGGER.trace(logBuffer.toString());//from   w ww .j  av a  2 s  .  com
}

From source file:com.couchbase.capi.servlet.CAPIServlet.java

/**
 * Handle _revs_diff by claiming we don't have any of these revisions
 *
 * @param req/*  w w  w.  j  a  va2  s .  co m*/
 * @param resp
 * @param database
 * @throws ServletException
 * @throws IOException
 */
protected void handleRevsDiff(HttpServletRequest req, HttpServletResponse resp, String database)
        throws ServletException, IOException {

    if (!req.getMethod().equals("POST")) {
        throw new UnsupportedOperationException("_revs_diff must be POST");
    }

    logger.trace("Got revs diff request for " + database);

    OutputStream os = resp.getOutputStream();
    InputStream is = req.getInputStream();

    int requestLength = req.getContentLength();
    byte[] buffer = new byte[requestLength];
    IOUtils.readFully(is, buffer, 0, requestLength);

    logger.trace("revs diff request body was {}", new String(buffer));

    @SuppressWarnings("unchecked")
    Map<String, Object> parsedValue = (Map<String, Object>) mapper.readValue(buffer, Map.class);

    logger.trace("revs diff parsed value is " + parsedValue);

    try {
        Map<String, Object> responseMap = capiBehavior.revsDiff(database, parsedValue);

        if (responseMap != null) {
            mapper.writeValue(os, responseMap);
        } else {
            sendNotFoundResponse(resp, "missing");
        }
    } catch (UnavailableException e) {
        sendServiceUnavailableResponse(resp, "too many concurrent requests");
    }
}

From source file:com.meikai.common.web.servlet.FCKeditorConnectorServlet.java

/**
 * Manage the Post requests (FileUpload).<br>
 * /*  w ww. j  av a2 s .c om*/
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br>
 * <br>
 * It store the file (renaming it in case a file with the same name exists)
 * and then return an HTML file with a javascript command in it.
 * 
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN Connector DOPOST ---");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");

    String retVal = "0";
    String newName = "";

    // edit check user uploader file size
    int contextLength = request.getContentLength();
    int fileSize = (int) (((float) contextLength) / ((float) (1024)));
    PrintWriter out = response.getWriter();

    if (fileSize < 30240) {

        String commandStr = request.getParameter("Command");
        String typeStr = request.getParameter("Type");
        String currentFolderStr = request.getParameter("CurrentFolder");
        String currentPath = baseDir + typeStr + "/" + dateCreated.substring(0, 4) + "/"
                + dateCreated.substring(5) + currentFolderStr;
        // create user dir
        makeDirectory(getServletContext().getRealPath("/"), currentPath);
        String currentDirPath = getServletContext().getRealPath(currentPath);
        // edit end ++++++++++++++++

        if (debug)
            System.out.println(currentDirPath);

        if (!commandStr.equals("FileUpload"))
            retVal = "203";
        else {
            DiskFileUpload upload = new DiskFileUpload();

            try {

                upload.setSizeMax(1 * 1024 * 1024); // ??,??: 
                upload.setSizeThreshold(4096); // ???,??: 
                upload.setRepositoryPath("c:/temp/"); // ?getSizeThreshold()? 
                List items = upload.parseRequest(request);

                Map fields = new HashMap();

                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField())
                        fields.put(item.getFieldName(), item.getString());
                    else
                        fields.put(item.getFieldName(), item);
                }
                FileItem uplFile = (FileItem) fields.get("NewFile");
                String fileNameLong = uplFile.getName();
                fileNameLong = fileNameLong.replace('\\', '/');
                String[] pathParts = fileNameLong.split("/");
                String fileName = pathParts[pathParts.length - 1];

                String nameWithoutExt = getNameWithoutExtension(fileName);
                String ext = getExtension(fileName);
                File pathToSave = new File(currentDirPath, fileName);
                if (FckeditorUtil.extIsAllowed(allowedExtensions, deniedExtensions, typeStr, ext)) {
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                        retVal = "201";
                        pathToSave = new File(currentDirPath, newName);
                        counter++;
                    }
                    uplFile.write(pathToSave);
                    // ?
                    if (logger.isInfoEnabled()) {
                        logger.info("...");
                    }
                } else {
                    retVal = "202";
                    if (debug)
                        System.out.println("Invalid file type: " + ext);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                retVal = "203";
            }
        }
    } else {
        retVal = "204";
    }
    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');");
    out.println("</script>");
    out.flush();
    out.close();

    if (debug)
        System.out.println("--- END DOPOST ---");

}