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

The following examples show how to use org.apache.http.client.utils.URIBuilder#toString() . 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: 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 2
Source File: AppConfig.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@Bean("serverUrl")
public String serverUrl() throws URISyntaxException {
    URIBuilder builder = new URIBuilder(appProperties.getUrl());
    String url = builder.toString();
    if (url.endsWith("/")) {
        url = url.substring(0, url.length() - 1);
    }
    return url;
}
 
Example 3
Source File: MinimalQueryInserterTestCase.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void requireThatGroupingStepsAreAttachedToQuery() {
    URIBuilder builder = new URIBuilder();
    builder.setPath("search/");

    builder.setParameter("yql", "select foo from bar where baz contains 'cox';");
    Query query = new Query(builder.toString());
    execution.search(query);
    assertEquals("baz:cox", query.getModel().getQueryTree().toString());
    assertGrouping("[]", query);

    assertEquals(1, query.getPresentation().getSummaryFields().size());
    assertEquals("foo", query.getPresentation().getSummaryFields().toArray(new String[1])[0]);

    builder.setParameter("yql", "select foo from bar where baz contains 'cox' " +
                                "| all(group(a) each(output(count())));");
    query = new Query(builder.toString());
    execution.search(query);
    assertEquals("baz:cox", query.getModel().getQueryTree().toString());
    assertGrouping("[[]all(group(a) each(output(count())))]", query);

    builder.setParameter("yql", "select foo from bar where baz contains 'cox' " +
                                "| all(group(a) each(output(count()))) " +
                                "| all(group(b) each(output(count())));");
    query = new Query(builder.toString());
    execution.search(query);
    assertEquals("baz:cox", query.getModel().getQueryTree().toString());
    assertGrouping("[[]all(group(a) each(output(count())))," +
                   " []all(group(b) each(output(count())))]", query);
}
 
Example 4
Source File: RemoteHoodieTableFileSystemView.java    From hudi with Apache License 2.0 5 votes vote down vote up
private <T> T executeRequest(String requestPath, Map<String, String> queryParameters, TypeReference reference,
    RequestMethod method) throws IOException {
  ValidationUtils.checkArgument(!closed, "View already closed");

  URIBuilder builder =
      new URIBuilder().setHost(serverHost).setPort(serverPort).setPath(requestPath).setScheme("http");

  queryParameters.forEach(builder::addParameter);

  // Adding mandatory parameters - Last instants affecting file-slice
  timeline.lastInstant().ifPresent(instant -> builder.addParameter(LAST_INSTANT_TS, instant.getTimestamp()));
  builder.addParameter(TIMELINE_HASH, timeline.getTimelineHash());

  String url = builder.toString();
  LOG.info("Sending request : (" + url + ")");
  Response response;
  int timeout = 1000 * 300; // 5 min timeout
  switch (method) {
    case GET:
      response = Request.Get(url).connectTimeout(timeout).socketTimeout(timeout).execute();
      break;
    case POST:
    default:
      response = Request.Post(url).connectTimeout(timeout).socketTimeout(timeout).execute();
      break;
  }
  String content = response.returnContent().asString();
  return mapper.readValue(content, reference);
}
 
Example 5
Source File: URIUtils.java    From elucidate-server with MIT License 5 votes vote down vote up
public static String buildBaseUrl(String baseScheme, String baseHost, int basePort, String basePath) {
    URIBuilder builder = new URIBuilder();
    builder.setScheme(baseScheme);
    builder.setHost(baseHost);

    if (!DEFAULT_PORTS.containsKey(baseScheme.toLowerCase()) || DEFAULT_PORTS.get(baseScheme) != basePort) {
        builder.setPort(basePort);
    }

    builder.setPath(basePath);
    return builder.toString();
}
 
Example 6
Source File: HttpGetParams.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
@Override
protected CloseableHttpResponse send(CloseableHttpClient httpClient, String baseUrl) throws Exception {
	URIBuilder uri = new URIBuilder(baseUrl);
	for (String key : params.keySet()) {
		String value = params.get(key);
		uri.addParameter(key, value);
	}
	HttpUriRequest request = new HttpGet(uri.toString());
	return httpClient.execute(request);
}
 
Example 7
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 8
Source File: RunApplication.java    From vertx-deploy-tools with Apache License 2.0 5 votes vote down vote up
private String buildRemoteRepo() {
    URI remoteRepo = deployConfig.getNexusUrl();
    if (remoteRepo != null && deployConfig.isHttpAuthentication()) {
        URIBuilder builder = new URIBuilder(remoteRepo);
        builder.setUserInfo(deployConfig.getHttpAuthUser() + ":" + deployConfig.getHttpAuthPassword());
        return builder.toString();
    }
    return deployConfig.getNexusUrl().toString();
}
 
Example 9
Source File: MinimalQueryInserterTestCase.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void requireThatGroupingContinuationsAreAttachedToQuery() {
    URIBuilder builder = new URIBuilder();
    builder.setPath("search/");

    builder.setParameter("yql", "select foo from bar where baz contains 'cox';");
    Query query = new Query(builder.toString());
    execution.search(query);
    assertEquals("baz:cox", query.getModel().getQueryTree().toString());
    assertGrouping("[]", query);

    builder.setParameter("yql", "select foo from bar where baz contains 'cox' " +
                                "| [{ 'continuations':['BCBCBCBEBG', 'BCBKCBACBKCCK'] }]" +
                                "all(group(a) each(output(count())));");
    query = new Query(builder.toString());
    execution.search(query);
    assertEquals("baz:cox", query.getModel().getQueryTree().toString());
    assertGrouping("[[BCBCBCBEBG, BCBKCBACBKCCK]all(group(a) each(output(count())))]", query);

    builder.setParameter("yql", "select foo from bar where baz contains 'cox' " +
                                "| [{ 'continuations':['BCBCBCBEBG', 'BCBKCBACBKCCK'] }]" +
                                "all(group(a) each(output(count()))) " +
                                "| [{ 'continuations':['BCBBBBBDBF', 'BCBJBPCBJCCJ'] }]" +
                                "all(group(b) each(output(count())));");
    query = new Query(builder.toString());
    execution.search(query);
    assertEquals("baz:cox", query.getModel().getQueryTree().toString());
    assertGrouping("[[BCBCBCBEBG, BCBKCBACBKCCK]all(group(a) each(output(count())))," +
                   " [BCBBBBBDBF, BCBJBPCBJCCJ]all(group(b) each(output(count())))]", query);
}
 
Example 10
Source File: AWebdavHandler.java    From nextcloud-java-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Build the full URL for the webdav access to a resource
 * 
 * @param remotePath remote path for file (Not including remote.php/webdav/)
 * @return Full URL including http....
 */
protected String buildWebdavPath(String remotePath)
{
    URIBuilder uB= new URIBuilder()
    .setScheme(_serverConfig.isUseHTTPS() ? "https" : "http")
    .setHost(_serverConfig.getServerName())
    .setPort(_serverConfig.getPort())
    .setPath( WEB_DAV_BASE_PATH + remotePath);
    return uB.toString();
}
 
Example 11
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 12
Source File: HttpRequestUtils.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
public static String doGet(String url, Map<String, String> params) {
	Assert.hasLength(url, "请求地址为空");
	try {
		URIBuilder builder = new URIBuilder(url);
		builder.setParameters(getNameValuePair(params));
		HttpGet httpGet = new HttpGet(builder.toString());
		String result = execute(httpGet);
		return result;
	} catch (Exception e) {
		throw new ServiceException(e);
	}
}
 
Example 13
Source File: GoogleTranslator.java    From AndroidLocalizePlugin with Apache License 2.0 5 votes vote down vote up
@Override
public String query() throws Exception {
    URIBuilder uri = new URIBuilder(url);
    for (String key : formData.keySet()) {
        String value = formData.get(key);
        uri.addParameter(key, value);
    }
    HttpGet request = new HttpGet(uri.toString());

    RequestConfig.Builder builder = RequestConfig.copy(RequestConfig.DEFAULT)
            .setSocketTimeout(5000)
            .setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000);

    if (PluginConfig.isEnableProxy()) {
        HttpHost proxy = new HttpHost(PluginConfig.getHostName(), PluginConfig.getPortNumber());
        builder.setProxy(proxy);
    }

    RequestConfig config = builder.build();
    request.setConfig(config);
    CloseableHttpResponse response = httpClient.execute(request);
    HttpEntity entity = response.getEntity();

    String result = EntityUtils.toString(entity, "UTF-8");
    EntityUtils.consume(entity);
    response.getEntity().getContent().close();
    response.close();

    return result;
}
 
Example 14
Source File: SharethroughUriBuilderUtil.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates uri with parameters for sharethrough request
 */
static String buildSharethroughUrl(String baseUri, String supplyId, String strVersion, String formattedDate,
                                   StrUriParameters params) {
    final URIBuilder uriBuilder = new URIBuilder()
            .setPath(baseUri)
            .addParameter("placement_key", params.getPkey())
            .addParameter("bidId", params.getBidID())
            .addParameter("consent_required", getBooleanStringValue(params.getConsentRequired()))
            .addParameter("consent_string", params.getConsentString())
            .addParameter("us_privacy", params.getUsPrivacySignal())
            .addParameter("instant_play_capable", getBooleanStringValue(params.getInstantPlayCapable()))
            .addParameter("stayInIframe", getBooleanStringValue(params.getIframe()))
            .addParameter("height", String.valueOf(params.getHeight()))
            .addParameter("width", String.valueOf(params.getWidth()))
            .addParameter("adRequestAt", formattedDate)
            .addParameter("supplyId", supplyId)
            .addParameter("strVersion", strVersion);

    final String ttduid = params.getTheTradeDeskUserId();
    if (StringUtils.isNotBlank(ttduid)) {
        uriBuilder.addParameter("ttduid", ttduid);
    }
    final String stxuid = params.getSharethroughUserId();
    if (StringUtils.isNotBlank(stxuid)) {
        uriBuilder.addParameter("stxuid", stxuid);
    }

    return uriBuilder.toString();
}
 
Example 15
Source File: MysqlSessions.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
protected String buildUri(boolean withConnParams, boolean withDB,
                          boolean autoReconnect, Integer timeout) {
    String url = this.config.get(MysqlOptions.JDBC_URL);
    if (!url.endsWith("/")) {
        url = String.format("%s/", url);
    }
    if (withDB) {
        url = String.format("%s%s", url, this.database());
    }

    int maxTimes = this.config.get(MysqlOptions.JDBC_RECONNECT_MAX_TIMES);
    int interval = this.config.get(MysqlOptions.JDBC_RECONNECT_INTERVAL);
    String sslMode = this.config.get(MysqlOptions.JDBC_SSL_MODE);

    URIBuilder builder = this.newConnectionURIBuilder();
    builder.setPath(url).setParameter("useSSL", sslMode);
    if (withConnParams) {
        builder.setParameter("characterEncoding", "utf-8")
               .setParameter("rewriteBatchedStatements", "true")
               .setParameter("useServerPrepStmts", "false")
               .setParameter("autoReconnect", String.valueOf(autoReconnect))
               .setParameter("maxReconnects", String.valueOf(maxTimes))
               .setParameter("initialTimeout", String.valueOf(interval));
    }
    if (timeout != null) {
        builder.setParameter("socketTimeout", String.valueOf(timeout));
    }
    return builder.toString();
}
 
Example 16
Source File: JettyServer.java    From celos with Apache License 2.0 5 votes vote down vote up
private void startServer() throws Exception {
    URL url = Thread.currentThread().getContextClassLoader().getResource("WEB-INF");
    URIBuilder uriBuilder = new URIBuilder(url.toURI());
    uriBuilder.setPath(Paths.get(url.getPath()).getParent().toString());

    context = new WebAppContext(uriBuilder.toString() + "/", "/");
    context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");

    context.setExtractWAR(false);

    server.setHandler(context);
    server.start();
}
 
Example 17
Source File: AppConfig.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@Bean("serverUrl")
public String serverUrl() throws URISyntaxException {
    URIBuilder builder = new URIBuilder(appProperties.getUrl());
    String url = builder.toString();
    if (url.endsWith("/")) {
        url = url.substring(0, url.length() - 1);
    }
    return url;
}
 
Example 18
Source File: ComponentContainer.java    From Selenium-Foundation with Apache License 2.0 4 votes vote down vote up
/**
 * Get the URL defined by the specified {@link PageUrl} annotation.
 * <p>
 * <b>NOTES</b>: <ul>
 *     <li>If the {@code pageUrl} argument is {@code null} or the {@code value} element of the specified
 *         {@link PageUrl} annotation is unspecified, this method returns {@code null}.
 *     <li>If {@code scheme} of the specified {@code pageUrl} argument is unspecified or set to {@code http/https},
 *         the specified {@code targetUri} is overlaid by the elements of the {@link PageUrl} annotation to
 *         produce the fully-qualified <b>HTTP</b> target page URL.<ul>
 *         <li>If the {@code value} element specifies an absolute path, this path is returned as-is.</li>
 *         <li>If the {@code value} element specifies a relative path, this is appended to the path specified by
 *             {@code targetUri} to resolve the page URL.</li>
 *         <li>If the {@code scheme} element is specified, its value overrides the scheme of {@code targetUri}.
 *             If the value of the {@code scheme} element is empty, the scheme of {@code targetUri} is set to
 *             {@code null}.</li>
 *         <li>If the {@code userInfo} element is specified, its value overrides the userInfo of {@code targetUrl}.
 *             If the value of the {@code userInfo} element is empty, the userInfo of {@code targetUri} is set to
 *             {@code null}.</li>
 *         <li>If the {@code host} element is specified, its value overrides the host of {@code targetUrl}. If the
 *             value of the {@code host} element is empty, the host of {@code targetUri} is set to {@code null}.
 *             </li>
 *         <li>If the {@code port} element is specified, its value overrides the port of {@code targetUri}. If the
 *             value of the {@code port} element is empty, the port of {@code targetUri} is set to <b>-1</b>.</li>
 *     </ul></li>
 *     <li>For <b>HTTP</b> URLs that require query parameters, these parameters must be included in the
 *         {@code value} element of the specified {@link PageUrl} annotation. The {@code params} element of the
 *         annotation is only used for pattern-based landing page verification.</li>
 *     <li>If {@code scheme} of the specified {@code pageUrl} is set to {@code file}, the value of the
 *         {@code targetUri} argument is ignored. The only element of the {@link PageUrl} annotation that
 *         is used to produce the fully-qualified <b>FILE</b> target page URL is {@code value}. The value of the
 *         {@code value} element specifies the relative path of a file within your project's resources, which is
 *         resolved via {@link ClassLoader#getResource}.</li>
 * </ul>
 * 
 * @param pageUrl page URL annotation
 * @param targetUri target URI
 * @return defined page URL as a string (may be 'null')
 */
@SuppressWarnings({"squid:S3776", "squid:MethodCyclomaticComplexity"})
public static String getPageUrl(final PageUrl pageUrl, final URI targetUri) {
    if (pageUrl == null || PLACEHOLDER.equals(pageUrl.value())) {
        return null;
    }
    
    String result = null;
    String scheme = pageUrl.scheme();
    String path = pageUrl.value();
    
    if ("file".equals(scheme)) {
        result = Thread.currentThread().getContextClassLoader().getResource(path).toString();
    } else {
        String userInfo = pageUrl.userInfo();
        String host = pageUrl.host();
        String port = pageUrl.port();
        
        URIBuilder builder = new URIBuilder(targetUri);
        
        if (!path.isEmpty()) {
            URI pathUri = URI.create(path);
            if (pathUri.isAbsolute()) {
                return pathUri.toString();
            } else {
                builder.setPath(URI.create(LOOPBACK + builder.getPath() + "/").resolve("./" + path).getPath());
            }
        }
        
        if (!PLACEHOLDER.equals(scheme)) {
            builder.setScheme(scheme.isEmpty() ? null : scheme);
        }
        
        if (!PLACEHOLDER.equals(userInfo)) {
            builder.setUserInfo(userInfo.isEmpty() ? null : userInfo);
        }
        
        if (!PLACEHOLDER.equals(host)) {
            builder.setHost(host.isEmpty() ? null : host);
        }
        
        if (!PLACEHOLDER.equals(port)) {
            builder.setPort(port.isEmpty() ? -1 : Integer.parseInt(port));
        }
        
        result = builder.toString();
    }
    
    return result;
}
 
Example 19
Source File: BuildAuthorizationRequestContextAction.java    From shibboleth-oidc with Apache License 2.0 4 votes vote down vote up
/**
 * Check for none prompt pair.
 *
 * @param client      the client
 * @param authRequest the auth request
 * @return the pair
 */
private Pair<Events, ? extends Object> checkForNonePrompt(final ClientDetailsEntity client,
                                                          final OIDCAuthorizationRequestContext authRequest) {
    log.debug("Prompt contains {}", ConnectRequestParameters.PROMPT_NONE);
    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (auth != null) {
        log.debug("Authentication context is found for {}. Already logged in; continue without prompt",
                auth.getPrincipal());
        return new Pair(Events.Success, auth);
    }

    log.info("Client requested no prompt");
    if (client != null && authRequest.getRedirectUri() != null) {
        try {
            final String url = redirectResolver.resolveRedirect(authRequest.getRedirectUri(), client);
            log.debug("Initial redirect url resolved for client {} is {}", client.getClientName(), url);

            final URIBuilder uriBuilder = new URIBuilder(url);
            
            if (authRequest.isImplicitResponseType()) {
                log.debug("Request is asking for implicit grant type. Encoding parameters as fragments");
                final StringBuilder builder = new StringBuilder();
                builder.append(ConnectRequestParameters.ERROR)
                       .append('=')
                       .append(ConnectRequestParameters.LOGIN_REQUIRED);

                if (!Strings.isNullOrEmpty(authRequest.getState())) {
                    builder.append('&')
                           .append(ConnectRequestParameters.STATE)
                           .append('=')
                           .append(authRequest.getState());
                }
                uriBuilder.setFragment(builder.toString());
            } else {
                log.debug("Request is asking for code grant type. Encoding parameters as url parameters");
                uriBuilder.addParameter(ConnectRequestParameters.ERROR,
                        ConnectRequestParameters.LOGIN_REQUIRED);
                if (!Strings.isNullOrEmpty(authRequest.getState())) {
                    uriBuilder.addParameter(ConnectRequestParameters.STATE, authRequest.getState());
                }
            }
            log.debug("Resolved redirect url {}", uriBuilder.toString());
            return new Pair<>(Events.Redirect, uriBuilder.toString());

        } catch (final URISyntaxException e) {
            log.error("Can't build redirect URI for prompt=none, sending error instead", e);
        }
    } else {
        log.warn("Access denied. Either client is not found or no redirect uri is specified");

    }
    return new Pair(Events.Failure, null);
}
 
Example 20
Source File: UrlUtil.java    From gocd with Apache License 2.0 4 votes vote down vote up
public static String urlWithQuery(String oldUrl, String paramName, String paramValue) throws URISyntaxException {
    URIBuilder uriBuilder = new URIBuilder(oldUrl);
    uriBuilder.addParameter(paramName, paramValue);
    return uriBuilder.toString();
}