Example usage for javax.servlet.http HttpServletResponse setIntHeader

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

Introduction

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

Prototype

public void setIntHeader(String name, int value);

Source Link

Document

Sets a response header with the given name and integer value.

Usage

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>//from w ww .  j  a v a2s.com
 * 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.apache.click.ClickServlet.java

/**
 * Set the HTTP headers in the servlet response. The Page response headers
 * are defined in {@link Page#getHeaders()}.
 *
 * @param response the response to set the headers in
 * @param headers the map of HTTP headers to set in the response
 *///from   w w  w. j  a  v a 2 s  . com
protected void setPageResponseHeaders(HttpServletResponse response, Map<String, Object> headers) {

    for (Map.Entry<String, Object> entry : headers.entrySet()) {
        String name = entry.getKey();
        Object value = entry.getValue();

        if (value instanceof String) {
            String strValue = (String) value;
            if (!strValue.equalsIgnoreCase("Content-Encoding")) {
                response.setHeader(name, strValue);
            }

        } else if (value instanceof Date) {
            long time = ((Date) value).getTime();
            response.setDateHeader(name, time);

        } else if (value instanceof Integer) {
            int intValue = (Integer) value;
            response.setIntHeader(name, intValue);

        } else if (value != null) {
            throw new IllegalStateException("Invalid Page header value type: " + value.getClass()
                    + ". Header value must of type String, Date or Integer.");
        }
    }
}

From source file:com.google.acre.servlet.ProxyPassServlet.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
 * @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 av  a  2s.  c o m
private void executeProxyRequest(HttpRequestBase httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(AllClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    String proxy_host = Configuration.Values.HTTP_PROXY_HOST.getValue();
    int proxy_port = -1;
    if (!(proxy_host.length() == 0)) {
        proxy_port = Configuration.Values.HTTP_PROXY_PORT.getInteger();
        HttpHost proxy = new HttpHost(proxy_host, proxy_port, "http");
        client.getParams().setParameter(AllClientPNames.DEFAULT_PROXY, proxy);
    }

    // Execute the request
    HttpResponse res = client.execute(httpMethodProxyRequest);
    int rescode = res.getStatusLine().getStatusCode();

    // Pass response headers back to the client
    Header[] headerArrayResponse = res.getAllHeaders();
    for (Header header : headerArrayResponse) {
        httpServletResponse.addHeader(header.getName(), header.getValue());
    }

    // 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 (rescode >= 300 && rescode < 304) {
        String stringStatusCode = Integer.toString(rescode);
        String stringLocation = httpMethodProxyRequest.getFirstHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Recieved 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();
        httpServletResponse.sendRedirect(
                stringLocation.replace(this.metawebAPIHostAndPort + this.metawebAPIPath, stringMyHostName));
        return;
    } else if (rescode == 304) {
        // 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(304);
        return;
    }

    httpServletResponse.setStatus(rescode);

    InputStream instream = new BufferedInputStream(res.getEntity().getContent());
    OutputStream outstream = httpServletResponse.getOutputStream();
    IOUtils.copy(instream, outstream);
    instream.close();
}

From source file:org.jboss.orion.openshift.server.proxy.JsonProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link javax.servlet.http.HttpServletResponse}
 *
 * @param proxyDetails/*  ww w .j av  a2  s  .  com*/
 * @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 java.io.IOException            Can be thrown by the {@link HttpClient}.executeMethod
 * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, ServletException {
    httpMethodProxyRequest.setDoAuthentication(false);
    httpMethodProxyRequest.setFollowRedirects(false);

    // Create a default HttpClient
    HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest);

    // Execute the request
    int intProxyResponseCode = 500;
    try {
        intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // 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();
        httpServletResponse.sendRedirect(stringLocation
                .replace(proxyDetails.getProxyHostAndPort() + proxyDetails.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 (!ProxySupport.isHopByHopHeader(header.getName())) {
            if (ProxySupport.isSetCookieHeader(header)) {
                HttpProxyRule proxyRule = proxyDetails.getProxyRule();
                String setCookie = ProxySupport.replaceCookieAttributes(header.getValue(),
                        proxyRule.getCookiePath(), proxyRule.getCookieDomain());
                httpServletResponse.setHeader(header.getName(), setCookie);
            } else {
                httpServletResponse.setHeader(header.getName(), header.getValue());
            }
        }
    }

    // check if we got data, that is either the Content-Length > 0
    // or the response code != 204
    int code = httpMethodProxyRequest.getStatusCode();
    boolean noData = code == HttpStatus.SC_NO_CONTENT;
    if (!noData) {
        String length = httpServletRequest.getHeader(STRING_CONTENT_LENGTH_HEADER_NAME);
        if (length != null && "0".equals(length.trim())) {
            noData = true;
        }
    }

    if (!noData) {
        // Send the content to the client
        InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        int intNextByte;
        while ((intNextByte = bufferedInputStream.read()) != -1) {
            outputStreamClientResponse.write(intNextByte);
        }
    }
}

From source file:it.geosdi.era.server.servlet.HTTPProxy.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 digest //from  w  w w.ja v  a  2 s  . c  om
 * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, String user, String password)
        throws IOException, ServletException {
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();

    if (user != null && password != null) {
        UsernamePasswordCredentials upc = new UsernamePasswordCredentials(user, password);
        httpClient.getState().setCredentials(AuthScope.ANY, upc);
    }

    httpMethodProxyRequest.setFollowRedirects(false);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);

    // 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("Recieved 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();
        httpServletResponse.sendRedirect(
                stringLocation.replace(getProxyHostAndPort() + 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) {
        // Skip GZIP Responses
        if (header.getName().equalsIgnoreCase(HTTP_HEADER_ACCEPT_ENCODING)
                && header.getValue().toLowerCase().contains("gzip"))
            continue;
        else if (header.getName().equalsIgnoreCase(HTTP_HEADER_CONTENT_ENCODING)
                && header.getValue().toLowerCase().contains("gzip"))
            continue;
        else if (header.getName().equalsIgnoreCase(HTTP_HEADER_TRANSFER_ENCODING))
            continue;
        else
            httpServletResponse.setHeader(header.getName(), header.getValue());
    }

    // Send the content to the client
    InputStream inputStreamServerResponse = httpMethodProxyRequest.getResponseBodyAsStream();
    OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();

    int read;
    while ((read = inputStreamServerResponse.read()) > 0) {
        if (escapeHtmlFull(read) > 0) {
            outputStreamClientResponse.write(read);
        }
    }

    inputStreamServerResponse.close();

    outputStreamClientResponse.write('\n');
    outputStreamClientResponse.flush();
    outputStreamClientResponse.close();
}

From source file:org.codeartisans.proxilet.Proxilet.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  .  j a  va 2s.  c o m
 *
 * @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
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    // Create a default HttpClient
    HttpClient httpClient;
    httpClient = createClientWithLogin();
    httpMethodProxyRequest.setFollowRedirects(false);

    // 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(HEADER_LOCATION).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + HEADER_LOCATION + " 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) {
            httpServletResponse
                    .sendRedirect(stringLocation.replace(getProxyHostAndPort() + proxyPath, 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(HEADER_CONTENT_LENGTH, 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")) {
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

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

    // FIXME We should handle both String and bytes response in the same way:
    String response = null;
    byte[] bodyBytes = null;

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

    if (httpServletResponse.getContentType() != null && httpServletResponse.getContentType().contains("text")) {
        LOGGER.trace("Received status code: {} Response: {}", intProxyResponseCode, response);
    } else {
        LOGGER.trace("Received status code: {} [Response is not textual]", intProxyResponseCode);
    }

    // Send the content to the client
    if (response != null) {
        httpServletResponse.getWriter().write(response);
    } else if (bodyBytes != null) {
        httpServletResponse.getOutputStream().write(bodyBytes);
    } else {
        IOUtils.copy(httpMethodProxyRequest.getResponseBodyAsStream(), httpServletResponse.getOutputStream());
    }
}

From source file:com.metaparadigm.jsonrpc.JSONRPCServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ClassCastException {
    // Find the JSONRPCBridge for this session or create one
    // if it doesn't exist
    HttpSession session = request.getSession();
    JSONRPCBridge json_bridge = null;/* w w w.  j a  va  2 s .  com*/
    json_bridge = (JSONRPCBridge) session.getAttribute("JSONRPCBridge");
    if (json_bridge == null) {
        // Only create a new bridge if not disabled in config
        if (!auto_session_bridge) {
            // Use the global bridge only, and don't set on session.
            json_bridge = JSONRPCBridge.getGlobalBridge();
            if (json_bridge.isDebug())
                log.info("Using global bridge.");
        } else {
            json_bridge = new JSONRPCBridge();
            session.setAttribute("JSONRPCBridge", json_bridge);
            if (json_bridge.isDebug())
                log.info("Created a bridge for this session.");
        }
    }

    // Encode using UTF-8, although We are actually ASCII clean as
    // all unicode data is JSON escaped using backslash u. This is
    // less data efficient for foreign character sets but it is
    // needed to support naughty browsers such as Konqueror and Safari
    // which do not honour the charset set in the response
    response.setContentType("text/plain;charset=utf-8");
    OutputStream out = response.getOutputStream();

    // Decode using the charset in the request if it exists otherwise
    // use UTF-8 as this is what all browser implementations use.
    // The JSON-RPC-Java JavaScript client is ASCII clean so it
    // although here we can correctly handle data from other clients
    // that do not escape non ASCII data
    String charset = request.getCharacterEncoding();
    if (charset == null)
        charset = "UTF-8";
    BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset));

    // Read the request
    CharArrayWriter data = new CharArrayWriter();
    char buf[] = new char[buf_size];
    int ret;
    while ((ret = in.read(buf, 0, buf_size)) != -1)
        data.write(buf, 0, ret);
    if (json_bridge.isDebug())
        log.fine("recieve: " + data.toString());

    // Process the request
    JSONObject json_req = null;
    JSONRPCResult json_res = null;
    try {
        json_req = new JSONObject(data.toString());
        json_res = json_bridge.call(new Object[] { request }, json_req);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Write the response
    if (json_bridge.isDebug())
        log.fine("send: " + json_res.toString());
    byte[] bout = json_res.toString().getBytes("UTF-8");
    if (keepalive) {
        response.setIntHeader("Content-Length", bout.length);
    }

    out.write(bout);
    out.flush();
    out.close();
}

From source file:cn.knet.showcase.demos.servletproxy.ProxyServlet.java

protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    //initialize request attributes from caches if unset by a subclass by this point
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }// w  ww . j a  v a 2 s .  c om
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // 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 of these two headers signal that there is a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        proxyRequest = newProxyRequestWithEntity(method, proxyRequestUri, servletRequest);
    } else {
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }

    copyRequestHeaders(servletRequest, proxyRequest);

    setXForwardedForHeader(servletRequest, proxyRequest);

    HttpResponse proxyResponse = null;
    try {
        // Execute the request

        //Fallback on using older client:

        proxyResponse = proxyClient.execute(getTargetHost(servletRequest), proxyRequest);

        // Process the response:

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

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

        if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
            // 304 needs special handling.  See:
            // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
            // Don't send body entity/content!
            servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
        } else {
            // Send the content to the client
            copyResponseEntity(proxyResponse, servletResponse);
        }

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

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

From source file:com.fuseim.webapp.ProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    //initialize request attributes from caches if unset by a subclass by this point
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }/*from www  .j  a  v  a 2 s  .com*/
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // 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;
    proxyRequest = initProxyRequest(servletRequest, method, proxyRequestUri);
    copyRequestHeaders(servletRequest, proxyRequest);

    setXForwardedForHeader(servletRequest, proxyRequest);

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

        proxyResponse = proxyClient.execute(getTargetHost(servletRequest), proxyRequest);

        // Process the response:

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

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

        if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
            // 304 needs special handling.  See:
            // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
            // Don't send body entity/content!
            servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
        } else {
            // Send the content to the client
            copyResponseEntity(proxyResponse, servletResponse, proxyRequest, servletRequest);
        }

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

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

From source file:org.madsonic.controller.StreamController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

    TransferStatus status = null;/*  w ww.  ja  v a 2s  . c om*/
    PlayQueueInputStream in = null;
    Player player = playerService.getPlayer(request, response, false, true);
    User user = securityService.getUserByName(player.getUsername());

    try {

        if (!user.isStreamRole()) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "Streaming is forbidden for user " + user.getUsername());
            return null;
        }

        // If "playlist" request parameter is set, this is a Podcast request. In that case, create a separate
        // play queue (in order to support multiple parallel Podcast streams).
        Integer playlistId = ServletRequestUtils.getIntParameter(request, "playlist");
        boolean isPodcast = playlistId != null;
        if (isPodcast) {
            PlayQueue playQueue = new PlayQueue();
            playQueue.addFiles(false, playlistService.getFilesInPlaylist(playlistId));
            player.setPlayQueue(playQueue);
            Util.setContentLength(response, playQueue.length());
            LOG.info("Incoming Podcast request for playlist " + playlistId);
        }

        response.addHeader("Access-Control-Allow-Origin", "*");

        String contentType = StringUtil.getMimeType(request.getParameter("suffix"));

        //            if (player.isWeb()) {
        //               contentType = StringUtil.getMimeType("mp3");
        //            }

        response.setContentType(contentType);

        String preferredTargetFormat = request.getParameter("format");
        Integer maxBitRate = ServletRequestUtils.getIntParameter(request, "maxBitRate");
        if (Integer.valueOf(0).equals(maxBitRate)) {
            maxBitRate = null;
        }

        VideoTranscodingSettings videoTranscodingSettings = null;

        // Is this a request for a single file (typically from the embedded Flash player)?
        // In that case, create a separate playlist (in order to support multiple parallel streams).
        // Also, enable partial download (HTTP byte range).
        MediaFile file = getSingleFile(request);
        boolean isSingleFile = file != null;
        HttpRange range = null;

        if (isSingleFile) {
            PlayQueue playQueue = new PlayQueue();
            playQueue.addFiles(true, file);
            player.setPlayQueue(playQueue);

            if (!file.isVideo()) {
                response.setIntHeader("ETag", file.getId());
                response.setHeader("Accept-Ranges", "bytes");
            }

            TranscodingService.Parameters parameters = transcodingService.getParameters(file, player,
                    maxBitRate, preferredTargetFormat, null, false);
            long fileLength = getFileLength(parameters);
            boolean isConversion = parameters.isDownsample() || parameters.isTranscode();
            boolean estimateContentLength = ServletRequestUtils.getBooleanParameter(request,
                    "estimateContentLength", false);
            boolean isHls = ServletRequestUtils.getBooleanParameter(request, "hls", false);

            range = getRange(request, file);
            if (range != null) {
                LOG.info("Got HTTP range: " + range);
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                Util.setContentLength(response,
                        range.isClosed() ? range.size() : fileLength - range.getFirstBytePos());
                long lastBytePos = range.getLastBytePos() != null ? range.getLastBytePos() : fileLength - 1;
                response.setHeader("Content-Range",
                        "bytes " + range.getFirstBytePos() + "-" + lastBytePos + "/" + fileLength);
            } else if (!isHls && (!isConversion || estimateContentLength)) {
                Util.setContentLength(response, fileLength);
            }

            if (isHls) {
                response.setContentType(StringUtil.getMimeType("ts")); // HLS is always MPEG TS.
            } else {

                String transcodedSuffix = transcodingService.getSuffix(player, file, preferredTargetFormat);

                //                    if (player.isWeb()) {
                //                       transcodedSuffix = "mp3";
                //                    }
                response.setContentType(StringUtil.getMimeType(transcodedSuffix));
                setContentDuration(response, file);
            }

            if (file.isVideo() || isHls) {
                videoTranscodingSettings = createVideoTranscodingSettings(file, request);
            }
        }

        if (request.getMethod().equals("HEAD")) {
            return null;
        }

        // Terminate any other streams to this player.
        if (!isPodcast && !isSingleFile) {
            for (TransferStatus streamStatus : statusService.getStreamStatusesForPlayer(player)) {
                if (streamStatus.isActive()) {
                    streamStatus.terminate();
                }
            }
        }

        status = statusService.createStreamStatus(player);

        in = new PlayQueueInputStream(player, status, maxBitRate, preferredTargetFormat,
                videoTranscodingSettings, transcodingService, audioScrobblerService, mediaFileService,
                searchService);
        OutputStream out = RangeOutputStream.wrap(response.getOutputStream(), range);

        // Enabled SHOUTcast, if requested.
        boolean isShoutCastRequested = "1".equals(request.getHeader("icy-metadata"));
        if (isShoutCastRequested && !isSingleFile) {
            response.setHeader("icy-metaint", "" + ShoutCastOutputStream.META_DATA_INTERVAL);
            response.setHeader("icy-notice1", "This stream is served using Madsonic");
            response.setHeader("icy-notice2", "Madsonic - Free media streamer - madsonic.org");
            response.setHeader("icy-name", "Madsonic");
            response.setHeader("icy-genre", "Mixed");
            response.setHeader("icy-url", "http://madsonic.org/");
            out = new ShoutCastOutputStream(out, player.getPlayQueue(), settingsService);
        }

        final int BUFFER_SIZE = 2048;
        byte[] buf = new byte[BUFFER_SIZE];

        while (true) {

            // Check if stream has been terminated.
            if (status.terminated()) {
                return null;
            }

            if (player.getPlayQueue().getStatus() == PlayQueue.Status.STOPPED) {
                if (isPodcast || isSingleFile) {
                    break;
                } else {
                    sendDummy(buf, out);
                }
            } else {

                int n = in.read(buf);
                if (n == -1) {
                    if (isPodcast || isSingleFile) {
                        break;
                    } else {
                        sendDummy(buf, out);
                    }
                } else {
                    out.write(buf, 0, n);
                }
            }
        }

    } finally {
        if (status != null) {
            securityService.updateUserByteCounts(user, status.getBytesTransfered(), 0L, 0L);
            statusService.removeStreamStatus(status);
        }
        IOUtils.closeQuietly(in);
    }
    return null;
}