下面列出了org.apache.http.client.utils.URIBuilder#toString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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());
}
@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);
}
@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;
}
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();
}
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();
}
/**
* 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();
}
@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;
}
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);
}
}
/** 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);
}
}
/**
* 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();
}
@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;
}
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();
}
@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());
}
@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);
}
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();
}
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);
}
@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);
}
/**
* 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;
}
/**
* 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);
}
public static String urlWithQuery(String oldUrl, String paramName, String paramValue) throws URISyntaxException {
URIBuilder uriBuilder = new URIBuilder(oldUrl);
uriBuilder.addParameter(paramName, paramValue);
return uriBuilder.toString();
}