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

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

Introduction

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

Prototype

@Override
    public String toString() 

Source Link

Usage

From source file:com.munichtrading.tracking.camera.APIIPCamera.java

private boolean getSettings() {
    try {/*from  ww  w .j a  v a2s.c o  m*/
        URIBuilder builder = new URIBuilder().setScheme("http").setHost(this.device.getHostName())
                .setPath("/parameters");
        HttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet(builder.build());
        request.addHeader("User-Agent", USER_AGENT);
        HttpResponse response = client.execute(request);
        logger.info("Sending request: " + builder.toString());
        logger.info("Response Code  : " + response.getStatusLine().getStatusCode());
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        this.updateSettings(result.toString());
    } catch (Exception e) {
        return false;
    }
    return true;
}

From source file:com.hp.octane.integrations.services.coverage.SonarServiceImpl.java

@Override
public synchronized void ensureSonarWebhookExist(String ciCallbackUrl, String sonarURL, String sonarToken)
        throws SonarIntegrationException {
    //problem in sonar project key in new project
    try {//from ww w.  j  a  va  2 s.com
        String webhookKey = getWebhookKey(ciCallbackUrl, sonarURL, sonarToken);
        if (webhookKey == null) {
            HttpClient httpClient = HttpClientBuilder.create().build();

            URIBuilder uriBuilder = new URIBuilder(sonarURL + WEBHOOK_CREATE_URI)
                    .setParameter("name", "ci_" + configurer.octaneConfiguration.getInstanceId())
                    .setParameter("url", ciCallbackUrl);

            HttpPost request = new HttpPost(uriBuilder.toString());
            setTokenInHttpRequest(request, sonarToken);
            HttpResponse response = httpClient.execute(request);

            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                // error can sometimes return empty results
                String errorMessage = "exception during webhook registration for  ciNotificationUrl: "
                        .concat(ciCallbackUrl).concat(" with status code: ")
                        .concat(String.valueOf(response.getStatusLine().getStatusCode()));
                throw new SonarIntegrationException(errorMessage);
            }
        }

    } catch (SonarIntegrationException e) {
        logger.error(e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        String errorMessage = "exception during webhook registration for ciNotificationUrl: " + ciCallbackUrl;
        logger.error(errorMessage, e);
        throw new SonarIntegrationException(errorMessage, e);
    }
}

From source file:com.munichtrading.tracking.camera.APIIPCamera.java

private void sendGet(String parameter, String value) {
    try {/*from ww  w  .ja v a  2 s . c  o  m*/
        URIBuilder builder = new URIBuilder().setScheme("http").setHost(this.device.getHostName())
                .setPath("/parameters").addParameter(parameter, value);

        HttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet(builder.build());
        request.addHeader("User-Agent", USER_AGENT);
        HttpResponse response = client.execute(request);

        logger.info("Sending request: " + builder.toString());
        logger.info("Response Code  : " + response.getStatusLine().getStatusCode());

        if (response.getStatusLine().getStatusCode() == 200) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            this.updateSettings(result.toString());
        } else {
            throw new Exception("Request unsuccessfull");
        }
    } catch (HttpHostConnectException e) {
        logger.error("Could not connect to device");
    } catch (Exception e) {
        logger.error("Something went wrong");
    }
}

From source file:org.mitre.oauth2.web.OAuthConfirmationController.java

@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping("/oauth/confirm_access")
public String confimAccess(Map<String, Object> model,
        @ModelAttribute("authorizationRequest") AuthorizationRequest authRequest, Principal p) {

    // Check the "prompt" parameter to see if we need to do special processing

    String prompt = (String) authRequest.getExtensions().get(PROMPT);
    List<String> prompts = Splitter.on(PROMPT_SEPARATOR).splitToList(Strings.nullToEmpty(prompt));
    ClientDetailsEntity client = null;/*from   w  w w.j  a va2 s . c o  m*/

    try {
        client = clientService.loadClientByClientId(authRequest.getClientId());
    } catch (OAuth2Exception e) {
        logger.error("confirmAccess: OAuth2Exception was thrown when attempting to load client", e);
        model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
        return HttpCodeView.VIEWNAME;
    } catch (IllegalArgumentException e) {
        logger.error("confirmAccess: IllegalArgumentException was thrown when attempting to load client", e);
        model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
        return HttpCodeView.VIEWNAME;
    }

    if (client == null) {
        logger.error("confirmAccess: could not find client " + authRequest.getClientId());
        model.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        return HttpCodeView.VIEWNAME;
    }

    if (prompts.contains("none")) {
        // if we've got a redirect URI then we'll send it

        String url = redirectResolver.resolveRedirect(authRequest.getRedirectUri(), client);

        try {
            URIBuilder uriBuilder = new URIBuilder(url);

            uriBuilder.addParameter("error", "interaction_required");
            if (!Strings.isNullOrEmpty(authRequest.getState())) {
                uriBuilder.addParameter("state", authRequest.getState()); // copy the state parameter if one was given
            }

            return "redirect:" + uriBuilder.toString();

        } catch (URISyntaxException e) {
            logger.error("Can't build redirect URI for prompt=none, sending error instead", e);
            model.put("code", HttpStatus.FORBIDDEN);
            return HttpCodeView.VIEWNAME;
        }
    }

    model.put("auth_request", authRequest);
    model.put("client", client);

    String redirect_uri = authRequest.getRedirectUri();

    model.put("redirect_uri", redirect_uri);

    // pre-process the scopes
    Set<SystemScope> scopes = scopeService.fromStrings(authRequest.getScope());

    Set<SystemScope> sortedScopes = new LinkedHashSet<>(scopes.size());
    Set<SystemScope> systemScopes = scopeService.getAll();

    // sort scopes for display based on the inherent order of system scopes
    for (SystemScope s : systemScopes) {
        if (scopes.contains(s)) {
            sortedScopes.add(s);
        }
    }

    // add in any scopes that aren't system scopes to the end of the list
    sortedScopes.addAll(Sets.difference(scopes, systemScopes));

    model.put("scopes", sortedScopes);

    // get the userinfo claims for each scope
    UserInfo user = userInfoService.getByUsername(p.getName());
    Map<String, Map<String, String>> claimsForScopes = new HashMap<>();
    if (user != null) {
        JsonObject userJson = user.toJson();

        for (SystemScope systemScope : sortedScopes) {
            Map<String, String> claimValues = new HashMap<>();

            Set<String> claims = scopeClaimTranslationService.getClaimsForScope(systemScope.getValue());
            for (String claim : claims) {
                if (userJson.has(claim) && userJson.get(claim).isJsonPrimitive()) {
                    // TODO: this skips the address claim
                    claimValues.put(claim, userJson.get(claim).getAsString());
                }
            }

            claimsForScopes.put(systemScope.getValue(), claimValues);
        }
    }

    model.put("claims", claimsForScopes);

    // client stats
    Integer count = statsService.getCountForClientId(client.getId());
    model.put("count", count);

    // contacts
    if (client.getContacts() != null) {
        String contacts = Joiner.on(", ").join(client.getContacts());
        model.put("contacts", contacts);
    }

    // if the client is over a week old and has more than one registration, don't give such a big warning
    // instead, tag as "Generally Recognized As Safe" (gras)
    Date lastWeek = new Date(System.currentTimeMillis() - (60 * 60 * 24 * 7 * 1000));
    if (count > 1 && client.getCreatedAt() != null && client.getCreatedAt().before(lastWeek)) {
        model.put("gras", true);
    } else {
        model.put("gras", false);
    }

    return "approve";
}

From source file:fr.gael.dhus.olingo.v1.V1Processor.java

/** Makes the `next` link for navigation purposes. */
private String makeNextLink(int skip) throws ODataException {
    URI selfLnk = getServiceRoot();
    URIBuilder ub = new URIBuilder(selfLnk);
    ub.setParameter("$skip", String.valueOf(skip));
    return ub.toString();
}

From source file:org.exfio.weave.storage.StorageContext.java

private URI buildCollectionUri(String collection, String[] ids, Double older, Double newer, Integer index_above,
        Integer index_below, Integer limit, Integer offset, String sort, String format, boolean full)
        throws WeaveException {

    URI location = this.storageURL.resolve(URIUtils.sanitize(String.format("storage/%s", collection)));

    //Build list of URL querystring parameters
    List<NameValuePair> params = new LinkedList<NameValuePair>();

    if (ids != null && ids.length > 0) {
        String value = "";
        String delim = "";
        for (int i = 0; i < ids.length; i++) {
            value = value + delim + ids[i];
            delim = ",";
        }/*from   w  ww  .  j a  v a  2 s. c  o  m*/
        params.add(new BasicNameValuePair("ids", value));
    }
    if (older != null) {
        params.add(new BasicNameValuePair("older", String.format("%.2f", older.doubleValue())));
    }
    if (newer != null) {
        params.add(new BasicNameValuePair("newer", String.format("%.2f", newer.doubleValue())));
    }
    if (index_above != null) {
        params.add(new BasicNameValuePair("index_above", index_above.toString()));
    }
    if (index_below != null) {
        params.add(new BasicNameValuePair("index_below", index_below.toString()));
    }
    if (limit != null) {
        params.add(new BasicNameValuePair("limit", limit.toString()));
    }
    if (offset != null) {
        params.add(new BasicNameValuePair("offset", offset.toString()));
    }
    if (sort != null) {
        sort = sort.toLowerCase();
        if (sort.matches("oldest|newest|index")) {
            params.add(new BasicNameValuePair("sort", sort.toString()));
        } else {
            throw new WeaveException(
                    String.format("getCollection() sort parameter value of '%s' not recognised", sort));
        }
    }
    if (format != null) {
        //Only default format supported
        throw new WeaveException(
                String.format("getCollection() format parameter value of '%s' not supported", format));
    }
    if (full) {
        //returns entire WBO
        params.add(new BasicNameValuePair("full", "1"));
    }

    try {
        //FIXME - use URI builder for all uri handling

        //Use URIBuilder to encode query string parameters. java.util.URI DOES NOT correctly handle commas
        URIBuilder uri = new URIBuilder(location);
        if (params.size() > 0) {
            uri.setParameters(params);
        }
        location = new URI(uri.toString());
    } catch (URISyntaxException e) {
        throw new WeaveException(e);
    }

    return location;
}

From source file:com.dawg6.d3api.server.D3IO.java

public Account getAccount(Token token) throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();

    URIBuilder builder = new URIBuilder(ACCOUNT_API_URL);
    builder.addParameter("access_token", token.access_token);

    //      log.info("Request = " + builder.toString());
    HttpGet request = new HttpGet(builder.toString());

    HttpResponse response = client.execute(request);

    if (response.getStatusLine().getStatusCode() != 200) {
        log.log(Level.SEVERE, "HTTP Server Response: " + response.getStatusLine().getStatusCode());
        throw new RuntimeException("HTTP Server Response: " + response.getStatusLine().getStatusCode());
    }/*from w w  w. ja  v a2  s  .  co  m*/

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }

    client.close();

    ObjectMapper mapper = new ObjectMapper();
    mapper = mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    Account account = mapper.readValue(result.toString(), Account.class);

    if ((account != null) && (account.error != null))
        throw new RuntimeException(token.error_description);

    return account;
}

From source file:com.activiti.service.activiti.ActivitiClientService.java

public String getServerUrl(String contextRoot, String restRoot, String serverAddress, Integer port,
        String uri) {//www.  j  a  v  a2  s . c  o m
    String actualContextRoot = null;
    if (contextRoot != null) {
        actualContextRoot = stripSlashes(contextRoot);
    } else {
        actualContextRoot = DEFAULT_ACTIVITI_CONTEXT_ROOT;
    }

    String actualRestRoot = null;
    if (restRoot != null) {
        actualRestRoot = stripSlashes(restRoot);
    } else {
        actualRestRoot = DEFAULT_ACTIVITI_REST_ROOT;
    }

    String finalUrl = serverAddress + ":" + port;
    if (StringUtils.isNotEmpty(actualContextRoot)) {
        finalUrl += "/" + actualContextRoot;
    }

    if (StringUtils.isNotEmpty(actualRestRoot)) {
        finalUrl += "/" + actualRestRoot;
    }

    URIBuilder builder = createUriBuilder(finalUrl + "/" + uri);

    return builder.toString();
}

From source file:org.trendafilov.odesk.notifier.connectivity.RequestHandler.java

private String buildUrl(SearchCriteria criteria) throws ConfigurationException {
    URIBuilder builder = new URIBuilder();
    Configurable config = Configuration.getInstance();
    builder.setScheme(config.getStringValue("api.scheme", "https"))
            .setHost(config.getStringValue("api.host", "www.odesk.com"))
            .setPath(config.getStringValue("api.query.path"))
            .setParameter("page", "0;" + config.getIntValue("api.item.count", 20))
            .setParameter("q", criteria.getQuery()).setParameter("fb", criteria.getClientScore())
            .setParameter("min", criteria.getMinBudget()).setParameter("t", criteria.getJobType())
            .setParameter("wl", criteria.getWorkHours()).setParameter("dur", criteria.getDuration());
    return builder.toString();
}

From source file:org.flowable.admin.service.engine.FlowableClientService.java

public String getServerUrl(String contextRoot, String restRoot, String serverAddress, Integer port,
        String uri) {/* ww w .ja  v  a 2  s.com*/
    String actualContextRoot = null;
    if (contextRoot != null) {
        actualContextRoot = stripSlashes(contextRoot);
    } else {
        actualContextRoot = DEFAULT_FLOWABLE_CONTEXT_ROOT;
    }

    String actualRestRoot = null;
    if (restRoot != null) {
        actualRestRoot = stripSlashes(restRoot);
    } else {
        actualRestRoot = DEFAULT_FLOWABLE_REST_ROOT;
    }

    String finalUrl = serverAddress + ":" + port;
    if (StringUtils.isNotEmpty(actualContextRoot)) {
        finalUrl += "/" + actualContextRoot;
    }

    if (StringUtils.isNotEmpty(actualRestRoot)) {
        finalUrl += "/" + actualRestRoot;
    }

    URIBuilder builder = createUriBuilder(finalUrl + "/" + uri);

    return builder.toString();
}