Example usage for org.apache.commons.httpclient HttpMethodBase getResponseCharSet

List of usage examples for org.apache.commons.httpclient HttpMethodBase getResponseCharSet

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethodBase getResponseCharSet.

Prototype

public String getResponseCharSet() 

Source Link

Document

Returns the character encoding of the response from the Content-Type header.

Usage

From source file:com.snaker.DownloadManager.java

private Runnable createRunnable(final Downloader d) {
    final Task task = d.getTask();
    return new Runnable() {
        @Override/*from   w ww  .  ja  va  2  s.  co m*/
        public void run() {
            logger.info("start download:" + d.getUrl());
            HttpClient client = clients.get(task.getId());
            DownloadHandler handler = d.getHandler();
            HttpMethodBase m = null;
            d.setStatus(Status.STARTED);
            d.setStartTime(System.currentTimeMillis());
            try {
                String url = d.getUrl();
                if (d.isGet()) {
                    GetMethod get = new GetMethod(url);
                    m = get;
                } else {
                    final String requestCharset = d.getRequestCharset();
                    PostMethod post = new PostMethod(url) {
                        public String getRequestCharSet() {
                            if (requestCharset != null)
                                return requestCharset;
                            else
                                return super.getRequestCharSet();
                        }

                        public boolean getFollowRedirects() {
                            return d.isFollowRedirects();
                        }
                    };
                    if (requestCharset != null) {
                        post.setRequestHeader("ContentType",
                                "application/x-www-form-urlencoded;charset=" + requestCharset);
                    }
                    DownloadParams parms = d.getParms();
                    if (parms != null)
                        post.setRequestBody(parms.toNVP());
                    m = post;
                }
                { // set the headers
                    m.setRequestHeader("User-Agent",
                            "Mozilla/5.0 (Windows NT 5.1; rv:8.0.1) Gecko/20100101 Firefox/8.0.1");
                    m.setRequestHeader("Accept",
                            "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                    m.setRequestHeader("Accept-Language", "en-us,zh-cn;q=0.5");
                    m.setRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                    m.setRequestHeader("Referer", url);
                }
                client.executeMethod(m);
                //check status
                int sc = m.getStatusCode();
                d.setStatusCode(sc);

                if (isBadStatusCode(sc)) {
                    logger.error("download failed,url:" + d.getUrl() + ",Status Code:" + sc);
                    d.setStatus(Status.FAILED);
                    d.setDescription(m.getStatusText());
                    return;
                } else if (sc == 404 || sc == 410) {
                    d.setStatus(Status.FINISHED);
                    d.setDescription("NOT FOUND");
                    return;
                }

                long size = m.getResponseContentLength();
                d.setFileSize(size);

                // get File Name
                if (d.getFileName() == null) {
                    Header h = m.getResponseHeader("Content-Disposition");
                    String fileName = null;
                    if (h != null) {
                        String f = h.getValue();
                        int tag = f.indexOf("filename=");
                        if (tag != -1 && tag != f.length() - 1)
                            fileName = f.substring(tag + 1);
                    }

                    if (fileName == null || fileName.length() == 0) {
                        int tag1 = url.lastIndexOf("/");
                        int tag2 = url.lastIndexOf("?");
                        if (tag1 != -1 && tag1 != url.length() - 1) {
                            if (tag2 > tag1) {
                                fileName = url.substring(tag1 + 1, tag2);
                            } else {
                                fileName = url.substring(tag1 + 1);
                            }
                        }
                    }
                    d.setFileName(fileName);
                }

                // set the all headers
                Header[] headers = m.getResponseHeaders();
                if (headers != null) {
                    for (Header header : headers) {
                        d.addResponseHeader(header.getName(), header.getValue());
                    }
                }
                d.setStatus(Status.RUNNING);
                // recv the body
                if (handler == null) {
                    byte[] content = m.getResponseBody();
                    int len = content.length;
                    d.setFileSize(len);
                    d.setReceived(len);
                    d.setResponseCharset(m.getResponseCharSet());
                    d.setResponseBody(content);
                } else {
                    InputStream is = m.getResponseBodyAsStream();
                    handler.start(d);
                    byte[] buffer = new byte[102400];
                    long count = 0;
                    while (true) {
                        int r = is.read(buffer);
                        if (r > 0) {
                            count += r;
                            d.setReceived(count);
                            handler.handle(buffer, r);
                        } else {
                            break;
                        }
                    }
                    is.close();
                }
                d.setStatus(Status.FINISHED);
            } catch (Exception e) {
                logger.error("download failed,url:" + d.getUrl(), e);
                d.setStatus(Status.FAILED);
                d.setDescription(e.getMessage());
            } finally {
                m.releaseConnection();
                if (handler != null) {
                    handler.stop();
                }
                downloadings.remove(d);
                d.setEndTime(System.currentTimeMillis());
                while (downloaded.size() >= maxDownloadedCount) {
                    downloaded.poll();
                }
                downloaded.offer(d);
                task.downloadFininshed(d);
            }
        }
    };
}

From source file:org.alfresco.repo.remoteconnector.RemoteConnectorServiceImpl.java

/**
 * Executes the specified request, and return the response
 *//*from  w w w  .j  av  a 2 s .  c  o m*/
public RemoteConnectorResponse executeRequest(RemoteConnectorRequest request) throws IOException,
        AuthenticationException, RemoteConnectorClientException, RemoteConnectorServerException {
    RemoteConnectorRequestImpl reqImpl = (RemoteConnectorRequestImpl) request;
    HttpMethodBase httpRequest = reqImpl.getMethodInstance();

    // Attach the headers to the request
    for (Header hdr : request.getRequestHeaders()) {
        httpRequest.addRequestHeader(hdr);
    }

    // Attach the body, if possible
    if (httpRequest instanceof EntityEnclosingMethod) {
        if (request.getRequestBody() != null) {
            ((EntityEnclosingMethod) httpRequest).setRequestEntity(reqImpl.getRequestBody());
        }
    }

    // Grab our thread local HttpClient instance
    // Remember - we must then clean it up!
    HttpClient httpClient = HttpClientHelper.getHttpClient();

    // The url should already be vetted by the RemoteConnectorRequest
    URL url = new URL(request.getURL());

    // Use the appropriate Proxy Host if required
    if (httpProxyHost != null && url.getProtocol().equals("http") && requiresProxy(url.getHost())) {
        httpClient.getHostConfiguration().setProxyHost(httpProxyHost);
        if (logger.isDebugEnabled())
            logger.debug(" - using HTTP proxy host for: " + url);
        if (httpProxyCredentials != null) {
            httpClient.getState().setProxyCredentials(httpAuthScope, httpProxyCredentials);
            if (logger.isDebugEnabled())
                logger.debug(" - using HTTP proxy credentials for proxy: " + httpProxyHost.getHostName());
        }
    } else if (httpsProxyHost != null && url.getProtocol().equals("https") && requiresProxy(url.getHost())) {
        httpClient.getHostConfiguration().setProxyHost(httpsProxyHost);
        if (logger.isDebugEnabled())
            logger.debug(" - using HTTPS proxy host for: " + url);
        if (httpsProxyCredentials != null) {
            httpClient.getState().setProxyCredentials(httpsAuthScope, httpsProxyCredentials);
            if (logger.isDebugEnabled())
                logger.debug(" - using HTTPS proxy credentials for proxy: " + httpsProxyHost.getHostName());
        }
    } else {
        //host should not be proxied remove any configured proxies
        httpClient.getHostConfiguration().setProxyHost(null);
        httpClient.getState().clearProxyCredentials();
    }

    // Log what we're doing
    if (logger.isDebugEnabled()) {
        logger.debug("Performing " + request.getMethod() + " request to " + request.getURL());
        for (Header hdr : request.getRequestHeaders()) {
            logger.debug("Header: " + hdr);
        }
        Object requestBody = null;
        if (request != null) {
            requestBody = request.getRequestBody();
        }
        if (requestBody != null && requestBody instanceof StringRequestEntity) {
            StringRequestEntity re = (StringRequestEntity) request.getRequestBody();
            logger.debug("Payload (string): " + re.getContent());
        } else if (requestBody != null && requestBody instanceof ByteArrayRequestEntity) {
            ByteArrayRequestEntity re = (ByteArrayRequestEntity) request.getRequestBody();
            logger.debug("Payload (byte array): " + re.getContent().toString());
        } else {
            logger.debug("Payload is not of a readable type.");
        }
    }

    // Perform the request, and wrap the response
    int status = -1;
    String statusText = null;
    RemoteConnectorResponse response = null;
    try {
        status = httpClient.executeMethod(httpRequest);
        statusText = httpRequest.getStatusText();

        Header[] responseHdrs = httpRequest.getResponseHeaders();
        Header responseContentTypeH = httpRequest
                .getResponseHeader(RemoteConnectorRequestImpl.HEADER_CONTENT_TYPE);
        String responseCharSet = httpRequest.getResponseCharSet();
        String responseContentType = (responseContentTypeH != null ? responseContentTypeH.getValue() : null);

        if (logger.isDebugEnabled()) {
            logger.debug(
                    "response url=" + request.getURL() + ", length =" + httpRequest.getResponseContentLength()
                            + ", responceContentType " + responseContentType + ", statusText =" + statusText);
        }

        // Decide on how best to handle the response, based on the size
        // Ideally, we want to close the HttpClient resources immediately, but
        //  that isn't possible for very large responses
        // If we can close immediately, it makes cleanup simpler and fool-proof
        if (httpRequest.getResponseContentLength() > MAX_BUFFER_RESPONSE_SIZE
                || httpRequest.getResponseContentLength() == -1) {
            if (logger.isTraceEnabled()) {
                logger.trace("large response (or don't know length) url=" + request.getURL());
            }

            // Need to wrap the InputStream in something that'll close
            InputStream wrappedStream = new HttpClientReleasingInputStream(httpRequest);
            httpRequest = null;

            // Now build the response
            response = new RemoteConnectorResponseImpl(request, responseContentType, responseCharSet, status,
                    responseHdrs, wrappedStream);
        } else {
            if (logger.isTraceEnabled()) {
                logger.debug("small response for url=" + request.getURL());
            }
            // Fairly small response, just keep the bytes and make life simple
            response = new RemoteConnectorResponseImpl(request, responseContentType, responseCharSet, status,
                    responseHdrs, httpRequest.getResponseBody());

            // Now we have the bytes, we can close the HttpClient resources
            httpRequest.releaseConnection();
            httpRequest = null;
        }
    } finally {
        // Make sure, problems or not, we always tidy up (if not large stream based)
        // This is important because we use a thread local HttpClient instance
        if (httpRequest != null) {
            httpRequest.releaseConnection();
            httpRequest = null;
        }
    }

    // Log the response
    if (logger.isDebugEnabled())
        logger.debug("Response was " + status + " " + statusText);

    // Decide if we should throw an exception
    if (status >= 300) {
        // Tidy if needed
        if (httpRequest != null)
            httpRequest.releaseConnection();

        // Specific exceptions
        if (status == Status.STATUS_FORBIDDEN || status == Status.STATUS_UNAUTHORIZED) {
            // TODO Forbidden may need to be handled differently.
            // TODO Need to get error message into the AuthenticationException
            throw new AuthenticationException(statusText);
        }

        // Server side exceptions
        if (status >= 500 && status <= 599) {
            logger.error("executeRequest: remote connector server exception: [" + status + "] " + statusText);
            throw new RemoteConnectorServerException(status, statusText);
        }
        if (status == Status.STATUS_PRECONDITION_FAILED) {
            logger.error("executeRequest: remote connector client exception: [" + status + "] " + statusText);
            throw new RemoteConnectorClientException(status, statusText, response);
        } else {
            // Client request exceptions
            if (httpRequest != null) {
                // Response wasn't too big and is available, supply it
                logger.error(
                        "executeRequest: remote connector client exception: [" + status + "] " + statusText);
                throw new RemoteConnectorClientException(status, statusText, response);
            } else {
                // Response was too large, report without it
                logger.error(
                        "executeRequest: remote connector client exception: [" + status + "] " + statusText);
                throw new RemoteConnectorClientException(status, statusText, null);
            }
        }
    }

    // If we get here, then the request/response was all fine
    // So, return our created response
    return response;
}

From source file:org.apache.sling.commons.testing.integration.HttpTestBase.java

/** Return m's response body as a string, optionally limiting the length that we read
 * @param maxLength if 0, no limit/*from ww  w  .  j a  v  a2  s.  com*/
 */
public static String getResponseBodyAsStream(HttpMethodBase m, int maxLength) throws IOException {
    final InputStream is = m.getResponseBodyAsStream();
    final StringBuilder content = new StringBuilder();
    final String charset = m.getResponseCharSet();
    final byte[] buffer = new byte[16384];
    int n = 0;
    while ((n = is.read(buffer, 0, buffer.length)) > 0) {
        content.append(new String(buffer, 0, n, charset));
        if (maxLength != 0 && content.length() > maxLength) {
            throw new IllegalArgumentException("Response body size is over maxLength (" + maxLength + ")");
        }
    }
    return content.toString();
}

From source file:org.deri.pipes.utils.HttpResponseCache.java

private static HttpResponseData getDataFromRequest(HttpClient client, String location,
        Map<String, String> requestHeaders) throws IOException, HttpException {
    HttpMethodBase method = new GetMethod(location);
    method.setFollowRedirects(true);/*from   www  .  j av  a  2s  . co  m*/
    try {
        if (location.length() > 2000 && location.indexOf('?') >= 0) {
            logger.info("Using post method because request location is very long");
            PostMethod postMethod = new PostMethod(location.substring(0, location.indexOf('?')));
            String urlDecoded = URLDecoder.decode(location.substring(location.indexOf('?') + 1), "UTF-8");
            String[] parts = urlDecoded.split("\\&");
            for (String part : parts) {
                String[] keyval = part.split("=", 2);
                if (keyval.length == 2) {
                    postMethod.addParameter(keyval[0], keyval[1]);
                } else {
                    postMethod.addParameter(keyval[0], "");
                }
            }
            method = postMethod;
        }
        addRequestHeaders(method, requestHeaders);
        int response = client.executeMethod(method);
        HttpResponseData data = new HttpResponseData();
        setExpires(data, method);
        data.setResponse(response);
        data.setCharSet(method.getResponseCharSet());
        Header lastModifiedHeader = method.getResponseHeader(HEADER_LAST_MODIFIED);
        if (lastModifiedHeader != null) {
            data.setLastModified(lastModifiedHeader.getValue());
        }
        Header contentTypeHeader = method.getResponseHeader(HEADER_CONTENT_TYPE);
        if (contentTypeHeader != null) {
            data.setContentType(contentTypeHeader.getValue());
        }
        data.setBody(method.getResponseBody(MAX_CONTENT_SIZE));

        return data;
    } finally {
        method.releaseConnection();
    }
}

From source file:org.eclipse.mylyn.internal.gerrit.core.client.GerritClient.java

/**
 * Retrieves the root URL for the Gerrit instance and attempts to parse the configuration from the JavaScript
 * portion of the page./*  ww w.  jav a2s.  co  m*/
 */
private GerritConfigX refreshGerritConfig(final IProgressMonitor monitor) throws GerritException {
    try {
        GerritConfigX gerritConfig = client.execute(new Request<GerritConfigX>() {
            @Override
            public HttpMethodBase createMethod() throws IOException {
                return new GetMethod(client.getUrl() + "/"); //$NON-NLS-1$
            }

            @Override
            public GerritConfigX process(HttpMethodBase method) throws IOException {
                InputStream in = WebUtil.getResponseBodyAsStream(method, monitor);
                try {
                    GerritHtmlProcessor processor = new GerritHtmlProcessor();
                    processor.parse(in, method.getResponseCharSet());
                    return processor.getConfig();
                } finally {
                    in.close();
                }
            }
        }, monitor);

        if (gerritConfig == null) {
            throw new GerritException("Failed to obtain Gerrit configuration"); //$NON-NLS-1$
        }
        return gerritConfig;
    } catch (UnknownHostException cause) {
        GerritException e = new GerritException("Unknown host: " + cause.getMessage()); //$NON-NLS-1$
        e.initCause(cause);
        throw e;
    } catch (IOException cause) {
        GerritException e = new GerritException(cause.getMessage());
        e.initCause(cause);
        throw e;
    }
}

From source file:org.folg.werelatedata.editor.PageEditor.java

private String getResponse(HttpMethodBase m) throws IOException {
    InputStream s = m.getResponseBodyAsStream();
    int bytesRead = -1;
    int totalBytes = 0;
    int bytesToRead = BUF_SIZE;
    byte[] buf = new byte[BUF_SIZE];
    while (true) {
        bytesRead = s.read(buf, totalBytes, bytesToRead);
        if (bytesRead < 0) {
            break;
        }//w  ww. jav  a 2 s  . c  o m
        totalBytes += bytesRead;
        bytesToRead -= bytesRead;
        if (bytesToRead == 0) { // buffer full, so allocate more
            if (buf.length * 2 > MAX_BUF_SIZE) {
                throw new IOException("Response too long: " + m.getURI().toString());
            }
            byte[] temp = buf;
            buf = new byte[temp.length * 2];
            System.arraycopy(temp, 0, buf, 0, temp.length);
            bytesToRead = temp.length;
        }
    }
    if (totalBytes > 0) {
        return EncodingUtil.getString(buf, 0, totalBytes, m.getResponseCharSet());
    } else {
        return null;
    }
}

From source file:org.openrdf.repository.sparql.query.SPARQLGraphQuery.java

public GraphQueryResult evaluate() throws QueryEvaluationException {
    try {/*ww w.ja  v a 2s . c o m*/
        BackgroundGraphResult result = null;
        HttpMethodBase response = getResponse();
        try {
            RDFParser parser = getParser(response);
            InputStream in = response.getResponseBodyAsStream();
            String charset_str = response.getResponseCharSet();
            Charset charset;
            try {
                charset = Charset.forName(charset_str);
            } catch (IllegalCharsetNameException e) {
                // work around for Joseki-3.2
                // Content-Type: application/rdf+xml;
                // charset=application/rdf+xml
                charset = Charset.forName("UTF-8");
            }
            result = new BackgroundGraphResult(parser, in, charset, getUrl(), response);
            execute(result);
            return result;
        } catch (HttpException e) {
            throw new QueryEvaluationException(e);
        } finally {
            if (result == null) {
                response.abort();
            }
        }
    } catch (IOException e) {
        throw new QueryEvaluationException(e);
    }
}

From source file:org.portletbridge.portlet.BridgeViewPortlet.java

/**
 * Writes out the transformed content from the downstream site.
 */// w  w w  .  j a  va2 s  .co m
public void doView(final RenderRequest request, final RenderResponse response)
        throws PortletException, IOException {

    ResourceBundle resourceBundle = getPortletConfig().getResourceBundle(request.getLocale());

    // noop if window is minimised
    if (request.getWindowState().equals(WindowState.MINIMIZED)) {
        return;
    }

    response.setContentType("text/html");

    try {
        PortletSession session = request.getPortletSession();
        String portletId = response.getNamespace();
        PortletBridgeMemento tempMemento = (PortletBridgeMemento) session.getAttribute(mementoSessionKey,
                PortletSession.APPLICATION_SCOPE);
        if (tempMemento == null) {
            tempMemento = new DefaultPortletBridgeMemento(idParamKey, bridgeAuthenticator, initUrlFactory);
            session.setAttribute(mementoSessionKey, tempMemento, PortletSession.APPLICATION_SCOPE);
        }
        final PortletBridgeMemento memento = tempMemento;
        final PerPortletMemento perPortletMemento = memento.getPerPortletMemento(portletId);
        perPortletMemento.setPreferences(request);
        String urlId = request.getParameter(idParamKey);

        final BridgeRequest bridgeRequest;

        if (urlId != null) {
            bridgeRequest = memento.getBridgeRequest(urlId);
        } else {

            if (log.isDebugEnabled()) {
                log.debug("no bridge request found, using initUrl");
            }

            bridgeRequest = null;
        }

        if (urlId == null || bridgeRequest == null) {
            // this is the default start page for the portlet so go and
            // fetch it
            final URI initUrl = perPortletMemento.getInitUrl();
            httpClientTemplate.service(new GetMethod(initUrl.toString()), perPortletMemento,
                    new HttpClientCallback() {
                        public Object doInHttpClient(int statusCode, HttpMethodBase method) throws Throwable {
                            transformer.transform(memento, perPortletMemento, initUrl, request, response,
                                    new InputStreamReader(method.getResponseBodyAsStream(),
                                            method.getResponseCharSet()));
                            return null;
                        }
                    });
        } else {
            PortletBridgeContent content = perPortletMemento.dequeueContent(bridgeRequest.getId());
            if (content == null) {
                // we're rerendering
                httpClientTemplate.service(new GetMethod(bridgeRequest.getUrl().toString()), perPortletMemento,
                        new HttpClientCallback() {
                            public Object doInHttpClient(int statusCode, HttpMethodBase method)
                                    throws Throwable {
                                transformer.transform(memento, perPortletMemento, bridgeRequest.getUrl(),
                                        request, response, new InputStreamReader(
                                                method.getResponseBodyAsStream(), method.getResponseCharSet()));
                                return null;
                            }
                        });
            } else {
                // we have content, transform that
                transformer.transform(memento, perPortletMemento, bridgeRequest.getUrl(), request, response,
                        new StringReader(content.getContent()));
            }
        }

    } catch (ResourceException resourceException) {
        String format = MessageFormat.format(resourceBundle.getString(resourceException.getMessage()),
                resourceException.getArgs());
        throw new PortletException(format, resourceException.getCause());
    }
}

From source file:org.portletbridge.portlet.PortletBridgeServlet.java

/**
 * @param response/*from  w  w  w  .j av  a2s .  c o  m*/
 * @param bridgeRequest
 * @param perPortletMemento
 * @param url
 * @throws ServletException
 */
protected void fetch(final HttpServletRequest request, final HttpServletResponse response,
        final BridgeRequest bridgeRequest, final PortletBridgeMemento memento,
        final PerPortletMemento perPortletMemento, final URI url) throws ServletException {
    try {
        GetMethod getMethod = new GetMethod(url.toString());
        // TODO: suspect to send the same request headers after a redirect?
        copyRequestHeaders(request, getMethod);
        httpClientTemplate.service(getMethod, perPortletMemento, new HttpClientCallback() {
            public Object doInHttpClient(int statusCode, HttpMethodBase method)
                    throws ResourceException, Throwable {
                if (statusCode == HttpStatus.SC_OK) {
                    // if it's text/html then store it and redirect
                    // back to the portlet render view (portletUrl)
                    org.apache.commons.httpclient.URI effectiveUri = method.getURI();
                    BridgeRequest effectiveBridgeRequest = null;
                    if (!effectiveUri.toString().equals(url.toString())) {
                        PseudoRenderResponse renderResponse = createRenderResponse(bridgeRequest);
                        effectiveBridgeRequest = memento.createBridgeRequest(renderResponse,
                                new DefaultIdGenerator().nextId(), new URI(effectiveUri.toString()));
                    } else {
                        effectiveBridgeRequest = bridgeRequest;
                    }
                    Header responseHeader = method.getResponseHeader("Content-Type");
                    if (responseHeader != null && responseHeader.getValue().startsWith("text/html")) {
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        // TODO: think about cleaning this up if we
                        // don't get back to the render
                        perPortletMemento.enqueueContent(effectiveBridgeRequest.getId(),
                                new PortletBridgeContent(url, "get", content));
                        // redirect
                        // TODO: worry about this... adding the id
                        // at the end
                        response.sendRedirect(effectiveBridgeRequest.getPageUrl());
                    } else if (responseHeader != null
                            && responseHeader.getValue().startsWith("text/javascript")) {
                        // rewrite external javascript
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        BridgeFunctions bridge = bridgeFunctionsFactory.createBridgeFunctions(memento,
                                perPortletMemento, getServletName(), url,
                                new PseudoRenderRequest(request.getContextPath()),
                                createRenderResponse(effectiveBridgeRequest));
                        response.setContentType("text/javascript");
                        PrintWriter writer = response.getWriter();
                        writer.write(bridge.script(null, content));
                        writer.flush();
                    } else if (responseHeader != null && responseHeader.getValue().startsWith("text/css")) {
                        // rewrite external css
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        BridgeFunctions bridge = bridgeFunctionsFactory.createBridgeFunctions(memento,
                                perPortletMemento, getServletName(), url,
                                new PseudoRenderRequest(request.getContextPath()),
                                createRenderResponse(effectiveBridgeRequest));
                        response.setContentType("text/css");
                        PrintWriter writer = response.getWriter();
                        writer.write(bridge.style(null, content));
                        writer.flush();
                    } else {
                        // if it's anything else then stream it
                        // back... consider stylesheets and
                        // javascript
                        // TODO: javascript and css rewriting
                        Header header = method.getResponseHeader("Content-Type");
                        response.setContentType(((null == header.getName() ? "" : header.getName()) + ": "
                                + (null == header.getValue() ? "" : header.getValue())));

                        log.trace("fetch(): returning URL=" + url + ", as stream, content type=" + header);
                        ResourceUtil.copy(method.getResponseBodyAsStream(), response.getOutputStream(), 4096);
                    }
                } else {
                    // if there is a problem with the status code
                    // then return that error back
                    response.sendError(statusCode);
                }
                return null;
            }
        });
    } catch (ResourceException resourceException) {
        String format = MessageFormat.format(resourceBundle.getString(resourceException.getMessage()),
                resourceException.getArgs());
        throw new ServletException(format, resourceException);
    }
}

From source file:org.portletbridge.portlet.PortletBridgeServlet.java

protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    // get the id
    final String id = portletBridgeService.getIdFromRequestUri(request.getContextPath(),
            request.getRequestURI());/*from  w  w w  . j a v a 2s .c o m*/
    // look up the data associated with that id from the session
    HttpSession session = request.getSession();
    if (session == null) {
        throw new ServletException(resourceBundle.getString("error.nosession"));
    }
    final PortletBridgeMemento memento = (PortletBridgeMemento) session.getAttribute(mementoSessionKey);
    if (memento == null) {
        throw new ServletException(resourceBundle.getString("error.nomemento"));
    }
    final BridgeRequest bridgeRequest = memento.getBridgeRequest(id);
    if (bridgeRequest == null) {
        throw new ServletException(resourceBundle.getString("error.nobridgerequest"));
    }
    final PerPortletMemento perPortletMemento = memento.getPerPortletMemento(bridgeRequest.getPortletId());
    if (perPortletMemento == null) {
        throw new ServletException(resourceBundle.getString("error.noperportletmemento"));
    }

    // go and fetch the data from the backend as appropriate
    final URI url = bridgeRequest.getUrl();

    log.debug("doPost(): URL=" + url);

    try {
        PostMethod postMethod = new PostMethod(url.toString());
        copyRequestHeaders(request, postMethod);
        postMethod.setRequestEntity(new InputStreamRequestEntity(request.getInputStream()));
        httpClientTemplate.service(postMethod, perPortletMemento, new HttpClientCallback() {
            public Object doInHttpClient(int statusCode, HttpMethodBase method)
                    throws ResourceException, Throwable {
                if (statusCode == HttpStatus.SC_OK) {
                    // if it's text/html then store it and redirect
                    // back to the portlet render view (portletUrl)
                    Header responseHeader = method.getResponseHeader("Content-Type");
                    if (responseHeader != null && responseHeader.getValue().startsWith("text/html")) {
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        // TODO: think about cleaning this up if we
                        // don't get back to the render
                        perPortletMemento.enqueueContent(bridgeRequest.getId(),
                                new PortletBridgeContent(url, "post", content));
                        // redirect
                        // TODO: worry about this... adding the id
                        // at the end

                        log.debug("doPost(): doing response.sendRedirect to URL=" + bridgeRequest.getPageUrl());

                        response.sendRedirect(bridgeRequest.getPageUrl());
                    } else {
                        // if it's anything else then stream it
                        // back... consider stylesheets and
                        // javascript
                        // TODO: javascript and css rewriting
                        response.setContentType(method.getResponseHeader("Content-Type").toExternalForm());
                        ResourceUtil.copy(method.getResponseBodyAsStream(), response.getOutputStream(), 4096);
                    }
                } else if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                    Header locationHeader = method.getResponseHeader("Location");
                    if (locationHeader != null) {
                        URI redirectUrl = new URI(locationHeader.getValue().trim());
                        log.debug("redirecting to [" + redirectUrl + "]");
                        PseudoRenderResponse renderResponse = createRenderResponse(bridgeRequest);
                        BridgeRequest updatedBridgeRequest = memento.createBridgeRequest(renderResponse,
                                new DefaultIdGenerator().nextId(), redirectUrl);
                        fetch(request, response, updatedBridgeRequest, memento, perPortletMemento, redirectUrl);

                    } else {
                        throw new PortletBridgeException("error.missingLocation");
                    }
                } else {
                    // if there is a problem with the status code
                    // then return that error back
                    response.sendError(statusCode);
                }
                return null;
            }
        });
    } catch (ResourceException resourceException) {
        String format = MessageFormat.format(resourceBundle.getString(resourceException.getMessage()),
                resourceException.getArgs());
        throw new ServletException(format, resourceException);
    }
}