org.springframework.web.util.UriTemplate Java Examples

The following examples show how to use org.springframework.web.util.UriTemplate. 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: WireMockJsonSnippet.java    From restdocs-wiremock with Apache License 2.0 6 votes vote down vote up
/**
 * If ATTRIBUTE_NAME_URL_TEMPLATE is present use it to build a urlPattern instead of a urlPath.
 *
 * This allows for more flexible request matching when the path contains variable elements.
 *
 * ATTRIBUTE_NAME_URL_TEMPLATE is present if the urlTemplate factore methods of RestDocumentationRequestBuilders are used.
 *
 * @param operation
 * @param requestBuilder
 */
private void urlPathOrUrlPattern(Operation operation, Maps.Builder<Object, Object> requestBuilder) {
	String urlTemplate = (String) operation.getAttributes().get(ATTRIBUTE_NAME_URL_TEMPLATE);
	if (StringUtils.isEmpty(urlTemplate)) {
		requestBuilder.put("urlPath", operation.getRequest().getUri().getRawPath());
	} else {
		UriTemplate uriTemplate = new UriTemplate(urlTemplate);
		UriComponentsBuilder uriTemplateBuilder = UriComponentsBuilder.fromUriString(urlTemplate);
		Maps.Builder<String, String> uriVariables = Maps.builder();
		for (String variableName : uriTemplate.getVariableNames()) {
			uriVariables.put(variableName, "[^/]+");
		}
		String uriPathRegex = uriTemplateBuilder.buildAndExpand(uriVariables.build()).getPath();
		requestBuilder.put("urlPathPattern", uriPathRegex);
	}
}
 
Example #2
Source File: RestScriptsController.java    From engine with GNU General Public License v3.0 6 votes vote down vote up
protected String parseScriptUrlForVariables(SiteContext siteContext, String scriptUrl,
                                            Map<String, Object> variables) {
    ContentStoreService storeService = siteContext.getStoreService();
    if (!storeService.exists(siteContext.getContext(), scriptUrl) && urlTemplateScanner != null) {
        List<UriTemplate> urlTemplates = urlTemplateScanner.scan(siteContext);
        if (CollectionUtils.isNotEmpty(urlTemplates)) {
            for (UriTemplate template : urlTemplates) {
                if (template.matches(scriptUrl)) {
                    Map<String, String> pathVars = template.match(scriptUrl);
                    String actualScriptUrl = template.toString();

                    variables.put(GroovyScriptUtils.VARIABLE_PATH_VARS, pathVars);

                    return actualScriptUrl;
                }
            }
        }
    }

    return scriptUrl;
}
 
Example #3
Source File: RequestEntityTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void uriVariablesExpansion() throws URISyntaxException {
	URI uri = new UriTemplate("https://example.com/{foo}").expand("bar");
	RequestEntity.get(uri).accept(MediaType.TEXT_PLAIN).build();

	String url = "https://www.{host}.com/{path}";
	String host = "example";
	String path = "foo/bar";
	URI expected = new URI("https://www.example.com/foo/bar");

	uri = new UriTemplate(url).expand(host, path);
	RequestEntity<?> entity = RequestEntity.get(uri).build();
	assertEquals(expected, entity.getUrl());

	Map<String, String> uriVariables = new HashMap<>(2);
	uriVariables.put("host", host);
	uriVariables.put("path", path);

	uri = new UriTemplate(url).expand(uriVariables);
	entity = RequestEntity.get(uri).build();
	assertEquals(expected, entity.getUrl());
}
 
Example #4
Source File: ScriptUrlTemplateScannerImpl.java    From engine with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<UriTemplate> scan(SiteContext siteContext) {
    Context context = siteContext.getContext();
    ContentStoreService storeService = siteContext.getStoreService();
    ScriptFactory scriptFactory = siteContext.getScriptFactory();
    List<String> scriptUrls = new ArrayList<>();
    List<UriTemplate> urlTemplates = new ArrayList<>();

    findScripts(context, storeService, scriptFactory, scriptsFolder, scriptUrls);

    if (CollectionUtils.isNotEmpty(scriptUrls)) {
        for (String scriptUrl : scriptUrls) {
            Matcher matcher = urlVariablePlaceholderPattern.matcher(scriptUrl);
            if (matcher.find()) {
                urlTemplates.add(new UriTemplate(scriptUrl));
            }
        }
    }

    return urlTemplates;
}
 
Example #5
Source File: RequestEntityTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void uriVariablesExpansion() throws URISyntaxException {
	URI uri = new UriTemplate("http://example.com/{foo}").expand("bar");
	RequestEntity.get(uri).accept(MediaType.TEXT_PLAIN).build();

	String url = "http://www.{host}.com/{path}";
	String host = "example";
	String path = "foo/bar";
	URI expected = new URI("http://www.example.com/foo/bar");

	uri = new UriTemplate(url).expand(host, path);
	RequestEntity<?> entity = RequestEntity.get(uri).build();
	assertEquals(expected, entity.getUrl());

	Map<String, String> uriVariables = new HashMap<>(2);
	uriVariables.put("host", host);
	uriVariables.put("path", path);

	uri = new UriTemplate(url).expand(uriVariables);
	entity = RequestEntity.get(uri).build();
	assertEquals(expected, entity.getUrl());
}
 
Example #6
Source File: RequestEntityTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void uriVariablesExpansion() throws URISyntaxException {
	URI uri = new UriTemplate("http://example.com/{foo}").expand("bar");
	RequestEntity.get(uri).accept(MediaType.TEXT_PLAIN).build();

	String url = "http://www.{host}.com/{path}";
	String host = "example";
	String path = "foo/bar";
	URI expected = new URI("http://www.example.com/foo/bar");

	uri = new UriTemplate(url).expand(host, path);
	RequestEntity<?> entity = RequestEntity.get(uri).build();
	assertEquals(expected, entity.getUrl());

	Map<String, String> uriVariables = new HashMap<>(2);
	uriVariables.put("host", host);
	uriVariables.put("path", path);

	uri = new UriTemplate(url).expand(uriVariables);
	entity = RequestEntity.get(uri).build();
	assertEquals(expected, entity.getUrl());
}
 
Example #7
Source File: UriTemplateTest.java    From booties with Apache License 2.0 6 votes vote down vote up
@Test
public void checkParameters() {
	Map<String, Object> uriVariables = new HashMap<>();
	uriVariables.put("first", "eins");
	uriVariables.put("second", "zwei");
	uriVariables.put("bar", "baz");
	uriVariables.put("thing", "something");
	URI uri = new UriTemplate("http://example.org/{first}/path/{second}?foo={bar}&bar={thing}")
			.expand(uriVariables);

	String uriString = uri.toString();
	Assertions.assertThat(uriString).contains("foo=baz");
	Assertions.assertThat(uriString).contains("bar=something");
	Assertions.assertThat(uriString).contains("eins/path/zwei");
	System.out.println(uri.toString());
}
 
Example #8
Source File: RequestContext.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Return a context-aware URl for the given relative URL with placeholders (named keys with braces {@code {}}).
 * For example, send in a relative URL {@code foo/{bar}?spam={spam}} and a parameter map
 * {@code {bar=baz,spam=nuts}} and the result will be {@code [contextpath]/foo/baz?spam=nuts}.
 * @param relativeUrl the relative URL part
 * @param params a map of parameters to insert as placeholders in the url
 * @return a URL that points back to the server with an absolute path (also URL-encoded accordingly)
 */
public String getContextUrl(String relativeUrl, Map<String, ?> params) {
	String url = getContextPath() + relativeUrl;
	UriTemplate template = new UriTemplate(url);
	url = template.expand(params).toASCIIString();
	if (this.response != null) {
		url = this.response.encodeURL(url);
	}
	return url;
}
 
Example #9
Source File: SetPathGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public GatewayFilter apply(Config config) {
	UriTemplate uriTemplate = new UriTemplate(config.template);

	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			ServerHttpRequest req = exchange.getRequest();
			addOriginalRequestUrl(exchange, req.getURI());

			Map<String, String> uriVariables = getUriTemplateVariables(exchange);

			URI uri = uriTemplate.expand(uriVariables);
			String newPath = uri.getRawPath();

			exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, uri);

			ServerHttpRequest request = req.mutate().path(newPath).build();

			return chain.filter(exchange.mutate().request(request).build());
		}

		@Override
		public String toString() {
			return filterToStringCreator(SetPathGatewayFilterFactory.this)
					.append("template", config.getTemplate()).toString();
		}
	};
}
 
Example #10
Source File: InitializrService.java    From nb-springboot with Apache License 2.0 5 votes vote down vote up
public JsonNode getDependencies(String bootVersion) throws Exception {
    if (!dependencyMetaMap.containsKey(bootVersion)) {
        // set connection timeouts
        timeoutFromPrefs();
        // prepare request
        final String serviceUrl = NbPreferences.forModule(PrefConstants.class).get(PREF_INITIALIZR_URL,
                PrefConstants.DEFAULT_INITIALIZR_URL);
        UriTemplate template = new UriTemplate(serviceUrl.concat("/dependencies?bootVersion={bootVersion}"));
        RequestEntity<Void> req = RequestEntity
                .get(template.expand(bootVersion))
                .accept(MediaType.valueOf("application/vnd.initializr.v2.1+json"))
                .header("User-Agent", REST_USER_AGENT)
                .build();
        // connect
        logger.log(INFO, "Getting Spring Initializr dependencies metadata from: {0}", template);
        logger.log(INFO, "Asking metadata as: {0}", REST_USER_AGENT);
        long start = System.currentTimeMillis();
        ResponseEntity<String> respEntity = rt.exchange(req, String.class);
        // analyze response
        final HttpStatus statusCode = respEntity.getStatusCode();
        if (statusCode == OK) {
            ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
            final JsonNode depMeta = mapper.readTree(respEntity.getBody());
            logger.log(INFO, "Retrieved Spring Initializr dependencies metadata for boot version {0}. Took {1} msec",
                    new Object[]{bootVersion, System.currentTimeMillis() - start});
            if (logger.isLoggable(FINE)) {
                logger.fine(mapper.writeValueAsString(depMeta));
            }
            dependencyMetaMap.put(bootVersion, depMeta);
        } else {
            // log status code
            final String errMessage = String.format("Spring initializr service connection problem. HTTP status code: %s",
                    statusCode.toString());
            logger.severe(errMessage);
            // throw exception in order to set error message
            throw new RuntimeException(errMessage);
        }
    }
    return dependencyMetaMap.get(bootVersion);
}
 
Example #11
Source File: DependencyToggleBox.java    From nb-springboot with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
    JComponent c = (JComponent) e.getSource();
    final Object urlTemplate = c.getClientProperty(PROP_REFERENCE_TEMPLATE_URL);
    if (urlTemplate != null && currentBootVersion != null) {
        try {
            UriTemplate template = new UriTemplate(urlTemplate.toString());
            final URI uri = template.expand(currentBootVersion);
            HtmlBrowser.URLDisplayer.getDefault().showURL(uri.toURL());
        } catch (MalformedURLException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
 
Example #12
Source File: DependencyToggleBox.java    From nb-springboot with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
    JComponent c = (JComponent) e.getSource();
    final Object urlTemplate = c.getClientProperty(PROP_GUIDE_TEMPLATE_URL);
    if (urlTemplate != null && currentBootVersion != null) {
        try {
            UriTemplate template = new UriTemplate(urlTemplate.toString());
            final URI uri = template.expand(currentBootVersion);
            HtmlBrowser.URLDisplayer.getDefault().showURL(uri.toURL());
        } catch (MalformedURLException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
 
Example #13
Source File: RequestContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return a context-aware URl for the given relative URL with placeholders (named keys with braces {@code {}}).
 * For example, send in a relative URL {@code foo/{bar}?spam={spam}} and a parameter map
 * {@code {bar=baz,spam=nuts}} and the result will be {@code [contextpath]/foo/baz?spam=nuts}.
 * @param relativeUrl the relative URL part
 * @param params a map of parameters to insert as placeholders in the url
 * @return a URL that points back to the server with an absolute path (also URL-encoded accordingly)
 */
public String getContextUrl(String relativeUrl, Map<String, ?> params) {
	String url = getContextPath() + relativeUrl;
	UriTemplate template = new UriTemplate(url);
	url = template.expand(params).toASCIIString();
	if (this.response != null) {
		url = this.response.encodeURL(url);
	}
	return url;
}
 
Example #14
Source File: RestResourceHelper.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
private Map<String, String> getMatchList(final UriInfo uriInfo, final ResourceTemplate template) {
    final UriTemplate uriTemplate = new UriTemplate(template.getTemplate());
    String path = uriInfo.getRequestUri().getPath();
    if (path.endsWith("/")) {
        path = path.substring(0, (path.length() - 1));
    }
    return uriTemplate.match(path);
}
 
Example #15
Source File: RequestContext.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Return a context-aware URl for the given relative URL with placeholders (named keys with braces {@code {}}).
 * For example, send in a relative URL {@code foo/{bar}?spam={spam}} and a parameter map
 * {@code {bar=baz,spam=nuts}} and the result will be {@code [contextpath]/foo/baz?spam=nuts}.
 * @param relativeUrl the relative URL part
 * @param params a map of parameters to insert as placeholders in the url
 * @return a URL that points back to the server with an absolute path (also URL-encoded accordingly)
 */
public String getContextUrl(String relativeUrl, Map<String, ?> params) {
	String url = getContextPath() + relativeUrl;
	UriTemplate template = new UriTemplate(url);
	url = template.expand(params).toASCIIString();
	if (this.response != null) {
		url = this.response.encodeURL(url);
	}
	return url;
}
 
Example #16
Source File: RestHttpOperationInvoker.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves one Link from a Collection of Links based on the command invocation matching multiple relations from
 * the Link Index.
 * <p/>
 * @param command the CommandRequest object encapsulating details of the command invocation.
 * @param links a Collection of Links for the command matching the relation.
 * @return the resolved Link matching the command exactly as entered by the user.
 * @see #findLink(com.gemstone.gemfire.management.internal.cli.CommandRequest)
 * @see com.gemstone.gemfire.management.internal.cli.CommandRequest
 * @see com.gemstone.gemfire.management.internal.web.domain.Link
 * @see org.springframework.web.util.UriTemplate
 */
// Find and use the Link with the greatest number of path variables that can be expanded!
protected Link resolveLink(final CommandRequest command, final List<Link> links) {
  // NOTE, Gfsh's ParseResult contains a Map entry for all command options whether or not the user set the option
  // with a value on the command-line, argh!
  final Map<String, String> commandParametersCopy = CollectionUtils.removeKeys(
    new HashMap<String, String>(command.getParameters()), ExcludeNoValueFilter.INSTANCE);

  Link resolvedLink = null;

  int pathVariableCount = 0;

  for (final Link link : links) {
    final List<String> pathVariables = new UriTemplate(decode(link.getHref().toString())).getVariableNames();

    // first, all path variables in the URL/URI template must be resolvable/expandable for this Link
    // to even be considered...
    if (commandParametersCopy.keySet().containsAll(pathVariables)) {
      // then, either we have not found a Link for the command yet, or the number of resolvable/expandable
      // path variables in this Link has to be greater than the number of resolvable/expandable path variables
      // for the last Link
      if (resolvedLink == null || (pathVariables.size() > pathVariableCount)) {
        resolvedLink = link;
        pathVariableCount = pathVariables.size();
      }
    }
  }

  if (resolvedLink == null) {
    throw new RestApiCallForCommandNotFoundException(String.format("No REST API call for command (%1$s) was found!",
      command.getInput()));
  }

  return resolvedLink;
}
 
Example #17
Source File: CartRepositoryImpl.java    From the-app with Apache License 2.0 5 votes vote down vote up
@Autowired
public CartRepositoryImpl(@Value("${redis.cart.microservice.url}") String baseUrl,
                          RestTemplate restTemplate) {
    this.restTemplate = restTemplate;

    CREATE_TEMPLATE = new UriTemplate(baseUrl + CREATE);
    GET_TEMPLATE = new UriTemplate(baseUrl + GET);
    ADD_TEMPLATE = new UriTemplate(baseUrl + ADD);
    REMOVE_TEMPLATE = new UriTemplate(baseUrl + REMOVE);
    CLEAR_TEMPLATE = new UriTemplate(baseUrl + CLEAR);
}
 
Example #18
Source File: WireMockJsonSnippet.java    From restdocs-wiremock with Apache License 2.0 5 votes vote down vote up
private String responseBody(Operation operation) {
	OperationResponse response = operation.getResponse();
	String urlTemplateString = (String) operation.getAttributes().get(ATTRIBUTE_NAME_URL_TEMPLATE);

	return new ResponseTemplateProcessor(responseFieldTemplateDescriptors,
			urlTemplateString != null ? new UriTemplate(urlTemplateString) : null,
			response.getContentAsString()).replaceTemplateFields();
}
 
Example #19
Source File: ResponseTemplateProcessorTest.java    From restdocs-wiremock with Apache License 2.0 5 votes vote down vote up
@Test
public void should_replace_with_uri_variable_expression() {
    ResponseFieldTemplateDescriptor templateDescriptor = templatedResponseField("id").replacedWithUriTemplateVariableValue("someId");
    ResponseTemplateProcessor templateProcessor = new ResponseTemplateProcessor(
            singletonList(templateDescriptor),
            new UriTemplate("http://localhost/api/things/{someId}"),
            jsonBody);

    String result = templateProcessor.replaceTemplateFields();

    assertThat(result, sameJSONAs("{\n" +
            "  \"id\": \"{{request.requestLine.pathSegments.[2]}}\",\n" +
            "  \"name\": \"some\"\n" +
            "}"));
}
 
Example #20
Source File: ResponseTemplateProcessorTest.java    From restdocs-wiremock with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void should_throw_when_variable_name_not_found() {
    ResponseFieldTemplateDescriptor templateDescriptor = templatedResponseField("id").replacedWithUriTemplateVariableValue("someId");
    ResponseTemplateProcessor templateProcessor = new ResponseTemplateProcessor(
            singletonList(templateDescriptor),
            new UriTemplate("http://localhost/api/things/{someOtherId}"),
            jsonBody);

    templateProcessor.replaceTemplateFields();
}
 
Example #21
Source File: RestHttpOperationInvoker.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves one Link from a Collection of Links based on the command invocation matching multiple relations from
 * the Link Index.
 * <p/>
 * @param command the CommandRequest object encapsulating details of the command invocation.
 * @param links a Collection of Links for the command matching the relation.
 * @return the resolved Link matching the command exactly as entered by the user.
 * @see #findLink(com.gemstone.gemfire.management.internal.cli.CommandRequest)
 * @see com.gemstone.gemfire.management.internal.cli.CommandRequest
 * @see com.gemstone.gemfire.management.internal.web.domain.Link
 * @see org.springframework.web.util.UriTemplate
 */
// Find and use the Link with the greatest number of path variables that can be expanded!
protected Link resolveLink(final CommandRequest command, final List<Link> links) {
  // NOTE, Gfsh's ParseResult contains a Map entry for all command options whether or not the user set the option
  // with a value on the command-line, argh!
  final Map<String, String> commandParametersCopy = CollectionUtils.removeKeys(
    new HashMap<String, String>(command.getParameters()), ExcludeNoValueFilter.INSTANCE);

  Link resolvedLink = null;

  int pathVariableCount = 0;

  for (final Link link : links) {
    final List<String> pathVariables = new UriTemplate(decode(link.getHref().toString())).getVariableNames();

    // first, all path variables in the URL/URI template must be resolvable/expandable for this Link
    // to even be considered...
    if (commandParametersCopy.keySet().containsAll(pathVariables)) {
      // then, either we have not found a Link for the command yet, or the number of resolvable/expandable
      // path variables in this Link has to be greater than the number of resolvable/expandable path variables
      // for the last Link
      if (resolvedLink == null || (pathVariables.size() > pathVariableCount)) {
        resolvedLink = link;
        pathVariableCount = pathVariables.size();
      }
    }
  }

  if (resolvedLink == null) {
    throw new RestApiCallForCommandNotFoundException(String.format("No REST API call for command (%1$s) was found!",
      command.getInput()));
  }

  return resolvedLink;
}
 
Example #22
Source File: HttpSpringStarterInitializer.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Override
public Project<SpringBootProjectParams> initialize(Path parentFolder, String identifier, SpringBootProjectParams variables) throws ProjectInitializationException {
	// @formatter:off
	String url = springStarterProperties.getUrl()
			+ "?name={artifactId}"
			+ "&groupId=fr.sii"
			+ "&artifactId={artifactId}"
			+ "&version={version}"
			+ "&description="
			+ "&packageName=fr.sii.spring.boot.runtime.testing"
			+ "&type={type}"
			+ "&packaging=jar"
			+ "&javaVersion={javaVersion}"
			+ "&language=java"
			+ "&bootVersion={springBootVersion}";
	// @formatter:on
	for (SpringBootDependency dependency : variables.getSpringBootDependencies()) {
		url += "&dependencies=" + dependency.getModule();
	}
	UriTemplate template = new UriTemplate(url);
	URI expanded = template.expand(identifier,
			identifier,
			oghamProperties.getOghamVersion(),
			variables.getBuildTool().getType(),
			variables.getJavaVersion().getVersion(),
			variables.getSpringBootVersion());
	log.debug("Starter resolved url: {}", expanded);
	RequestEntity<Void> request = RequestEntity.get(expanded)
									.header(USER_AGENT, "ogham/"+oghamProperties.getOghamVersion())
									.build();
	ResponseEntity<byte[]> response = restTemplate.exchange(request, byte[].class);
	if(response.getStatusCode().is2xxSuccessful()) {
		try {
			return new Project<>(unzip(response.getBody(), identifier, parentFolder), variables);
		} catch(IOException | ZipException | RuntimeException e) {
			throw new ProjectInitializationException("Failed to initialize Spring Boot project while trying to unzip Spring starter zip", e);
		}
	}
	throw new ProjectInitializationException("Failed to download Spring starter zip");
}
 
Example #23
Source File: StatusesTemplate.java    From booties with Apache License 2.0 5 votes vote down vote up
@Override
public Status createStatus(String owner, String repository, String sha, StatusRequest body) {
	Map<String, Object> uriVariables = new HashMap<>();
	uriVariables.put("owner", owner);
	uriVariables.put("repository", repository);
	uriVariables.put("sha", sha);
	
	URI uri = new UriTemplate(buildUriString("/repos/{owner}/{repository}/statuses/{sha}")).expand(uriVariables);
	RequestEntity<StatusRequest> entity = RequestEntity.post(uri).contentType(MediaType.APPLICATION_JSON)
			.body(body);

	ResponseEntity<Status> responseEntity = getRestOperations().exchange(entity, Status.class);
	return responseEntity.getBody();
}
 
Example #24
Source File: IssuesTemplate.java    From booties with Apache License 2.0 5 votes vote down vote up
@Override
public Issue createIssue(IssueRequest issueRequest, String owner, String repo) {
	Map<String, Object> uriVariables = new HashMap<>();
	uriVariables.put("owner", owner);
	uriVariables.put("repo", repo);

	URI uri = new UriTemplate(buildUriString("/repos/{owner}/{repo}/issues")).expand(uriVariables);
	RequestEntity<IssueRequest> entity = RequestEntity.post(uri).contentType(MediaType.APPLICATION_JSON)
			.body(issueRequest);

	ResponseEntity<Issue> responseEntity = getRestOperations().exchange(entity, Issue.class);
	return responseEntity.getBody();
}
 
Example #25
Source File: WebIntegrationTests.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void executeConditionalGetRequests() throws Exception {

	Customer customer = customers.findAll().iterator().next();
	URI uri = new UriTemplate("/customers/{id}").expand(customer.getId());

	MockHttpServletResponse response = mvc.perform(get(uri)).//
			andExpect(header().string(ETAG, is(notNullValue()))).//
			andExpect(header().string(LAST_MODIFIED, is(notNullValue()))).//
			andReturn().getResponse();

	// ETag-based

	response = mvc.perform(get(uri).header(IF_NONE_MATCH, response.getHeader(ETAG))).//
			andExpect(status().isNotModified()).//
			andExpect(header().string(ETAG, is(notNullValue()))).//
			andExpect(header().string(LAST_MODIFIED, is(notNullValue()))).//
			andDo(document("if-none-match")).//
			andReturn().getResponse();

	// Last-modified-based

	mvc.perform(get(uri).header(IF_MODIFIED_SINCE, response.getHeader(LAST_MODIFIED))).//
			andExpect(status().isNotModified()).//
			andExpect(header().string(ETAG, is(notNullValue()))).//
			andExpect(header().string(LAST_MODIFIED, is(notNullValue()))).//
			andDo(document("if-modified-since"));
}
 
Example #26
Source File: CartRepositoryImpl.java    From AppStash with Apache License 2.0 5 votes vote down vote up
@Autowired
public CartRepositoryImpl(@Value("${redis.cart.microservice.url}") String baseUrl,
                          RestTemplate restTemplate) {
    this.restTemplate = restTemplate;

    CREATE_TEMPLATE = new UriTemplate(baseUrl + CREATE);
    GET_TEMPLATE = new UriTemplate(baseUrl + GET);
    ADD_TEMPLATE = new UriTemplate(baseUrl + ADD);
    REMOVE_TEMPLATE = new UriTemplate(baseUrl + REMOVE);
    CLEAR_TEMPLATE = new UriTemplate(baseUrl + CLEAR);
}
 
Example #27
Source File: RootController.java    From tutorials with MIT License 5 votes vote down vote up
@GetMapping("/")
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) {
    final String rootUri = request.getRequestURL()
        .toString();

    final URI fooUri = new UriTemplate("{rootUri}{resource}").expand(rootUri, "foos");
    final String linkToFoos = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection");
    response.addHeader("Link", linkToFoos);
}
 
Example #28
Source File: RequestContext.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Return a context-aware URl for the given relative URL with placeholders (named keys with braces {@code {}}).
 * For example, send in a relative URL {@code foo/{bar}?spam={spam}} and a parameter map
 * {@code {bar=baz,spam=nuts}} and the result will be {@code [contextpath]/foo/baz?spam=nuts}.
 * @param relativeUrl the relative URL part
 * @param params a map of parameters to insert as placeholders in the url
 * @return a URL that points back to the server with an absolute path (also URL-encoded accordingly)
 */
public String getContextUrl(String relativeUrl, Map<String, ?> params) {
	String url = getContextPath() + relativeUrl;
	UriTemplate template = new UriTemplate(url);
	url = template.expand(params).toASCIIString();
	if (this.response != null) {
		url = this.response.encodeURL(url);
	}
	return url;
}
 
Example #29
Source File: GithubApiUriUtil.java    From booties with Apache License 2.0 4 votes vote down vote up
public URI buildUri(String path, Map<String, Object> uriVariables) {
	return new UriTemplate(buildUriString(path)).expand(uriVariables);
}
 
Example #30
Source File: RestUserController.java    From Spring with Apache License 2.0 4 votes vote down vote up
/**
 * Determines URL of user resource based on the full URL of the given request,
 * appending the path info with the given childIdentifier using a UriTemplate.
 */
private static String getLocationForUser(StringBuffer url, Object childIdentifier) {
	final UriTemplate template = new UriTemplate(url.toString() + "/{$username}");
	return template.expand(childIdentifier).toASCIIString();
}