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:controllers.controller.java

private void subirArchivo(HttpSession session, HttpServletRequest request, HttpServletResponse response,
        QUID quid, PrintWriter out) throws Exception {
    String FormFrom = "";
    if (ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) {
        System.out.println("Tamao del archivo: " + request.getContentLength());
        if (PageParameters.getParameter("fileSizeLimited").equals("1") && (request.getContentLength() == -1//Este valor aparece cuando se desconoce el tamano
                || request.getContentLength() > Integer
                        .parseInt(PageParameters.getParameter("maxSizeToUpload")))) {
            this.getServletConfig().getServletContext().getRequestDispatcher(""
                    + PageParameters.getParameter("msgUtil")
                    + "/msgNBack.jsp?title=Error&type=error&msg=El tamao mximo del archivo es de "
                    + StringUtil.formatDouble1Decimals(
                            Double.parseDouble(PageParameters.getParameter("maxSizeToUpload")) / 1048576)
                    + " MBytes.").forward(request, response);
        } else {/*from w ww  . j  av  a2 s  . co m*/

            ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
            List items = upload.parseRequest(request);
            Iterator i = items.iterator();
            LinkedList filesToUpload = new LinkedList();
            HashMap parameters = new HashMap();
            while (i.hasNext()) {
                FileItem item = (FileItem) i.next();
                if (item.isFormField()) {
                    if (item.getFieldName().equalsIgnoreCase("FormFrom")) {
                        FormFrom = item.getString();
                    } else {
                        parameters.put(item.getFieldName(), item.getString());
                    }
                } else {
                    filesToUpload.add(item);
                }
            }
            switch (FormFrom) {

            case "insertObjetoArchivo":
                this.insertarObjetoArchivo(session, request, response, quid, out, parameters, filesToUpload,
                        FormFrom);
                break;
            }
        }
    }
}

From source file:org.webguitoolkit.ui.controls.form.fileupload.FileUploadServlet.java

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

    int eventId = 0;
    Hashtable parameters = new Hashtable();

    String cssId = "";

    List eventParameters = null;/*from w  w w. jav  a 2  s  .  c  o  m*/
    try {
        cssId = request.getQueryString().replaceAll("cssId=", "");
        UploadListener listener = new UploadListener(request, cssId, 30);

        // Create a factory for disk-based file items
        FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        // currently only one file is uploaded
        List fileItems = new ArrayList();

        // process uploads ..
        int contentlength = request.getContentLength();
        if (contentlength > maxFileSize) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head><title></title></head>");
            out.println("<body onLoad=\"window.parent.eventParam('" + cssId + "', new Array('File to large','"
                    + contentlength + "'));window.parent.fireWGTEvent('" + cssId + "','"
                    + FileUpload.EVENT_FILE_TO_LARGE + "');\">");
            out.println("</body>");
            out.println("</html>");

            request.getSession().setAttribute("uploadInfo", new UploadInfo(1, 1, 1, 1, "error"));
            return;
        }
        // parsing request and generate tmp files
        List items = upload.parseRequest(request);
        for (Iterator iter = items.iterator(); iter.hasNext();) {
            FileItem item = (FileItem) iter.next();

            // if file item is a parameter, add to parameter map
            // eles add filename to parameter map and store fileitem in the
            // fileitem list
            String name = item.getFieldName();
            if (item.isFormField()) {
                parameters.put(name, item.getString());
            } else {
                parameters.put(name, item.getName());
                fileItems.add(item);
            }
        }
        IFileHandler fileHandler = null;

        // filehandler class specified in the fileupload tag.
        String fileHandlerClass = (String) parameters.get("fileHandler");

        // of the filehandler (rather than for a Classname)
        cssId = (String) parameters.get("cssId");
        if (StringUtils.isNotEmpty(cssId) && fileHandler == null) {
            // get access through component event mechanism
            FileUpload fu = null;
            try {
                fu = (FileUpload) DWRController.getInstance().getComponentById(cssId);
            } catch (NullPointerException e) {
                // not instance found, probably not the GuiSessionController
                // filter configured
                // to catch the requests for this Servlet
            }
            // this is only possible if the GuiSessionFilter is enabled for
            // this servlet
            if (fu != null) {
                fileHandler = fu.getFileHandler();
            }
        } else if (StringUtils.isNotEmpty(fileHandlerClass))
            fileHandler = (IFileHandler) Class.forName(fileHandlerClass).newInstance();

        if (fileItems == null || fileItems.isEmpty()
                || StringUtils.isEmpty(((FileItem) fileItems.get(0)).getName())) {
            eventId = FileUpload.EVENT_NO_FILE;
            eventParameters = new ArrayList();
            eventParameters.add("error.fileupload.nofile@No file specified!");
        } else if (fileHandler != null) {
            fileHandler.init(fileItems, parameters, request);

            // method to process the Upload
            fileHandler.processUpload();

            // get returnparameter of the filehandler to send them bag to
            // the fileupload action listener.
            eventParameters = fileHandler.getEventParameters();
        } else {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head><title></title></head>");
            out.println("<body onLoad=\"window.parent.eventParam('" + cssId
                    + "', new Array('No File Handler found'));window.parent.fireWGTEvent('" + cssId + "','"
                    + FileUpload.EVENT_UPLOAD_ERROR + "');\">");
            out.println("</body>");
            out.println("</html>");

            request.getSession().setAttribute("uploadInfo", new UploadInfo(1, 1, 1, 1, "error"));
            return;
        }
    } catch (Exception e) {
        // event Id for errors
        eventId = FileUpload.EVENT_UPLOAD_ERROR;
        eventParameters = new ArrayList();
        eventParameters.add(cssId);
        eventParameters.add(e.toString());
        // e.printStackTrace(); // To change page of catch statement use
        // File | Settings | File Templates.
    } finally {
        // try to get cssId to send an event about the result of the upload
        // to the server
        cssId = (String) parameters.get("cssId");
    }

    // put the return parameters in a js array for sending them back to the
    // fileupload's action listener
    String eventParameterArray = "new Array(";
    if (eventParameters != null) {
        for (Iterator iter = eventParameters.iterator(); iter.hasNext();) {
            eventParameterArray += "'" + StringEscapeUtils.escapeJavaScript((String) iter.next()) + "'";
            if (iter.hasNext())
                eventParameterArray += ",";
        }
    }
    eventParameterArray += ")";

    // tell parrent page to do fire the event
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head><title></title></head>");
    out.println("<body onLoad=\"window.parent.eventParam('" + cssId + "', " + eventParameterArray
            + ");window.parent.fireWGTEvent('" + cssId + "','" + eventId + "');\">");
    out.println("</body>");
    out.println("</html>");
}

From source file:org.bigmouth.nvwa.network.http.HttpServletRequestLogger.java

public void info(final HttpServletRequest request) {
    if (null == request)
        return;//from w  w w . j av  a  2s  . c  o m
    if (LOGGER.isInfoEnabled()) {
        StringBuilder url = new StringBuilder(256);
        StringBuilder parameter = new StringBuilder(256);
        StringBuilder headers = new StringBuilder(256);
        StringBuilder body = new StringBuilder();
        String uri = request.getRequestURI();
        String address = request.getRemoteAddr();
        Map<?, ?> map = request.getParameterMap();
        if (MapUtils.isNotEmpty(map)) {
            parameter.append("?");
        }
        for (Entry<?, ?> entry : map.entrySet()) {
            Object key = entry.getKey();
            Object value = entry.getValue();
            parameter.append(key);
            if (value instanceof String[]) {
                parameter.append("=");
                String[] values = (String[]) value;
                for (int i = 0; i < values.length; i++) {
                    parameter.append(values[i]);
                }
            }
            parameter.append("&");
        }
        url.append(uri).append(StringUtils.removeEnd(parameter.toString(), "&"));
        String method = request.getMethod();
        int contentLength = request.getContentLength();
        Enumeration<?> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            Object nextElement = headerNames.nextElement();
            String value = request.getHeader(String.valueOf(nextElement));
            headers.append(nextElement).append(": ").append(value).append(";");
        }
        HttpServletRequestLog log = new HttpServletRequestLog();
        log.setAddress(address);
        log.setContentLength(contentLength);
        log.setHeaders(StringUtils.removeEnd(headers.toString(), ";"));
        log.setMethod(method);
        log.setUri(url.toString());
        log.setBody(body.toString());
        LOGGER.info(log.toString());
    }
}

From source file:org.tuckey.web.filters.urlrewrite.RequestProxy.java

/**
 * This method performs the proxying of the request to the target address.
 *
 * @param target     The target address. Has to be a fully qualified address. The request is send as-is to this address.
 * @param hsRequest  The request data which should be send to the
 * @param hsResponse The response data which will contain the data returned by the proxied request to target.
 * @throws java.io.IOException Passed on from the connection logic.
 *///from  w ww .  ja  v  a  2s  . c  om
public static void execute(final String target, final HttpServletRequest hsRequest,
        final HttpServletResponse hsResponse) throws IOException {
    if (log.isInfoEnabled()) {
        log.info("execute, target is " + target);
        log.info("response commit state: " + hsResponse.isCommitted());
    }

    if (StringUtils.isBlank(target)) {
        log.error("The target address is not given. Please provide a target address.");
        return;
    }

    log.info("checking url");
    final URL url;
    try {
        url = new URL(target);
    } catch (MalformedURLException e) {
        log.error("The provided target url is not valid.", e);
        return;
    }

    log.info("seting up the host configuration");

    final HostConfiguration config = new HostConfiguration();

    ProxyHost proxyHost = getUseProxyServer((String) hsRequest.getAttribute("use-proxy"));
    if (proxyHost != null)
        config.setProxyHost(proxyHost);

    final int port = url.getPort() != -1 ? url.getPort() : url.getDefaultPort();
    config.setHost(url.getHost(), port, url.getProtocol());

    if (log.isInfoEnabled())
        log.info("config is " + config.toString());

    final HttpMethod targetRequest = setupProxyRequest(hsRequest, url);
    if (targetRequest == null) {
        log.error("Unsupported request method found: " + hsRequest.getMethod());
        return;
    }

    //perform the reqeust to the target server
    final HttpClient client = new HttpClient(new SimpleHttpConnectionManager());
    if (log.isInfoEnabled()) {
        log.info("client state" + client.getState());
        log.info("client params" + client.getParams().toString());
        log.info("executeMethod / fetching data ...");
    }

    final int result;
    if (targetRequest instanceof EntityEnclosingMethod) {
        final RequestProxyCustomRequestEntity requestEntity = new RequestProxyCustomRequestEntity(
                hsRequest.getInputStream(), hsRequest.getContentLength(), hsRequest.getContentType());
        final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) targetRequest;
        entityEnclosingMethod.setRequestEntity(requestEntity);
        result = client.executeMethod(config, entityEnclosingMethod);

    } else {
        result = client.executeMethod(config, targetRequest);
    }

    //copy the target response headers to our response
    setupResponseHeaders(targetRequest, hsResponse);

    InputStream originalResponseStream = targetRequest.getResponseBodyAsStream();
    //the body might be null, i.e. for responses with cache-headers which leave out the body
    if (originalResponseStream != null) {
        OutputStream responseStream = hsResponse.getOutputStream();
        copyStream(originalResponseStream, responseStream);
    }

    log.info("set up response, result code was " + result);
}

From source file:net.yacy.http.ProxyHandler.java

@Override
public void handleRemote(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {

    sb.proxyLastAccess = System.currentTimeMillis();

    RequestHeader proxyHeaders = ProxyHandler.convertHeaderFromJetty(request);
    setProxyHeaderForClient(request, proxyHeaders);

    final HTTPClient client = new HTTPClient(ClientIdentification.yacyProxyAgent);
    client.setTimout(timeout);//from w w w  .  j av a2s . c  o  m
    client.setHeader(proxyHeaders.entrySet());
    client.setRedirecting(false);
    // send request
    try {
        String queryString = request.getQueryString() != null ? "?" + request.getQueryString() : "";
        DigestURL digestURI = new DigestURL(request.getScheme(), request.getServerName(),
                request.getServerPort(), request.getRequestURI() + queryString);
        if (request.getMethod().equals(HeaderFramework.METHOD_GET)) {
            client.GET(digestURI, false);
        } else if (request.getMethod().equals(HeaderFramework.METHOD_POST)) {
            client.POST(digestURI, request.getInputStream(), request.getContentLength(), false);
        } else if (request.getMethod().equals(HeaderFramework.METHOD_HEAD)) {
            client.HEADResponse(digestURI, false);
        } else {
            throw new ServletException("Unsupported Request Method");
        }
        HttpResponse clientresponse = client.getHttpResponse();
        int statusCode = clientresponse.getStatusLine().getStatusCode();
        final ResponseHeader responseHeaderLegacy = new ResponseHeader(statusCode,
                clientresponse.getAllHeaders());

        if (responseHeaderLegacy.isEmpty()) {
            throw new SocketException(clientresponse.getStatusLine().toString());
        }
        cleanResponseHeader(clientresponse);

        // reserver cache entry
        final net.yacy.crawler.retrieval.Request yacyRequest = new net.yacy.crawler.retrieval.Request(null,
                digestURI, null, //requestHeader.referer() == null ? null : new DigestURI(requestHeader.referer()).hash(), 
                "", responseHeaderLegacy.lastModified(), sb.crawler.defaultProxyProfile.handle(), 0,
                sb.crawler.defaultProxyProfile.timezoneOffset()); //sizeBeforeDelete < 0 ? 0 : sizeBeforeDelete);
        final Response yacyResponse = new Response(yacyRequest, null, responseHeaderLegacy,
                sb.crawler.defaultProxyProfile, false, null);

        final String storeError = yacyResponse.shallStoreCacheForProxy();
        final boolean storeHTCache = yacyResponse.profile().storeHTCache();
        final String supportError = TextParser.supports(yacyResponse.url(), yacyResponse.getMimeType());

        if (
        /*
         * Now we store the response into the htcache directory if
         * a) the response is cacheable AND
         */
        (storeError == null) &&
        /*
         * b) the user has configured to use the htcache OR
         * c) the content should be indexed
         */
                ((storeHTCache) || (supportError != null))) {
            // we don't write actually into a file, only to RAM, and schedule writing the file.
            int l = responseHeaderLegacy.size();
            final ByteArrayOutputStream byteStream = new ByteArrayOutputStream((l < 32) ? 32 : l);
            final OutputStream toClientAndMemory = new MultiOutputStream(
                    new OutputStream[] { response.getOutputStream(), byteStream });
            convertHeaderToJetty(clientresponse, response);
            response.setStatus(statusCode);
            client.writeTo(toClientAndMemory);

            // cached bytes
            storeToCache(yacyResponse, byteStream.toByteArray());
        } else {
            // no caching
            /*if (log.isFine()) log.logFine(reqID +" "+ url.toString() + " not cached." +
             " StoreError=" + ((storeError==null)?"None":storeError) +
             " StoreHTCache=" + storeHTCache +
             " SupportError=" + supportError);*/
            convertHeaderToJetty(clientresponse, response);
            response.setStatus(statusCode);

            if (statusCode == HttpServletResponse.SC_OK) { // continue to serve header to client e.g. HttpStatus = 302 (while skiping content)
                client.writeTo(response.getOutputStream()); // may throw exception on httpStatus=302 while gzip encoded inputstream
            }

        }
    } catch (final SocketException se) {
        throw new ServletException("Socket Exception: " + se.getMessage());
    } finally {
        client.finish();
    }

    // we handled this request, break out of handler chain
    logProxyAccess(request);
    baseRequest.setHandled(true);
}

From source file:io.mapzone.controller.vm.http.HttpRequestForwarder.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, URISyntaxException {
    targetUriObj = new URI(targetUri.get());
    targetHost = URIUtils.extractHost(targetUriObj);

    // Make the Request
    // note: we won't transfer the protocol version because I'm not sure it would
    // truly be compatible
    String method = request.getMethod();
    String proxyRequestUri = rewriteUrlFromRequest(request);

    // spec: RFC 2616, sec 4.3: either of these two headers signal that there is
    // a message body.
    if (request.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || request.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(request.getInputStream(), request.getContentLength()));
        proxyRequest = eProxyRequest;/* ww w .j  a v a2s.  co  m*/
    } else {
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }

    copyRequestHeaders(request);

    setXForwardedForHeader(request);

    // Execute the request
    try {
        active.set(this);

        log.debug("REQUEST " + "[" + StringUtils.right(Thread.currentThread().getName(), 2) + "] " + method
                + ": " + request.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri());
        proxyResponse = proxyClient.execute(targetHost, proxyRequest);
    } 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 {
        active.set(null);
    }
    // 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.ejbca.ui.web.protocol.OCSPServletBase.java

/**
 * Reads the request bytes and verifies min and max size of the request. If an error occurs it throws a MalformedRequestException. 
 * Can get request bytes both from a HTTP GET and POST request
 * //from  w w w  .j a  v a 2 s  .co  m
 * @param request
 * @param response
 * @return the request bytes or null if an error occured.
 * @throws IOException In case there is no stream to read
 * @throws MalformedRequestException 
 */
private byte[] checkAndGetRequestBytes(HttpServletRequest request)
        throws IOException, MalformedRequestException {
    final byte[] ret;
    // Get the request data
    String method = request.getMethod();
    String remoteAddress = request.getRemoteAddr();
    final int n = request.getContentLength();
    if (m_log.isDebugEnabled()) {
        m_log.debug(">checkAndGetRequestBytes. Received " + method + " request with content length: " + n
                + " from " + remoteAddress);
    }
    if (n > LimitLengthASN1Reader.MAX_REQUEST_SIZE) {
        String msg = intres.getLocalizedMessage("ocsp.toolarge", LimitLengthASN1Reader.MAX_REQUEST_SIZE, n);
        m_log.info(msg);
        throw new MalformedRequestException(msg);
    }
    // So we passed basic tests, now we can read the bytes, but still keep an eye on the size
    // we can not fully trust the sent content length.
    if (StringUtils.equals(method, "POST")) {
        final ServletInputStream in = request.getInputStream(); // ServletInputStream does not have to be closed, container handles this
        ret = new LimitLengthASN1Reader(in, n).readFirstASN1Object();
        if (n > ret.length) {
            // The client is sending more data than the OCSP request. It might be slightly broken or trying to bog down the server on purpose.
            // In the interest of not breaking existing systems that might have slightly broken clients we just log for a warning for now.
            String msg = intres.getLocalizedMessage("ocsp.additionaldata", ret.length, n);
            m_log.warn(msg);
            //throw new MalformedRequestException(msg);   // Responding with MALFORMED_REQUEST. 
        }
    } else if (StringUtils.equals(method, "GET")) {
        // GET request
        final StringBuffer url = request.getRequestURL();
        // RFC2560 A.1.1 says that request longer than 255 bytes SHOULD be sent by POST, we support GET for longer requests anyway.
        if (url.length() <= LimitLengthASN1Reader.MAX_REQUEST_SIZE) {
            final String decodedRequest;
            try {
                // We have to extract the pathInfo manually, to avoid multiple slashes being converted to a single
                // According to RFC 2396 2.2 chars only have to encoded if they conflict with the purpose, so
                // we can for example expect both '/' and "%2F" in the request.
                final String fullServletpath = request.getContextPath() + request.getServletPath();
                final int paramIx = Math.max(url.indexOf(fullServletpath), 0) + fullServletpath.length() + 1;
                final String requestString = paramIx < url.length() ? url.substring(paramIx) : "";
                decodedRequest = URLDecoder.decode(requestString, "UTF-8").replaceAll(" ", "+");
                //                  if (m_log.isDebugEnabled()) {
                //                     m_log.debug("URL: "+url.toString());
                //                  }
            } catch (Exception e) {
                String msg = intres.getLocalizedMessage("ocsp.badurlenc");
                m_log.info(msg);
                throw new MalformedRequestException(e);
            }
            if (decodedRequest != null && decodedRequest.length() > 0) {
                if (m_log.isDebugEnabled()) {
                    // Don't log the request if it's too long, we don't want to cause denial of service by filling log files or buffers.
                    if (decodedRequest.length() < 2048) {
                        m_log.debug("decodedRequest: " + decodedRequest);
                    } else {
                        m_log.debug("decodedRequest too long to log: " + decodedRequest.length());
                    }
                }
                try {
                    ret = org.ejbca.util.Base64.decode(decodedRequest.getBytes());
                } catch (Exception e) {
                    String msg = intres.getLocalizedMessage("ocsp.badurlenc");
                    m_log.info(msg);
                    throw new MalformedRequestException(e);
                }
            } else {
                String msg = intres.getLocalizedMessage("ocsp.missingreq");
                m_log.info(msg);
                throw new MalformedRequestException(msg);
            }
        } else {
            String msg = intres.getLocalizedMessage("ocsp.toolarge", LimitLengthASN1Reader.MAX_REQUEST_SIZE,
                    url.length());
            m_log.info(msg);
            throw new MalformedRequestException(msg);
        }
    } else {
        // Strange, an unknown method
        String msg = intres.getLocalizedMessage("ocsp.unknownmethod", method);
        m_log.info(msg);
        throw new MalformedRequestException(msg);
    }
    // Make a final check that we actually received something
    if ((ret == null) || (ret.length == 0)) {
        String msg = intres.getLocalizedMessage("ocsp.emptyreq", remoteAddress);
        m_log.info(msg);
        throw new MalformedRequestException(msg);
    }
    return ret;
}

From source file:org.sigmah.server.servlet.FileServlet.java

/**
 * See {@link ServletMethod#UPLOAD_ORGANIZATION_LOGO} for JavaDoc.
 * /*  w w  w . j  av a 2 s  .co  m*/
 * @param request
 *          The HTTP request containing the Organization id parameter.
 * @param response
 *          The HTTP response on which the file content is written.
 * @param context
 *          The execution context.
 * @throws java.io.IOException
 *           If an error occured while reading or writing to the socket or if an error occured while storing the
 *           uploaded file.
 * @throws org.sigmah.server.servlet.base.StatusServletException
 *           If the id parameter was not found or not parseable or if the request type is not MULTIPART or if the file
 *           exceeded the maximum allowed size.
 * @throws org.apache.commons.fileupload.FileUploadException
 *           If an error occured while reading the uploaded file.
 * @throws javax.servlet.ServletException
 *           If the given organization could not be found.
 */
protected void uploadOrganizationLogo(final HttpServletRequest request, final HttpServletResponse response,
        final ServletExecutionContext context)
        throws IOException, StatusServletException, ServletException, FileUploadException {

    // --
    // Retrieving parameters from request.
    // --

    final Integer organizationId = getIntegerParameter(request, RequestParameter.ID, false);

    // --
    // Retrieving Organization entity.
    // --

    final Organization organization = organizationDAO.findById(organizationId);
    if (organization == null) {
        throw new ServletException("Cannot find Organization with id '" + organizationId + "'.");
    }

    final String previousLogoFileName = organization.getLogo();

    // --
    // Verifying content length.
    // --

    final int contentLength = request.getContentLength();

    if (contentLength == 0) {
        LOG.error("Empty logo file.");
        throw new StatusServletException(Response.SC_NO_CONTENT);
    }

    if (contentLength > FileUploadUtils.MAX_UPLOAD_IMAGE_SIZE) {
        LOG.error("Logo file's size is too big to be uploaded (size: {}, maximum : {}).", contentLength,
                FileUploadUtils.MAX_UPLOAD_IMAGE_SIZE);
        throw new StatusServletException(Response.SC_REQUEST_ENTITY_TOO_LARGE);
    }

    // --
    // Saving new logo.
    // --

    organization.setLogo(organization.getId() + "_" + new Date().getTime());
    processUpload(new MultipartRequest(request), response, organization.getLogo(), true);
    organizationDAO.persist(organization, context.getUser());

    // --
    // Deleting previous logo file.
    // --

    if (StringUtils.isNotBlank(previousLogoFileName)) {
        fileStorageProvider.delete(previousLogoFileName);
    }

    response.getWriter().write(organization.getLogo());
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.Default.java

public void handlePut(HttpServletRequest request, HttpServletResponse response, String pathInContext,
        Resource resource) throws ServletException, IOException {
    boolean exists = resource != null && resource.exists();
    if (exists && !passConditionalHeaders(request, response, resource))
        return;/* w  w w .ja v  a  2 s  .c om*/

    if (pathInContext.endsWith("/")) {
        if (!exists) {
            if (!resource.getFile().mkdirs())
                response.sendError(HttpResponse.__403_Forbidden, "Directories could not be created");
            else {
                response.setStatus(HttpResponse.__201_Created);
                response.flushBuffer();
            }
        } else {
            response.setStatus(HttpResponse.__200_OK);
            response.flushBuffer();
        }
    } else {
        try {
            int toRead = request.getContentLength();
            InputStream in = request.getInputStream();
            OutputStream out = resource.getOutputStream();
            if (toRead >= 0)
                IO.copy(in, out, toRead);
            else
                IO.copy(in, out);
            out.close();

            response.setStatus(exists ? HttpResponse.__200_OK : HttpResponse.__201_Created);
            response.flushBuffer();
        } catch (Exception ex) {
            log.warn(LogSupport.EXCEPTION, ex);
            response.sendError(HttpResponse.__403_Forbidden, ex.getMessage());
        }
    }
}

From source file:be.milieuinfo.core.proxy.controller.ProxyServlet.java

@SuppressWarnings("deprecation")
@Override/*from  www  . j  a  va2  s  .com*/
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;
    //spec: RFC 2616, sec 4.3: either 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);

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

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

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            //just to be sure, but is probably a no-op
            EntityUtils.consume(proxyResponse.getEntity());
            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);

        // 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;
        if (e instanceof IOException)
            throw (IOException) e;
        throw new RuntimeException(e);
    }
}