Example usage for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED

List of usage examples for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED.

Prototype

int SC_NOT_MODIFIED

To view the source code for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED.

Click Source Link

Document

Status code (304) indicating that a conditional GET operation found that the resource was available and not modified.

Usage

From source file:edu.chalmers.dat076.moviefinder.controller.FileController.java

/**
 * Process the actual request./*from  w  w w. ja va 2s .  c o  m*/
 *
 * @param request The request to be processed.
 * @param response The response to be created.
 * @param content Whether the request body should be written (GET) or not
 * (HEAD).
 * @throws IOException If something fails at I/O level.
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content,
        String path, String defaultContentType) throws IOException {
    // Validate the requested file ------------------------------------------------------------

    // URL-decode the file name (might contain spaces and on) and prepare file object.
    File file = new File(path);

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file.
    String fileName = file.getName();
    long length = file.length();
    long lastModified = file.lastModified();
    String eTag = fileName + "_" + length + "_" + lastModified;
    long expires = System.currentTimeMillis() + FileControllerUtils.DEFAULT_EXPIRE_TIME;

    // Validate request headers for caching ---------------------------------------------------
    // If-None-Match header should contain "*" or ETag. If so, then return 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && FileControllerUtils.matches(ifNoneMatch, eTag)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so, then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
        return;
    }

    // Validate request headers for resume ----------------------------------------------------
    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !FileControllerUtils.matches(ifMatch, eTag)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range -------------------------------------------------------------
    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        // If-Range header should either match ETag or be greater then LastModified. If not,
        // then return full file.
        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(eTag)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid.
                if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
                long start = FileControllerUtils.sublong(part, 0, part.indexOf("-"));
                long end = FileControllerUtils.sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response --------------------------------------------------------
    // Get content type by file name and set default GZIP support and content disposition.
    String contentType = request.getServletContext().getMimeType(fileName);
    boolean acceptsGzip = false;
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    //if (contentType == null) {
    contentType = defaultContentType;
    //}

    // If content type is text, then determine whether GZIP content encoding is supported by
    // the browser and expand content type with the one and right character encoding.
    if (contentType.startsWith("text")) {
        String acceptEncoding = request.getHeader("Accept-Encoding");
        acceptsGzip = acceptEncoding != null && FileControllerUtils.accepts(acceptEncoding, "gzip");
        contentType += ";charset=UTF-8";
    } // Else, expect for images, determine content disposition. If content type is supported by
      // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
    else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && FileControllerUtils.accepts(accept, contentType) ? "inline"
                : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(FileControllerUtils.DEFAULT_BUFFER_SIZE);
    //response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", expires);

    // Send requested file (part(s)) to client ------------------------------------------------
    // Prepare streams.
    RandomAccessFile input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new RandomAccessFile(file, "r");
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            Range r = full;
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);

            if (content) {
                if (acceptsGzip) {
                    // The browser accepts GZIP, so GZIP the content.
                    response.setHeader("Content-Encoding", "gzip");
                    output = new GZIPOutputStream(output, FileControllerUtils.DEFAULT_BUFFER_SIZE);
                } else {
                    // Content length is not directly predictable in case of GZIP.
                    // So only add it if there is no means of GZIP, else browser will hang.
                    response.setHeader("Content-Length", String.valueOf(r.length));
                }

                // Copy full range.
                FileControllerUtils.copy(input, output, r.start, r.length);
            }

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (content) {
                // Copy single part range.
                FileControllerUtils.copy(input, output, r.start, r.length);
            }

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + FileControllerUtils.MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (content) {
                // Cast back to ServletOutputStream to get the easy println methods.
                ServletOutputStream sos = (ServletOutputStream) output;

                // Copy multi part range.
                for (Range r : ranges) {
                    // Add multipart boundary and header fields for every range.
                    sos.println();
                    sos.println("--" + FileControllerUtils.MULTIPART_BOUNDARY);
                    sos.println("Content-Type: " + contentType);
                    sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                    // Copy single part range of multi part range.
                    FileControllerUtils.copy(input, output, r.start, r.length);
                }

                // End with multipart boundary.
                sos.println();
                sos.println("--" + FileControllerUtils.MULTIPART_BOUNDARY + "--");
            }
        }
    } finally {
        // Gently close streams.
        FileControllerUtils.close(output);
        FileControllerUtils.close(input);
    }
}

From source file:com.github.zhanhb.ckfinder.download.PathPartial.java

/**
 * Check if the if-none-match condition is satisfied.
 *
 * @param request The servlet request we are processing
 * @param etag ETag of the entity//  w  w  w . j  a  va 2  s . c o m
 */
private void checkIfNoneMatch(HttpServletRequest request, String etag) {
    String headerValue = request.getHeader(HttpHeaders.IF_NONE_MATCH);
    if (headerValue != null && (headerValue.equals("*") || anyMatches(headerValue, etag))) {
        // For GET and HEAD, we should respond with
        // 304 Not Modified.
        // For every other method, 412 Precondition Failed is sent
        // back.
        String method = request.getMethod();
        if ("GET".equals(method) || "HEAD".equals(method)) {
            throw new UncheckException(HttpServletResponse.SC_NOT_MODIFIED);
        } else {
            throw new UncheckException(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
    }
}

From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 *
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @param httpServletRequest Request object pertaining to the proxied HTTP request
 * @throws IOException      Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 *//*w w  w .  j  a  v a  2 s.c o  m*/
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    getCredential(httpServletRequest.getParameter("servername"));
    if (credentials != null) {
        httpClient.getParams().setAuthenticationPreemptive(true);
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    httpMethodProxyRequest.setFollowRedirects(true);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    String response = httpMethodProxyRequest.getResponseBodyAsString();

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES
            /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        if (followRedirects) {
            if (stringLocation.contains("jsessionid")) {
                Cookie cookie = new Cookie("JSESSIONID",
                        stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11));
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL");
            } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) {
                Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie");
                String[] cookieDetails = header.getValue().split(";");
                String[] nameValue = cookieDetails[0].split("=");

                Cookie cookie = new Cookie(nameValue[0], nameValue[1]);
                cookie.setPath("/");
                //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath());
                httpServletResponse.addCookie(cookie);
            }
            httpServletResponse.sendRedirect(stringLocation
                    .replace(getProxyHostAndPort(httpServletRequest) + this.getProxyPath(), stringMyHostName));
            return;
        }
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header
                header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    if (isBodyParameterGzipped(responseHeaders)) {
        debug("GZipped: true");
        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            response = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(STRING_LOCATION_HEADER, response);
        } else {
            response = new String(ungzip(httpMethodProxyRequest.getResponseBody()));
        }
        httpServletResponse.setContentLength(response.length());
    }

    // Send the content to the client
    if (intProxyResponseCode == 200)
        httpServletResponse.getWriter().write(response);
    else
        httpServletResponse.getWriter().write(intProxyResponseCode);
}

From source file:helma.servlet.AbstractServletClient.java

/**
 * Forward the request to a static file. The file must be reachable via
 * the context's protectedStatic resource base.
 *//*  ww w.j ava 2  s . c o m*/
void sendForward(HttpServletResponse res, HttpServletRequest req, ResponseTrans hopres) throws IOException {
    String forward = hopres.getForward();
    // Jetty 5.1 bails at forward paths without leading slash, so fix it
    if (!forward.startsWith("/")) {
        forward = "/" + forward;
    }
    ServletContext cx = getServletConfig().getServletContext();
    String path = cx.getRealPath(forward);
    if (path == null) {
        throw new IOException("Resource " + forward + " not found");
    }

    File file = new File(path);
    // check if the client has an up-to-date copy so we can
    // send a not-modified response
    if (checkNotModified(file, req, res)) {
        res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    int length = (int) file.length();
    res.setContentLength(length);
    res.setContentType(hopres.getContentType());

    InputStream in = cx.getResourceAsStream(forward);
    if (in == null) {
        throw new IOException("Can't read " + path);
    }
    try {
        OutputStream out = res.getOutputStream();

        int bufferSize = 4096;
        byte buffer[] = new byte[bufferSize];
        int l;

        while (length > 0) {
            if (length < bufferSize) {
                l = in.read(buffer, 0, length);
            } else {
                l = in.read(buffer, 0, bufferSize);
            }
            if (l == -1) {
                break;
            }

            length -= l;
            out.write(buffer, 0, l);
        }
    } finally {
        in.close();
    }
}

From source file:com.twinsoft.convertigo.engine.servlets.ReverseProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 * //from w w w.  ja v  a2s . c  om
 * @param httpMethodProxyRequest
 *            An object representing the proxy request to be made
 * @param httpServletResponse
 *            An object by which we can send the proxied response back to
 *            the client
 * @throws IOException
 *             Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException
 *             Can be thrown to indicate that another error has occurred
 * @throws EngineException
 */
private void doRequest(HttpMethodType httpMethodType, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    try {
        Engine.logEngine.debug("(ReverseProxyServlet) Starting request handling");

        if (Boolean.parseBoolean(EnginePropertiesManager.getProperty(PropertyName.SSL_DEBUG))) {
            System.setProperty("javax.net.debug", "all");
            Engine.logEngine.trace("(ReverseProxyServlet) Enabling SSL debug mode");
        } else {
            System.setProperty("javax.net.debug", "");
            Engine.logEngine.debug("(ReverseProxyServlet) Disabling SSL debug mode");
        }

        String baseUrl;
        String projectName;
        String connectorName;
        String contextName;
        String extraPath;

        {
            String requestURI = httpServletRequest.getRequestURI();
            Engine.logEngine.trace("(ReverseProxyServlet) Requested URI : " + requestURI);
            Matcher m = reg_fields.matcher(requestURI);
            if (m.matches() && m.groupCount() >= 5) {
                baseUrl = m.group(1);
                projectName = m.group(2);
                connectorName = m.group(3);
                contextName = m.group(4);
                extraPath = m.group(5);
            } else {
                throw new MalformedURLException(
                        "The request doesn't contains needed fields : projectName, connectorName and contextName");
            }
        }

        String sessionID = httpServletRequest.getSession().getId();

        Engine.logEngine.debug("(ReverseProxyServlet) baseUrl : " + baseUrl + " ; projectName : " + projectName
                + " ; connectorName : " + connectorName + " ; contextName : " + contextName + " ; extraPath : "
                + extraPath + " ; sessionID : " + sessionID);

        Context context = Engine.theApp.contextManager.get(null, contextName, sessionID, null, projectName,
                connectorName, null);

        Project project = Engine.theApp.databaseObjectsManager.getProjectByName(projectName);
        context.projectName = projectName;
        context.project = project;

        ProxyHttpConnector proxyHttpConnector = (ProxyHttpConnector) project.getConnectorByName(connectorName);
        context.connector = proxyHttpConnector;
        context.connectorName = proxyHttpConnector.getName();

        HostConfiguration hostConfiguration = proxyHttpConnector.hostConfiguration;

        // Proxy configuration
        String proxyServer = Engine.theApp.proxyManager.getProxyServer();
        String proxyUser = Engine.theApp.proxyManager.getProxyUser();
        String proxyPassword = Engine.theApp.proxyManager.getProxyPassword();
        int proxyPort = Engine.theApp.proxyManager.getProxyPort();

        if (!proxyServer.equals("")) {
            hostConfiguration.setProxy(proxyServer, proxyPort);
            Engine.logEngine.debug("(ReverseProxyServlet) Using proxy: " + proxyServer + ":" + proxyPort);
        } else {
            // Remove old proxy configuration
            hostConfiguration.setProxyHost(null);
        }

        String targetHost = proxyHttpConnector.getServer();
        Engine.logEngine.debug("(ReverseProxyServlet) Target host: " + targetHost);
        int targetPort = proxyHttpConnector.getPort();
        Engine.logEngine.debug("(ReverseProxyServlet) Target port: " + targetPort);

        // Configuration SSL
        Engine.logEngine.debug("(ReverseProxyServlet) Https: " + proxyHttpConnector.isHttps());
        CertificateManager certificateManager = proxyHttpConnector.certificateManager;
        boolean trustAllServerCertificates = proxyHttpConnector.isTrustAllServerCertificates();

        if (proxyHttpConnector.isHttps()) {
            Engine.logEngine.debug("(ReverseProxyServlet) Setting up SSL properties");
            certificateManager.collectStoreInformation(context);

            Engine.logEngine.debug(
                    "(ReverseProxyServlet) CertificateManager has changed: " + certificateManager.hasChanged);
            if (certificateManager.hasChanged || (!targetHost.equalsIgnoreCase(hostConfiguration.getHost()))
                    || (hostConfiguration.getPort() != targetPort)) {
                Engine.logEngine
                        .debug("(ReverseProxyServlet) Using MySSLSocketFactory for creating the SSL socket");
                Protocol myhttps = new Protocol("https",
                        MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore,
                                certificateManager.keyStorePassword, certificateManager.trustStore,
                                certificateManager.trustStorePassword, trustAllServerCertificates),
                        targetPort);

                hostConfiguration.setHost(targetHost, targetPort, myhttps);
            }

            Engine.logEngine.debug("(ReverseProxyServlet) Updated host configuration for SSL purposes");
        } else {
            hostConfiguration.setHost(targetHost, targetPort);
        }

        HttpMethod httpMethodProxyRequest;

        String targetPath = proxyHttpConnector.getBaseDir() + extraPath;

        // Handle the query string
        if (httpServletRequest.getQueryString() != null) {
            targetPath += "?" + httpServletRequest.getQueryString();
        }
        Engine.logEngine.debug("(ReverseProxyServlet) Target path: " + targetPath);

        Engine.logEngine.debug("(ReverseProxyServlet) Requested method: " + httpMethodType);

        if (httpMethodType == HttpMethodType.GET) {
            // Create a GET request
            httpMethodProxyRequest = new GetMethod();
        } else if (httpMethodType == HttpMethodType.POST) {
            // Create a standard POST request
            httpMethodProxyRequest = new PostMethod();
            ((PostMethod) httpMethodProxyRequest)
                    .setRequestEntity(new InputStreamRequestEntity(httpServletRequest.getInputStream()));
        } else {
            throw new IllegalArgumentException("Unknown HTTP method: " + httpMethodType);
        }

        String charset = httpMethodProxyRequest.getParams().getUriCharset();
        URI targetURI;
        try {
            targetURI = new URI(targetPath, true, charset);
        } catch (URIException e) {
            // Bugfix #1484
            String newTargetPath = "";
            for (String part : targetPath.split("&")) {
                if (!newTargetPath.equals("")) {
                    newTargetPath += "&";
                }
                String[] pair = part.split("=");
                try {
                    newTargetPath += URLDecoder.decode(pair[0], "UTF-8") + "="
                            + (pair.length > 1 ? URLEncoder.encode(URLDecoder.decode(pair[1], "UTF-8"), "UTF-8")
                                    : "");
                } catch (UnsupportedEncodingException ee) {
                    newTargetPath = targetPath;
                }
            }

            targetURI = new URI(newTargetPath, true, charset);
        }
        httpMethodProxyRequest.setURI(targetURI);

        // Tells the method to automatically handle authentication.
        httpMethodProxyRequest.setDoAuthentication(true);

        HttpState httpState = getHttpState(proxyHttpConnector, context);

        String basicUser = proxyHttpConnector.getAuthUser();
        String basicPassword = proxyHttpConnector.getAuthPassword();
        String givenBasicUser = proxyHttpConnector.getGivenAuthUser();
        String givenBasicPassword = proxyHttpConnector.getGivenAuthPassword();

        // Basic authentication configuration
        String realm = null;
        if (!basicUser.equals("") || (basicUser.equals("") && (givenBasicUser != null))) {
            String userName = ((givenBasicUser == null) ? basicUser : givenBasicUser);
            String userPassword = ((givenBasicPassword == null) ? basicPassword : givenBasicPassword);
            httpState.setCredentials(new AuthScope(targetHost, targetPort, realm),
                    new UsernamePasswordCredentials(userName, userPassword));
            Engine.logEngine.debug("(ReverseProxyServlet) Credentials: " + userName + ":******");
        }

        // Setting basic authentication for proxy
        if (!proxyServer.equals("") && !proxyUser.equals("")) {
            httpState.setProxyCredentials(new AuthScope(proxyServer, proxyPort),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            Engine.logEngine.debug("(ReverseProxyServlet) Proxy credentials: " + proxyUser + ":******");
        }

        // Forward the request headers
        setProxyRequestHeaders(httpServletRequest, httpMethodProxyRequest, proxyHttpConnector);

        // Use the CEMS HttpClient
        HttpClient httpClient = Engine.theApp.httpClient;
        httpMethodProxyRequest.setFollowRedirects(false);

        // Execute the request
        int intProxyResponseCode = httpClient.executeMethod(hostConfiguration, httpMethodProxyRequest,
                httpState);

        // Check if the proxy response is a redirect
        // The following code is adapted from
        // org.tigris.noodle.filters.CheckForRedirect
        // Hooray for open source software
        if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
                && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
            String stringStatusCode = Integer.toString(intProxyResponseCode);
            String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            if (stringLocation == null) {
                throw new ServletException("Received status code: " + stringStatusCode + " but no "
                        + STRING_LOCATION_HEADER + " header was found in the response");
            }
            // Modify the redirect to go to this proxy servlet rather that
            // the
            // proxied host
            String redirect = handleRedirect(stringLocation, baseUrl, proxyHttpConnector);
            httpServletResponse.sendRedirect(redirect);
            Engine.logEngine.debug("(ReverseProxyServlet) Send redirect (" + redirect + ")");
            return;
        } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
            // 304 needs special handling. See:
            // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
            // We get a 304 whenever passed an 'If-Modified-Since'
            // header and the data on disk has not changed; server
            // responds w/ a 304 saying I'm not going to send the
            // body because the file has not changed.
            httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
            httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            Engine.logEngine.debug("(ReverseProxyServlet) NOT MODIFIED (304)");
            return;
        }

        // Pass the response code back to the client
        httpServletResponse.setStatus(intProxyResponseCode);

        // Pass response headers back to the client
        Engine.logEngine.debug("(ReverseProxyServlet) Response headers back to the client:");
        Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
        for (Header header : headerArrayResponse) {
            String headerName = header.getName();
            String headerValue = header.getValue();
            if (!headerName.equalsIgnoreCase("Transfer-Encoding")
                    && !headerName.equalsIgnoreCase("Set-Cookie")) {
                httpServletResponse.setHeader(headerName, headerValue);
                Engine.logEngine.debug("   " + headerName + "=" + headerValue);
            }
        }

        String contentType = null;
        Header[] contentTypeHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Type");
        for (Header contentTypeHeader : contentTypeHeaders) {
            contentType = contentTypeHeader.getValue();
            break;
        }

        String pageCharset = "UTF-8";
        if (contentType != null) {
            int iCharset = contentType.indexOf("charset=");
            if (iCharset != -1) {
                pageCharset = contentType.substring(iCharset + "charset=".length()).trim();
            }
            Engine.logEngine.debug("(ReverseProxyServlet) Using charset: " + pageCharset);
        }

        InputStream siteIn = httpMethodProxyRequest.getResponseBodyAsStream();

        // Handle gzipped content
        Header[] contentEncodingHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Encoding");
        boolean bGZip = false, bDeflate = false;
        for (Header contentEncodingHeader : contentEncodingHeaders) {
            HeaderElement[] els = contentEncodingHeader.getElements();
            for (int j = 0; j < els.length; j++) {
                if ("gzip".equals(els[j].getName())) {
                    Engine.logBeans.debug("(ReverseProxyServlet) Decode GZip stream");
                    siteIn = new GZIPInputStream(siteIn);
                    bGZip = true;
                } else if ("deflate".equals(els[j].getName())) {
                    Engine.logBeans.debug("(ReverseProxyServlet) Decode Deflate stream");
                    siteIn = new InflaterInputStream(siteIn, new Inflater(true));
                    bDeflate = true;
                }
            }
        }

        byte[] bytesDataResult;

        ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);

        // String resourceUrl = projectName + targetPath;

        String t = context.statistics.start(EngineStatistics.APPLY_USER_REQUEST);

        try {
            // Read either from the cache, either from the remote server
            // InputStream is = proxyCacheManager.getResource(resourceUrl);
            // if (is != null) {
            // Engine.logEngine.debug("(ReverseProxyServlet) Getting data from cache");
            // siteIn = is;
            // }
            int c = siteIn.read();
            while (c > -1) {
                baos.write(c);
                c = siteIn.read();
            }
            // if (is != null) is.close();
        } finally {
            context.statistics.stop(t, true);
        }

        bytesDataResult = baos.toByteArray();
        baos.close();
        Engine.logEngine.debug("(ReverseProxyServlet) Data retrieved!");

        // if (isDynamicContent(httpServletRequest.getPathInfo(),
        // proxyHttpConnector.getDynamicContentFiles())) {
        Engine.logEngine.debug("(ReverseProxyServlet) Dynamic content");

        bytesDataResult = handleStringReplacements(baseUrl, contentType, pageCharset, proxyHttpConnector,
                bytesDataResult);

        String billingClassName = context.getConnector().getBillingClassName();
        if (billingClassName != null) {
            try {
                Engine.logContext.debug("Billing class name required: " + billingClassName);
                AbstractBiller biller = (AbstractBiller) Class.forName(billingClassName).newInstance();
                Engine.logContext.debug("Executing the biller");
                biller.insertBilling(context);
            } catch (Throwable e) {
                Engine.logContext.warn("Unable to execute the biller (the billing is thus ignored): ["
                        + e.getClass().getName() + "] " + e.getMessage());
            }
        }
        // }
        // else {
        // Engine.logEngine.debug("(ReverseProxyServlet) Static content: " +
        // contentType);
        //            
        // // Determine if the resource has already been cached or not
        // CacheEntry cacheEntry =
        // proxyCacheManager.getCacheEntry(resourceUrl);
        // if (cacheEntry instanceof FileCacheEntry) {
        // FileCacheEntry fileCacheEntry = (FileCacheEntry) cacheEntry;
        // File file = new File(fileCacheEntry.fileName);
        // if (!file.exists())
        // proxyCacheManager.removeCacheEntry(cacheEntry);
        // cacheEntry = null;
        // }
        // if (cacheEntry == null) {
        // bytesDataResult = handleStringReplacements(contentType,
        // proxyHttpConnector, bytesDataResult);
        //
        // if (intProxyResponseCode == 200) {
        // Engine.logEngine.debug("(ReverseProxyServlet) Resource stored: "
        // + resourceUrl);
        // cacheEntry = proxyCacheManager.storeResponse(resourceUrl,
        // bytesDataResult);
        // cacheEntry.contentLength = bytesDataResult.length;
        // cacheEntry.contentType = contentType;
        // Engine.logEngine.debug("(ReverseProxyServlet) Cache entry: " +
        // cacheEntry);
        // }
        // }
        // }

        // Send the content to the client
        if (Engine.logEngine.isDebugEnabled() && MimeType.Html.is(contentType)) {
            Engine.logEngine.debug("Data proxied:\n" + new String(bytesDataResult, pageCharset));
        }

        if (bGZip || bDeflate) {
            baos = new ByteArrayOutputStream();
            OutputStream compressedOutputStream = bGZip ? new GZIPOutputStream(baos)
                    : new DeflaterOutputStream(baos,
                            new Deflater(Deflater.DEFAULT_COMPRESSION | Deflater.DEFAULT_STRATEGY, true));
            compressedOutputStream.write(bytesDataResult);
            compressedOutputStream.close();
            bytesDataResult = baos.toByteArray();
            baos.close();
        }

        httpServletResponse.setContentLength(bytesDataResult.length);
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        outputStreamClientResponse.write(bytesDataResult);

        Engine.logEngine.debug("(ReverseProxyServlet) End of document retransmission");
    } catch (Exception e) {
        Engine.logEngine.error("Error while trying to proxy page", e);
        throw new ServletException("Error while trying to proxy page", e);
    }
}

From source file:ch.entwine.weblounge.common.impl.request.Http11ProtocolHandler.java

/**
 * Method generateHeaders./*from ww w  .  j a v  a  2s  .  com*/
 * 
 * @param resp
 * @param type
 */
public static void generateHeaders(HttpServletResponse resp, Http11ResponseType type) {

    /* generate headers only once! */
    if (type.headers)
        return;
    type.headers = true;

    /* adjust the statistics */
    ++stats[STATS_HEADER_GENERATED];
    incResponseStats(type.type, headerStats);

    /* set the date header */
    resp.setDateHeader(HEADER_DATE, type.time);

    /* check expires */
    if (type.expires > type.time + MS_PER_YEAR) {
        type.expires = type.time + MS_PER_YEAR;
        log.warn("Expiration date too far in the future. Adjusting.");
    }

    /* set the standard headers and status code */
    switch (type.type) {
    case RESPONSE_PARTIAL_CONTENT:
        if (type.expires > type.time)
            resp.setDateHeader(HEADER_EXPIRES, type.expires);
        if (type.modified > 0) {
            resp.setHeader(HEADER_ETAG, Http11Utils.calcETag(type.modified));
            resp.setDateHeader(HEADER_LAST_MODIFIED, type.modified);
        }
        if (type.size < 0 || type.from < 0 || type.to < 0 || type.from > type.to || type.to > type.size) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            break;
        }
        resp.setContentLength((int) type.size);
        resp.setHeader(HEADER_CONTENT_RANGE, "bytes " + type.from + "-" + type.to + "/" + type.size);
        resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        break;

    case RESPONSE_OK:
        if (type.expires > type.time) {
            resp.setDateHeader(HEADER_EXPIRES, type.expires);
        } else if (type.expires == 0) {
            resp.setHeader(HEADER_CACHE_CONTROL, "no-cache");
            resp.setHeader(HEADER_PRAGMA, "no-cache");
            resp.setDateHeader(HEADER_EXPIRES, 0);
        }
        if (type.modified > 0) {
            resp.setHeader(HEADER_ETAG, Http11Utils.calcETag(type.modified));
            resp.setDateHeader(HEADER_LAST_MODIFIED, type.modified);
        }
        if (type.size >= 0)
            resp.setContentLength((int) type.size);
        resp.setStatus(HttpServletResponse.SC_OK);
        break;

    case RESPONSE_NOT_MODIFIED:
        if (type.expires > type.time)
            resp.setDateHeader(HEADER_EXPIRES, type.expires);
        if (type.modified > 0)
            resp.setHeader(HEADER_ETAG, Http11Utils.calcETag(type.modified));
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        break;

    case RESPONSE_METHOD_NOT_ALLOWED:
        resp.setHeader(HEADER_ALLOW, "GET, POST, HEAD");
        resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        break;

    case RESPONSE_PRECONDITION_FAILED:
        if (type.expires > type.time)
            resp.setDateHeader(HEADER_EXPIRES, type.expires);
        if (type.modified > 0) {
            resp.setHeader(HEADER_ETAG, Http11Utils.calcETag(type.modified));
            resp.setDateHeader(HEADER_LAST_MODIFIED, type.modified);
        }
        resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
        break;

    case RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE:
        if (type.expires > type.time)
            resp.setDateHeader(HEADER_EXPIRES, type.expires);
        if (type.modified > 0) {
            resp.setHeader(HEADER_ETAG, Http11Utils.calcETag(type.modified));
            resp.setDateHeader(HEADER_LAST_MODIFIED, type.modified);
        }
        if (type.size >= 0)
            resp.setHeader(HEADER_CONTENT_RANGE, "*/" + type.size);
        break;

    case RESPONSE_INTERNAL_SERVER_ERROR:
    default:
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.nuxeo.ecm.core.opencmis.impl.NuxeoSessionTestCase.java

@Test
public void testContentStream() throws Exception {
    Document file = (Document) session.getObjectByPath("/testfolder1/testfile1");

    // check ETag header
    if (isAtomPub || isBrowser) {
        RepositoryInfo ri = session.getRepositoryInfo();
        String uri = ri.getThinClientUri() + ri.getId() + "/";
        uri += isAtomPub ? "content?id=" : "root?objectId=";
        uri += file.getId();/*from  w  w  w. j a v  a  2s  .  c o m*/
        String eTag = file.getPropertyValue("nuxeo:contentStreamDigest");
        String encoding = Base64.encodeBytes(new String(USERNAME + ":" + PASSWORD).getBytes());
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(uri);
        request.setHeader("Authorization", "Basic " + encoding);
        request.setHeader("If-None-Match", eTag);
        try {
            HttpResponse response = client.execute(request);
            assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatusLine().getStatusCode());
        } finally {
            client.getConnectionManager().shutdown();
        }
    }

    // get stream
    ContentStream cs = file.getContentStream();
    assertNotNull(cs);
    assertEquals("text/plain", cs.getMimeType());
    assertEquals("testfile.txt", cs.getFileName());
    if (!(isAtomPub || isBrowser)) {
        // TODO fix AtomPub/Browser case where the length is unknown (streaming)
        assertEquals(Helper.FILE1_CONTENT.length(), cs.getLength());
    }
    assertEquals(Helper.FILE1_CONTENT, Helper.read(cs.getStream(), "UTF-8"));

    // set stream
    // TODO convenience constructors for ContentStreamImpl
    byte[] streamBytes = STREAM_CONTENT.getBytes("UTF-8");
    ByteArrayInputStream stream = new ByteArrayInputStream(streamBytes);
    cs = new ContentStreamImpl("foo.txt", BigInteger.valueOf(streamBytes.length), "text/plain; charset=UTF-8",
            stream);
    file.setContentStream(cs, true);

    // refetch stream
    file = (Document) session.getObject(file);
    cs = file.getContentStream();
    assertNotNull(cs);
    // AtomPub lowercases charset -> TODO proper mime type comparison
    String mimeType = cs.getMimeType().toLowerCase().replace(" ", "");
    assertEquals("text/plain;charset=utf-8", mimeType);
    // TODO fix AtomPub case where the filename is null
    assertEquals("foo.txt", cs.getFileName());
    if (!(isAtomPub || isBrowser)) {
        // TODO fix AtomPub/Browser case where the length is unknown (streaming)
        assertEquals(streamBytes.length, cs.getLength());
    }
    assertEquals(STREAM_CONTENT, Helper.read(cs.getStream(), "UTF-8"));

    // delete
    file.deleteContentStream();
    file.refresh();
    assertEquals(null, file.getContentStream());
}

From source file:com.vectorcast.plugins.vectorcastexecution.job.NewSingleJob.java

/**
 * Create project//  w w  w  .  j a  v a 2  s  .  c  o m
 * @return project
 * @throws IOException exception
 * @throws JobAlreadyExistsException exception
 */
@Override
protected Project createProject() throws IOException, JobAlreadyExistsException {
    if (getBaseName().isEmpty()) {
        getResponse().sendError(HttpServletResponse.SC_NOT_MODIFIED, "No project name specified");
        return null;
    }
    projectName = getBaseName() + ".vcast.single";
    if (getJobName() != null && !getJobName().isEmpty()) {
        projectName = getJobName();
    }
    if (getInstance().getJobNames().contains(projectName)) {
        throw new JobAlreadyExistsException(projectName);
    }
    Project project = getInstance().createProject(FreeStyleProject.class, projectName);
    if (getNodeLabel() != null && !getNodeLabel().isEmpty()) {
        Label label = new LabelAtom(getNodeLabel());
        project.setAssignedLabel(label);
    }
    return project;
}

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

/**
 * If the request addresses a resource which may be served by the
 * <code>getResource</code> method of the
 * {@link #getResourceProvider() resource provider}, this method serves it
 * and returns <code>true</code>. Otherwise <code>false</code> is returned.
 * <code>false</code> is also returned if the resource provider has no
 * <code>getResource</code> method.
 * <p>//  www  .  ja va  2 s  .  co  m
 * If <code>true</code> is returned, the request is considered complete and
 * request processing terminates. Otherwise request processing continues
 * with normal plugin rendering.
 *
 * @param request The request object
 * @param response The response object
 * @return <code>true</code> if the request causes a resource to be sent back.
 *
 * @throws IOException If an error occurs accessing or spooling the resource.
 */
private final boolean spoolResource(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    // no resource if no resource accessor
    Method getResourceMethod = getGetResourceMethod();
    if (getResourceMethod == null) {
        return false;
    }

    String pi = request.getPathInfo();
    InputStream ins = null;
    try {

        // check for a resource, fail if none
        URL url = (URL) getResourceMethod.invoke(getResourceProvider(), new Object[] { pi });
        if (url == null) {
            return false;
        }

        // open the connection and the stream (we use the stream to be able
        // to at least hint to close the connection because there is no
        // method to explicitly close the conneciton, unfortunately)
        URLConnection connection = url.openConnection();
        ins = connection.getInputStream();

        // FELIX-2017 Equinox may return an URL for a non-existing
        // resource but then (instead of throwing) return null on
        // getInputStream. We should account for this situation and
        // just assume a non-existing resource in this case.
        if (ins == null) {
            return false;
        }

        // check whether we may return 304/UNMODIFIED
        long lastModified = connection.getLastModified();
        if (lastModified > 0) {
            long ifModifiedSince = request.getDateHeader("If-Modified-Since");
            if (ifModifiedSince >= (lastModified / 1000 * 1000)) {
                // Round down to the nearest second for a proper compare
                // A ifModifiedSince of -1 will always be less
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

                return true;
            }

            // have to send, so set the last modified header now
            response.setDateHeader("Last-Modified", lastModified);
        }

        // describe the contents
        response.setContentType(getServletContext().getMimeType(pi));
        response.setIntHeader("Content-Length", connection.getContentLength());

        // spool the actual contents
        OutputStream out = response.getOutputStream();
        byte[] buf = new byte[2048];
        int rd;
        while ((rd = ins.read(buf)) >= 0) {
            out.write(buf, 0, rd);
        }

        // over and out ...
        return true;
    } catch (IllegalAccessException iae) {
        // log or throw ???
    } catch (InvocationTargetException ite) {
        // log or throw ???
        // Throwable cause = ite.getTargetException();
    } finally {
        IOUtils.closeQuietly(ins);
    }

    return false;
}

From source file:org.ireland.jnetty.webapp.ErrorPageManager.java

/**
 * Sends an HTTP error to the browser.//from  w  ww.java2  s. c o m
 * 
 * @param code
 *            the HTTP error code
 * @param message
 *            a string message
 */
public void sendErrorImpl(CauchoRequest request, CauchoResponse response, int code, String message)
        throws IOException {
    response.resetBuffer();

    /* XXX: if we've already got an error, won't this just mask it?
    if (responseStream.isCommitted())
      throw new IllegalStateException("response can't sendError() after commit");
    */

    response.setStatus(code, message);

    try {
        if (handleErrorStatus(request, response, code, message)
                || code == HttpServletResponse.SC_NOT_MODIFIED) {
            return;
        }

        response.setContentType("text/html; charset=utf-8");
        boolean isOutputStreamWrapper = false;
        PrintWriter out;

        try {
            out = response.getWriter();
        } catch (IllegalStateException e) {
            log.debug(e.toString(), e);

            out = Vfs.openWrite(response.getOutputStream()).getPrintWriter();
            isOutputStreamWrapper = true;
        }

        out.println("<html>");
        if (!response.isCommitted()) {
            out.print("<head><title>");
            out.print(code);
            out.print(" ");
            out.print(escapeHtml(message));
            out.println("</title></head>");
        }

        out.println("<body>");
        out.print("<h1>");
        out.print(code);
        out.print(" ");
        out.print(escapeHtml(message));
        out.println("</h1>");

        if (code == HttpServletResponse.SC_NOT_FOUND) {
            out.println(escapeHtml(request.getPageURI()) + " was not found on this server.");
        }

        printVersion(out);

        out.println("</body></html>");

        String userAgent = request.getHeader("User-Agent");

        if (userAgent != null && userAgent.indexOf("MSIE") >= 0) {
            out.write(MSIE_PADDING, 0, MSIE_PADDING.length);
        }

        if (isOutputStreamWrapper) {
            out.flush();
            out.close();
        }
    } catch (Exception e) {
        log.warn(e.toString(), e);
    }
}