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.talend.dataprep.api.service.command.preparation.PreparationReorderStep.java

private HttpRequestBase onExecute(final String preparationId, final String stepId, final String parentStepId) {
    try {/*w w  w .  j av  a  2 s . c  o  m*/
        URIBuilder builder = new URIBuilder(
                preparationServiceUrl + "/preparations/" + preparationId + "/steps/" + stepId + "/order");
        if (StringUtils.isNotBlank(parentStepId)) {
            builder.addParameter("parentStepId", parentStepId);
        }
        return new HttpPost(builder.build());
    } catch (URISyntaxException e) {
        throw new TDPException(UNEXPECTED_EXCEPTION, e);
    }
}

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

@Override
public String buildAuthRequestUrl(ServerConfiguration serverConfig, RegisteredClient clientConfig,
        String redirectUri, String nonce, String state, Map<String, String> options, String loginHint) {

    // create our signed JWT for the request object
    JWTClaimsSet.Builder claims = new JWTClaimsSet.Builder();

    //set parameters to JwtClaims
    claims.claim("response_type", "code");
    claims.claim("client_id", clientConfig.getClientId());
    claims.claim("scope", Joiner.on(" ").join(clientConfig.getScope()));

    // build our redirect URI
    claims.claim("redirect_uri", redirectUri);

    // this comes back in the id token
    claims.claim("nonce", nonce);

    // this comes back in the auth request return
    claims.claim("state", state);

    // Optional parameters
    for (Entry<String, String> option : options.entrySet()) {
        claims.claim(option.getKey(), option.getValue());
    }/*  www. ja  v a2 s  . co  m*/

    // if there's a login hint, send it
    if (!Strings.isNullOrEmpty(loginHint)) {
        claims.claim("login_hint", loginHint);
    }

    EncryptedJWT jwt = new EncryptedJWT(new JWEHeader(alg, enc), claims.build());

    JWTEncryptionAndDecryptionService encryptor = encrypterService.getEncrypter(serverConfig.getJwksUri());

    encryptor.encryptJwt(jwt);

    try {
        URIBuilder uriBuilder = new URIBuilder(serverConfig.getAuthorizationEndpointUri());
        uriBuilder.addParameter("request", jwt.serialize());

        // build out the URI
        return uriBuilder.build().toString();
    } catch (URISyntaxException e) {
        throw new AuthenticationServiceException("Malformed Authorization Endpoint Uri", e);
    }
}

From source file:org.aesop.serializer.batch.reader.UserInfoServiceReader.java

/**
 * Returns a number of {@link UserInfo} instances looked up from a service end-point.
 * Note : The end-point and parameters used here are very specific to this sample. Also the code is mostly for testing and production 
 * ready (no Http connection pools etc.) 
 * @see org.trpr.platform.batch.spi.spring.reader.BatchItemStreamReader#batchRead(org.springframework.batch.item.ExecutionContext)
 *//*w w w  . jav a2  s.  c  o  m*/
public UserInfo[] batchRead(ExecutionContext context)
        throws Exception, UnexpectedInputException, ParseException {
    objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    UserInfo[] results = new UserInfo[PHONE_NUMBERS.length];
    for (int i = 0; i < PHONE_NUMBERS.length; i++) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet executionGet = new HttpGet(SERVICE_URL);
        URIBuilder uriBuilder = new URIBuilder(executionGet.getURI());
        uriBuilder.addParameter("primary_phone", PHONE_NUMBERS[i]);
        uriBuilder.addParameter("require", "{\"preferences\":true,\"addresses\":true}");
        ((HttpRequestBase) executionGet).setURI(uriBuilder.build());
        HttpResponse httpResponse = httpclient.execute(executionGet);
        String response = new String(EntityUtils.toByteArray(httpResponse.getEntity()));
        SearchResult searchResult = objectMapper.readValue(response, SearchResult.class);
        results[i] = searchResult.results[0]; // we take only the first result
    }
    return results;
}

From source file:com.epam.ngb.cli.manager.command.handler.http.DatasetListHandler.java

private HttpRequestBase createTreeRequest(Long parentId) {
    try {//from   w  w w .j a  va  2s.  c  om
        URIBuilder builder = new URIBuilder(
                serverParameters.getServerUrl() + serverParameters.getProjectTreeUrl());
        builder.addParameter("parentId", String.valueOf(parentId));

        HttpGet get = new HttpGet(builder.build());
        setDefaultHeader(get);
        if (isSecure()) {
            addAuthorizationToRequest(get);
        }
        return get;
    } catch (URISyntaxException e) {
        throw new ApplicationException(e.getMessage(), e);
    }
}

From source file:it.smartcommunitylab.aac.oauth.ExtOAuth2SuccessHandler.java

protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
        throws IOException, ServletException {

    OAuth2Authentication oauth = (OAuth2Authentication) authentication;
    @SuppressWarnings("unchecked")
    Map<String, Object> details = (Map<String, Object>) oauth.getUserAuthentication().getDetails();
    details = preprocess(details);//w w w  .  ja  va  2 s  . c  o m
    try {
        URIBuilder builder = new URIBuilder(getDefaultTargetUrl());
        for (String key : details.keySet()) {
            builder.addParameter(key, details.get(key).toString());
            request.setAttribute(key, details.get(key));
        }
        request.getRequestDispatcher(builder.build().toString()).forward(request, response);
        //         response.sendRedirect("forward:"+builder.build().toString());
        //         getRedirectStrategy().sendRedirect(request, response, builder.build().toString());
    } catch (URISyntaxException e) {
        throw new ServletException(e.getMessage());
    }
}

From source file:com.intuit.wasabi.export.rest.impl.DefaultRestEndPoint.java

@Override
public URI getRestEndPointURI() {
    URI assignmentURI = null;/*from www  .j  ava2  s .  com*/
    try {
        URIBuilder uriBuilder = new URIBuilder().setScheme(configuration.getScheme())
                .setHost(configuration.getHost()).setPath(configuration.getPath());
        int port = configuration.getPort();
        if (port != 0) {
            uriBuilder.setPort(port);
        }
        assignmentURI = uriBuilder.build();
    } catch (URISyntaxException e) {
        LOGGER.error("URL Syntax Error: ", e);
    }
    return assignmentURI;
}

From source file:com.simple.toadiot.rtinfosdk.http.DefaultRequestHandler.java

private HttpRequestBase buildRequest(HttpMethod method, String path, Map<String, String> headers, Object body,
        Map<String, Object> params) {
    AcceptedMediaType mediaType = AppConfig.getResponseMediaType();

    HttpRequestBase request = null;/*  www  .  j  a  va  2s.c o m*/
    StringEntity entity = getEntity(body);
    switch (method) {
    case DELETE:
        request = new HttpDelete();
        break;
    case GET:
        request = new HttpGet();
        break;
    case POST:
        request = new HttpPost();
        if (entity != null) {
            ((HttpPost) request).setEntity(entity);
        }
        break;
    case PUT:
        request = new HttpPut();
        if (entity != null) {
            ((HttpPut) request).setEntity(entity);
        }
        break;
    default:
        return null;
    }

    try {
        if (!path.toLowerCase(Locale.ENGLISH).startsWith("http")) {
            URIBuilder uriBuilder = buildUri(method, path, params, mediaType);
            request.setURI(uriBuilder.build());
        } else {
            request.setURI(new URI(path));
        }
    } catch (URISyntaxException e) {
        throw new RequestInvalidException("Invalid URI requested.", e);
    }
    //      request.addHeader("accept", mediaType.getMediaType());
    //      request.addHeader(HEADER_KEY_API, AppConfig.getInstance().getApiKey());
    //      request.addHeader(HEADER_USER_AGENT, XIVELY_USER_AGENT);
    /**
     *  Header
     */
    request.addHeader("Content-Type", mediaType.getMediaType() + ";charset=" + AppConfig.getCharset());
    if (headers != null && !headers.isEmpty()) {
        int index = 0;
        Header[] header = new Header[headers.size()];
        for (Entry<String, String> element : headers.entrySet()) {
            header[index++] = new BasicHeader(element.getKey(), element.getValue());
        }
        request.setHeaders(header);
    }
    //      if (params != null && !params.isEmpty()) {
    //         HttpParams hparams = new SyncBasicHttpParams();
    //         for (Entry<String, Object> param : params.entrySet()) {
    //            hparams.setParameter(param.getKey(), param.getValue());
    //         }
    //         request.setParams(hparams);
    //      }
    return request;
}

From source file:org.cloudcrawler.domain.crawler.robotstxt.RobotsTxtService.java

/**
 * This method is used to evaluate if the provided uri is
 * allowed to be crawled against the robots.txt of the website.
 *
 * @param uri/*from   w  ww . j  a  v a 2  s  . c  om*/
 * @return
 * @throws Exception
 */
public boolean isAllowedUri(URI uri) throws Exception {
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme(uri.getScheme());
    uriBuilder.setHost(uri.getHost());
    uriBuilder.setUserInfo(uri.getUserInfo());
    uriBuilder.setPath("/robots.txt");

    URI robotsTxtUri = uriBuilder.build();
    BaseRobotRules rules = (BaseRobotRules) cache.get(robotsTxtUri.toString());

    if (rules == null) {
        HttpResponse response = httpService.get(robotsTxtUri);

        try {

            // HACK! DANGER! Some sites will redirect the request to the top-level domain
            // page, without returning a 404. So look for a response which has a redirect,
            // and the fetched content is not plain text, and assume it's one of these...
            // which is the same as not having a robotstxt.txt file.

            String contentType = response.getEntity().getContentType().getValue();
            boolean isPlainText = (contentType != null) && (contentType.startsWith("text/plain"));

            if (response.getStatusLine().getStatusCode() == 404 || !isPlainText) {
                rules = robotsTxtParser.failedFetch(HttpStatus.SC_GONE);
            } else {
                StringWriter writer = new StringWriter();

                IOUtils.copy(response.getEntity().getContent(), writer);

                rules = robotsTxtParser.parseContent(uri.toString(), writer.toString().getBytes(),
                        response.getEntity().getContentType().getValue(), httpService.getUserAgent());

            }
        } catch (Exception e) {
            EntityUtils.consume(response.getEntity());
            throw e;
        }

        EntityUtils.consume(response.getEntity());
        cache.set(robotsTxtUri.toString(), 60 * 60 * 24, rules);
    }

    return rules.isAllowed(uri.toString());
}

From source file:org.talend.dataprep.api.service.command.folder.FolderDataSetList.java

private HttpRequestBase onExecute(String sort, String order, String folder) {
    try {/*from w ww .  j a  va  2s.  c om*/
        URIBuilder uriBuilder = new URIBuilder(datasetServiceUrl + "/folders/datasets");
        uriBuilder.addParameter("sort", sort);
        uriBuilder.addParameter("order", order);
        if (StringUtils.isNotEmpty(folder)) {
            uriBuilder.addParameter("folder", folder);
        }
        return new HttpGet(uriBuilder.build());
    } catch (URISyntaxException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }
}

From source file:eu.fthevenet.util.github.GithubApi.java

/**
 * Returns a list of all release from the specified repository.
 *
 * @param owner the repository's owner// ww w .j a va 2s  .  co  m
 * @param repo  the repository's name
 * @return a list of all release from the specified repository.
 * @throws IOException        if an IO error occurs while communicating with GitHub.
 * @throws URISyntaxException if the crafted URI is incorrect.
 */
public List<GithubRelease> getAllReleases(String owner, String repo) throws IOException, URISyntaxException {
    URIBuilder requestUrl = new URIBuilder().setScheme(URL_PROTOCOL).setHost(GITHUB_API_HOSTNAME)
            .setPath("/repos/" + owner + "/" + repo + "/releases");

    logger.debug(() -> "requestUrl = " + requestUrl);
    HttpGet httpget = new HttpGet(requestUrl.build());
    return httpClient.execute(httpget, new AbstractResponseHandler<List<GithubRelease>>() {
        @Override
        public List<GithubRelease> handleEntity(HttpEntity entity) throws IOException {
            return gson.fromJson(EntityUtils.toString(entity), new TypeToken<ArrayList<GithubRelease>>() {
            }.getType());
        }
    });
}