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

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

Introduction

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

Prototype

public abstract URI getURI() throws URIException;

Source Link

Usage

From source file:org.eclipsetrader.yahoojapanfx.internal.core.connector.BackfillConnector.java

@Override
public IOHLC[] backfillHistory(IFeedIdentifier identifier, Date from, Date to, TimeSpan timeSpan) {
    List<OHLC> list = new ArrayList<OHLC>();

    String period = "";
    if (timeSpan.getUnits() == TimeSpan.Units.Days) {
        period = "1d";
    } else if (timeSpan.getUnits() == TimeSpan.Units.Minutes) {
        period = String.valueOf(timeSpan.getLength()) + "m";
    }//  w  ww. j  ava2s  .c  om

    HttpClient client = new HttpClient();
    try {
        HttpMethod method = Util.getPrepareHistoryFeedMethod(identifier);
        Util.setupProxy(client, method.getURI().getHost());

        client.executeMethod(method);

        BufferedReader in;
        if ((method.getResponseHeader("Content-Encoding") != null)
                && (method.getResponseHeader("Content-Encoding").getValue().equals("gzip"))) {
            in = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(method.getResponseBodyAsStream())));
        } else {
            in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        }
        String inputLine;
        String c = "";
        while ((inputLine = in.readLine()) != null) {
            if (inputLine.indexOf("YJFIN.c =") >= 0) {
                c = inputLine.substring(inputLine.indexOf("YJFIN.c =") + 11, inputLine.indexOf("\";"));
            }
        }
        in.close();

        method = Util.getHistoryFeedMethod(identifier, period, c);

        client.executeMethod(method);

        if ((method.getResponseHeader("Content-Encoding") != null)
                && (method.getResponseHeader("Content-Encoding").getValue().equals("gzip"))) {
            in = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(method.getResponseBodyAsStream())));
        } else {
            in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        }
        if (timeSpan.getUnits() == TimeSpan.Units.Days) {
            readHistoryStream(in, list);
        } else {
            readIntradayStream(in, list);
        }
        in.close();
    } catch (Exception e) {
        Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error reading data", e); //$NON-NLS-1$
        Activator.log(status);
    }

    Collections.sort(list, new Comparator<OHLC>() {

        @Override
        public int compare(OHLC o1, OHLC o2) {
            return o1.getDate().compareTo(o2.getDate());
        }
    });

    for (Iterator<OHLC> iter = list.iterator(); iter.hasNext();) {
        OHLC ohlc = iter.next();
        if (ohlc.getDate().before(from) || ohlc.getDate().after(to)) {
            iter.remove();
        }
    }

    return list.toArray(new IOHLC[list.size()]);
}

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:/*w  w w  .  ja v  a 2s.c o m*/
        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);
}

From source file:org.entando.entando.plugins.jpoauthclient.aps.system.httpclient.OAuthHttpClient.java

@Override
public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException {
    final String method = request.method;
    final String url = request.url.toExternalForm();
    final InputStream body = request.getBody();
    final boolean isDelete = DELETE.equalsIgnoreCase(method);
    final boolean isPost = POST.equalsIgnoreCase(method);
    final boolean isPut = PUT.equalsIgnoreCase(method);
    byte[] excerpt = null;
    HttpMethod httpMethod;
    if (isPost || isPut) {
        EntityEnclosingMethod entityEnclosingMethod = isPost ? new PostMethod(url) : new PutMethod(url);
        if (body != null) {
            ExcerptInputStream e = new ExcerptInputStream(body);
            String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH);
            entityEnclosingMethod.setRequestEntity((length == null) ? new InputStreamRequestEntity(e)
                    : new InputStreamRequestEntity(e, Long.parseLong(length)));
            excerpt = e.getExcerpt();/* w  w w  . j  a va  2s  .  c  om*/
        }
        httpMethod = entityEnclosingMethod;
    } else if (isDelete) {
        httpMethod = new DeleteMethod(url);
    } else {
        httpMethod = new GetMethod(url);
    }
    for (Map.Entry<String, Object> p : parameters.entrySet()) {
        String name = p.getKey();
        String value = p.getValue().toString();
        if (FOLLOW_REDIRECTS.equals(name)) {
            httpMethod.setFollowRedirects(Boolean.parseBoolean(value));
        } else if (READ_TIMEOUT.equals(name)) {
            httpMethod.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, Integer.parseInt(value));
        }
    }
    for (Map.Entry<String, String> header : request.headers) {
        httpMethod.addRequestHeader(header.getKey(), header.getValue());
    }
    HttpClient client = this._clientPool.getHttpClient(new URL(httpMethod.getURI().toString()));
    client.executeMethod(httpMethod);
    return new HttpMethodResponse(httpMethod, excerpt, request.getContentCharset());
}

From source file:org.exist.xquery.modules.httpclient.BaseHTTPClientFunction.java

/**
 * Takes the HTTP Response Body from the HTTP Method and attempts to insert it into the response tree we are building.
 *
 * <p>Conversion Preference - 1) Try and parse as XML, if successful returns a Node 2) Try and parse as HTML returning as XML compatible HTML, if
 * successful returns a Node 3) Return as base64Binary encoded data</p>
 *
 * @param   context  The context of the calling XQuery
 * @param   method   The HTTP Request Method
 * @param   builder  The MemTreeBuilder that is being used
 *
 * @throws  IOException     /*from   ww w . j a  v  a2s. c o m*/
 * @throws  XPathException  
 */
private void insertResponseBody(final XQueryContext context, final HttpMethod method,
        final MemTreeBuilder builder, final Map<String, Boolean> parserFeatures,
        final Map<String, String> parserProperties) throws IOException, XPathException {
    NodeImpl responseNode = null;

    final InputStream bodyAsStream = method.getResponseBodyAsStream();

    // check if there is a response body
    if (bodyAsStream != null) {

        CachingFilterInputStream cfis = null;
        FilterInputStreamCache cache = null;
        try {

            //we have to cache the input stream, so we can reread it, as we may use it twice (once for xml attempt and once for string attempt)
            cache = FilterInputStreamCacheFactory
                    .getCacheInstance(new FilterInputStreamCacheFactory.FilterInputStreamCacheConfiguration() {
                        @Override
                        public String getCacheClass() {
                            return (String) context.getBroker().getConfiguration()
                                    .getProperty(Configuration.BINARY_CACHE_CLASS_PROPERTY);
                        }
                    });

            cfis = new CachingFilterInputStream(cache, bodyAsStream);

            //mark the start of the stream
            cfis.mark(Integer.MAX_VALUE);

            // determine the type of the response document
            final Header responseContentType = method.getResponseHeader("Content-Type");

            final MimeType responseMimeType = getResponseMimeType(responseContentType);
            if (responseContentType != null) {
                builder.addAttribute(new QName("mimetype", null, null), responseContentType.getValue());
            }

            //try and parse the response as XML
            try {
                //we have to use CloseShieldInputStream otherwise the parser closes the stream and we cant later reread
                final InputStream shieldedInputStream = new CloseShieldInputStream(cfis);
                responseNode = (NodeImpl) ModuleUtils.streamToXML(context, shieldedInputStream);
                builder.addAttribute(new QName("type", null, null), "xml");
                responseNode.copyTo(null, new DocumentBuilderReceiver(builder));
            } catch (final SAXException se) {
                // could not parse to xml
                // not an error in itself, it will be treated either as HTML,
                // text or binary here below
                final String msg = "Request for URI '" + method.getURI().toString()
                        + "' Could not parse http response content as XML (will try html, text or fallback to binary): "
                        + se.getMessage();
                if (logger.isDebugEnabled()) {
                    logger.debug(msg, se);
                } else {
                    logger.info(msg);
                }
            } catch (final IOException ioe) {
                final String msg = "Request for URI '" + method.getURI().toString()
                        + "' Could not read http response content: " + ioe.getMessage();
                logger.error(msg, ioe);
                throw new XPathException(msg, ioe);
            }

            if (responseNode == null) {
                //response is NOT parseable as XML

                //is it a html document?
                if (responseMimeType.getName().equals(MimeType.HTML_TYPE.getName())) {

                    //html document
                    try {

                        //reset the stream to the start, as we need to reuse since attempting to parse to XML
                        cfis.reset();

                        //parse html to xml(html)

                        //we have to use CloseShieldInputStream otherwise the parser closes the stream and we cant later reread
                        final InputStream shieldedInputStream = new CloseShieldInputStream(cfis);

                        responseNode = (NodeImpl) ModuleUtils
                                .htmlToXHtml(context, method.getURI().toString(),
                                        new InputSource(shieldedInputStream), parserFeatures, parserProperties)
                                .getDocumentElement();
                        builder.addAttribute(new QName("type", null, null), "xhtml");
                        responseNode.copyTo(null, new DocumentBuilderReceiver(builder));
                    } catch (final URIException ue) {
                        throw new XPathException(this, ue.getMessage(), ue);
                    } catch (final SAXException se) {
                        //could not parse to xml(html)
                        logger.debug(
                                "Could not parse http response content from HTML to XML: " + se.getMessage(),
                                se);
                    }
                }
            }

            if (responseNode == null) {

                //reset the stream to the start, as we need to reuse since attempting to parse to HTML->XML
                cfis.reset();

                if (responseMimeType.getName().startsWith("text/")) {

                    // Assume it's a text body and URL encode it
                    builder.addAttribute(new QName("type", null, null), "text");
                    builder.addAttribute(new QName("encoding", null, null), "URLEncoded");

                    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    final byte buf[] = new byte[4096];
                    int read = -1;
                    while ((read = cfis.read(buf)) > -1) {
                        baos.write(buf);
                    }

                    builder.characters(URLEncoder.encode(EncodingUtil.getString(baos.toByteArray(),
                            ((HttpMethodBase) method).getResponseCharSet()), "UTF-8"));
                    baos.close();
                } else {

                    // Assume it's a binary body and Base64 encode it
                    builder.addAttribute(new QName("type", null, null), "binary");
                    builder.addAttribute(new QName("encoding", null, null), "Base64Encoded");

                    BinaryValue binary = null;
                    try {
                        binary = BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(),
                                cfis);
                        builder.characters(binary.getStringValue());
                    } finally {
                        // free resources
                        if (binary != null) {
                            binary.destroy(context, null);
                        }
                    }
                }
            }
        } finally {
            if (cache != null) {
                try {
                    cache.invalidate();
                } catch (final IOException ioe) {
                    LOG.error(ioe.getMessage(), ioe);
                }
            }

            if (cfis != null) {
                try {
                    cfis.close();
                } catch (final IOException ioe) {
                    LOG.error(ioe.getMessage(), ioe);
                }
            }
        }
    }
}

From source file:org.geosdi.geoplatform.services.httpclient.GeoSDIHttpClient.java

private int executeMethod(HttpMethod method) throws IOException, HttpException {
    String host = method.getURI().getHost();
    if (host != null && this.nonProxyHosts.contains(host.toLowerCase())) {
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine("Bypassing proxy config due to nonProxyHosts for " + method.getURI().toString());
        }//  w w w  . jav  a 2 s  .co  m

        return this.client.executeMethod(this.hostConfigNoProxy, method);
    } else {
        return this.client.executeMethod(method);
    }
}

From source file:org.geoserver.gss.HTTPGSSClient.java

/**
 * Executes the http method, checks the response status, parses the response and returns it.
 * Will throw an exception in case of communication errors, error codes, or service exceptions
 * /*from   www.  ja  va2 s  .  c  o m*/
 * @throws IOException
 */
Object executeMethod(HttpMethod method) throws IOException {
    Object response;
    try {
        if (LOGGER.isLoggable(Level.FINE)) {
            if (method instanceof GetMethod) {
                GetMethod gm = (GetMethod) method;
                LOGGER.fine("Sending GET request:\n " + method.getURI());
            } else if (method instanceof PostMethod) {
                PostMethod pm = (PostMethod) method;
                XMLEntity entity = (XMLEntity) pm.getRequestEntity();
                String request = entity.toString();
                LOGGER.fine("Sending POST request:\n " + method.getURI() + "\n" + request);
                // ugly, but Encoder cannot be reused, so we have to set a new entity
                // that uses the already generated string
                pm.setRequestEntity(new StringRequestEntity(request, "text/xml", "UTF-8"));
            } else {
                LOGGER.fine("Sending unknown method type : " + method);
            }
        }

        // plain execution
        int statusCode = client.executeMethod(method);

        // check the HTTP status
        if (statusCode != HttpStatus.SC_OK) {
            throw new IOException("HTTP client returned with code " + statusCode);
        }

        // parse the response
        Parser parser = new Parser(configuration);
        parser.setStrict(true);
        parser.setFailOnValidationError(true);
        InputStream is;
        if (LOGGER.isLoggable(Level.FINE)) {
            String responseString = method.getResponseBodyAsString();
            LOGGER.log(Level.FINE, "Response from Unit:\n" + responseString);
            is = new ByteArrayInputStream(responseString.getBytes());
        } else {
            is = method.getResponseBodyAsStream();
        }
        response = parser.parse(is);
    } catch (Exception e) {
        throw (IOException) new IOException("Error occurred while executing " + "a call to the Unit")
                .initCause(e);
    } finally {
        method.releaseConnection();
    }

    // convert a service exception into an IOException if necessary
    if (response instanceof ExceptionReportType) {
        ExceptionReportType report = (ExceptionReportType) response;
        StringBuilder sb = new StringBuilder("The Unit service reported a failure: ");
        for (Iterator it = report.getException().iterator(); it.hasNext();) {
            ExceptionType et = (ExceptionType) it.next();
            for (Iterator eit = et.getExceptionText().iterator(); eit.hasNext();) {
                String text = (String) eit.next();
                sb.append(text);
                if (eit.hasNext())
                    sb.append(". ");
            }

        }

        throw new IOException(sb.toString());
    }

    return response;
}

From source file:org.glite.slcs.shibclient.ShibbolethClient.java

/**
 * Delegates execution of the HttpMethod to the underlying HttpClient.
 * /*ww w.j av  a  2s  .co  m*/
 * @param method
 *            The HttpMethod to execute.
 * @return The method's response code.
 * @throws HttpException
 *             If an I/O (transport) error occurs.
 * @throws IOException
 *             If a protocol exception occurs.
 */
public int executeMethod(HttpMethod method) throws HttpException, IOException {
    if (LOG.isTraceEnabled())
        LOG.trace("exec: " + method.getName() + " " + method.getURI());
    // use delegate
    return this.httpClient_.executeMethod(method);
}

From source file:org.gradle.api.internal.artifacts.repositories.transport.http.HttpResourceCollection.java

private int executeMethod(HttpMethod method) throws IOException {
    LOGGER.debug("Performing HTTP GET: {}", method.getURI());
    configureProxyIfRequired(method);//www .j  av a2  s  . c o  m
    return client.executeMethod(method);
}

From source file:org.gradle.api.internal.artifacts.repositories.transport.http.HttpResourceCollection.java

private void configureProxyIfRequired(HttpMethod method) throws URIException {
    HttpProxySettings.HttpProxy proxy = proxySettings.getProxy(method.getURI().getHost());
    if (proxy != null) {
        setProxyForClient(client, proxy);
    } else {/*from   w w w . ja  v a 2  s.c  om*/
        client.getHostConfiguration().setProxyHost(null);
    }
}

From source file:org.infoscoop.request.BasicAuthenticator.java

public void doAuthentication(HttpClient client, ProxyRequest request, HttpMethod method, String uid, String pwd)
        throws ProxyAuthenticationException {
    try {/*from  w w w.j av  a 2  s  . c  om*/
        client.getParams().setAuthenticationPreemptive(true);
        // create the information of certification(an userID and a password).
        Credentials defaultcreds1 = new UsernamePasswordCredentials(uid, pwd);
        // the scope of the certification.
        URL urlObj = new URL(method.getURI().toString());
        AuthScope scope1 = new AuthScope(urlObj.getHost(), urlObj.getPort(), null);
        // set a pair of a scope and an information of the certification.
        client.getState().setCredentials(scope1, defaultcreds1);
    } catch (Exception e) {
        throw new ProxyAuthenticationException(e);
    }
}