org.springframework.web.util.DefaultUriBuilderFactory Java Examples

The following examples show how to use org.springframework.web.util.DefaultUriBuilderFactory. 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: WebClientRequestsUnitTest.java    From tutorials with MIT License 7 votes vote down vote up
@Test
public void whenUriComponentEncoding_thenQueryParamsNotEscaped() {
    DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(BASE_URL);
    factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.URI_COMPONENT);
    this.webClient = WebClient
            .builder()
            .uriBuilderFactory(factory)
            .baseUrl(BASE_URL)
            .exchangeFunction(exchangeFunction)
            .build();
    this.webClient.get()
            .uri(uriBuilder -> uriBuilder
                    .path("/products/")
                    .queryParam("name", "AndroidPhone")
                    .queryParam("color", "black")
                    .queryParam("deliveryDate", "13/04/2019")
                    .build())
            .exchange()
            .block(Duration.ofSeconds(1));
    verifyCalledUrl("/products/?name=AndroidPhone&color=black&deliveryDate=13/04/2019");
}
 
Example #2
Source File: AsyncRestTemplate.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Configure default URI variable values. This is a shortcut for:
 * <pre class="code">
 * DefaultUriTemplateHandler handler = new DefaultUriTemplateHandler();
 * handler.setDefaultUriVariables(...);
 *
 * AsyncRestTemplate restTemplate = new AsyncRestTemplate();
 * restTemplate.setUriTemplateHandler(handler);
 * </pre>
 * @param defaultUriVariables the default URI variable values
 * @since 4.3
 */
@SuppressWarnings("deprecation")
public void setDefaultUriVariables(Map<String, ?> defaultUriVariables) {
	UriTemplateHandler handler = this.syncTemplate.getUriTemplateHandler();
	if (handler instanceof DefaultUriBuilderFactory) {
		((DefaultUriBuilderFactory) handler).setDefaultUriVariables(defaultUriVariables);
	}
	else if (handler instanceof org.springframework.web.util.AbstractUriTemplateHandler) {
		((org.springframework.web.util.AbstractUriTemplateHandler) handler)
				.setDefaultUriVariables(defaultUriVariables);
	}
	else {
		throw new IllegalArgumentException(
				"This property is not supported with the configured UriTemplateHandler.");
	}
}
 
Example #3
Source File: AviRestUtils.java    From sdk with Apache License 2.0 6 votes vote down vote up
public static RestTemplate getRestTemplate(AviCredentials creds) {
	RestTemplate restTemplate = null;
	if (creds != null) {
		try {
			restTemplate = getInitializedRestTemplate(creds);
			restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(getControllerURL(creds) + API_PREFIX));
			List<ClientHttpRequestInterceptor> interceptors = 
					Collections.<ClientHttpRequestInterceptor>singletonList(
							new AviAuthorizationInterceptor(creds));
			restTemplate.setInterceptors(interceptors);
			restTemplate.setMessageConverters(getMessageConverters(restTemplate));
			return restTemplate;
		} catch (Exception e) {
			LOGGER.severe("Exception during rest template initialization");

		}
	}
	return restTemplate;
}
 
Example #4
Source File: PatreonAPI.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
public PatreonAPI(@NonNull String accessToken) {

        this.restTemplate = new RestTemplateBuilder()
                .rootUri(BASE_URI)
                .setConnectTimeout(HTTP_TIMEOUT_DURATION)
                .setReadTimeout(HTTP_TIMEOUT_DURATION)
                .uriTemplateHandler(new DefaultUriBuilderFactory(BASE_URI))
                .additionalInterceptors((request, body, execution) -> {
                    HttpHeaders headers = request.getHeaders();
                    headers.add("Authorization", "Bearer " + accessToken);
                    headers.add("User-Agent", "JuniperBot");
                    return execution.execute(request, body);
                })
                .additionalMessageConverters(new JsonApiHttpMessageConverter(
                        Member.class,
                        User.class
                ))
                .build();
    }
 
Example #5
Source File: RestTemplateTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void getForObjectWithCustomUriTemplateHandler() throws Exception {
	DefaultUriBuilderFactory uriTemplateHandler = new DefaultUriBuilderFactory();
	template.setUriTemplateHandler(uriTemplateHandler);
	mockSentRequest(GET, "http://example.com/hotels/1/pic/pics%2Flogo.png/size/150x150");
	mockResponseStatus(HttpStatus.OK);
	given(response.getHeaders()).willReturn(new HttpHeaders());
	given(response.getBody()).willReturn(StreamUtils.emptyInput());

	Map<String, String> uriVariables = new HashMap<>(2);
	uriVariables.put("hotel", "1");
	uriVariables.put("publicpath", "pics/logo.png");
	uriVariables.put("scale", "150x150");

	String url = "http://example.com/hotels/{hotel}/pic/{publicpath}/size/{scale}";
	template.getForObject(url, String.class, uriVariables);

	verify(response).close();
}
 
Example #6
Source File: RestTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void getForObjectWithCustomUriTemplateHandler() throws Exception {
	DefaultUriBuilderFactory uriTemplateHandler = new DefaultUriBuilderFactory();
	template.setUriTemplateHandler(uriTemplateHandler);
	mockSentRequest(GET, "https://example.com/hotels/1/pic/pics%2Flogo.png/size/150x150");
	mockResponseStatus(HttpStatus.OK);
	given(response.getHeaders()).willReturn(new HttpHeaders());
	given(response.getBody()).willReturn(StreamUtils.emptyInput());

	Map<String, String> uriVariables = new HashMap<>(2);
	uriVariables.put("hotel", "1");
	uriVariables.put("publicpath", "pics/logo.png");
	uriVariables.put("scale", "150x150");

	String url = "https://example.com/hotels/{hotel}/pic/{publicpath}/size/{scale}";
	template.getForObject(url, String.class, uriVariables);

	verify(response).close();
}
 
Example #7
Source File: DefaultWebClient.java    From spring-analysis-note with MIT License 6 votes vote down vote up
DefaultWebClient(ExchangeFunction exchangeFunction, @Nullable UriBuilderFactory factory,
		@Nullable HttpHeaders defaultHeaders, @Nullable MultiValueMap<String, String> defaultCookies,
		@Nullable Consumer<RequestHeadersSpec<?>> defaultRequest, DefaultWebClientBuilder builder) {

	this.exchangeFunction = exchangeFunction;
	this.uriBuilderFactory = (factory != null ? factory : new DefaultUriBuilderFactory());
	this.defaultHeaders = defaultHeaders;
	this.defaultCookies = defaultCookies;
	this.defaultRequest = defaultRequest;
	this.builder = builder;
}
 
Example #8
Source File: DefaultWebClientBuilder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private UriBuilderFactory initUriBuilderFactory() {
	if (this.uriBuilderFactory != null) {
		return this.uriBuilderFactory;
	}
	DefaultUriBuilderFactory factory = this.baseUrl != null ?
			new DefaultUriBuilderFactory(this.baseUrl) : new DefaultUriBuilderFactory();
	factory.setDefaultUriVariables(this.defaultUriVariables);
	return factory;
}
 
Example #9
Source File: WebTestClientTestBase.java    From spring-auto-restdocs with Apache License 2.0 6 votes vote down vote up
private String getAccessToken(String username, String password) {
    String authorization = "Basic "
            + new String(Base64Utils.encode("app:very_secret".getBytes()));
    String contentType = MediaType.APPLICATION_JSON + ";charset=UTF-8";

    String body = new String(webTestClient.post()
            .uri(uriBuilder -> new DefaultUriBuilderFactory()
                    .uriString("/oauth/token").queryParam("username", username)
                    .queryParam("password", password)
                    .queryParam("grant_type", "password")
                    .queryParam("scope", "read write").queryParam("client_id", "app")
                    .queryParam("client_secret", "very_secret").build())
            .header("Authorization", authorization)
            .contentType(MediaType.APPLICATION_FORM_URLENCODED).exchange()
            .expectStatus().isOk().expectHeader().contentType(contentType)
            .expectBody().jsonPath("$.access_token").isNotEmpty()
            .jsonPath("$.token_type").isEqualTo("bearer").jsonPath("$.refresh_token")
            .isNotEmpty().jsonPath("$.expires_in").isNumber().jsonPath("$.scope")
            .isEqualTo("read write").returnResult().getResponseBody());

    return body.substring(17, 53);
}
 
Example #10
Source File: AsyncRestTemplate.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Configure default URI variable values. This is a shortcut for:
 * <pre class="code">
 * DefaultUriTemplateHandler handler = new DefaultUriTemplateHandler();
 * handler.setDefaultUriVariables(...);
 *
 * AsyncRestTemplate restTemplate = new AsyncRestTemplate();
 * restTemplate.setUriTemplateHandler(handler);
 * </pre>
 * @param defaultUriVariables the default URI variable values
 * @since 4.3
 */
@SuppressWarnings("deprecation")
public void setDefaultUriVariables(Map<String, ?> defaultUriVariables) {
	UriTemplateHandler handler = this.syncTemplate.getUriTemplateHandler();
	if (handler instanceof DefaultUriBuilderFactory) {
		((DefaultUriBuilderFactory) handler).setDefaultUriVariables(defaultUriVariables);
	}
	else if (handler instanceof org.springframework.web.util.AbstractUriTemplateHandler) {
		((org.springframework.web.util.AbstractUriTemplateHandler) handler)
				.setDefaultUriVariables(defaultUriVariables);
	}
	else {
		throw new IllegalArgumentException(
				"This property is not supported with the configured UriTemplateHandler.");
	}
}
 
Example #11
Source File: Jira.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
/**
 * @param templateBuilder
 * @param logger
 * @param jiraProperties
 */
public Jira(@Qualifier("tracker") RestTemplateBuilder templateBuilder, Logger logger, JiraProperties jiraProperties) {

	String baseUri = String.format("%s/rest/api/2", jiraProperties.getApiUrl());

	this.operations = templateBuilder.uriTemplateHandler(new DefaultUriBuilderFactory(baseUri)).build();
	this.logger = logger;
	this.jiraProperties = jiraProperties;
}
 
Example #12
Source File: ModuleClient.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
public void deleteTemplate(String templateName, ModuleIO moduleInput, String tryTo, boolean urlEncodeTemplateName) {
    DefaultUriBuilderFactory.EncodingMode defaultEncodingMode = defaultUriBuilderFactory.getEncodingMode();
    try {
        if (!urlEncodeTemplateName) {
            defaultUriBuilderFactory.setEncodingMode(NONE);
        }
        restTemplate.deleteForEntity("/modules/{name}/{version}/{type}/templates/" + templateName,
                getResponseType(tryTo, ResponseEntity.class),
                urlEncodeUtf8(moduleInput.getName()),
                urlEncodeUtf8(moduleInput.getVersion()),
                TestVersionType.fromIsWorkingCopy(moduleInput.getIsWorkingCopy()));
    } finally {
        defaultUriBuilderFactory.setEncodingMode(defaultEncodingMode);
    }
}
 
Example #13
Source File: ModuleClient.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
public void getTemplate(String templateName, ModuleIO moduleInput, String tryTo, boolean urlEncodeTemplateName) {
    DefaultUriBuilderFactory.EncodingMode defaultEncodingMode = defaultUriBuilderFactory.getEncodingMode();
    try {
        if (!urlEncodeTemplateName) {
            defaultUriBuilderFactory.setEncodingMode(NONE);
        }
        restTemplate.getForEntity("/modules/{name}/{version}/{type}/templates/" + templateName,
                getResponseType(tryTo, TemplateIO.class),
                moduleInput.getName(),
                moduleInput.getVersion(),
                TestVersionType.fromIsWorkingCopy(moduleInput.getIsWorkingCopy()));
    } finally {
        defaultUriBuilderFactory.setEncodingMode(defaultEncodingMode);
    }
}
 
Example #14
Source File: ModuleClient.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@Autowired
public ModuleClient(CustomRestTemplate restTemplate,
                    DefaultUriBuilderFactory defaultUriBuilderFactory,
                    TestContext testContext) {
    this.restTemplate = restTemplate;
    this.defaultUriBuilderFactory = defaultUriBuilderFactory;
    this.testContext = testContext;
}
 
Example #15
Source File: DogApiService.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@PostConstruct
public void init() {
    String apiKey = workerProperties.getDogApi().getKey();
    if (StringUtils.isEmpty(apiKey)) {
        return;
    }
    this.restTemplate = new RestTemplateBuilder()
            .rootUri(BASE_URI)
            .setConnectTimeout(HTTP_TIMEOUT_DURATION)
            .setReadTimeout(HTTP_TIMEOUT_DURATION)
            .uriTemplateHandler(new DefaultUriBuilderFactory(BASE_URI))
            .additionalInterceptors((request, body, execution) -> {
                HttpHeaders headers = request.getHeaders();
                headers.add("x-api-key", apiKey);
                headers.add("User-Agent", "JuniperBot");
                return execution.execute(request, body);
            })
            .build();
}
 
Example #16
Source File: CredHubRestTemplateFactory.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
/**
 * Configure a {@link RestTemplate} for communication with a CredHub server.
 * @param restTemplate an existing {@link RestTemplate} to configure
 * @param baseUri the base URI for the CredHub server
 * @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
 * creating new connections
 */
private static void configureRestTemplate(RestTemplate restTemplate, String baseUri,
		ClientHttpRequestFactory clientHttpRequestFactory) {
	restTemplate.setRequestFactory(clientHttpRequestFactory);
	restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(baseUri));
	restTemplate.getInterceptors().add(new CredHubRequestInterceptor());
	restTemplate.setMessageConverters(
			Arrays.asList(new ByteArrayHttpMessageConverter(), new StringHttpMessageConverter(),
					new MappingJackson2HttpMessageConverter(JsonUtils.buildObjectMapper())));
}
 
Example #17
Source File: SpringRESTClientConnector.java    From egeria with Apache License 2.0 5 votes vote down vote up
/**
 * Default constructor
 */
public SpringRESTClientConnector() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException
{
    super();

    /*
     * Rather than creating a RestTemplate directly, the RestTemplateBuilder is used so that the
     * uriTemplateHandler can be specified. The URI encoding is set to VALUES_ONLY so that the
     * '+' character, which is used in queryParameters conveying searchCriteria, which can be a
     * regex, is encoded as '+' and not converted to a space character.
     * Prior to this change a regex containing a '+' character would be split into two space
     * separated words. For example, the regex "name_0+7" (which would match name_07, name_007,
     * name_0007, etc) would be sent to the server as "name_0 7".
     */
    DefaultUriBuilderFactory builderFactory = new DefaultUriBuilderFactory();
    builderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY);


    /* TODO: Disable SSL cert verification -- for now */
    HttpsURLConnection.setDefaultHostnameVerifier(bypassVerifier);
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, INSECURE_MANAGER, null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    restTemplate = new RestTemplate();

    restTemplate.setUriTemplateHandler(builderFactory);

    /* Ensure that the REST template always uses UTF-8 */
    List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
    converters.removeIf(httpMessageConverter -> httpMessageConverter instanceof StringHttpMessageConverter);
    converters.add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));

}
 
Example #18
Source File: RestTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Configure default URI variable values. This is a shortcut for:
 * <pre class="code">
 * DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory();
 * handler.setDefaultUriVariables(...);
 *
 * RestTemplate restTemplate = new RestTemplate();
 * restTemplate.setUriTemplateHandler(handler);
 * </pre>
 * @param uriVars the default URI variable values
 * @since 4.3
 */
@SuppressWarnings("deprecation")
public void setDefaultUriVariables(Map<String, ?> uriVars) {
	if (this.uriTemplateHandler instanceof DefaultUriBuilderFactory) {
		((DefaultUriBuilderFactory) this.uriTemplateHandler).setDefaultUriVariables(uriVars);
	}
	else if (this.uriTemplateHandler instanceof org.springframework.web.util.AbstractUriTemplateHandler) {
		((org.springframework.web.util.AbstractUriTemplateHandler) this.uriTemplateHandler)
				.setDefaultUriVariables(uriVars);
	}
	else {
		throw new IllegalArgumentException(
				"This property is not supported with the configured UriTemplateHandler.");
	}
}
 
Example #19
Source File: GitHub.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
/**
 * @param templateBuilder
 * @param logger
 * @param properties
 */
public GitHub(@Qualifier("tracker") RestTemplateBuilder templateBuilder, Logger logger, GitHubProperties properties) {

	this.operations = templateBuilder.uriTemplateHandler(new DefaultUriBuilderFactory(properties.getApiUrl())).build();
	this.logger = logger;
	this.properties = properties;
}
 
Example #20
Source File: DefaultWebClientBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
private UriBuilderFactory initUriBuilderFactory() {
	if (this.uriBuilderFactory != null) {
		return this.uriBuilderFactory;
	}
	DefaultUriBuilderFactory factory = this.baseUrl != null ?
			new DefaultUriBuilderFactory(this.baseUrl) : new DefaultUriBuilderFactory();
	factory.setDefaultUriVariables(this.defaultUriVariables);
	return factory;
}
 
Example #21
Source File: DefaultWebClient.java    From java-technology-stack with MIT License 5 votes vote down vote up
DefaultWebClient(ExchangeFunction exchangeFunction, @Nullable UriBuilderFactory factory,
		@Nullable HttpHeaders defaultHeaders, @Nullable MultiValueMap<String, String> defaultCookies,
		@Nullable Consumer<RequestHeadersSpec<?>> defaultRequest, DefaultWebClientBuilder builder) {

	this.exchangeFunction = exchangeFunction;
	this.uriBuilderFactory = (factory != null ? factory : new DefaultUriBuilderFactory());
	this.defaultHeaders = defaultHeaders;
	this.defaultCookies = defaultCookies;
	this.defaultRequest = defaultRequest;
	this.builder = builder;
}
 
Example #22
Source File: RestTemplate.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Configure default URI variable values. This is a shortcut for:
 * <pre class="code">
 * DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory();
 * handler.setDefaultUriVariables(...);
 *
 * RestTemplate restTemplate = new RestTemplate();
 * restTemplate.setUriTemplateHandler(handler);
 * </pre>
 * @param uriVars the default URI variable values
 * @since 4.3
 */
@SuppressWarnings("deprecation")
public void setDefaultUriVariables(Map<String, ?> uriVars) {
	if (this.uriTemplateHandler instanceof DefaultUriBuilderFactory) {
		((DefaultUriBuilderFactory) this.uriTemplateHandler).setDefaultUriVariables(uriVars);
	}
	else if (this.uriTemplateHandler instanceof org.springframework.web.util.AbstractUriTemplateHandler) {
		((org.springframework.web.util.AbstractUriTemplateHandler) this.uriTemplateHandler)
				.setDefaultUriVariables(uriVars);
	}
	else {
		throw new IllegalArgumentException(
				"This property is not supported with the configured UriTemplateHandler.");
	}
}
 
Example #23
Source File: TestRestTemplateWrapper.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
// TODO : upgrade to spring 5 will having warning's , we'll fix it later
  private Map<String, ?> defaultUriVariablesOf(RestTemplate wrapper1) {
    return ((DefaultUriBuilderFactory) wrapper1.getUriTemplateHandler()).getDefaultUriVariables();
  }
 
Example #24
Source File: TestRestTemplateConfig.java    From hesperides with GNU General Public License v3.0 4 votes vote down vote up
@Bean
public CustomRestTemplate buildRestTemplate(Environment environment, Gson gson, DefaultUriBuilderFactory defaultUriBuilderFactory) {
    return new CustomRestTemplate(gson, new LocalHostUriTemplateHandler(environment, "http", defaultUriBuilderFactory));
}
 
Example #25
Source File: TestRestTemplateConfig.java    From hesperides with GNU General Public License v3.0 4 votes vote down vote up
@Bean
public DefaultUriBuilderFactory defaultUriBuilderFactory() {
    return new DefaultUriBuilderFactory();
}
 
Example #26
Source File: IntegTestHttpConfig.java    From hesperides with GNU General Public License v3.0 4 votes vote down vote up
@Bean
public CustomRestTemplate buildRestTemplate(Gson gson, DefaultUriBuilderFactory defaultUriBuilderFactory) throws Exception {
    return new CustomRestTemplate(gson, defaultUriBuilderFactory, buildHttpClient());
}
 
Example #27
Source File: IntegTestHttpConfig.java    From hesperides with GNU General Public License v3.0 4 votes vote down vote up
@Bean
public DefaultUriBuilderFactory defaultUriBuilderFactory() {
    return new DefaultUriBuilderFactory(remoteBaseUrl);
}
 
Example #28
Source File: PaverClient.java    From data-highway with Apache License 2.0 4 votes vote down vote up
public PaverClient(String host, String user, String pass) {
  handler = new DefaultUriBuilderFactory("https://" + host + "/paver/v1");
  creds = "Basic " + Base64.getEncoder().encodeToString((user + ":" + pass).getBytes(UTF_8));
}
 
Example #29
Source File: RestTemplate.java    From java-technology-stack with MIT License 4 votes vote down vote up
private static DefaultUriBuilderFactory initUriTemplateHandler() {
	DefaultUriBuilderFactory uriFactory = new DefaultUriBuilderFactory();
	uriFactory.setEncodingMode(EncodingMode.URI_COMPONENT);  // for backwards compatibility..
	return uriFactory;
}
 
Example #30
Source File: RestTemplate.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private static DefaultUriBuilderFactory initUriTemplateHandler() {
	DefaultUriBuilderFactory uriFactory = new DefaultUriBuilderFactory();
	uriFactory.setEncodingMode(EncodingMode.URI_COMPONENT);  // for backwards compatibility..
	return uriFactory;
}