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

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

Introduction

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

Prototype

public URIBuilder addParameters(final List<NameValuePair> nvps) 

Source Link

Document

Adds URI query parameters.

Usage

From source file:com.twosigma.cook.jobclient.JobClient.java

/**
 * Query a group for its status.//  w w  w.j  a v a 2 s .co m
 * @param group specifies the group to be queried.
 * @return a {@link Group} status.
 * @throws JobClientException
 */
public Group queryGroup(UUID guuid) throws JobClientException {
    if (_groupURI == null) {
        throw groupEndpointMissingException("Cannot query groups if the jobclient's group endpoint is null");
    }
    final List<NameValuePair> allParams = new ArrayList<NameValuePair>();
    allParams.add(new BasicNameValuePair("detailed", "true"));
    allParams.add(new BasicNameValuePair("uuid", guuid.toString()));

    Group result;
    HttpResponse httpResponse;
    HttpRequestBase httpRequest;
    try {
        URIBuilder uriBuilder = new URIBuilder(_groupURI);
        uriBuilder.addParameters(allParams);
        httpRequest = new HttpGet(uriBuilder.build());
        httpResponse = _httpClient.execute(httpRequest);
    } catch (IOException | URISyntaxException e) {
        throw releaseAndCreateException(null, null,
                "Can not submit GET request " + allParams + " via uri " + _jobURI, e);
    }

    // Check status code.
    final StatusLine statusLine = httpResponse.getStatusLine();
    // Base on the decision graph
    // http://clojure-liberator.github.io/liberator/tutorial/decision-graph.html
    // The status code for the proper GET response is 200.
    if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
        throw releaseAndCreateException(httpRequest, httpResponse,
                "The response of GET request " + allParams + " via uri " + _jobURI + ": "
                        + statusLine.getReasonPhrase() + ", " + statusLine.getStatusCode(),
                null);
    }
    // Parse the response.
    String response = null;
    try {
        // parse the response to string.
        final HttpEntity entity = httpResponse.getEntity();
        response = EntityUtils.toString(entity);
        // Ensure that the entity content has been fully consumed and the underlying stream has been closed.
        EntityUtils.consume(entity);
        result = Group.parseFromJSON(response, _instanceDecorator).get(0);
    } catch (JSONException | ParseException | IOException | IndexOutOfBoundsException e) {
        throw new JobClientException("Can not parse the response = " + response + " for GET request "
                + allParams + " via uri " + _jobURI, e);
    } finally {
        httpRequest.releaseConnection();
    }
    return result;
}

From source file:com.twosigma.cook.jobclient.JobClient.java

/**
 * Query jobs for a given list of job {@link UUID}s. If the list size is larger that the
 * {@code _batchRequestSize}, it will partition the list into smaller lists and query them
 * respectively and return all query results together.
 *
 * @param uuids specifies a list of job {@link UUID}s expected to query.
 * @return a {@link ImmutableMap} from job {@link UUID} to {@link Job}.
 * @throws JobClientException/* w  w  w. ja va 2  s .c o m*/
 */
public ImmutableMap<UUID, Job> queryJobs(Collection<UUID> uuids) throws JobClientException {
    final List<NameValuePair> allParams = new ArrayList<NameValuePair>(uuids.size());
    for (UUID uuid : uuids) {
        allParams.add(new BasicNameValuePair("job", uuid.toString()));
    }
    final ImmutableMap.Builder<UUID, Job> UUIDToJob = ImmutableMap.builder();
    // Partition a large query into small queries.
    for (final List<NameValuePair> params : Lists.partition(allParams, _batchRequestSize)) {
        HttpResponse httpResponse;
        HttpRequestBase httpRequest;
        try {
            URIBuilder uriBuilder = new URIBuilder(_jobURI);
            uriBuilder.addParameters(params);
            httpRequest = new HttpGet(uriBuilder.build());
            httpResponse = _httpClient.execute(httpRequest);
        } catch (IOException | URISyntaxException e) {
            throw releaseAndCreateException(null, null,
                    "Can not submit GET request " + params + " via uri " + _jobURI, e);
        }
        // Check status code.
        final StatusLine statusLine = httpResponse.getStatusLine();
        // Base on the decision graph
        // http://clojure-liberator.github.io/liberator/tutorial/decision-graph.html
        // The status code for the proper GET response is 200.
        if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
            throw releaseAndCreateException(httpRequest, httpResponse,
                    "The response of GET request " + params + " via uri " + _jobURI + ": "
                            + statusLine.getReasonPhrase() + ", " + statusLine.getStatusCode(),
                    null);
        }
        // Parse the response.
        String response = null;
        try {
            // parse the response to string.
            final HttpEntity entity = httpResponse.getEntity();
            response = EntityUtils.toString(entity);
            // Ensure that the entity content has been fully consumed and the underlying stream has been closed.
            EntityUtils.consume(entity);
            for (Job job : Job.parseFromJSON(response, _instanceDecorator)) {
                UUIDToJob.put(job.getUUID(), job);
            }
        } catch (JSONException | ParseException | IOException e) {
            throw new JobClientException("Can not parse the response = " + response + " for GET request "
                    + params + " via uri " + _jobURI, e);
        } finally {
            httpRequest.releaseConnection();
        }
    }
    return UUIDToJob.build();
}

From source file:com.twosigma.cook.jobclient.JobClient.java

/**
 * Abort jobs for a given list of job {@link UUID}s. If the size of the list is larger that the
 * {@code _batchRequestSize}, it will partition the list into smaller lists to abort separately.
 *
 * @param uuids specifies a list of job {@link UUID}s expected to abort.
 * @throws JobClientException//  w w  w.j  a va  2  s.  com
 */
public void abort(Collection<UUID> uuids) throws JobClientException {
    final List<NameValuePair> allParams = new ArrayList<NameValuePair>(uuids.size());
    for (UUID uuid : uuids) {
        allParams.add(new BasicNameValuePair("job", uuid.toString()));
    }
    // Partition a large query into small queries.
    for (final List<NameValuePair> params : Lists.partition(allParams, _batchRequestSize)) {
        HttpRequestBase httpRequest;
        try {
            URIBuilder uriBuilder = new URIBuilder(_jobURI);
            uriBuilder.addParameters(params);
            httpRequest = new HttpDelete(uriBuilder.build());
        } catch (URISyntaxException e) {
            throw releaseAndCreateException(null, null,
                    "Can not submit DELETE request " + params + " via uri " + _jobURI, e);
        }
        HttpResponse httpResponse;
        try {
            httpResponse = _httpClient.execute(httpRequest);
        } catch (IOException e) {
            throw releaseAndCreateException(httpRequest, null,
                    "Can not submit DELETE request " + params + " via uri " + _jobURI, e);
        }
        // Check status code.
        final StatusLine statusLine = httpResponse.getStatusLine();
        // Base on the decision graph
        // http://clojure-liberator.github.io/liberator/tutorial/decision-graph.html
        // If jobs are aborted successfully, the returned status code is 204.
        if (statusLine.getStatusCode() != HttpStatus.SC_NO_CONTENT) {
            throw releaseAndCreateException(
                    httpRequest, httpResponse, "The response of DELETE request " + params + " via uri "
                            + _jobURI + ": " + statusLine.getReasonPhrase() + ", " + statusLine.getStatusCode(),
                    null);
        }
        // Parse the response.
        try {
            // Parse the response to string.
            final HttpEntity entity = httpResponse.getEntity();
            if (null != entity) {
                final String response = EntityUtils.toString(entity);
                if (_log.isDebugEnabled()) {
                    _log.debug("Response String for aborting jobs " + uuids + " is " + response);
                }
            }
        } catch (ParseException | IOException e) {
            throw new JobClientException(
                    "Can not parse the response for DELETE request " + params + " via uri " + _jobURI, e);
        } finally {
            httpRequest.releaseConnection();
        }
    }
}

From source file:com.twosigma.cook.jobclient.JobClient.java

/**
 * Query a collection of groups for their status.
 * @param guuids specifies the uuids of the {@link Group}s to be queried.
 * @return a map of {@link UUID}s to {@link Group}s.
 * @throws JobClientException//from  www  .  j a  va 2  s.  c  o  m
 */
public ImmutableMap<UUID, Group> queryGroups(Collection<UUID> guuids) throws JobClientException {
    if (_groupURI == null) {
        throw groupEndpointMissingException("Cannot query groups if the jobclient's group endpoint is null");
    }
    final List<NameValuePair> allParams = new ArrayList<NameValuePair>(guuids.size());
    for (UUID guuid : guuids) {
        allParams.add(new BasicNameValuePair("uuid", guuid.toString()));
    }
    allParams.add(new BasicNameValuePair("detailed", "true"));
    final ImmutableMap.Builder<UUID, Group> UUIDToGroup = ImmutableMap.builder();
    // Partition a large query into small queries.
    for (final List<NameValuePair> params : Lists.partition(allParams, _batchRequestSize)) {
        HttpResponse httpResponse;
        HttpRequestBase httpRequest;
        try {
            URIBuilder uriBuilder = new URIBuilder(_groupURI);
            uriBuilder.addParameters(params);
            httpRequest = new HttpGet(uriBuilder.build());
            httpResponse = _httpClient.execute(httpRequest);
        } catch (IOException | URISyntaxException e) {
            throw releaseAndCreateException(null, null,
                    "Can not submit GET request " + params + " via uri " + _jobURI, e);
        }
        // Check status code.
        final StatusLine statusLine = httpResponse.getStatusLine();
        // Base on the decision graph
        // http://clojure-liberator.github.io/liberator/tutorial/decision-graph.html
        // The status code for the proper GET response is 200.
        if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
            throw releaseAndCreateException(httpRequest, httpResponse,
                    "The response of GET request " + params + " via uri " + _jobURI + ": "
                            + statusLine.getReasonPhrase() + ", " + statusLine.getStatusCode(),
                    null);
        }
        // Parse the response.
        String response = null;
        try {
            // parse the response to string.
            final HttpEntity entity = httpResponse.getEntity();
            response = EntityUtils.toString(entity);
            // Ensure that the entity content has been fully consumed and the underlying stream has been closed.
            EntityUtils.consume(entity);
            for (Group group : Group.parseFromJSON(response, _instanceDecorator)) {
                UUIDToGroup.put(group.getUUID(), group);
            }
        } catch (JSONException | ParseException | IOException e) {
            throw new JobClientException("Can not parse the response = " + response + " for GET request "
                    + params + " via uri " + _jobURI, e);
        } finally {
            httpRequest.releaseConnection();
        }
    }
    return UUIDToGroup.build();

}

From source file:pt.meocloud.sdk.MeoCloudImpl.java

private Response performRequest(Boolean content, String method, String aditionalPath,
        List<NameValuePair> parameters, Verb verb, boolean supportsMode) {
    try {/*from w  ww. j  av a 2  s .  c  o  m*/
        String path = String.format("/%s/%s", MEOCLOUD_API_VERSION, method);
        if (supportsMode)
            path = String.format("%s/%s", path, apiMode.getCode());
        if (aditionalPath != null)
            path = String.format("%s%s", path, aditionalPath);
        URIBuilder builder = new URIBuilder();
        builder.setScheme(MEOCLOUD_SCHEME);
        builder.setHost(content ? MEOCLOUD_API_CONTENT_ENDPOINT : MEOCLOUD_API_ENDPOINT);
        builder.setPath(path);
        if (verb == Verb.GET && parameters != null && parameters.size() > 0)
            builder.addParameters(parameters);
        String url = builder.build().toString();
        OAuthRequest request = new OAuthRequest(verb, url);
        if (verb == Verb.POST && parameters != null) {
            for (NameValuePair parameter : parameters) {
                request.addBodyParameter(parameter.getName(), parameter.getValue());
            }
        }
        service.signRequest(token, request);
        Response response = request.send();
        log.debug("Requested MeoCloudApi: {}", url);
        log.debug("Response code: {}", response.getCode());
        return response;
    } catch (URISyntaxException e) {
        log.error("Error generating url.", e);
    }
    return null;
}

From source file:eu.esdihumboldt.hale.io.gml.reader.internal.wfs.WfsBackedGmlInstanceCollection.java

/**
 * Create a GML instance collection based on the given WFS source.
 * /*from  ww  w . ja v a  2 s  . co m*/
 * @param source the source
 * @param sourceSchema the source schema
 * @param restrictToFeatures if only instances that are GML features shall
 *            be loaded
 * @param ignoreRoot if the root element should be ignored for creating
 *            instances even if it is recognized as an allowed instance type
 * @param strict if associating elements with properties should be done
 *            strictly according to the schema, otherwise a fall-back is
 *            used trying to populate values also on invalid property paths
 * @param ignoreNamespaces if parsing of the XML instances should allow
 *            types and properties with namespaces that differ from those
 *            defined in the schema
 * @param crsProvider CRS provider in case no CRS is specified, may be
 *            <code>null</code>
 * @param provider the I/O provider to get values
 * @param featuresPerRequest Number of features to retrieve at most with one
 *            WFS GetFeature request, or {@value #UNLIMITED} to disable
 *            pagination
 * @throws URISyntaxException thrown if the WFS request URL cannot be
 *             generated from the source location URI
 */
public WfsBackedGmlInstanceCollection(LocatableInputSupplier<? extends InputStream> source,
        TypeIndex sourceSchema, boolean restrictToFeatures, boolean ignoreRoot, boolean strict,
        boolean ignoreNamespaces, CRSProvider crsProvider, IOProvider provider, int featuresPerRequest)
        throws URISyntaxException {

    this.sourceSchema = sourceSchema;
    this.restrictToFeatures = restrictToFeatures;
    this.ignoreRoot = ignoreRoot;
    this.strict = strict;
    this.crsProvider = crsProvider;
    this.ignoreNamespaces = ignoreNamespaces;
    this.ioProvider = provider;

    this.primordialUri = source.getLocation();

    // Build base URI from original location by removing STARTINDEX and
    // MAXFEATURES/COUNT parameters if present
    URIBuilder builder = new URIBuilder(primordialUri);
    builder.getQueryParams()
            .forEach(qp -> primordialQueryParams.put(qp.getName().toUpperCase(), qp.getValue()));

    wfsVersion = primordialQueryParams.get("VERSION");
    if (wfsVersion == null || wfsVersion.isEmpty()) {
        throw new IllegalArgumentException("WFS URL must contain VERSION parameter");
    }

    List<NameValuePair> params = builder.getQueryParams();
    params.removeIf(nvp -> nvp.getName().equalsIgnoreCase("STARTINDEX"));
    params.removeIf(nvp -> nvp.getName().equalsIgnoreCase(getMaxFeaturesParameterName(wfsVersion)));
    builder.clearParameters();
    builder.addParameters(params);
    this.baseUri = builder.build();

    // If a MAXFEATURES/COUNT parameter is present in the primordial URI,
    // set maxNumberOfFeatures accordingly
    if (primordialQueryParams.containsKey(getMaxFeaturesParameterName(wfsVersion))) {
        // Allow possible NumberFormatException to be thrown up to prevent
        // unintended retrieval of too many features
        maxNumberOfFeatures = Integer
                .parseInt(primordialQueryParams.get(getMaxFeaturesParameterName(wfsVersion)));

        if (maxNumberOfFeatures < 0) {
            throw new IllegalArgumentException(
                    MessageFormat.format("Parameter \"{0}\" must be a non-negative integer.",
                            getMaxFeaturesParameterName(wfsVersion)));
        }
    }

    // Use primordial URI and issue "hits" request to check if the WFS will
    // return anything at all
    int hits;
    try {
        hits = requestHits(primordialUri);
    } catch (WFSException e) {
        log.debug(MessageFormat.format("Failed to perform hits query (REQUESTTYPE=hits): {0}", e.getMessage()),
                e);
        hits = UNKNOWN_SIZE;
    }

    switch (wfsVersion) {
    case "1.1.0":
        // The "numberOfFeatures" reported by a 1.1.0 WFS may be smaller
        // than the actual number of features matches by the query if the
        // number of features returned per query is limited on the server
        // side. Therefore do not rely on it as a size information here.
        this.size = UNKNOWN_SIZE;
        break;
    case "2.0.0":
    case "2.0.2":
        // The "numberMatched" reported by a 2.0.0/2.0.2 WFS should be
        // number of features matched by the query. If hits equals
        // UNKNOWN_SIZE then size is also set to that value
        this.size = isLimited() ? Math.min(maxNumberOfFeatures, hits) : hits;
        break;
    default:
        this.size = UNKNOWN_SIZE;
    }

    if (featuresPerRequest != UNLIMITED && featuresPerRequest <= 0) {
        throw new IllegalArgumentException(MessageFormat.format(
                "featuresPerRequest must be a positive integer or {0} to disable pagination", UNLIMITED));
    }
    this.featuresPerRequest = featuresPerRequest;
}

From source file:org.codice.ddf.security.servlet.logout.LocalLogoutServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setHeader("Cache-Control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("text/html");

    URIBuilder redirectUrlBuilder = null;
    List<NameValuePair> params = new ArrayList<>();

    try {/*from  w  ww  .  jav  a2s .com*/
        redirectUrlBuilder = new URIBuilder("/logout/logout-response.html");

        HttpSession session = request.getSession();
        if (session != null) {
            SecurityTokenHolder savedToken = (SecurityTokenHolder) session
                    .getAttribute(SecurityConstants.SAML_ASSERTION);
            if (savedToken != null) {
                Subject subject = ThreadContext.getSubject();
                boolean hasSecurityAuditRole = Arrays
                        .stream(System.getProperty("security.audit.roles").split(","))
                        .anyMatch(subject::hasRole);
                if (hasSecurityAuditRole) {
                    SecurityLogger.audit("Subject with admin privileges has logged out", subject);
                }

                savedToken.removeAll();
            }
            session.invalidate();
            deleteJSessionId(response);
        }

        //Check for pki
        if (request.getAttribute("javax.servlet.request.X509Certificate") != null
                && ((X509Certificate[]) request
                        .getAttribute("javax.servlet.request.X509Certificate")).length > 0) {
            params.add(new BasicNameValuePair("msg", "Please close your browser to finish logging out"));
        }

        //Check for basic
        Enumeration authHeaders = request.getHeaders(javax.ws.rs.core.HttpHeaders.AUTHORIZATION);
        while (authHeaders.hasMoreElements()) {
            if (((String) authHeaders.nextElement()).contains("Basic")) {
                params.add(new BasicNameValuePair("msg", "Please close your browser to finish logging out"));
                break;
            }
        }
        redirectUrlBuilder.addParameters(params);
        response.sendRedirect(redirectUrlBuilder.build().toString());
    } catch (URISyntaxException e) {
        LOGGER.debug("Invalid URI", e);
    }
}

From source file:org.codice.ddf.catalog.content.resource.reader.DerivedContentActionProvider.java

@Override
public <T> List<Action> getActions(T input) {
    if (!canHandle(input)) {
        return Collections.emptyList();
    }/*from  www .  j  a  va  2s .  c o m*/
    // Expect only 1
    List<Action> resourceActions = resourceActionProvider.getActions(input);
    if (resourceActions.isEmpty()) {
        return Collections.emptyList();
    }

    return ((Metacard) input).getAttribute(Metacard.DERIVED_RESOURCE_URI).getValues().stream().map(value -> {
        try {
            URI uri = new URI(value.toString());
            URIBuilder builder = new URIBuilder(resourceActions.get(0).getUrl().toURI());
            if (StringUtils.equals(uri.getScheme(), ContentItem.CONTENT_SCHEME)) {
                String qualifier = uri.getFragment();

                builder.addParameters(
                        Collections.singletonList(new BasicNameValuePair(ContentItem.QUALIFIER, qualifier)));
                return Optional.of(new ActionImpl(ID, "View " + qualifier, DESCRIPTION_PREFIX + qualifier,
                        builder.build().toURL()));
            } else {
                return Optional.of(new ActionImpl(ID, "View " + uri.toString(),
                        DESCRIPTION_PREFIX + uri.toString(), uri.toURL()));
            }
        } catch (URISyntaxException | MalformedURLException e) {
            LOGGER.debug("Unable to create action URL.", e);
            return Optional.<Action>empty();
        }
    }).filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
}

From source file:org.opennms.protocols.http.HttpUrlConnection.java

@Override
public InputStream getInputStream() throws IOException {
    try {/*w  ww .ja va 2s .  co  m*/
        if (m_clientWrapper == null) {
            connect();
        }

        // Build URL
        int port = m_url.getPort() > 0 ? m_url.getPort() : m_url.getDefaultPort();
        URIBuilder ub = new URIBuilder();
        ub.setPort(port);
        ub.setScheme(m_url.getProtocol());
        ub.setHost(m_url.getHost());
        ub.setPath(m_url.getPath());
        if (m_url.getQuery() != null && !m_url.getQuery().trim().isEmpty()) {
            final List<NameValuePair> params = URLEncodedUtils.parse(m_url.getQuery(),
                    Charset.forName("UTF-8"));
            if (!params.isEmpty()) {
                ub.addParameters(params);
            }
        }

        // Build Request
        HttpRequestBase request = null;
        if (m_request != null && m_request.getMethod().equalsIgnoreCase("post")) {
            final Content cnt = m_request.getContent();
            HttpPost post = new HttpPost(ub.build());
            ContentType contentType = ContentType.create(cnt.getType());
            LOG.info("Processing POST request for {}", contentType);
            if (contentType.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
                FormFields fields = JaxbUtils.unmarshal(FormFields.class, cnt.getData());
                post.setEntity(fields.getEntity());
            } else {
                StringEntity entity = new StringEntity(cnt.getData(), contentType);
                post.setEntity(entity);
            }
            request = post;
        } else {
            request = new HttpGet(ub.build());
        }

        if (m_request != null) {
            // Add Custom Headers
            for (final Header header : m_request.getHeaders()) {
                request.addHeader(header.getName(), header.getValue());
            }
        }

        // Get Response
        CloseableHttpResponse response = m_clientWrapper.execute(request);
        return response.getEntity().getContent();
    } catch (Exception e) {
        throw new IOException(
                "Can't retrieve " + m_url.getPath() + " from " + m_url.getHost() + " because " + e.getMessage(),
                e);
    }
}