protected String adjustURIForPort(String uri) throws URISyntaxException { URI metadataURI = new URI(uri); if (metadataURI.getPort() < 0) { switch (metadataURI.getScheme()) { case "https": return new URIBuilder(uri).setPort(443).build().toString(); case "http": return new URIBuilder(uri).setPort(80).build().toString(); default: return uri; } } return uri; }
public CompletableFuture<ClusterStateSimpleEntity> fetchClusterMode(String app, String ip, int port) { if (StringUtil.isBlank(ip) || port <= 0) { return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter")); } try { URIBuilder uriBuilder = new URIBuilder(); uriBuilder.setScheme("http").setHost(ip).setPort(port) .setPath(FETCH_CLUSTER_MODE_PATH); return executeCommand(FETCH_CLUSTER_MODE_PATH, uriBuilder.build()) .thenApply(r -> JSON.parseObject(r, ClusterStateSimpleEntity.class)); } catch (Exception ex) { logger.warn("Error when fetching cluster mode", ex); return AsyncUtils.newFailedFuture(ex); } }
public static String addPaginationParam(String url, String paginationParamName, Integer pageNumber) { try { if (pageNumber > 1) { return new URIBuilder(url).addParameter(paginationParamName, String.valueOf(pageNumber)).build().toString(); } } catch (URISyntaxException e) { // If we run into trouble, do nothing - we'll just return the url that we were given. } return url; }
public static String urlWithQuery(String oldUrl, String paramName, String paramValue) throws URISyntaxException { URIBuilder uriBuilder = new URIBuilder(oldUrl); uriBuilder.addParameter(paramName, paramValue); return uriBuilder.toString(); }
URIBuilder builder = new URIBuilder(); builder.setScheme("http").setHost(host).setPort(port).setPath(restPath + taskUri + "/" + taskId) .setParameter("parts", "all") .setParameter("params", routingOptionsJson) .setParameter("action", "finish"); HttpPost post = getHttpPostMethod(builder.build());
URIBuilder b = new URIBuilder("http://example.com"); b.addParameter("t", "search"); b.addParameter("q", "apples"); Url url = b.build().toUrl();
@Test public void shouldReturnResponseByMatchingStringBody() throws IOException, URISyntaxException { // when getMockServerClient() .when( request() .withBody( exact("some_random_body") ), Times.exactly(2) ) .respond( response() .withBody("some_string_body_response") ); // then HttpClient httpClient = createHttpClient(); HttpPost request = new HttpPost( new URIBuilder() .setScheme("http") .setHost("localhost") .setPort(getServerPort()) .setPath(addContextToPath("some_path")) .build() ); request.setEntity(new StringEntity("some_random_body")); HttpResponse response = httpClient.execute(request); assertThat(new String(EntityUtils.toByteArray(response.getEntity()), UTF_8), is("some_string_body_response")); assertThat(response.getStatusLine().getStatusCode(), is(OK_200.code())); }
public void destroy() throws AnalyticsServiceException { URIBuilder builder = new URIBuilder(); builder.setScheme(protocol).setHost(hostname).setPort(port).setPath(AnalyticsAPIConstants.ANALYTICS_SERVICE_PROCESSOR_URI); try { HttpPost postMethod = new HttpPost(builder.build().toString()); postMethod.addHeader(AnalyticsAPIConstants.SESSION_ID, sessionId); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair(AnalyticsAPIConstants.OPERATION, AnalyticsAPIConstants.DESTROY_OPERATION)); postMethod.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(postMethod); String response = getResponseString(httpResponse); if (httpResponse.getStatusLine().getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) { throw new AnalyticsServiceUnauthorizedException("Unable to destroy the process . " + response); } else if (httpResponse.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) { throw new AnalyticsServiceException("Unable to destroy the process . " + response); } } catch (URISyntaxException e) { throw new AnalyticsServiceAuthenticationException("Malformed URL provided. " + e.getMessage(), e); } catch (IOException e) { throw new AnalyticsServiceAuthenticationException("Error while connecting to the remote service. " + e.getMessage(), e); } }
builder.setMaxConnTotal(100); CloseableHttpClient httpclient = builder.build(); URI uri = new URIBuilder(url).build(); RequestConfig config = custom().setConnectTimeout(timeout) .setConnectionRequestTimeout(timeout) .setSocketTimeout(timeout) .build(); HttpGet httpGet = new HttpGet(uri); HttpClientContext context = HttpClientContext.create(); context.setRequestConfig(config); CloseableHttpResponse response = httpclient.execute(httpGet, context); try { int statusCode = response.getStatusLine().getStatusCode(); long end = System.currentTimeMillis(); long cost = end - start; } else { String errorMsg = EntityUtils.toString(response.getEntity()); throw new RuntimeException("requestGet remote error, url=" + uri.toString() + ", code=" + statusCode + ", error msg=" + errorMsg); httpGet.releaseConnection();
/** * Calls API of lucene-geo-gazetteer to search location name in gazetteer. * @param locations List of locations to be searched in gazetteer * @return Map of input location strings to gazetteer locations */ public Map<String, List<Location>> getLocations(List<String> locations){ HttpClient httpClient = new DefaultHttpClient(); try { URIBuilder uri = new URIBuilder(url+SEARCH_API); for(String loc: locations){ uri.addParameter(SEARCH_PARAM, loc); } HttpGet httpGet = new HttpGet(uri.build()); HttpResponse resp = httpClient.execute(httpGet); String respJson = IOUtils.toString(resp.getEntity().getContent(), Charsets.UTF_8); @SuppressWarnings("serial") Type typeDef = new TypeToken<Map<String, List<Location>>>(){}.getType(); return new Gson().fromJson(respJson, typeDef); } catch (Exception e) { LOG.error(e.getMessage(), e); } return null; }
HttpGet request = new HttpGet( new URIBuilder() .setScheme("http") .setHost("localhost") .setPort(getServerPort()) .setPath(addContextToPath("some_path")) .build() ); HttpResponse response = httpClient.execute(request); assertThat(new String(EntityUtils.toByteArray(response.getEntity()), UTF_8), is("some_body")); assertThat(response.getStatusLine().getStatusCode(), is(OK_200.code())); request = new HttpGet( new URIBuilder() .setScheme("http") .setHost("localhost") .setPort(getServerPort()) .setPath(addContextToPath("some_path")) .build() ); response = httpClient.execute(request); assertThat(new String(EntityUtils.toByteArray(response.getEntity()), UTF_8), is(""));
@SuppressWarnings("unchecked") public List<String> listRecordStoreNames() { URIBuilder builder = new URIBuilder(); builder.setScheme(protocol).setHost(hostname).setPort(port).setPath(AnalyticsAPIConstants.ANALYTIC_RECORD_STORE_PROCESSOR_SERVICE_URI) .addParameter(AnalyticsAPIConstants.OPERATION, AnalyticsAPIConstants.LIST_RECORD_STORES_OPERATION); try { HttpGet getMethod = new HttpGet(builder.build().toString()); getMethod.addHeader(AnalyticsAPIConstants.SESSION_ID, sessionId); HttpResponse httpResponse = httpClient.execute(getMethod); if (httpResponse.getStatusLine().getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) { String response = getResponseString(httpResponse); throw new AnalyticsServiceUnauthorizedException("Unable to list the record stores." + response); } else if (httpResponse.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) { String response = getResponseString(httpResponse); throw new AnalyticsServiceException("Unable to list the record stores." + response); } else { Object listOfRecordStores = GenericUtils.deserializeObject(httpResponse.getEntity().getContent()); EntityUtils.consumeQuietly(httpResponse.getEntity()); if (listOfRecordStores != null && listOfRecordStores instanceof List) {
/** * Workaround for users with Fitbit user profile set to other other than en_US. Due * to the many variations in responses, this client is only compatible handling * en_US values. * * @see Fitbit#restoreLocale * * @return true if successful */ public boolean enableLocaleOverride( ) { try { URIBuilder builder = new URIBuilder( I18N_URL ); builder.addParameter( "locale", "en_US" ); HttpGet get = new HttpGet( builder.build( ).toURL( ).toString( ) ); String result = EntityUtils.toString( this.getHttpClient( ).execute( get ).getEntity( ) ).trim( ); return result.contains("Succeeded" ); } catch( Exception e ) { throw new FitbitExecutionException( e ); } }
URIBuilder builder = new URIBuilder().setScheme(scheme).setHost(host).setPort(port); builder.setPath(path); try { LOG.debug("About to issue a GET to {}", builder); HttpGet httpget = new HttpGet(builder.build()); String responseBody; responseBody = httpclient.execute(httpget, GETStringResponseHandler.getInstance()); returnValue = responseBody; } catch (Exception e) {
private static String buildUrl(String path, List<NameValuePair> qparams) throws RestApiClientException { URIBuilder builder = new URIBuilder(); builder.setPath(path); ListIterator<NameValuePair> i = qparams.listIterator(); while (i.hasNext()) { NameValuePair keyValue = i.next(); builder.setParameter(keyValue.getName(), keyValue.getValue()); } URI uri; try { uri = builder.build(); } catch (Exception e) { throw new RestApiClientException("Failed to build url; error - " + e.getMessage(), e); } return new HttpGet(uri).getURI().toString(); }
public void sparqlSelectQuery(String queryStr, ResultSetConsumer consumer) throws RDFServiceException { //QueryEngineHTTP qh = new QueryEngineHTTP(readEndpointURI, queryStr); try { HttpGet meth = new HttpGet(new URIBuilder(readEndpointURI).addParameter("query", queryStr).build()); meth.addHeader("Accept", "application/sparql-results+xml"); HttpContext context = getContext(meth); HttpResponse response = context != null ? httpClient.execute(meth, context) : httpClient.execute(meth); try { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode > 399) { log.error("response " + statusCode + " to query. \n"); log.debug("update string: \n" + queryStr); throw new RDFServiceException("Unable to perform SPARQL UPDATE"); } try (InputStream in = response.getEntity().getContent()) { consumer.processResultSet(ResultSetFactory.fromXML(in)); } } finally { EntityUtils.consume(response.getEntity()); } } catch (IOException | URISyntaxException ioe) { throw new RuntimeException(ioe); } }
/** * Adds the fragment to the end of the path and optionally adds an id param depending upon * the value of appendIdToRelativeURI. */ protected String buildRelativeUrlWithParam(String currentUrl, String fragment, String idParam, String idValue) { try { URIBuilder builder = new URIBuilder(currentUrl); builder.setPath(builder.getPath() + "/" + fragment); if (appendIdToRelativeURI) { builder.setParameter(idParam, String.valueOf(idValue)); } return builder.build().toString(); } catch (URISyntaxException e) { return currentUrl; } }
public String getConnectionURI(boolean includeDatabase) throws URISyntaxException { this.setSSLOptions(); URIBuilder uriBuilder = new URIBuilder(); uriBuilder.setScheme("jdbc:mysql"); uriBuilder.setHost(host); uriBuilder.setPort(port); if (database != null && includeDatabase) { uriBuilder.setPath("/" + database); } for (Map.Entry<String, String> jdbcOption : jdbcOptions.entrySet()) { uriBuilder.addParameter(jdbcOption.getKey(), jdbcOption.getValue()); } // added by d8888 2018/09/10, force JDBC to use UTF-8 to support using non-english db, table & column names uriBuilder.addParameter("characterEncoding", "UTF-8"); uriBuilder.addParameter("tinyInt1isBit", "false"); return uriBuilder.build().toString(); }