Java Code Examples for org.springframework.web.util.UriComponentsBuilder#queryParam()

The following examples show how to use org.springframework.web.util.UriComponentsBuilder#queryParam() . 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: DockerServiceImpl.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
@Override
public ServiceCallResult subscribeToEvents(GetEventsArg arg) {
    ServiceCallResult callResult = new ServiceCallResult();
    UriComponentsBuilder ucb = makeUrl("events");
    if(arg.getSince() != null) {
        ucb.queryParam("since", arg.getSince());
    }
    if(arg.getUntil() != null) {
        ucb.queryParam("until", arg.getUntil());
    }
    URI uri = ucb.build().toUri();
    try {
        ListenableFuture<Object> future = restTemplate.execute(uri, HttpMethod.GET, null, response -> {
            online();// may be we need schedule it into another thread
            StreamContext<DockerEvent> context = new StreamContext<>(response.getBody(), arg.getWatcher());
            context.getInterrupter().setFuture(arg.getInterrupter());
            eventStreamProcessor.processResponseStream(context);
            return null;
        });
        waitFuture(callResult, future);
    } catch (HttpStatusCodeException e) {
        processStatusCodeException(e, callResult, uri);
    }
    return callResult;
}
 
Example 2
Source File: GithubDataGrabber.java    From Refactoring-Bot with MIT License 6 votes vote down vote up
/**
 * This method creates a pull request on Github.
 * 
 * @param request
 * @param gitConfig
 * @throws URISyntaxException
 * @throws GitHubAPIException
 */
public GithubPullRequest createRequest(GithubCreateRequest request, GitConfiguration gitConfig)
		throws URISyntaxException, GitHubAPIException {

	URI configUri = createURIFromApiLink(gitConfig.getRepoApiLink());

	// Build URI
	UriComponentsBuilder apiUriBuilder = UriComponentsBuilder.newInstance().scheme(configUri.getScheme())
			.host(configUri.getHost()).path(configUri.getPath() + "/pulls");

	apiUriBuilder.queryParam("access_token", gitConfig.getBotToken());

	URI pullsUri = apiUriBuilder.build().encode().toUri();

	RestTemplate rest = new RestTemplate();

	try {
		// Send request to the GitHub-API
		return rest.exchange(pullsUri, HttpMethod.POST, new HttpEntity<>(request), GithubPullRequest.class)
				.getBody();
	} catch (RestClientException r) {
		throw new GitHubAPIException("Could not create pull request on Github!", r);
	}
}
 
Example 3
Source File: DefaultSkipperClient.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<Deployer> listDeployers() {
	ParameterizedTypeReference<HateoasResponseWrapper<DeployersResponseWrapper>> typeReference =
			new ParameterizedTypeReference<HateoasResponseWrapper<DeployersResponseWrapper>>() { };
	UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUri + "/deployers");
	builder.queryParam("size", "2000");

	ResponseEntity<HateoasResponseWrapper<DeployersResponseWrapper>> resourceResponseEntity =
			restTemplate.exchange(builder.toUriString(),
					HttpMethod.GET,
					null,
					typeReference);
	DeployersResponseWrapper embedded = resourceResponseEntity.getBody().getEmbedded();
	if (embedded != null) {
		return embedded.getDeployers();
	}
	else {
		return Collections.emptyList();
	}
}
 
Example 4
Source File: RemoteJobServerService.java    From spring-batch-lightmin with Apache License 2.0 6 votes vote down vote up
@Override
public JobExecutionPage getJobExecutionPage(final Long jobInstanceId,
                                            final Integer startIndex,
                                            final Integer pageSize,
                                            final LightminClientApplication lightminClientApplication) {
    final String uri = this.getClientUri(lightminClientApplication) + "/jobexecutionpages";
    final UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(uri);
    final Integer startIndexParam = startIndex != null ? startIndex : 0;
    final Integer pageSizeParam = pageSize != null ? pageSize : 10;
    uriComponentsBuilder.queryParam("jobinstanceid", jobInstanceId);
    uriComponentsBuilder.queryParam("startindex", startIndexParam);
    uriComponentsBuilder.queryParam("pagesize", pageSizeParam);
    final ResponseEntity<JobExecutionPage> response =
            this.restTemplate.getForEntity(uriComponentsBuilder.toUriString(), JobExecutionPage.class, jobInstanceId);
    this.checkHttpOk(response);
    return response.getBody();
}
 
Example 5
Source File: DefaultSkipperClient.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<Repository> listRepositories() {
	ParameterizedTypeReference<HateoasResponseWrapper<RepositoriesResponseWrapper>> typeReference =
			new ParameterizedTypeReference<HateoasResponseWrapper<RepositoriesResponseWrapper>>() { };
	UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUri + "/repositories");
	builder.queryParam("size", "2000");

	ResponseEntity<HateoasResponseWrapper<RepositoriesResponseWrapper>> resourceResponseEntity =
			restTemplate.exchange(builder.toUriString(),
					HttpMethod.GET,
					null,
					typeReference);
	RepositoriesResponseWrapper embedded = resourceResponseEntity.getBody().getEmbedded();
	if (embedded != null) {
		return embedded.getRepositories();
	}
	else {
		return Collections.emptyList();
	}
}
 
Example 6
Source File: DefaultSkipperClient.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Map<String, DeploymentState>> states(String... releaseNames) {
	ParameterizedTypeReference<Map<String, Map<String, DeploymentState>>> typeReference =
			new ParameterizedTypeReference<Map<String, Map<String, DeploymentState>>>() { };

	UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUri + "/release/states");
	builder.queryParam("names", StringUtils.arrayToCommaDelimitedString(releaseNames));

	ResponseEntity<Map<String, Map<String, DeploymentState>>> responseEntity =
			restTemplate.exchange(builder.toUriString(),
					HttpMethod.GET,
					null,
					typeReference);
	return responseEntity.getBody();
}
 
Example 7
Source File: GithubDataGrabber.java    From Refactoring-Bot with MIT License 5 votes vote down vote up
/**
 * This method deletes a repository from Github.
 * 
 * @param gitConfig
 * @throws URISyntaxException
 * @throws GitHubAPIException
 */
public void deleteRepository(GitConfiguration gitConfig) throws URISyntaxException, GitHubAPIException {
	String originalRepo = gitConfig.getRepoApiLink();
	String forkRepo = gitConfig.getForkApiLink();
	// Never delete the original repository
	if (originalRepo.equals(forkRepo)) {
		return;
	}

	// Read URI from configuration
	URI configUri = createURIFromApiLink(gitConfig.getForkApiLink());

	// Build URI
	UriComponentsBuilder apiUriBuilder = UriComponentsBuilder.newInstance().scheme(configUri.getScheme())
			.host(configUri.getHost()).path(configUri.getPath());

	apiUriBuilder.queryParam("access_token", gitConfig.getBotToken());

	URI repoUri = apiUriBuilder.build().encode().toUri();

	RestTemplate rest = new RestTemplate();

	try {
		// Send request to the Github-API
		rest.exchange(repoUri, HttpMethod.DELETE, null, String.class);
	} catch (RestClientException r) {
		throw new GitHubAPIException("Could not delete repository from Github!", r);
	}
}
 
Example 8
Source File: GithubDataGrabber.java    From Refactoring-Bot with MIT License 5 votes vote down vote up
/**
 * This method updates a pull request on Github.
 * 
 * @param send
 * @param gitConfig
 * @throws GitHubAPIException
 * @throws URISyntaxException
 */
public void updatePullRequest(GithubUpdateRequest send, GitConfiguration gitConfig, Integer requestNumber)
		throws GitHubAPIException, URISyntaxException {

	URI configUri = createURIFromApiLink(gitConfig.getRepoApiLink());

	// Build URI
	UriComponentsBuilder apiUriBuilder = UriComponentsBuilder.newInstance().scheme(configUri.getScheme())
			.host(configUri.getHost()).path(configUri.getPath() + "/pulls/" + requestNumber);

	apiUriBuilder.queryParam("access_token", gitConfig.getBotToken());

	URI pullsUri = apiUriBuilder.build().encode().toUri();

	// For PATCH-Requests
	HttpHeaders headers = new HttpHeaders();
	MediaType mediaType = new MediaType("application", "merge-patch+json");
	headers.setContentType(mediaType);

	HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
	RestTemplate rest = new RestTemplate(requestFactory);

	try {
		// Send request to the GitHub-API
		rest.exchange(pullsUri, HttpMethod.PATCH, new HttpEntity<>(send), String.class);
	} catch (RestClientException e) {
		throw new GitHubAPIException("Could not update pull request!", e);
	}
}
 
Example 9
Source File: JobRestControllerIT.java    From spring-batch-lightmin with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetJobInstancesByJobName() {
    final String jobName = "simpleJob";
    final String uri = LOCALHOST + ":" + this.getServerPort() + AbstractRestController
            .JobRestControllerAPI.JOB_INSTANCES_JOB_NAME;
    final UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(uri);
    uriComponentsBuilder.queryParam("jobname", jobName);
    final ResponseEntity<JobInstancePage> response = this.restTemplate.getForEntity(uriComponentsBuilder.toUriString(), JobInstancePage.class);
    assertThat(response).isNotNull();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(response.getBody().getJobName()).isEqualTo(jobName);
}
 
Example 10
Source File: JobRestControllerIT.java    From spring-batch-lightmin with Apache License 2.0 5 votes vote down vote up
@Test
public void testgetJobInstancesByJobName() {
    final String jobName = "simpleJob";
    final String uri = LOCALHOST + ":" + this.getServerPort() + AbstractRestController.JobRestControllerAPI
            .JOB_INSTANCES_JOB_NAME;
    final UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(uri);
    uriComponentsBuilder.queryParam("jobname", jobName);
    final ResponseEntity<JobInstancePage> response = this.restTemplate.getForEntity(uriComponentsBuilder.toUriString(), JobInstancePage.class);
    assertThat(response).isNotNull();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(response.getBody().getTotalJobInstanceCount()).isNotNull();
    assertThat(response.getBody().getJobInstances()).isNotEmpty();
    assertThat(response.getBody().getPageSize()).isNotNull();
    assertThat(response.getBody().getJobName()).isEqualTo(jobName);
}
 
Example 11
Source File: EtcdClient.java    From spring-boot-etcd with MIT License 5 votes vote down vote up
public EtcdResponse deleteDir(String key) throws EtcdException {
	UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE);
	builder.pathSegment(key);
	builder.queryParam("dir", "true");

	return execute(builder, HttpMethod.DELETE, null, EtcdResponse.class);
}
 
Example 12
Source File: PostBackManager.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * クエリ・パラメータ付きのURLを生成します。
 * @param path パス
 * @param parameters クエリ・パラメータが格納された{@link Map}インスタンス
 * @param encode エンコードの有無
 * @return クエリ・パラメータ付きのURL
 */
public static String buildUri(String path, Map<String, String> parameters, boolean encode) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromPath(path);
    if (!parameters.isEmpty()) {
        Set<String> sets = parameters.keySet();
        for (String key : sets) {
            builder.queryParam(key, parameters.get(key));
        }
    }
    if (encode) {
        return builder.build().encode().toString();
    } else {
        return builder.build().toString();
    }
}
 
Example 13
Source File: DefaultSkipperClient.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Info> statuses(String... releaseNames) {
	ParameterizedTypeReference<Map<String, Info>> typeReference =
		new ParameterizedTypeReference<Map<String, Info>>() { };

	UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUri + "/release/statuses");
	builder.queryParam("names", StringUtils.arrayToCommaDelimitedString(releaseNames));

	ResponseEntity<Map<String, Info>> responseEntity =
			restTemplate.exchange(builder.toUriString(),
					HttpMethod.GET,
					null,
					typeReference);
	return responseEntity.getBody();
}
 
Example 14
Source File: WechatMessageTemplate.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
public UriComponentsBuilder createUriParameter(UriComponentsBuilder builder, Values context){
    builder.queryParam("agentid", this.getAgentId())
            .queryParam("msgtype","text")
            .queryParam("text",this.createMessage(context));
    if (StringUtils.hasText(toUser)) {
        builder.queryParam("touser", this.createUserIdList(context));
    }
    if (StringUtils.hasText(toParty)) {
        builder.queryParam("toparty", this.createDepartmentIdList(context));
    }
    return builder;
}
 
Example 15
Source File: DockerServiceImpl.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
@Override
public ServiceCallResult killContainer(KillContainerArg arg) {
    Assert.notNull(arg.getId(), "id is null");
    UriComponentsBuilder ub = getUrlContainer(arg.getId(), "kill");
    KillContainerArg.Signal signal = arg.getSignal();
    if (signal != null) {
        ub.queryParam("signal", signal);
    }
    return postAction(ub, null);

}
 
Example 16
Source File: AviApi.java    From sdk with Apache License 2.0 5 votes vote down vote up
public String buildApiParams(String path, Map<String, String> params) {
	UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(restTemplate.getUriTemplateHandler().expand("/").toString().concat(path));
	if (null != params) {
		for(String key: params.keySet()) {
			uriBuilder.queryParam(key, params.get(key));
		}
	}
	return uriBuilder.toUriString();
}
 
Example 17
Source File: OAuth2ConfigResourceClient.java    From spring-cloud-services-starters with Apache License 2.0 5 votes vote down vote up
private Resource getResource(String profile, String label, String path, ResourceType resourceType) {
	Assert.isTrue(configClientProperties.getName() != null && !configClientProperties.getName().isEmpty(),
			"Spring application name is undefined.");

	Assert.notEmpty(configClientProperties.getUri(), "Config server URI is undefined");
	Assert.hasText(configClientProperties.getUri()[0], "Config server URI is undefined.");

	if (profile == null) {
		profile = configClientProperties.getProfile();
		if (profile == null || profile.isEmpty()) {
			profile = "default";
		}
	}

	if (label == null) {
		label = configClientProperties.getLabel();
	}

	UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(configClientProperties.getUri()[0])
			.pathSegment(configClientProperties.getName()).pathSegment(profile).pathSegment(label)
			.pathSegment(path);
	if (label == null) {
		urlBuilder.queryParam("useDefaultLabel");
	}
	RequestEntity.HeadersBuilder<?> requestBuilder = RequestEntity.get(urlBuilder.build().toUri());
	if (StringUtils.hasText(configClientProperties.getToken())) {
		requestBuilder.header(TOKEN_HEADER, configClientProperties.getToken());
	}
	if (resourceType == ResourceType.BINARY) {
		requestBuilder.accept(MediaType.APPLICATION_OCTET_STREAM);
	}

	ResponseEntity<Resource> forEntity = restTemplate.exchange(requestBuilder.build(), Resource.class);
	return forEntity.getBody();
}
 
Example 18
Source File: RecaptchaAwareRedirectStrategy.java    From recaptcha-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
    UriComponentsBuilder urlBuilder = fromUriString(url);
    AuthenticationException exception = getAuthenticationException(request);
    if (exception instanceof RecaptchaAuthenticationException) {
        urlBuilder.queryParam(RECAPTCHA_ERROR_PARAMETER_NAME);
    } else {
        urlBuilder.queryParam(ERROR_PARAMETER_NAME);
    }
    if (failuresManager.isRecaptchaRequired(request)) {
        urlBuilder.queryParam(SHOW_RECAPTCHA_QUERY_PARAM);
    }
    super.sendRedirect(request, response, urlBuilder.build(true).toUriString());
}
 
Example 19
Source File: FrontChannelLogoutAction.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
protected Event doInternalExecute(final HttpServletRequest request, final HttpServletResponse response,
        final RequestContext context) throws Exception {

    final List<LogoutRequest> logoutRequests = WebUtils.getLogoutRequests(context);
    final Integer startIndex = getLogoutIndex(context);
    if (logoutRequests != null) {
        for (int i = startIndex; i < logoutRequests.size(); i++) {
            final LogoutRequest logoutRequest = logoutRequests.get(i);
            if (logoutRequest.getStatus() == LogoutRequestStatus.NOT_ATTEMPTED) {
                // assume it has been successful
                logoutRequest.setStatus(LogoutRequestStatus.SUCCESS);

                // save updated index
                putLogoutIndex(context, i + 1);

                final String logoutUrl = logoutRequest.getLogoutUrl().toExternalForm();
                LOGGER.debug("Using logout url [{}] for front-channel logout requests", logoutUrl);

                final String logoutMessage = logoutManager.createFrontChannelLogoutMessage(logoutRequest);
                LOGGER.debug("Front-channel logout message to send under [{}] is [{}]",
                        this.logoutRequestParameter, logoutMessage);

                // redirect to application with SAML logout message
                final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(logoutUrl);
                builder.queryParam(this.logoutRequestParameter, URLEncoder.encode(logoutMessage, "UTF-8"));

                return result(REDIRECT_APP_EVENT, DEFAULT_FLOW_ATTRIBUTE_LOGOUT_URL, builder.build().toUriString());
            }
        }
    }

    // no new service with front-channel logout -> finish logout
    return new Event(this, FINISH_EVENT);
}
 
Example 20
Source File: EtcdClient.java    From spring-boot-etcd with MIT License 3 votes vote down vote up
/**
 * Atomically deletes a key-value pair in etcd.
 * 
 * @param key
 *            the key
 * @param prevValue
 *            the previous value of the key
 * @return the response from etcd with the node
 * @throws EtcdException
 *             in case etcd returned an error
 */
public EtcdResponse compareAndDelete(final String key, String prevValue) throws EtcdException {
	UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE);
	builder.pathSegment(key);
	builder.queryParam("prevValue", prevValue);

	return execute(builder, HttpMethod.DELETE, null, EtcdResponse.class);
}