Example usage for org.apache.http.client.utils URIBuilder build

List of usage examples for org.apache.http.client.utils URIBuilder build

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIBuilder build.

Prototype

public URI build() throws URISyntaxException 

Source Link

Document

Builds a URI instance.

Usage

From source file:org.squashtest.tm.plugin.testautomation.jenkins.internal.net.HttpRequestFactory.java

/**
 * Mostly softens exceptions from URIBuilder.build()
 *
 * @param builder the URIBuilder which shall be used to build URI
 * @return the built URI//from   www  .  j  a v  a  2  s.  com
 */
private URI build(URIBuilder builder) {
    try {
        return builder.build();
    } catch (URISyntaxException ex) {
        throw handleUriException(ex);
    }
}

From source file:de.devbliss.apitester.dummyserver.DummyApiServer.java

public URI buildRequestUri(String pathOnServer) throws URISyntaxException {
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme("http");
    uriBuilder.setHost("localhost");
    uriBuilder.setPort(port);//from   ww w.ja v a2  s.com
    uriBuilder.setPath(pathOnServer);
    return uriBuilder.build();
}

From source file:com.ibm.subway.NewYorkSubway.java

public StationList getStationList(String routeId) throws Exception {
    logger.debug("Route {}", routeId);
    StationList returnedList = new StationList();

    try {//  ww  w  . j  a v  a 2s .  co m
        if (routeId != null) {
            RequestConfig config = RequestConfig.custom().setSocketTimeout(10 * 1000)
                    .setConnectTimeout(10 * 1000).build();
            CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(config).build();

            URIBuilder builder = new URIBuilder();
            builder.setScheme("http").setHost(url).setPath("/by-route/" + routeId);
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            httpGet.setHeader("Content-Type", "text/plain");

            HttpResponse httpResponse = httpclient.execute(httpGet);

            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));

                // Read all the trains from the list
                ObjectMapper mapper = new ObjectMapper();
                returnedList = mapper.readValue(rd, StationList.class);
            } else {
                logger.error("could not get list from MTA http code {}",
                        httpResponse.getStatusLine().getStatusCode());
            }
        }
    } catch (Exception e) {
        logger.error("could not get list from MTA {}", e.getMessage());
        throw e;
    }

    return returnedList;
}

From source file:org.mitre.openid.connect.client.service.impl.ThirdPartyIssuerService.java

@Override
public IssuerServiceResponse getIssuer(HttpServletRequest request) {

    // if the issuer is passed in, return that
    String iss = request.getParameter("iss");
    if (!Strings.isNullOrEmpty(iss)) {
        if (!whitelist.isEmpty() && !whitelist.contains(iss)) {
            throw new AuthenticationServiceException(
                    "Whitelist was nonempty, issuer was not in whitelist: " + iss);
        }//  w ww . ja v  a  2  s.c o  m

        if (blacklist.contains(iss)) {
            throw new AuthenticationServiceException("Issuer was in blacklist: " + iss);
        }

        return new IssuerServiceResponse(iss, request.getParameter("login_hint"),
                request.getParameter("target_link_uri"));
    } else {

        try {
            // otherwise, need to forward to the account chooser
            String redirectUri = request.getRequestURL().toString();
            URIBuilder builder = new URIBuilder(accountChooserUrl);

            builder.addParameter("redirect_uri", redirectUri);

            return new IssuerServiceResponse(builder.build().toString());

        } catch (URISyntaxException e) {
            throw new AuthenticationServiceException("Account Chooser URL is not valid", e);
        }

    }

}

From source file:org.apache.solr.kelvin.URLQueryPerformer.java

@Override
protected Object performTestQueries(ITestCase testCase, Properties queryParams) throws Exception {
    URIBuilder uriBuilder = new URIBuilder(this.baseUrl);
    for (String paramName : queryParams.stringPropertyNames()) {
        uriBuilder.setParameter(paramName, queryParams.getProperty(paramName));
    }//from w  w w  . j  a  va2 s.  c  o  m
    URI uri = uriBuilder.build();
    HttpGet httpget = new HttpGet(uri);

    System.out.println("executing request " + httpget.getURI());

    // Create a custom response handler
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        }

    };
    String responseBody = httpclient.execute(httpget, responseHandler);

    return responseBody;
}

From source file:org.jasig.portlet.proxy.service.web.interceptor.ProxyCASAuthenticationPreInterceptor.java

@Override
protected void prepareAuthentication(HttpContentRequestImpl contentRequest, PortletRequest portletRequest) {

    // retrieve the CAS ticket from the UserInfo map
    @SuppressWarnings("unchecked")
    Map<String, String> userinfo = (Map<String, String>) portletRequest.getAttribute(PortletRequest.USER_INFO);
    String ticket = (String) userinfo.get("casProxyTicket");

    if (ticket == null) {
        log.warn(//from  w  w w. ja  va2s . c  o m
                "No CAS ticket found in the UserInfo map. Is 'casProxyTicket' user-attribute declared in the portlet configuration?");
        return;
    }

    log.debug("serviceURL: {}, ticket: {}", this.serviceUrl, ticket);

    /* contact CAS and validate */
    try {

        // validate the ticket provided by the portal
        final Assertion assertion = this.ticketValidator.validate(ticket, this.serviceUrl);

        // get a proxy ticket for the target URL
        final String proxyTicket = assertion.getPrincipal()
                .getProxyTicketFor(contentRequest.getProxiedLocation());
        if (proxyTicket == null) {
            log.error("Failed to retrieve proxy ticket for assertion [{}]. Is the PGT still valid?",
                    assertion.toString());
            return;
        }
        log.trace("returning from proxy ticket request with proxy ticket [{}]", proxyTicket);

        // update the URL to include the proxy ticket
        final URIBuilder builder = new URIBuilder(contentRequest.getProxiedLocation());
        builder.addParameter("ticket", proxyTicket);

        String proxiedLocation = builder.build().toString();
        log.debug("Set final proxied location to be {}", proxiedLocation);
        contentRequest.setProxiedLocation(proxiedLocation);

    } catch (TicketValidationException e) {
        log.warn("Failed to validate proxy ticket", e);
        return;
    } catch (URISyntaxException e) {
        log.warn("Failed to parse proxy URL", e);
        return;
    }

}

From source file:com.github.dziga.orest.client.HttpRestClient.java

int Delete() throws IOException, URISyntaxException {
    URIBuilder uriBuilder = new URIBuilder().setScheme(scheme).setHost(host).setPath(path);
    addQueryParams(uriBuilder);//from   ww w  .j  a  v a  2  s .c o  m
    URI fullUri = uriBuilder.build();
    HttpDelete deleteMethod = new HttpDelete(fullUri);
    deleteMethod = (HttpDelete) addHeadersToMethod(deleteMethod);
    processResponse(httpClient.execute(deleteMethod));

    return getResponseCode();
}

From source file:org.talend.dataprep.api.service.command.dataset.CreateOrUpdateDataSet.java

/**
 * Private constructor./*w w  w  . j a v  a  2s  .c  o  m*/
 *
 * @param id the dataset id.
 * @param name the dataset name.
 * @param dataSetContent the new dataset content.
 */
private CreateOrUpdateDataSet(String id, String name, InputStream dataSetContent) {
    super(GenericCommand.DATASET_GROUP);
    execute(() -> {
        try {
            URIBuilder uriBuilder = new URIBuilder(datasetServiceUrl + "/datasets/" + id + "/raw/");
            if (!StringUtils.isEmpty(name)) {
                uriBuilder.addParameter("name", name);
            }
            final HttpPut put = new HttpPut(uriBuilder.build()); // $NON-NLS-1$ //$NON-NLS-2$
            put.setEntity(new InputStreamEntity(dataSetContent));
            return put;
        } catch (URISyntaxException e) {
            throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
        }
    });
    onError(e -> new TDPException(APIErrorCodes.UNABLE_TO_CREATE_OR_UPDATE_DATASET, e));
    on(HttpStatus.NO_CONTENT, HttpStatus.ACCEPTED).then(emptyString());
    on(HttpStatus.OK).then(asString());
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.HttpStreamTest.java

private URI makeURI() throws URISyntaxException {
    URIBuilder uriBuilder = new URIBuilder("http://localhost"); // NON-NLS
    uriBuilder.setHost("localhost"); // NON-NLS
    uriBuilder.setPort(TEST_PORT);//from w w w  . j a  va  2  s . co  m
    URI url = uriBuilder.build();
    return url;
}

From source file:org.apache.ambari.server.view.HttpImpersonatorImpl.java

/**
 * Returns the result of the HTTP request by setting the "doAs" impersonation for the query param and username
 * in @param impersonatorSetting.//from  w  w  w. j av a2  s.c om
 * @param url URL to request
 * @param requestType HTTP Request type: GET, PUT, POST, DELETE, etc.
 * @param impersonatorSetting Setting class with default values for username and doAs param name.
 *                           To use different values, call the setters of the object.
 * @return Return a response as a String
 */
@Override
public String requestURL(String url, String requestType, final ImpersonatorSetting impersonatorSetting) {
    String result = "";
    BufferedReader rd;
    String line;

    if (url.toLowerCase().contains(impersonatorSetting.getDoAsParamName().toLowerCase())) {
        throw new IllegalArgumentException(
                "URL cannot contain \"" + impersonatorSetting.getDoAsParamName() + "\" parameter");
    }

    try {
        String username = impersonatorSetting.getUsername();
        if (username != null) {
            URIBuilder builder = new URIBuilder(url);
            builder.addParameter(impersonatorSetting.getDoAsParamName(), username);
            url = builder.build().toString();
        }

        HttpURLConnection connection = urlStreamProvider.processURL(url, requestType, (String) null, null);

        int responseCode = connection.getResponseCode();
        InputStream resultInputStream;
        if (responseCode >= ProxyService.HTTP_ERROR_RANGE_START) {
            resultInputStream = connection.getErrorStream();
        } else {
            resultInputStream = connection.getInputStream();
        }

        rd = new BufferedReader(new InputStreamReader(resultInputStream));

        if (rd != null) {
            line = rd.readLine();
            while (line != null) {
                result += line;
                line = rd.readLine();
            }
            rd.close();
        }
    } catch (Exception e) {
        LOG.error("Exception caught processing impersonator request.", e);
    }
    return result;
}