下面列出了org.apache.http.client.utils.URIBuilder#build ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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();
}
private HttpRequestBase onExecute(final String parentId, final Sort sort, final Order order) {
try {
String uri = preparationServiceUrl + "/folders";
final URIBuilder uriBuilder = new URIBuilder(uri);
if (parentId != null) {
uriBuilder.addParameter("parentId", parentId);
}
if (sort != null) {
uriBuilder.addParameter("sort", sort.camelName());
}
if (order != null) {
uriBuilder.addParameter("order", order.camelName());
}
return new HttpGet(uriBuilder.build());
} catch (URISyntaxException e) {
throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
}
}
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;
}
@Override
protected Callable<Response> callable() {
return new Callable<Response>() {
@Override
public Response call() throws Exception {
URIBuilder uri = uri( HBase.SERVICE_PATH, "/", tableName, "/scanner/", scannerId );
HttpGet get = new HttpGet( uri.build() );
get.setHeader( "Accept", "application/json" );
return new Response( execute( get ) );
}
};
}
/**
* Remove selected fields from a URI producing a new URI
*
* @param uri the uri to convert
* @param excludes the parts to exclude
* @return The new URI instance
*/
static URI uriExclude(final URI uri, URIPart... excludes) {
URIBuilder urib = new URIBuilder();
EnumSet<URIPart> set = EnumSet.of(excludes[0], excludes);
for (URIPart part : URIPart.values()) {
if (set.contains(part))
continue;
switch (part) {
case SCHEME:
urib.setScheme(uri.getScheme());
break;
case USERINFO:
urib.setUserInfo(uri.getRawUserInfo());
break;
case HOST:
urib.setHost(uri.getHost());
break;
case PORT:
urib.setPort(uri.getPort());
break;
case PATH:
urib.setPath(uri.getPath());
break;
case QUERY:
urib.setCustomQuery(uri.getQuery());
break;
case FRAGMENT:
urib.setFragment(uri.getFragment());
break;
}
}
try {
return urib.build();
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
/**
* Lists folders.
* @param owner owner
* @param token token
* @return array of folders
* @throws URISyntaxException if invalid URL
* @throws IOException if operation fails
*/
public FolderEntry[] listFolders(String owner, String token) throws URISyntaxException, IOException {
URIBuilder builder = new URIBuilder(userUri(owner, null));
builder.setParameter("f", "json");
if (token!=null) {
builder.setParameter("token", token);
}
HttpGet req = new HttpGet(builder.build());
return execute(req,ContentResponse.class).folders;
}
@Test
public void contruct_uri_apache () throws URISyntaxException {
URIBuilder builder = new URIBuilder()
.setScheme("http")
.setHost("www.leveluplunch.com")
.setPath("/java/examples/");
URI uri = builder.build();
assertEquals(
"http://www.leveluplunch.com/java/examples/",
uri.toString());
}
private URI userUri(String owner, String folderId) throws URISyntaxException {
URIBuilder builder = new URIBuilder();
builder.setScheme(rootUrl.toURI().getScheme())
.setHost(rootUrl.toURI().getHost())
.setPort(rootUrl.toURI().getPort())
.setPath(rootUrl.toURI().getPath() + "sharing/rest/content/users/" + owner + (folderId!=null? "/"+folderId: ""));
return builder.build();
}
/**
* Builds the URI from the URI parameter hash
* <p>
* This will append each of the {key, value} pairs in uriParamsHash to the URI.
*
* @param uriParamsHash the hashtable containing parameters to be added to the URI for making the call to TMDB
* @return URI for making the HTTP call to TMDB API
* @throws URISyntaxException if the uri being built is in the incorrect format
*/
private static URI buildUriStringFromParamsHash(Hashtable<String, String> uriParamsHash, String path) throws URISyntaxException {
URIBuilder urib = new URIBuilder();
urib.setScheme("http"); //$NON-NLS-1$
urib.setHost(TMDB_BASE_URL);
urib.setPath(path);
urib.addParameter("api_key", themoviedbapikey); //$NON-NLS-1$
if (uriParamsHash != null) {
Set<String> keys = uriParamsHash.keySet();
for (String key : keys) {
urib.addParameter(key, uriParamsHash.get(key));
}
}
return urib.build();
}
@Override
protected Callable<Response> callable() {
return new Callable<Response>() {
@Override
public Response call() throws Exception {
URIBuilder uri = uri( Yarn.SERVICE_PATH, "/v1/cluster/apps/", appId, "/state" );
HttpGet request = new HttpGet( uri.build() );
return new Response( execute( request ) );
}
};
}
public static URI appendQueryStringToUri(URI uri, String parameterName, String parameterValue) {
URI modifiedUri = null;
try {
URIBuilder uriBuilder = new URIBuilder(uri);
uriBuilder.setQuery(parameterName + "=" + parameterValue);
modifiedUri = uriBuilder.build();
} catch(Exception e) {
throw new EFhirClientException("Unable to append query parameter '" + parameterName + "=" + parameterValue + " to URI " + uri, e);
}
return modifiedUri;
}
private void configureSampleDataset(String dataSetId) {
URI uri;
try {
final URIBuilder uriBuilder = new URIBuilder(datasetServiceUrl);
uriBuilder.setPath(uriBuilder.getPath() + "/datasets/" + dataSetId + "/sample/metadata");
uri = uriBuilder.build();
} catch (URISyntaxException e) {
throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
}
execute(() -> new HttpGet(uri));
on(HttpStatus.OK).then(convertResponse(objectMapper, DataSetMetadata.class));
}
@Override
protected Callable<Rename.Response> callable() {
return new Callable<Rename.Response>() {
@Override
public Rename.Response call() throws Exception {
URIBuilder uri = uri(Hdfs.SERVICE_PATH, file);
addQueryParam(uri, "op", "RENAME");
addQueryParam(uri, "destination", to);
HttpPut request = new HttpPut(uri.build());
return new Rename.Response(execute(request));
}
};
}
public static String buildAuthorizeUrl(String tenantId, String clientId, String redirectUri, String username) throws IOException {
URI uri;
try {
URIBuilder uriBuilder = new URIBuilder()
.setScheme("https")
.setHost("login.microsoftonline.com")
.addParameter("client_id", clientId)
.addParameter("response_type", "code")
.addParameter("redirect_uri", redirectUri)
.addParameter("response_mode", "query")
.addParameter("login_hint", username);
// force consent
//uriBuilder.addParameter("prompt", "consent")
// switch to new v2.0 OIDC compliant endpoint https://docs.microsoft.com/en-us/azure/active-directory/develop/azure-ad-endpoint-comparison
if (Settings.getBooleanProperty("davmail.enableOidc", false)) {
uriBuilder.setPath("/" + tenantId + "/oauth2/v2.0/authorize")
.addParameter("scope", "openid https://outlook.office365.com/EWS.AccessAsUser.All");
} else {
uriBuilder.setPath("/" + tenantId + "/oauth2/authorize")
.addParameter("resource", RESOURCE);
}
uri = uriBuilder.build();
} catch (URISyntaxException e) {
throw new IOException(e);
}
return uri.toString();
}
/**
* makeHistoryURI - Given a request UUID, and a fully qualified pipe name
* make a URI for the history reporting
*
* @param requestId the label for this request
* @param pipe the pipe name
* @param recentSeconds history only for items in the recentSeconds window
* @param beginMark mark from which history should be fetched
* @return URI for the insert request
*/
private URI makeHistoryURI(UUID requestId,
String pipe,
Integer recentSeconds,
String beginMark)
throws URISyntaxException
{
//if the table name is null, we have to abort
if (pipe == null)
{
throw new IllegalArgumentException();
}
//get the base endpoint UIR
URIBuilder builder = makeBaseURI(requestId);
//set the path for the URI
builder.setPath(String.format(HISTORY_ENDPOINT_FORMAT, pipe));
if (recentSeconds != null)
{
builder.setParameter(RECENT_HISTORY_IN_SECONDS,
String.valueOf(recentSeconds));
}
if (beginMark != null)
{
builder.setParameter(HISTORY_BEGIN_MARK, beginMark);
}
LOGGER.info("Final History URIBuilder - {}", builder.toString());
//build the final URI
return builder.build();
}
@Test
public void testCallHttpGet_API_TRANSFER_MODE() throws Exception {
HttpClient httpClient = HttpClientBuilder.create().build();
//inbound path : /stackoverflow/2.2/question/:path
//outbound path : http://api.stackexchange.com/2.2/questions
URIBuilder uriBuilder = new URIBuilder();
uriBuilder.setScheme("http")
.setHost("localhost")
.setPort(8080)
.setPath("/stackoverflow/2.2/question/test")
//Insert mandatory query param
.setParameter("site", "stackoverflow")
//Insert option query param
.setParameter("page", "2")
.setParameter("votes", "1");
HttpGet httpGet = new HttpGet(uriBuilder.build());
//this action is not needed. just for understanding.
httpGet.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON.toString());
httpGet.setHeader("apiKey", "1000-1000-1000-1000");
HttpResponse response = httpClient.execute(httpGet);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
response.getEntity().writeTo(outputStream);
logger.info("Response: {}", outputStream);
assertThat(response.containsHeader(HttpHeaders.CONTENT_TYPE), is(true));
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
/**
* @param stack name of stack.
* @param minZ (optional) only include layers with z values greater than or equal to this minimum.
* @param maxZ (optional) only include layers with z values less than or equal to this maximum.
*
* @return section data for set of layers in the specified stack.
*
* @throws IOException
* if the request fails for any reason.
*/
public List<SectionData> getStackSectionData(final String stack,
final Double minZ,
final Double maxZ)
throws IOException {
final URIBuilder builder = new URIBuilder(getUri(urls.getStackUrlString(stack) + "/sectionData"));
if (minZ != null) {
builder.addParameter("minZ", minZ.toString());
}
if (maxZ != null) {
builder.addParameter("maxZ", maxZ.toString());
}
final URI uri;
try {
uri = builder.build();
} catch (final URISyntaxException e) {
throw new IOException(e.getMessage(), e);
}
final HttpGet httpGet = new HttpGet(uri);
final String requestContext = "GET " + uri;
final TypeReference<List<SectionData>> typeReference = new TypeReference<List<SectionData>>() {};
final JsonUtils.GenericHelper<List<SectionData>> helper = new JsonUtils.GenericHelper<>(typeReference);
final JsonResponseHandler<List<SectionData>> responseHandler = new JsonResponseHandler<>(requestContext, helper);
LOG.info("getStackSectionData: submitting {}", requestContext);
return httpClient.execute(httpGet, responseHandler);
}
URI createGolrRequest(List<String []> tagvalues, String category, int start, int pagination) throws IOException {
try {
URIBuilder builder = new URIBuilder(server);
String currentPath = StringUtils.trimToEmpty(builder.getPath());
builder.setPath(currentPath+"/select");
builder.addParameter("defType", "edismax");
builder.addParameter("qt", "standard");
builder.addParameter("wt", "json");
if (isIndentJson()) {
builder.addParameter("indent","on");
}
builder.addParameter("fl",StringUtils.join(getRelevantFields(), ','));
builder.addParameter("facet","false");
builder.addParameter("json.nl","arrarr");
builder.addParameter("q","*:*");
builder.addParameter("rows", Integer.toString(pagination));
builder.addParameter("start", Integer.toString(start));
builder.addParameter("fq", "document_category:\""+category+"\"");
for (String [] tagvalue : tagvalues) {
if (tagvalue.length == 2) {
builder.addParameter("fq", tagvalue[0]+":\""+tagvalue[1]+"\"");
}
else if (tagvalue.length > 2) {
// if there is more than one value, assume that this is an OR query
StringBuilder value = new StringBuilder();
value.append(tagvalue[0]).append(":(");
for (int i = 1; i < tagvalue.length; i++) {
if (i > 1) {
value.append(" OR ");
}
value.append('"').append(tagvalue[i]).append('"');
}
value.append(')');
builder.addParameter("fq", value.toString());
}
}
return builder.build();
} catch (URISyntaxException e) {
throw new IOException("Could not build URI for Golr request", e);
}
}
/**
* Retrieves all versions for the specified business object data key.
*
* @param businessObjectDataKey the business object data key
*
* @return {@link org.finra.herd.model.api.xml.BusinessObjectDataVersions}
* @throws JAXBException if a JAXB error was encountered
* @throws IOException if an I/O error was encountered
* @throws URISyntaxException if a URI syntax error was encountered
* @throws KeyStoreException if a key store exception occurs
* @throws NoSuchAlgorithmException if a no such algorithm exception occurs
* @throws KeyManagementException if key management exception
*/
public BusinessObjectDataVersions getBusinessObjectDataVersions(BusinessObjectDataKey businessObjectDataKey)
throws URISyntaxException, IOException, JAXBException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException
{
LOGGER.info("Retrieving business object data versions from the registration server...");
BusinessObjectDataVersions businessObjectDataVersions;
try (CloseableHttpClient client = httpClientHelper
.createHttpClient(regServerAccessParamsDto.isTrustSelfSignedCertificate(), regServerAccessParamsDto.isDisableHostnameVerification()))
{
StringBuilder uriPathBuilder = new StringBuilder(300);
uriPathBuilder.append(HERD_APP_REST_URI_PREFIX);
uriPathBuilder.append("/businessObjectData/namespaces/").append(businessObjectDataKey.getNamespace());
uriPathBuilder.append("/businessObjectDefinitionNames/").append(businessObjectDataKey.getBusinessObjectDefinitionName());
uriPathBuilder.append("/businessObjectFormatUsages/").append(businessObjectDataKey.getBusinessObjectFormatUsage());
uriPathBuilder.append("/businessObjectFormatFileTypes/").append(businessObjectDataKey.getBusinessObjectFormatFileType());
uriPathBuilder.append("/versions");
URIBuilder uriBuilder = new URIBuilder().setScheme(getUriScheme()).setHost(regServerAccessParamsDto.getRegServerHost())
.setPort(regServerAccessParamsDto.getRegServerPort()).setPath(uriPathBuilder.toString())
.setParameter("partitionValue", businessObjectDataKey.getPartitionValue());
if (businessObjectDataKey.getSubPartitionValues() != null)
{
uriBuilder.setParameter("subPartitionValues", herdStringHelper.join(businessObjectDataKey.getSubPartitionValues(), "|", "\\"));
}
if (businessObjectDataKey.getBusinessObjectFormatVersion() != null)
{
uriBuilder.setParameter("businessObjectFormatVersion", businessObjectDataKey.getBusinessObjectFormatVersion().toString());
}
if (businessObjectDataKey.getBusinessObjectDataVersion() != null)
{
uriBuilder.setParameter("businessObjectDataVersion", businessObjectDataKey.getBusinessObjectDataVersion().toString());
}
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.addHeader("Accepts", DEFAULT_ACCEPT);
// If SSL is enabled, set the client authentication header.
if (regServerAccessParamsDto.isUseSsl())
{
httpGet.addHeader(getAuthorizationHeader());
}
LOGGER.info(String.format(" HTTP GET URI: %s", httpGet.getURI().toString()));
businessObjectDataVersions = getBusinessObjectDataVersions(httpClientOperations.execute(client, httpGet));
}
LOGGER.info(String.format("Successfully retrieved %d already registered version(s) for the business object data. businessObjectDataKey=%s",
businessObjectDataVersions.getBusinessObjectDataVersions().size(), jsonHelper.objectToJson(businessObjectDataKey)));
return businessObjectDataVersions;
}
/**
* Clones the specified stack.
*
* @param fromStack source stack to clone.
* @param toProject project for new stack with cloned data (null if same as source project).
* @param toStack new stack to hold cloned data.
* @param toStackVersion version data for the new stack.
*
* @throws IOException
* if the request fails for any reason.
*/
public void cloneStackVersion(final String fromStack,
final String toProject,
final String toStack,
final StackVersion toStackVersion,
final Boolean skipTransforms,
final List<Double> zValues)
throws IOException {
final String json = toStackVersion.toJson();
final StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
final URIBuilder builder = new URIBuilder(getUri(urls.getCloneToUrlString(fromStack, toStack)));
if (zValues != null) {
for (final Double z : zValues) {
builder.addParameter("z", z.toString());
}
}
if (toProject != null) {
builder.addParameter("toProject", toProject);
}
if (skipTransforms != null) {
builder.addParameter("skipTransforms", skipTransforms.toString());
}
final URI uri;
try {
uri = builder.build();
} catch (final URISyntaxException e) {
throw new IOException(e.getMessage(), e);
}
final String requestContext = "PUT " + uri;
final ResourceCreatedResponseHandler responseHandler = new ResourceCreatedResponseHandler(requestContext);
final HttpPut httpPut = new HttpPut(uri);
httpPut.setEntity(stringEntity);
LOG.info("cloneStackVersion: submitting {}", requestContext);
httpClient.execute(httpPut, responseHandler);
}