org.apache.http.client.utils.URIBuilder Java Examples
The following examples show how to use
org.apache.http.client.utils.URIBuilder.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: APIManagerAdapter.java From apimanager-swagger-promote with Apache License 2.0 | 8 votes |
public String getMethodNameForId(String apiId, String methodId) throws AppException { ObjectMapper mapper = new ObjectMapper(); String response = null; URI uri; try { uri = new URIBuilder(CommandParameters.getInstance().getAPIManagerURL()).setPath(RestAPICall.API_VERSION + "/proxies/"+apiId+"/operations/"+methodId).build(); RestAPICall getRequest = new GETRequest(uri, null); HttpResponse httpResponse = getRequest.execute(); response = EntityUtils.toString(httpResponse.getEntity()); EntityUtils.consume(httpResponse.getEntity()); LOG.trace("Response: " + response); JsonNode operationDetails = mapper.readTree(response); if(operationDetails.size()==0) { LOG.warn("No operation with ID: "+methodId+" found for API with id: " + apiId); return null; } return operationDetails.get("name").asText(); } catch (Exception e) { LOG.error("Can't load name for operation with id: "+methodId+" for API: "+apiId+". Can't parse response: " + response); throw new AppException("Can't load name for operation with id: "+methodId+" for API: "+apiId, ErrorCode.API_MANAGER_COMMUNICATION, e); } }
Example #2
Source File: GoogleOauthController.java From Bhadoo-Cloud-Drive with MIT License | 7 votes |
private User getUser(@NotNull Token token) throws IOException, URISyntaxException { URIBuilder builder = new URIBuilder(PROFILE_URL); builder.addParameter("access_token", token.getAccessToken()); HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet httpGet = new HttpGet(builder.build()); org.apache.http.HttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); InputStream inputStream = response.getEntity().getContent(); if (HttpUtilities.success(statusCode)) { User user = gson.fromJson(new InputStreamReader(inputStream), User.class); user.setToken(token); return user; } throw new ApiException(HttpStatus.valueOf(statusCode)); }
Example #3
Source File: PrepMetadataGetContentUrlGenerator.java From data-prep with Apache License 2.0 | 6 votes |
@Override public AsyncExecutionResult generateResultUrl(Object... args) { // check pre-condition Validate.notNull(args); Validate.isTrue(args.length == 2); Validate.isInstanceOf(String.class, args[0]); Validate.isInstanceOf(String.class, args[1]); String preparationId = (String) args[0]; String headId = (String) args[1]; URIBuilder builder = new URIBuilder(); builder.setPath("/api/preparations/" + preparationId + "/metadata"); if (StringUtils.isNotEmpty(headId)) { builder.setParameter("version", headId); } return new AsyncExecutionResult(builder.toString()); }
Example #4
Source File: GoogleOauthController.java From cloud-transfer-backend with MIT License | 6 votes |
private User getUser(@NotNull Token token) throws IOException, URISyntaxException { URIBuilder builder = new URIBuilder(PROFILE_URL); builder.addParameter("access_token", token.getAccessToken()); HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet httpGet = new HttpGet(builder.build()); org.apache.http.HttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); InputStream inputStream = response.getEntity().getContent(); if (HttpUtilities.success(statusCode)) { User user = gson.fromJson(new InputStreamReader(inputStream), User.class); user.setToken(token); return user; } throw new ApiException(HttpStatus.valueOf(statusCode)); }
Example #5
Source File: ResourceAddress.java From org.hl7.fhir.core with Apache License 2.0 | 6 votes |
public static URI buildEndpointUriFromString(String endpointPath) { URI uri = null; try { URIBuilder uriBuilder = new URIBuilder(endpointPath); uri = uriBuilder.build(); String scheme = uri.getScheme(); String host = uri.getHost(); if(!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https")) { throw new EFhirClientException("Scheme must be 'http' or 'https': " + uri); } if(StringUtils.isBlank(host)) { throw new EFhirClientException("host cannot be blank: " + uri); } } catch(URISyntaxException e) { throw new EFhirClientException("Invalid URI", e); } return uri; }
Example #6
Source File: UpdateAPIStatus.java From apimanager-swagger-promote with Apache License 2.0 | 6 votes |
public void updateRetirementDate(APIChangeState changeState) throws AppException { if(changeState!=null && changeState.getNonBreakingChanges().contains("retirementDate")) { // Ignore the retirementDate if desiredState is not deprecated as it's used nowhere if(!desiredState.getState().equals(IAPI.STATE_DEPRECATED)) { LOG.info("Ignoring given retirementDate as API-Status is not set to deprecated"); return; } try { URI uri = new URIBuilder(cmd.getAPIManagerURL()) .setPath(RestAPICall.API_VERSION+"/proxies/"+actualState.getId()+"/deprecate").build(); RestAPICall apiCall = new POSTRequest(new StringEntity("retirementDate="+formatRetirementDate(desiredState.getRetirementDate())), uri, this, true); apiCall.setContentType("application/x-www-form-urlencoded"); apiCall.execute(); } catch (Exception e) { ErrorState.getInstance().setError("Error while updating the retirementDate.", ErrorCode.CANT_UPDATE_API_PROXY); throw new AppException("Error while updating the retirementDate", ErrorCode.CANT_UPDATE_API_PROXY); } } return; }
Example #7
Source File: IntegrationMockClient.java From attic-stratos with Apache License 2.0 | 6 votes |
public boolean terminateInstance(String instanceId) { try { if (log.isDebugEnabled()) { log.debug(String.format("Terminate instance: [instance-id] %s", instanceId)); } URI uri = new URIBuilder(endpoint + INSTANCES_CONTEXT + instanceId).build(); org.apache.stratos.mock.iaas.client.rest.HttpResponse response = doDelete(uri); if (response != null) { if ((response.getStatusCode() >= 200) && (response.getStatusCode() < 300)) { return true; } else { GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); org.apache.stratos.mock.iaas.domain.ErrorResponse errorResponse = gson .fromJson(response.getContent(), org.apache.stratos.mock.iaas.domain.ErrorResponse.class); if (errorResponse != null) { throw new RuntimeException(errorResponse.getErrorMessage()); } } } throw new RuntimeException("An unknown error occurred"); } catch (Exception e) { String message = "Could not start mock instance"; throw new RuntimeException(message, e); } }
Example #8
Source File: PublicServiceValidator.java From halyard with Apache License 2.0 | 6 votes |
@Override public void validate(ConfigProblemSetBuilder p, PublicService n) { String overrideBaseUrl = n.getOverrideBaseUrl(); if (!StringUtils.isEmpty(overrideBaseUrl)) { try { URI uri = new URIBuilder(overrideBaseUrl).build(); if (StringUtils.isEmpty(uri.getScheme())) { p.addProblem(ERROR, "You must supply a URI scheme, e.g. 'http://' or 'https://'"); } if (StringUtils.isEmpty(uri.getHost())) { p.addProblem(ERROR, "You must supply a URI host"); } } catch (URISyntaxException e) { p.addProblem(ERROR, "Invalid base URL: " + e.getMessage()); } } }
Example #9
Source File: ConnectorCommon.java From nextcloud-java-api with GNU General Public License v3.0 | 6 votes |
private URI buildUrl(String subPath, List<NameValuePair> queryParams) { if(serverConfig.getSubpathPrefix()!=null) { subPath = serverConfig.getSubpathPrefix()+"/"+subPath; } URIBuilder uB= new URIBuilder() .setScheme(serverConfig.isUseHTTPS() ? "https" : "http") .setHost(serverConfig.getServerName()) .setPort(serverConfig.getPort()) .setUserInfo(serverConfig.getUserName(), serverConfig.getPassword()) .setPath(subPath); if (queryParams != null) { uB.addParameters(queryParams); } try { return uB.build(); } catch (URISyntaxException e) { throw new NextcloudApiException(e); } }
Example #10
Source File: CmmnTaskService.java From flowable-engine with Apache License 2.0 | 6 votes |
public JsonNode listTasks(ServerConfig serverConfig, ObjectNode bodyNode) { JsonNode resultNode = null; try { URIBuilder builder = clientUtil.createUriBuilder(HISTORIC_TASK_QUERY_URL); String uri = clientUtil.getUriWithPagingAndOrderParameters(builder, bodyNode); HttpPost post = clientUtil.createPost(uri, serverConfig); post.setEntity(clientUtil.createStringEntity(bodyNode.toString())); resultNode = clientUtil.executeRequest(post, serverConfig); } catch (Exception e) { throw new FlowableServiceException(e.getMessage(), e); } return resultNode; }
Example #11
Source File: WebService.java From pentaho-kettle with Apache License 2.0 | 6 votes |
HttpPost getHttpMethod( String vURLService ) throws URISyntaxException { URIBuilder uriBuilder = new URIBuilder( vURLService ); HttpPost vHttpMethod = new HttpPost( uriBuilder.build() ); vHttpMethod.setHeader( "Content-Type", "text/xml;charset=UTF-8" ); String soapAction = "\"" + meta.getOperationNamespace(); if ( !meta.getOperationNamespace().endsWith( "/" ) ) { soapAction += "/"; } soapAction += meta.getOperationName() + "\""; logDetailed( BaseMessages.getString( PKG, "WebServices.Log.UsingRequestHeaderSOAPAction", soapAction ) ); vHttpMethod.setHeader( "SOAPAction", soapAction ); return vHttpMethod; }
Example #12
Source File: UploadApiV2Test.java From packagedrone with Eclipse Public License 1.0 | 6 votes |
@Test public void upload1 () throws URISyntaxException, IOException { final ChannelTester tester = getTester (); final File file = getAbsolutePath ( CommonResources.BUNDLE_1_RESOURCE ); final URIBuilder b = new URIBuilder ( resolve ( "/api/v2/upload/channel/%s/%s", tester.getId (), file.getName () ) ); b.setUserInfo ( "deploy", this.deployKey ); b.addParameter ( "foo:bar", "baz" ); try ( final CloseableHttpResponse response = upload ( b, file ) ) { Assert.assertEquals ( 200, response.getStatusLine ().getStatusCode () ); } final Set<String> arts = tester.getAllArtifactIds (); Assert.assertEquals ( 1, arts.size () ); }
Example #13
Source File: QueryParametersTest.java From gravitee-gateway with Apache License 2.0 | 6 votes |
@Test public void call_get_query_with_special_separator() throws Exception { wireMockRule.stubFor( get(urlPathEqualTo("/team/my_team")) .willReturn( ok() .withBody("{{request.query.q}}") .withTransformers("response-template"))); String query = "from:2016-01-01;to:2016-01-31"; URI target = new URIBuilder("http://localhost:8082/test/my_team") .addParameter("id", "20000047") .addParameter("idType", "1") .addParameter("q", query) .build(); HttpResponse response = Request.Get(target).execute().returnResponse(); assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); String responseContent = StringUtils.copy(response.getEntity().getContent()); assertEquals(query, responseContent); wireMockRule.verify(1, getRequestedFor(urlPathEqualTo("/team/my_team"))); }
Example #14
Source File: AutoUpdateVerifierTest.java From wechatpay-apache-httpclient with Apache License 2.0 | 6 votes |
@Test public void getCertificateTest() throws Exception { URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/certificates"); HttpGet httpGet = new HttpGet(uriBuilder.build()); httpGet.addHeader("Accept", "application/json"); CloseableHttpResponse response1 = httpClient.execute(httpGet); assertEquals(200, response1.getStatusLine().getStatusCode()); try { HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity1); } finally { response1.close(); } }
Example #15
Source File: HttpRequestBuilder.java From gocd with Apache License 2.0 | 6 votes |
public HttpRequestBuilder withPath(String path) { try { URIBuilder uri = new URIBuilder(path); request.setServerName("test.host"); request.setContextPath(CONTEXT_PATH); request.setParameters(splitQuery(uri)); request.setRequestURI(CONTEXT_PATH + uri.getPath()); request.setServletPath(uri.getPath()); if (!uri.getQueryParams().isEmpty()) { request.setQueryString(URLEncodedUtils.format(uri.getQueryParams(), UTF_8)); } return this; } catch (Exception e) { throw new RuntimeException(e); } }
Example #16
Source File: HC4ExchangeFormAuthenticator.java From davmail with GNU General Public License v2.0 | 6 votes |
protected URI getAbsoluteUri(URI uri, String path) throws URISyntaxException { URIBuilder uriBuilder = new URIBuilder(uri); if (path != null) { // reset query string uriBuilder.clearParameters(); if (path.startsWith("/")) { // path is absolute, replace method path uriBuilder.setPath(path); } else if (path.startsWith("http://") || path.startsWith("https://")) { return URI.create(path); } else { // relative path, build new path String currentPath = uri.getPath(); int end = currentPath.lastIndexOf('/'); if (end >= 0) { uriBuilder.setPath(currentPath.substring(0, end + 1) + path); } else { throw new URISyntaxException(uriBuilder.build().toString(), "Invalid path"); } } } return uriBuilder.build(); }
Example #17
Source File: RestClient.java From attic-stratos with Apache License 2.0 | 5 votes |
public boolean undeployEntity(String resourcePath, String entityName) throws Exception { log.info(String.format("Undeploying [entity] %s, [resource-path] %s", entityName, resourcePath)); URI uri = new URIBuilder(this.endPoint + resourcePath).build(); HttpResponse response = doPost(uri, ""); if (response != null) { if ((response.getStatusCode() >= 200) && (response.getStatusCode() < 300)) { return true; } else { throw new RuntimeException(response.getContent()); } } throw new Exception("Null response received. Could not undeploy entity [entity name] " + entityName); }
Example #18
Source File: CaseInstanceService.java From flowable-engine with Apache License 2.0 | 5 votes |
public JsonNode listCaseInstances(ObjectNode bodyNode, ServerConfig serverConfig) { JsonNode resultNode = null; try { URIBuilder builder = new URIBuilder("cmmn-query/historic-case-instances"); String uri = clientUtil.getUriWithPagingAndOrderParameters(builder, bodyNode); HttpPost post = clientUtil.createPost(uri, serverConfig); post.setEntity(clientUtil.createStringEntity(bodyNode.toString())); resultNode = clientUtil.executeRequest(post, serverConfig); } catch (Exception e) { throw new FlowableServiceException(e.getMessage(), e); } return resultNode; }
Example #19
Source File: UserInputTestCase.java From vespa with Apache License 2.0 | 5 votes |
@Test public void testAnnotatedUserInputAccentRemoval() { URIBuilder builder = searchUri(); builder.setParameter("yql", "select * from sources * where [{\"accentDrop\": false}]userInput(\"nalle\");"); Query query = searchAndAssertNoErrors(builder); assertEquals( "select * from sources * where default contains ([{\"accentDrop\": false}]\"nalle\");", query.yqlRepresentation()); }
Example #20
Source File: TaskService.java From activiti6-boot2 with Apache License 2.0 | 5 votes |
public JsonNode getTask(ServerConfig serverConfig, String taskId, boolean runtime) { if(taskId == null) { throw new IllegalArgumentException("Task id is required"); } URIBuilder builder = null; if(runtime) { builder = clientUtil.createUriBuilder(MessageFormat.format(RUNTIME_TASK_URL, taskId)); } else { builder = clientUtil.createUriBuilder(MessageFormat.format(HISTORIC_TASK_URL, taskId)); } HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder)); return clientUtil.executeRequest(get, serverConfig); }
Example #21
Source File: APIManagerAdapter.java From apimanager-swagger-promote with Apache License 2.0 | 5 votes |
public static List<APIAccess> getOrgsApiAccess(String orgId, boolean forceReload) throws AppException { if(!forceReload && orgsApiAccess.containsKey(orgId)) { return orgsApiAccess.get(orgId); } ObjectMapper mapper = new ObjectMapper(); String response = null; URI uri; List<APIAccess> apiAccess; HttpResponse httpResponse = null; try { uri = new URIBuilder(CommandParameters.getInstance().getAPIManagerURL()).setPath(RestAPICall.API_VERSION + "/organizations/"+orgId+"/apis").build(); RestAPICall getRequest = new GETRequest(uri, null, true); httpResponse = getRequest.execute(); response = EntityUtils.toString(httpResponse.getEntity()); apiAccess = mapper.readValue(response, new TypeReference<List<APIAccess>>(){}); orgsApiAccess.put(orgId, apiAccess); return apiAccess; } catch (Exception e) { LOG.error("Error cant read API-Access for org: "+orgId+" from API-Manager. Can't parse response: " + response); throw new AppException("Error cant read API-Access for org: "+orgId+" from API-Manager", ErrorCode.API_MANAGER_COMMUNICATION, e); } finally { try { if(httpResponse!=null) ((CloseableHttpResponse)httpResponse).close(); } catch (Exception ignore) {} } }
Example #22
Source File: VMImpl.java From cs-actions with Apache License 2.0 | 5 votes |
@NotNull public static String createVMURL(NutanixCreateVMInputs nutanixCreateVMInputs) throws Exception { final URIBuilder uriBuilder = getUriBuilder(nutanixCreateVMInputs.getCommonInputs()); StringBuilder pathString = new StringBuilder() .append(API) .append(nutanixCreateVMInputs.getCommonInputs().getAPIVersion()) .append(GET_VM_DETAILS_PATH); uriBuilder.setPath(pathString.toString()); return uriBuilder.build().toURL().toString(); }
Example #23
Source File: PornCrawler.java From WebVideoBot with MIT License | 5 votes |
public Optional<String> getViewkey(WebURL webURL) { try { return new URIBuilder(webURL.getURL()) .getQueryParams() .stream() .filter(param -> param.getName().equalsIgnoreCase("viewkey")) .map(NameValuePair::getValue) .findFirst(); } catch (URISyntaxException e) { logger.error("getViewkey", e); return Optional.empty(); } }
Example #24
Source File: AccessTokenUtil.java From wechat-mp-sdk with Apache License 2.0 | 5 votes |
@Override public String load(License license) throws Exception { URI uri = new URIBuilder(WechatRequest.GET_ACCESS_TOKEN.getUrl()) .setParameter("grant_type", GrantType.CLIENT_CREDENTIAL.getValue()) .setParameter("appid", license.getAppId()) .setParameter("secret", license.getAppSecret()) .build(); log.info("get access token for {}, url = {}", license, uri); String json = Request.Get(uri) .connectTimeout(HttpUtil.CONNECT_TIMEOUT) .socketTimeout(HttpUtil.SOCKET_TIMEOUT) .execute().returnContent().asString(); log.info("get access token for {}, rtn = {}", license, json); AccessTokenJsonRtn rtn = JsonRtnUtil.parseJsonRtn(json, AccessTokenJsonRtn.class); if (rtn == null) { log.info("parse return json msg failed when get access token for {}, rtn = {}", license, json); return null; } if (!JsonRtnUtil.isSuccess(rtn)) { log.info("unsuccessfully get access token for {}, rtn = {}", license, rtn); return null; } // for safe, expiresSeconds - 60s int expiresSeconds = Ints.max(rtn.getExpiresIn() - 60, 0); queue.put(new DelayItem<License>(license, TimeUnit.NANOSECONDS.convert(expiresSeconds, TimeUnit.SECONDS))); String accessToken = rtn.getAccessToken(); log.info("successfully get access token for {}, rtn = {}", license, rtn); return accessToken; }
Example #25
Source File: LUISGrammarEvaluator.java From JVoiceXML with GNU Lesser General Public License v2.1 | 5 votes |
/** * {@inheritDoc} */ @Override public Object getSemanticInterpretation(final DataModel model, String utterance) { final HttpClientBuilder builder = HttpClientBuilder.create(); if (PROXY_HOST != null) { HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT); builder.setProxy(proxy); } try (CloseableHttpClient client = builder.build()){ final URIBuilder uribuilder = new URIBuilder(grammarUri); uribuilder.addParameter("subscription-key", subscriptionKey); uribuilder.addParameter("q", utterance); final URI uri = uribuilder.build(); final HttpGet request = new HttpGet(uri); final HttpResponse response = client.execute(request); final StatusLine statusLine = response.getStatusLine(); final int status = statusLine.getStatusCode(); if (status != HttpStatus.SC_OK) { final String reasonPhrase = statusLine.getReasonPhrase(); LOGGER.error("error accessing '" + uri +"': " + reasonPhrase + " (HTTP error code " + status + ")"); return null; } final HttpEntity entity = response.getEntity(); final InputStream input = entity.getContent(); final Object interpretation = parseLUISResponse(model, input); return interpretation; } catch (IOException | URISyntaxException | ParseException | SemanticError e) { LOGGER.error(e.getMessage(), e); return null; } }
Example #26
Source File: AbstractHttpClient.java From nano-framework with Apache License 2.0 | 5 votes |
/** * 根据请求信息创建HttpRequestBase. * * @param cls 类型Class * @param url URL * @param params 参数列表 * @return HttpRequestBase */ protected HttpRequestBase createBase(final Class<? extends HttpRequestBase> cls, final String url, final Map<String, String> params) { final URIBuilder builder = new URIBuilder(); builder.setPath(url); final List<NameValuePair> pairs = covertParams2Nvps(params); builder.setParameters(pairs); try { final URI uri = builder.build(); return ReflectUtils.newInstance(cls, uri); } catch (final Throwable e) { throw new HttpClientInvokeException(e.getMessage(), e); } }
Example #27
Source File: HomeGraphAPI.java From arcusplatform with Apache License 2.0 | 5 votes |
private String createUrl(String method) { try { return new URIBuilder(config.getHomeGraphApiUrl() + method) .addParameter("key", config.getHomeGraphApiKey()) .build() .toString(); } catch(URISyntaxException use) { throw new RuntimeException(use); } }
Example #28
Source File: UserInputTestCase.java From vespa with Apache License 2.0 | 5 votes |
@Test public void testAnnotatedUserInputPositionData() { URIBuilder builder = searchUri(); builder.setParameter("yql", "select * from sources * where [{\"usePositionData\": false}]userInput(\"nalle\");"); Query query = searchAndAssertNoErrors(builder); assertEquals( "select * from sources * where default contains ([{\"usePositionData\": false}]\"nalle\");", query.yqlRepresentation()); }
Example #29
Source File: HttpClientUtils.java From JobX with Apache License 2.0 | 5 votes |
public static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException { URIBuilder ub = new URIBuilder(); ub.setPath(url); ArrayList<NameValuePair> pairs = covertParams2NVPS(params); ub.setParameters(pairs); HttpGet httpGet = new HttpGet(ub.build()); return getResult(httpGet); }
Example #30
Source File: UrlArgument.java From gocd with Apache License 2.0 | 5 votes |
public String withoutCredentials() { try { return new URIBuilder(this.sanitizeUrl()).setUserInfo(null).build().toString(); } catch (URISyntaxException e) { return url; } }