Example usage for org.apache.commons.httpclient URI URI

List of usage examples for org.apache.commons.httpclient URI URI

Introduction

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

Prototype

public URI(URI base, URI relative) throws URIException 

Source Link

Document

Construct a general URI with the given relative URI.

Usage

From source file:org.easyj.http.RESTHttpClient.java

/**
 * Sets the uri for the http request/* w  w  w  . j av  a2s  . c  om*/
 *
 * @param uri URI of the resource to be requested
 */
protected void setURI(String uri) {
    try {
        method.setURI(new URI(buildURI(uri), false));
    } catch (URIException ex) {
        logger.error("Could not build the desired URI: [{}]", uri, ex);
    }
}

From source file:org.eclipse.smarthome.binding.yahooweather.discovery.YahooWeatherDiscoveryService.java

/**
 * Retrieves the woeid (Where On Earth IDentifier) used for determining the location
 * used in the Yahoo Weather interface/*w  ww  . j  av  a 2  s  . c o m*/
 * @param Coordinate in form latitude,longitude as String
 * @return Json text from woeid service as String 
 */
private String getWoeidData(String coordinate) {
    String query = "SELECT * FROM geo.placefinder WHERE text='" + coordinate + "' and gflags='R'";
    String url = null;
    try {
        URI uri = new URI("https://query.yahooapis.com/v1/public/yql", false);
        uri.setQuery("q=" + query + "&format=json");
        url = uri.toString();
    } catch (Exception e) {
        logger.debug("Error while getting location ID: {}", e.getMessage());
    }
    return downloadData(url);
}

From source file:org.eclipse.swordfish.plugins.resolver.proxy.impl.HttpCilentProxy.java

@Override
public ClientResponse invoke(ClientRequest request) {
    ClientResponse response = new ClientResponseImpl();
    HttpMethodBase method = getMethod(request.getMethod());

    try {// w w  w .j a v a 2  s  . com
        method.setURI(new URI(request.getURI().toString(), true));
        int statusCode = getClient().executeMethod(method);
        response.setStatus(Status.get(statusCode));

        String responseBody = method.getResponseBodyAsString();
        if (request.getEntityType() != null) {
            Reader responseReader = new StringReader(responseBody);
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            try {
                Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
                response.setEntity(JAXB.unmarshal(responseReader, request.getEntityType()));
            } finally {
                Thread.currentThread().setContextClassLoader(cl);
            }
        } else {
            response.setEntity(responseBody);
        }
    } catch (HttpException e) {
        response.setStatus(Status.ERROR);
        response.setEntity(e);
    } catch (IOException e) {
        response.setStatus(Status.ERROR);
        response.setEntity(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    return response;
}

From source file:org.eclipsetrader.yahoo.internal.core.Util.java

public static URL getRSSNewsFeedForSecurity(ISecurity security)
        throws MalformedURLException, URIException, NullPointerException {
    IFeedIdentifier identifier = (IFeedIdentifier) security.getAdapter(IFeedIdentifier.class);
    if (identifier == null) {
        return null;
    }/*  www.ja v a  2s.c o m*/

    String symbol = getSymbol(identifier);

    URI feedUrl = new URI("http://finance.yahoo.com/rss/headline?s=" + symbol, false);

    return new URL(feedUrl.toString());
}

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

public CommonsHttpTransport(Settings settings, String host) {
    this.settings = settings;
    httpInfo = host;/*from  w  w w.ja v  a 2s.  c om*/

    HttpClientParams params = new HttpClientParams();
    params.setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(settings.getHttpRetries(), false) {

                @Override
                public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) {
                    if (super.retryMethod(method, exception, executionCount)) {
                        stats.netRetries++;
                        return true;
                    }
                    return false;
                }
            });

    params.setConnectionManagerTimeout(settings.getHttpTimeout());
    params.setSoTimeout((int) settings.getHttpTimeout());
    HostConfiguration hostConfig = new HostConfiguration();

    hostConfig = setupSSLIfNeeded(settings, hostConfig);
    hostConfig = setupSocksProxy(settings, hostConfig);
    Object[] authSettings = setupHttpProxy(settings, hostConfig);
    hostConfig = (HostConfiguration) authSettings[0];

    try {
        hostConfig.setHost(new URI(escapeUri(host, settings.getNetworkSSLEnabled()), false));
    } catch (IOException ex) {
        throw new EsHadoopTransportException("Invalid target URI " + host, ex);
    }
    client = new HttpClient(params, new SocketTrackingConnectionManager());
    client.setHostConfiguration(hostConfig);

    addHttpAuth(settings, authSettings);
    completeAuth(authSettings);

    HttpConnectionManagerParams connectionParams = client.getHttpConnectionManager().getParams();
    // make sure to disable Nagle's protocol
    connectionParams.setTcpNoDelay(true);

    if (log.isTraceEnabled()) {
        log.trace("Opening HTTP transport to " + httpInfo);
    }
}

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

@Override
public Response execute(Request request) throws IOException {
    HttpMethod http = null;//from w w w  .  j av a2 s.  c om

    switch (request.method()) {
    case DELETE:
        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.elasticsearch.hadoop.rest.RestClient.java

public RestClient(Settings settings) {
    HttpClientParams params = new HttpClientParams();
    params.setConnectionManagerTimeout(settings.getHttpTimeout());

    client = new HttpClient(params);
    HostConfiguration hostConfig = new HostConfiguration();
    String targetUri = settings.getTargetUri();
    try {/*from   w w w  . ja v  a  2 s . com*/
        hostConfig.setHost(new URI(targetUri, false));
    } catch (IOException ex) {
        throw new IllegalArgumentException("Invalid target URI " + targetUri, ex);
    }
    client.setHostConfiguration(hostConfig);

    scrollKeepAlive = TimeValue.timeValueMillis(settings.getScrollKeepAlive());
    indexReadMissingAsEmpty = settings.getIndexReadMissingAsEmpty();
}

From source file:org.geotools.data.couchdb.client.CouchDBClient.java

/**
 * Create a new client that will connect to a CouchDB instance at the 
 * specified root URL//from w ww.  ja  v a2  s.c  om
 * @param root URL to instance, for example: "http://127.0.0.1:5984/"
 * @throws URIException if provided URL is invalid
 */
public CouchDBClient(String root) throws URIException {
    this.root = new URI(root, false);

    clientParams = new HttpClientParams();
    clientParams.setParameter(HttpClientParams.USER_AGENT, "gtcouchclient");

    httpClient = new HttpClient(clientParams);
}

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

/**
 * Processes the IdP response as a Browser/POST
 * /* w  w  w  . java  2 s.  c o m*/
 * @param idp
 *            The {@link IdentityProvider}.
 * @param idpSSOResponseURI
 *            The IdP SSO reponse {@link URI}.
 * @return the SP URI to go to
 * @throws RemoteException
 */
private URI processIdPBrowserPOST(IdentityProvider idp, URI idpSSOResponseURI, InputStream htmlStream)
        throws RemoteException {
    // return value
    URI browserPostResponseURI = null;
    RemoteException remoteException = null;

    try {
        Source source = new Source(htmlStream);
        List<Element> forms = source.findAllElements(Tag.FORM);
        if (!forms.isEmpty()) {
            // check if form contains a valid SAML Browser/POST
            for (Element form : forms) {
                String spSAMLURL = form.getAttributeValue("ACTION");
                LOG.debug("SAML Browser/POST URL=" + spSAMLURL);
                if (spSAMLURL == null) {
                    // no SAML post URL found
                    String htmlBody = inputStreamToString(htmlStream);
                    LOG.error("No SAML Browser/POST FORM ACTION found: " + idpSSOResponseURI + ": " + htmlBody);
                    remoteException = new RemoteException("No SAML Browser/POST FORM ACTION found: "
                            + idpSSOResponseURI + ". Please see the log file.");

                    break; // exit loop
                }

                // create POST method
                PostMethod postSPSAMLMethod = new PostMethod(spSAMLURL);
                // add all HIDDEN fields to POST
                List<FormControl> formControls = form.findFormControls();
                for (FormControl control : formControls) {
                    FormControlType type = control.getFormControlType();
                    if (type.equals(FormControlType.HIDDEN)) {
                        String name = control.getName();
                        Collection<CharSequence> values = control.getValues();
                        for (CharSequence value : values) {
                            LOG.debug("HIDDEN " + name + "=" + value);
                            // add all hidden fields
                            postSPSAMLMethod.addParameter(name, (String) value);
                        }
                    }
                }

                // execute the SAML post
                LOG.info("POST SPSAMLMethod: " + postSPSAMLMethod.getURI());
                int spSAMLResponseStatus = executeMethod(postSPSAMLMethod);
                LOG.debug(postSPSAMLMethod.getStatusLine());

                // status must be 302 and redirect Location
                Header location = postSPSAMLMethod.getResponseHeader("Location");
                if (spSAMLResponseStatus == 302 && location != null) {
                    String url = location.getValue();
                    browserPostResponseURI = new URI(url, false);
                    LOG.debug("Redirect: " + browserPostResponseURI);

                } else {
                    LOG.error(
                            "Unexpected SP response: Status=" + spSAMLResponseStatus + " Location=" + location);
                    remoteException = new RemoteException(
                            "Unexpected SP response: Status=" + spSAMLResponseStatus + " Location=" + location);
                }

                LOG.trace("postSPSAMLMethod.releaseConnection()");
                postSPSAMLMethod.releaseConnection();

            } // forms loop
        } else {
            // no SAML post found
            String htmlBody = inputStreamToString(htmlStream);
            LOG.error("No SAML Browser/POST profile found: " + idpSSOResponseURI + ": " + htmlBody);
            remoteException = new RemoteException(
                    "No SAML Browser/POST profile found: " + idpSSOResponseURI + ". Please see the log file.");
        }

    } catch (URIException e) {
        e.printStackTrace();
        remoteException = new RemoteException(e.getMessage(), e);
    } catch (IOException e) {
        e.printStackTrace();
        remoteException = new RemoteException(e.getMessage(), e);
    }

    if (browserPostResponseURI == null) {
        if (remoteException != null) {
            throw remoteException;
        }
    }

    return browserPostResponseURI;
}

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

/**
 * Gets the Shibboleth session needed afterward.
 * <p>//from  w  w w .jav  a  2  s  .  c om
 * Supports Shib1 (SAML1) WAFY and direct redirection to IdP, SAML2 direct
 * redirection to IdP, and SAML2 DS
 * 
 * @param entryURL
 * @param idp
 * @return
 * @throws URIException
 * @throws HttpException
 * @throws IOException
 * @throws RemoteException
 */
private URI processSPEntry(String entryURL, IdentityProvider idp)
        throws URIException, HttpException, IOException, RemoteException, ServiceException {
    GetMethod getSPEntryMethod = new GetMethod(entryURL);
    LOG.info("GET SPEntryMethod: " + getSPEntryMethod.getURI());
    // get only the first redirect, if any
    getSPEntryMethod.setFollowRedirects(false);

    int spEntryStatus = executeMethod(getSPEntryMethod);
    String spEntryStatusLine = getSPEntryMethod.getStatusLine().toString();
    LOG.debug("spEntryStatusLine=" + spEntryStatusLine);

    URI loginResponseURI = getSPEntryMethod.getURI();
    LOG.debug("loginResponseURI=" + loginResponseURI);
    if (spEntryStatus == 302) {
        Header locationHeader = getSPEntryMethod.getResponseHeader("Location");
        String location = locationHeader.getValue();
        LOG.debug("Redirect location=" + location);
        loginResponseURI = new URI(location, true);
    }

    LOG.trace("getSPEntryMethod.releaseConnection()");
    getSPEntryMethod.releaseConnection();

    String loginResponseURL = loginResponseURI.getEscapedURI();
    LOG.debug("loginResponseURL=" + loginResponseURL);

    if (spEntryStatus == 200 && loginResponseURL.startsWith(entryURL)) {
        LOG.debug("SP entry response is the same, already authenticated?");
        return loginResponseURI;
    }
    if (spEntryStatus != 302) {
        throw new RemoteException(
                "Unexpected SP response: " + spEntryStatusLine + " " + loginResponseURI + " for " + entryURL);
    }
    // checks if URL is Shib1 (SAML1) 'shire=' and 'target=' params (also
    // WAYF)
    if (loginResponseURL.indexOf("shire=") != -1 && loginResponseURL.indexOf("target=") != -1) {
        LOG.debug("loginResponseURL is Shib1 (SAML1, WAYF)");
        return loginResponseURI;

    }
    // checks if URL is SAML2 'SAMLRequest=' (direct redirection to IdP)
    // params
    else if (loginResponseURL.indexOf("SAMLRequest=") != -1) {
        LOG.debug("loginResponseURL is SAML2 redirection to IdP");
        return loginResponseURI;
    }
    // checks if URL is SAML2 'entityID=' and 'return=' (SAMLDS)
    else if (loginResponseURL.indexOf("entityID=") != -1 && loginResponseURL.indexOf("return=") != -1) {
        LOG.debug("loginResponseURL is SAML2 DiscoveryService");
        // redirect to return url with entityID of the IdP
        loginResponseURI = processSPSAML2DS(loginResponseURI, idp);
        return loginResponseURI;
    } else {
        String error = "SP response URL is not Shib1, nor SAML2 protocol: " + loginResponseURL;
        LOG.error(error);
        throw new RemoteException(error);
    }

}