Example usage for org.apache.commons.httpclient HttpMethod setURI

List of usage examples for org.apache.commons.httpclient HttpMethod setURI

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod setURI.

Prototype

public abstract void setURI(URI paramURI) throws URIException;

Source Link

Usage

From source file:com.yahoo.flowetl.services.http.BaseHttpCaller.java

/**
 * Attempts to call the given method using the given client and will attempt
 * this repeatedly up to the max redirect amount. If no redirect location is
 * found a http exception will be propagated upwards. Otherwise for
 * non-redirect codes this method will stop. This function is recursively
 * called./*ww w. j  a v  a  2s  .  co  m*/
 * 
 * @throws HttpException
 * @throws IOException
 */
private void handleRedirects(final HttpClient client, final HttpMethod method, final int curRedirAm,
        final int maxRedirAm) throws HttpException, IOException {
    if (logger.isEnabled(Level.DEBUG)) {
        logger.log(Level.DEBUG, "Executing " + method + " redir count = " + curRedirAm + " of " + maxRedirAm
                + " possible redirects ");
    }
    // exec and see what happened
    client.executeMethod(method);
    int code = method.getStatusCode();
    if (logger.isEnabled(Level.DEBUG)) {
        logger.log(Level.DEBUG, "Executing " + method + " got status code " + code + "");
    }
    // supposed redirect codes
    // everything else will just stop this function
    if (REDIR_CODES.contains(code) == false) {
        return;
    }
    // die or continue?
    if (curRedirAm < maxRedirAm) {
        // ok to try to find it
        Header locationHeader = method.getResponseHeader(REDIR_HEADER);
        String redirLoc = null;
        if (locationHeader != null) {
            redirLoc = locationHeader.getValue();
        }
        // cleanup and see if we can use it...
        redirLoc = StringUtils.trim(redirLoc);
        if (StringUtils.isEmpty(redirLoc) == false) {
            // reset uri
            URI nUri = new URI(redirLoc, false);
            method.setURI(nUri);
            if (logger.isEnabled(Level.DEBUG)) {
                logger.log(Level.DEBUG, "Attempting redirect " + (curRedirAm + 1) + " due to status code "
                        + code + " to location " + nUri);
            }
            handleRedirects(client, method, curRedirAm + 1, maxRedirAm);
        } else {
            // failure at finding header
            throw new HttpException("Unable to execute " + method + " - no " + REDIR_HEADER
                    + " header found to redirect to during redirect " + curRedirAm);
        }
    } else {
        // max redirects done
        throw new HttpException("Unable to execute " + method + " after attempting " + curRedirAm
                + " redirects of " + maxRedirAm + " attempts");
    }
}

From source file:com.cerema.cloud2.lib.common.OwnCloudClient.java

public RedirectionPath followRedirection(HttpMethod method) throws IOException {
    int redirectionsCount = 0;
    int status = method.getStatusCode();
    RedirectionPath result = new RedirectionPath(status, MAX_REDIRECTIONS_COUNT);
    while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        Header location = method.getResponseHeader("Location");
        if (location == null) {
            location = method.getResponseHeader("location");
        }/*from  ww  w.  j  av a  2 s.  c o  m*/
        if (location != null) {
            Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue());

            String locationStr = location.getValue();
            result.addLocation(locationStr);

            // Release the connection to avoid reach the max number of connections per host
            // due to it will be set a different url
            exhaustResponse(method.getResponseBodyAsStream());
            method.releaseConnection();

            method.setURI(new URI(locationStr, true));
            Header destination = method.getRequestHeader("Destination");
            if (destination == null) {
                destination = method.getRequestHeader("destination");
            }
            if (destination != null) {
                int suffixIndex = locationStr.lastIndexOf(
                        (mCredentials instanceof OwnCloudBearerCredentials) ? AccountUtils.ODAV_PATH
                                : AccountUtils.WEBDAV_PATH_4_0);
                String redirectionBase = locationStr.substring(0, suffixIndex);

                String destinationStr = destination.getValue();
                String destinationPath = destinationStr.substring(mBaseUri.toString().length());
                String redirectedDestination = redirectionBase + destinationPath;

                destination.setValue(redirectedDestination);
                method.setRequestHeader(destination);
            }
            status = super.executeMethod(method);
            result.addStatus(status);
            redirectionsCount++;

        } else {
            Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
            status = HttpStatus.SC_NOT_FOUND;
        }
    }
    return result;
}

From source file:it.greenvulcano.gvesb.virtual.http.HTTPCallOperation.java

/**
 * @see it.greenvulcano.gvesb.virtual.CallOperation#perform(it.greenvulcano.gvesb.buffer.GVBuffer)
 *///from w  ww .jav a  2  s  .  co m
@Override
public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException {
    logger.debug("BEGIN perform(GVBuffer gvBuffer)");
    HttpMethod method = null;
    try {
        String currMethodURI = null;
        Map<String, Object> params = GVBufferPropertiesHelper.getPropertiesMapSO(gvBuffer, true);

        String currHost = PropertiesHandler.expand(host, params, gvBuffer);
        String currPort = PropertiesHandler.expand(port, params, gvBuffer);
        logger.debug("Server Host: " + currHost + " - Port: " + currPort);
        httpClient.getHostConfiguration().setHost(currHost, Integer.parseInt(currPort), protocol);

        auth.setAuthentication(httpClient, host, Integer.parseInt(currPort), gvBuffer, params);
        proxy.setProxy(httpClient, gvBuffer, params);

        currMethodURI = PropertiesHandler.expand(contextPath + methodURI, params, gvBuffer);
        logger.debug("MethodURI[escaped:" + uriEscaped + "]=[" + currMethodURI + "]");
        switch (methodName) {
        case OPTIONS:
            method = new OptionsMethod();
            break;
        case GET:
            method = new GetMethod();
            break;
        case HEAD:
            method = new HeadMethod();
            break;
        case POST:
            method = new PostMethod();
            break;
        case PUT:
            method = new PutMethod();
            break;
        case DELETE:
            method = new DeleteMethod();
            break;
        default:
            throw new CallException("GV_CALL_SERVICE_ERROR",
                    new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() },
                            { "id", gvBuffer.getId().toString() },
                            { "message", "Unknown method = " + methodName } });
        }
        method.setURI(new URI(currMethodURI, uriEscaped));

        if ((refDP != null) && (refDP.length() > 0)) {
            logger.debug("Calling configured Data Provider: " + refDP);
            DataProviderManager dataProviderManager = DataProviderManager.instance();
            IDataProvider dataProvider = dataProviderManager.getDataProvider(refDP);
            try {
                dataProvider.setContext(method);
                dataProvider.setObject(gvBuffer);
                method = (HttpMethod) dataProvider.getResult();
            } finally {
                dataProviderManager.releaseDataProvider(refDP, dataProvider);
            }
        }

        int status = httpClient.executeMethod(method);
        gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(status));
        String statusTxt = method.getStatusText();
        gvBuffer.setProperty(RESPONSE_MESSAGE, (statusTxt != null ? statusTxt : "NULL"));
        Header[] responseHeaders = method.getResponseHeaders();
        for (Header header : responseHeaders) {
            String headerName = RESPONSE_HEADER_PREFIX + header.getName();
            String value = header.getValue();
            if (value == null) {
                value = "";
            }
            gvBuffer.setProperty(headerName, value);
        }
        String cType = "text/html";
        Header cTypeHeader = method.getResponseHeader("Content-Type");
        if (cTypeHeader != null) {
            String cTypeValue = cTypeHeader.getValue();
            if (cTypeValue != null) {
                cType = cTypeValue;
            }
        }
        logger.debug("Response content-type: " + cType);
        ContentType contentType = new ContentType(cType);
        byte[] responseBody = method.getResponseBody();
        Object object = responseBody;
        if (contentType.getPrimaryType().equals("multipart")) {
            object = handleMultipart(responseBody, cType);
        }
        gvBuffer.setObject(object);
    } catch (CallException exc) {
        throw exc;
    } catch (Exception exc) {
        logger.error("ERROR perform(GVBuffer gvBuffer)", exc);
        throw new CallException("GV_CALL_SERVICE_ERROR",
                new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() },
                        { "id", gvBuffer.getId().toString() }, { "message", exc.getMessage() } },
                exc);
    } finally {
        try {
            if (method != null) {
                method.releaseConnection();
            }
        } catch (Exception exc) {
            logger.warn("Error while releasing connection", exc);
        }
        logger.debug("END perform(GVBuffer gvBuffer)");
    }
    return gvBuffer;
}

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  www.  ja va2s  . co 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
 * @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:org.alfresco.httpclient.AbstractHttpClient.java

/**
 * Send Request to the repository/*  ww  w.j  av a  2s.  c  om*/
 */
protected HttpMethod sendRemoteRequest(Request req) throws AuthenticationException, IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("");
        logger.debug("* Request: " + req.getMethod() + " " + req.getFullUri()
                + (req.getBody() == null ? "" : "\n" + new String(req.getBody(), "UTF-8")));
    }

    HttpMethod method = createMethod(req);

    // execute method
    executeMethod(method);

    // Deal with redirect
    if (isRedirect(method)) {
        Header locationHeader = method.getResponseHeader("location");
        if (locationHeader != null) {
            String redirectLocation = locationHeader.getValue();
            method.setURI(new URI(redirectLocation, true));
            httpClient.executeMethod(method);
        }
    }

    return method;
}

From source file:org.apache.hadoop.hbase.stargate.client.Client.java

/**
 * Execute a transaction method given a complete URI.
 * @param method the transaction method/*from  w w w . j  a va 2 s  .  co m*/
 * @param headers HTTP header values to send
 * @param uri the URI
 * @return the HTTP response code
 * @throws IOException
 */
@SuppressWarnings("deprecation")
public int executeURI(HttpMethod method, Header[] headers, String uri) throws IOException {
    method.setURI(new URI(uri));
    if (headers != null) {
        for (Header header : headers) {
            method.addRequestHeader(header);
        }
    }
    long startTime = System.currentTimeMillis();
    int code = httpClient.executeMethod(method);
    long endTime = System.currentTimeMillis();
    if (LOG.isDebugEnabled()) {
        LOG.debug(method.getName() + " " + uri + ": " + code + " " + method.getStatusText() + " in "
                + (endTime - startTime) + " ms");
    }
    return code;
}

From source file:org.apache.wink.itest.MatrixParamTest.java

protected String sendGoodRequestAndGetResponse(String aPartialRequestURL, Class<? extends HttpMethod> aClass) {
    try {/*w w w  . jav a2s .  c  o m*/
        HttpMethod httpMethod = aClass.newInstance();
        httpMethod.setURI(new URI(BASE_URI + aPartialRequestURL, false));
        httpclient = new HttpClient();

        try {
            int result = httpclient.executeMethod(httpMethod);
            System.out.println("Response status code: " + result);
            System.out.println("Response body: ");
            String responseBody = httpMethod.getResponseBodyAsString();
            System.out.println(responseBody);
            assertEquals(result, 200);
            return responseBody;
        } catch (IOException ioe) {
            ioe.printStackTrace();
            fail(ioe.getMessage());
        } finally {
            httpMethod.releaseConnection();
        }
    } catch (URIException e) {
        e.printStackTrace();
        fail(e.getMessage());
    } catch (IllegalAccessException e) {
        e.printStackTrace();
        fail(e.getMessage());
    } catch (InstantiationException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    return null;
}

From source file:org.eclipse.swordfish.internal.resolver.backend.base.impl.HttpClientProxy.java

private ClientResponse doInvoke(ClientRequest request) {
    ClientResponse response = RegistryProxyFactory.getInstance().createResponse();
    HttpMethod method = getMethod(request.getMethod());

    try {/*from  w w  w  . j  a  v a 2 s.  c  o m*/
        String escapedRequestUrl = request.getURI().toASCIIString();
        HttpURL requestUrl = new HttpURL(escapedRequestUrl.toCharArray());
        if (request.getProperties() != null) {
            Map<String, String> properties = request.getProperties();
            String[] queryNames = properties.keySet().toArray(new String[0]);
            String[] queryValues = properties.values().toArray(new String[0]);
            requestUrl.setQuery(queryNames, queryValues);
        }

        method.setURI(requestUrl);
        int statusCode = getClient().executeMethod(method);
        response.setStatus(Status.get(statusCode));

        String responseBody = method.getResponseBodyAsString();
        if (request.getEntityType() != null) {
            response.setEntity(mapResponse(responseBody, request.getEntityType()));
        } else {
            response.setEntity(responseBody);
        }
    } catch (HttpException e) {
        LOG.error("Couldn't perform call to registry: ", e);
        response.setStatus(Status.ERROR);
        response.setEntity(e);
    } catch (IOException e) {
        LOG.error("Couldn't perform call to registry: ", e);
        response.setStatus(Status.ERROR);
        response.setEntity(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    return response;
}

From source file:org.eclipse.swordfish.internal.resolver.backend.base.impl.HttpClientProxyTest.java

@Test
public void testRetrieveWSDLList() throws Exception {
    Map<String, String> props = new HashMap<String, String>();
    props.put("property1", "value1");
    props.put("property2", "value2");
    props.put("property3", "value3");

    ClientRequest request = RegistryProxyFactory.getInstance().createRequest();
    request.setURI(new URI(DESCRIPTION_URL));
    request.setMethod(Method.GET);
    request.setEntityType(WSDLList.class);
    request.setProperties(props);/* w  w  w .  j  ava2 s . c  o m*/

    HttpMethod httpMethodMock = createNiceMock(HttpMethod.class);

    HttpClientProxyStub proxyStub = new HttpClientProxyStub();
    proxyStub.setClient(new HttpClientStub());
    proxyStub.setMethod(httpMethodMock);

    httpMethodMock.setURI(uriMatches(DESCRIPTION_URL, convertToQuery(props)));
    expectLastCall().atLeastOnce();
    httpMethodMock.getResponseBodyAsString();
    expectLastCall().andReturn(RESPONSE_WSDL_LIST).once();
    replay(httpMethodMock);

    ClientResponse response = proxyStub.get(request);
    assertNotNull("ClientResponse must not be null.", response);
    assertNotNull("Response status must be set.", response.getStatus());
    assertEquals(Status.SUCCESS, response.getStatus());

    assertNotNull("Response object must be set.", response.getEntity());
    assertEquals(WSDLList.class, response.getEntity().getClass());
    List<String> wsdls = WSDLList.class.cast(response.getEntity()).getUrl();

    assertNotNull(wsdls);
    assertEquals(2, wsdls.size());

    verify(httpMethodMock);
}

From source file:org.elasticsearch.hadoop.rest.commonshttp.CommonsHttpTransport.java

@Override
public Response execute(Request request) throws IOException {
    HttpMethod http = null;

    switch (request.method()) {
    case DELETE://from w  ww.j  av  a 2 s .  c  om
        http = new DeleteMethodWithBody();
        break;
    case HEAD:
        http = new HeadMethod();
        break;
    case GET:
        http = (request.body() == null ? new GetMethod() : new GetMethodWithBody());
        break;
    case POST:
        http = new PostMethod();
        break;
    case PUT:
        http = new PutMethod();
        break;

    default:
        throw new EsHadoopTransportException("Unknown request method " + request.method());
    }

    CharSequence uri = request.uri();
    if (StringUtils.hasText(uri)) {
        http.setURI(new URI(escapeUri(uri.toString(), settings.getNetworkSSLEnabled()), false));
    }
    // NB: initialize the path _after_ the URI otherwise the path gets reset to /
    http.setPath(prefixPath(request.path().toString()));

    try {
        // validate new URI
        uri = http.getURI().toString();
    } catch (URIException uriex) {
        throw new EsHadoopTransportException("Invalid target URI " + request, uriex);
    }

    CharSequence params = request.params();
    if (StringUtils.hasText(params)) {
        http.setQueryString(params.toString());
    }

    ByteSequence ba = request.body();
    if (ba != null && ba.length() > 0) {
        if (!(http instanceof EntityEnclosingMethod)) {
            throw new IllegalStateException(String.format("Method %s cannot contain body - implementation bug",
                    request.method().name()));
        }
        EntityEnclosingMethod entityMethod = (EntityEnclosingMethod) http;
        entityMethod.setRequestEntity(new BytesArrayRequestEntity(ba));
        entityMethod.setContentChunked(false);
    }

    // when tracing, log everything
    if (log.isTraceEnabled()) {
        log.trace(String.format("Tx %s[%s]@[%s][%s] w/ payload [%s]", proxyInfo, request.method().name(),
                httpInfo, request.path(), request.body()));
    }

    long start = System.currentTimeMillis();
    try {
        client.executeMethod(http);
    } finally {
        stats.netTotalTime += (System.currentTimeMillis() - start);
    }

    if (log.isTraceEnabled()) {
        Socket sk = ReflectionUtils.invoke(GET_SOCKET, conn, (Object[]) null);
        String addr = sk.getLocalAddress().getHostAddress();
        log.trace(String.format("Rx %s@[%s] [%s-%s] [%s]", proxyInfo, addr, http.getStatusCode(),
                HttpStatus.getStatusText(http.getStatusCode()), http.getResponseBodyAsString()));
    }

    // the request URI is not set (since it is retried across hosts), so use the http info instead for source
    return new SimpleResponse(http.getStatusCode(), new ResponseInputStream(http), httpInfo);
}