Java Code Examples for org.apache.http.client.utils.URIBuilder#setParameter()

The following examples show how to use org.apache.http.client.utils.URIBuilder#setParameter() . 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: JOpenCageGeocoder.java    From jopencage with Apache License 2.0 6 votes vote down vote up
public URI buildUri(JOpenCageRequest jOpenCageRequest) throws URISyntaxException {
  URIBuilder uriBuilder = new URIBuilder();
  if (httpsEnabled) {
    uriBuilder.setScheme("https");
  } else {
    uriBuilder.setScheme("http");
  }
  uriBuilder.setHost(host)
  .setPath(path + format);

  for (Entry<String, String> e : jOpenCageRequest.getParameter().entrySet()) {
    if (e.getValue() != null) {
      uriBuilder.setParameter(e.getKey(), e.getValue());
    }
  }
  uriBuilder.setParameter("key", apiKey);
  return uriBuilder.build();
}
 
Example 2
Source File: SimpleHttp.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private URI appendParameterToUrl(String url) throws IOException {
    URI uri = null;

    try {
        URIBuilder uriBuilder = new URIBuilder(url);

        if (params != null) {
            for (Map.Entry<String, String> p : params.entrySet()) {
                uriBuilder.setParameter(p.getKey(), p.getValue());
            }
        }

        uri = uriBuilder.build();
    } catch (URISyntaxException e) {
    }

    return uri;
}
 
Example 3
Source File: PrepMetadataGetContentUrlGenerator.java    From data-prep with Apache License 2.0 6 votes vote down vote up
@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: HttpServerUtilities.java    From Repeat with Apache License 2.0 6 votes vote down vote up
/**
 * Construct an HTTP redirect response. Note that this uses code 302, not 301.
 *
 * @param dest path to the destination. This is absolute path not including the domain.
 */
public static Void redirect(HttpAsyncExchange exchange, String dest, Map<String, String> params) throws IOException {
	String location = "";
	try {
		URIBuilder builder = new URIBuilder(exchange.getRequest().getRequestLine().getUri());
		builder.clearParameters();
		for (Entry<String, String> entry : params.entrySet()) {
			builder.setParameter(entry.getKey(), entry.getValue());
		}
		location = builder.setPath(dest).build().toString();
	} catch (URISyntaxException e) {
		LOGGER.log(Level.WARNING, "Unable to parse request URI.", e);
		return prepareTextResponse(exchange, 500, "Unable to parse request URI.");
	}

	HttpResponse response = exchange.getResponse();
	response.setStatusCode(302);
	response.addHeader("Location", location);
	exchange.submitResponse(new BasicAsyncResponseProducer(response));
	return null;
}
 
Example 5
Source File: AgpClient.java    From geoportal-server-harvester with Apache License 2.0 6 votes vote down vote up
/**
 * Reads item metadata.
 * @param itemId item id
 * @param format metadata format
 * @param token token
 * @return item metadata if available
 * @throws URISyntaxException if invalid URL
 * @throws IOException if operation fails
 */
public String readItemMetadata(String itemId, MetadataFormat format, String token) throws IOException, URISyntaxException {
  URIBuilder builder = new URIBuilder(itemMetaUri(itemId));
  
  builder.setParameter("format", (format != null ? format : MetadataFormat.DEFAULT).toString());
  if (token!=null) {
    builder.setParameter("token", token);
  }
  HttpGet req = new HttpGet(builder.build());
  
  try {
    return execute(req, 0);
  } catch (HttpResponseException ex) {
    if (ex.getStatusCode() == 500) {
      return null;
    }
    throw ex;
  }
}
 
Example 6
Source File: UserInputTestCase.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompositeWithoutArguments() {
    URIBuilder builder = searchUri();
    builder.setParameter("yql", "select * from sources * where bar contains \"a\" and foo contains phrase();");
    searchAndAssertNoErrors(builder);
    builder = searchUri();
    builder.setParameter("yql", "select * from sources * where bar contains \"a\" and nonEmpty(foo contains phrase());");
    assertQueryFails(builder);
}
 
Example 7
Source File: AgpClient.java    From geoportal-server-harvester with Apache License 2.0 5 votes vote down vote up
/**
 * Searches for items.
 * @param query query
 * @param num max number of items
 * @param start start item
 * @param token token (optional)
 * @return query response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if operation fails
 */
public QueryResponse search(String query, long num, long start, String token) throws URISyntaxException, IOException {
  URIBuilder builder = new URIBuilder(searchUri());
  
  builder.setParameter("f", "json");
  builder.setParameter("q", String.format("%s %s", query, QUERY_EXTRAS));
  if (token!=null) {
    builder.setParameter("token", token);
  }
  HttpGet req = new HttpGet(builder.build());
  
  return execute(req,QueryResponse.class);
}
 
Example 8
Source File: AgpClient.java    From geoportal-server-harvester with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 9
Source File: AgpClient.java    From geoportal-server-harvester with Apache License 2.0 5 votes vote down vote up
/**
 * Lists content.
 * @param owner owner
 * @param folderId folder id (optional)
 * @param num number items to return
 * @param start start item
 * @param token token (optional)
 * @return content response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if operation fails
 */
public ContentResponse listContent(String owner, String folderId, long num, long start, String token) throws URISyntaxException, IOException {
  URIBuilder builder = new URIBuilder(userUri(owner, folderId));
  
  builder.setParameter("f", "json");
  builder.setParameter("num", Long.toString(num));
  builder.setParameter("start", Long.toString(start));
  if (token!=null) {
    builder.setParameter("token", token);
  }
  HttpGet req = new HttpGet(builder.build());
  
  return execute(req,ContentResponse.class);
}
 
Example 10
Source File: UserInputTestCase.java    From vespa with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: PreparationGetContentUrlGenerator.java    From data-prep with Apache License 2.0 5 votes vote down vote up
@Override
public AsyncExecutionResult generateResultUrl(Object... args) {

    // check pre-condition
    Validate.notNull(args);
    Validate.isTrue(args.length == 1);
    Validate.isInstanceOf(ExportParameters.class, args[0]);

    ExportParameters param = (ExportParameters) args[0];

    URIBuilder builder = new URIBuilder();
    builder.setPath("/api/preparations/" + param.getPreparationId() + "/content");

    if (StringUtils.isNotEmpty(param.getStepId())) {
        builder.setParameter("version", param.getStepId());
    }

    if (param.getFrom() != null) {
        builder.setParameter("from", param.getFrom().name());
    }

    if (StringUtils.isNotEmpty(param.getFilter())) {
        builder.setParameter("filter", param.getFilter());
    }

    return new AsyncExecutionResult(builder.toString());
}
 
Example 12
Source File: ImportBackendAPI.java    From apimanager-swagger-promote with Apache License 2.0 5 votes vote down vote up
private void importFromWSDL() throws URISyntaxException, AppException, IOException {
	URI uri;
	HttpEntity entity = new StringEntity("");
	String username=null;
	String pass=null;
	String wsdlUrl=null;
	String completeWsdlUrl=null;
	if(this.desiredState.getAPIDefinition().getApiSpecificationFile().endsWith(".url")) {
		completeWsdlUrl = Utils.getAPIDefinitionUriFromFile(this.desiredState.getAPIDefinition().getApiSpecificationFile());
	} else {
		completeWsdlUrl = this.desiredState.getAPIDefinition().getApiSpecificationFile();
	}
	wsdlUrl = extractURI(completeWsdlUrl);
	username=extractUsername(completeWsdlUrl);
	pass=extractPassword(completeWsdlUrl);

	
	URIBuilder uriBuilder = new URIBuilder(cmd.getAPIManagerURL()).setPath(RestAPICall.API_VERSION+"/apirepo/importFromUrl/")
			.setParameter("organizationId", this.desiredState.getOrganizationId())
			.setParameter("type", "wsdl")
			.setParameter("url", wsdlUrl)
			.setParameter("name", this.desiredState.getName());
	if (username!=null) {
		uriBuilder.setParameter("username", username);
		uriBuilder.setParameter("password", pass);
	}
	uri=uriBuilder.build();
	RestAPICall importWSDL = new POSTRequest(entity, uri, this);
	importWSDL.setContentType("application/x-www-form-urlencoded");
	HttpResponse httpResponse = importWSDL.execute();
	int statusCode = httpResponse.getStatusLine().getStatusCode();
	if(statusCode != 201){
		LOG.error("Received Status-Code: " +statusCode+ ", Response: '" + EntityUtils.toString(httpResponse.getEntity()) + "'");
		throw new AppException("Can't import WSDL from URL / Create BE-API.", ErrorCode.CANT_CREATE_BE_API);
	}
}
 
Example 13
Source File: DigitalOceanClient.java    From digitalocean-api-java with MIT License 5 votes vote down vote up
private URI createUri(ApiRequest request) {
  URIBuilder ub = new URIBuilder();
  ub.setScheme(HTTPS_SCHEME);
  ub.setHost(apiHost);
  ub.setPath(createPath(request));

  if (null != request.getPageNo()) {
    ub.setParameter(PARAM_PAGE_NO, request.getPageNo().toString());
  }

  if (RequestMethod.GET == request.getMethod()) {
    if (null == request.getPerPage()) {
      ub.setParameter(PARAM_PER_PAGE, String.valueOf(DEFAULT_PAGE_SIZE)); // As per DO
      // documentation
    } else {
      ub.setParameter(PARAM_PER_PAGE, request.getPerPage().toString());
    }
  }

  if (null != request.getQueryParams()) {
    for (Map.Entry<String, String> entry : request.getQueryParams().entrySet()) {
      ub.setParameter(entry.getKey(), entry.getValue());
    }
  }

  URI uri = null;
  try {
    uri = ub.build();
  } catch (URISyntaxException use) {
    log.error(use.getMessage(), use);
  }

  return uri;
}
 
Example 14
Source File: UploaderWebClient.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the business object data upload credentials.
 *
 * @param manifest the manifest
 * @param storageName the storage name
 * @param businessObjectDataVersion the version of the business object data
 * @param createNewVersion specifies to provide credentials fof the next business object data version
 *
 * @return {@link BusinessObjectDataUploadCredential}
 * @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 BusinessObjectDataUploadCredential getBusinessObjectDataUploadCredential(DataBridgeBaseManifestDto manifest, String storageName,
    Integer businessObjectDataVersion, Boolean createNewVersion)
    throws URISyntaxException, IOException, JAXBException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException
{
    URIBuilder uriBuilder =
        new URIBuilder().setScheme(getUriScheme()).setHost(regServerAccessParamsDto.getRegServerHost()).setPort(regServerAccessParamsDto.getRegServerPort())
            .setPath(String.join("/", HERD_APP_REST_URI_PREFIX, "businessObjectData", "upload", "credential", "namespaces", manifest.getNamespace(),
                "businessObjectDefinitionNames", manifest.getBusinessObjectDefinitionName(), "businessObjectFormatUsages",
                manifest.getBusinessObjectFormatUsage(), "businessObjectFormatFileTypes", manifest.getBusinessObjectFormatFileType(),
                "businessObjectFormatVersions", manifest.getBusinessObjectFormatVersion(), "partitionValues", manifest.getPartitionValue()))
            .setParameter("storageName", storageName);
    if (manifest.getSubPartitionValues() != null)
    {
        uriBuilder.setParameter("subPartitionValues", herdStringHelper.join(manifest.getSubPartitionValues(), "|", "\\"));
    }
    if (businessObjectDataVersion != null)
    {
        uriBuilder.setParameter("businessObjectDataVersion", businessObjectDataVersion.toString());
    }
    if (createNewVersion != null)
    {
        uriBuilder.setParameter("createNewVersion", createNewVersion.toString());
    }
    HttpGet httpGet = new HttpGet(uriBuilder.build());
    httpGet.addHeader("Accepts", DEFAULT_ACCEPT);
    if (regServerAccessParamsDto.isUseSsl())
    {
        httpGet.addHeader(getAuthorizationHeader());
    }
    try (CloseableHttpClient httpClient = httpClientHelper
        .createHttpClient(regServerAccessParamsDto.isTrustSelfSignedCertificate(), regServerAccessParamsDto.isDisableHostnameVerification()))
    {
        LOGGER.info("Retrieving upload credentials from registration server...");
        return getBusinessObjectDataUploadCredential(httpClientOperations.execute(httpClient, httpGet));
    }
}
 
Example 15
Source File: UserInputTestCase.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void testSegmentedUserInput() {
    URIBuilder builder = searchUri();
    builder.setParameter("yql",
            "select * from sources * where [{\"grammar\": \"segment\"}]userInput(\"nal le\");");
    Query query = searchAndAssertNoErrors(builder);
    assertEquals("select * from sources * where default contains ([{\"origin\": {\"original\": \"nal le\", \"offset\": 0, \"length\": 6}}]phrase(\"nal\", \"le\"));", query.yqlRepresentation());
}
 
Example 16
Source File: Processor.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
/** Makes the `next` link for navigation purposes. */
private String makeNextLink(int skip) throws ODataException
{
   try
   {
      String selfLnk = ServiceFactory.ROOT_URL;
      URIBuilder ub = new URIBuilder(selfLnk);
      ub.setParameter("$skip", String.valueOf(skip));
      return ub.toString();
   }
   catch (URISyntaxException ex)
   {
      throw new ODataException("Cannot make next link", ex);
   }
}
 
Example 17
Source File: ClusterDependentTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
protected static String sendGetHttpRequestToMock(String path, Map<String, String> parameters) throws Exception {
    URIBuilder builder = new URIBuilder();
    builder.setScheme("http").setHost("localhost").setPort(mock().getHttpPort()).setPath(path);
    for (Map.Entry<String, String> entry: parameters.entrySet()) {
        builder.setParameter(entry.getKey(), entry.getValue());
    }
    HttpGet request = new HttpGet(builder.build());
    HttpClient client = HttpClientBuilder.create().build();
    HttpResponse response = client.execute(request);
    int status = response.getStatusLine().getStatusCode();
    if (status != 200) {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }
    return EntityUtils.toString(response.getEntity());
}
 
Example 18
Source File: UserInputTestCase.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void testAllowEmptyUserInput() {
    URIBuilder builder = searchUri();
    builder.setParameter("foo", "");
    builder.setParameter("yql", "select * from sources * where [{\"allowEmpty\": true}]userInput(@foo);");
    searchAndAssertNoErrors(builder);
}
 
Example 19
Source File: UploaderWebClient.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 20
Source File: RestUtils.java    From vxquery with Apache License 2.0 3 votes vote down vote up
/**
 * Builds the query result {@link URI} given the {@link QueryResultRequest}
 * 
 * @param resultRequest
 *            result request
 * @param restIpAddress
 *            rest server's ip
 * @param restPort
 *            port of the rest server
 * @return generated {@link URI}
 * @throws URISyntaxException
 */
public static URI buildQueryResultURI(QueryResultRequest resultRequest, String restIpAddress, int restPort)
        throws URISyntaxException {
    URIBuilder builder = new URIBuilder().setScheme("http").setHost(restIpAddress).setPort(restPort)
            .setPath(QUERY_RESULT_ENDPOINT.replace("*", String.valueOf(resultRequest.getResultId())));

    if (resultRequest.isShowMetrics()) {
        builder.setParameter(METRICS, String.valueOf(resultRequest.isShowMetrics()));
    }

    return builder.build();
}