@Test public void testSimple() throws Exception { final Map<String, Object> body = new HashMap<>(); body.put("foo", "Hello, world!"); body.put("bar", 12345); body.put("baz", "2017-02-10"); body.put("qux", Collections.emptyList()); final RequestEntity<Map<String, Object>> requestEntity = RequestEntity .post(new UriTemplate(url).expand(port)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .body(body); final ParameterizedTypeReference<Map<String, Object>> responseType = new ParameterizedTypeReference<Map<String, Object>>() { }; final ResponseEntity<Map<String, Object>> response = restTemplate.exchange(requestEntity, responseType); assertThat(response.getBody(), is(body)); }
@DataProvider Object[][] uriDataProvider() { return new Object[][] { { "/v1/site/123", new UriTemplate("/v1{attribute_uri}"), "/site/123" }, { "/v1/site/123/asset/345", new UriTemplate("/v1{attribute_uri}/asset/345"), "/site/123" }, { "/v1/site/123/asset/345", new UriTemplate("/v1{attribute_uri}/asset/{site_id}"), "/site/123" }, { "/v1/site/123/asset/345", new UriTemplate("/v1/site/123{attribute_uri}"), "/asset/345" }, { "/v1/site/123/asset/345", new UriTemplate("/v1{attribute_uri}"), "/site/123/asset/345" }, { "/v1/site/123/asset/345/report", new UriTemplate("/v1{attribute_uri}/report"), "/site/123/asset/345" }, // template doesnt match uri { "/v1/site/123/asset/345/report", new UriTemplate("/v2{attribute_uri}"), null }, // no attribute_uri variable in template { "/v1/site/123/asset/345/report", new UriTemplate("/v1{non_existent_variable}"), null }, // multiple attribute_uri variables in template { "/v1/site/123/asset/345", new UriTemplate("/v1{attribute_uri}/{attribute_uri}"), "345" }, }; }
@Test public void testNest() throws Exception { final Map<String, Object> grandchild = new HashMap<>(); grandchild.put("foo", "grandchild"); grandchild.put("bar", 1); grandchild.put("baz", "2017-02-01"); grandchild.put("qux", Collections.emptyList()); final Map<String, Object> child1 = new HashMap<>(); child1.put("foo", "child1"); child1.put("bar", 2); child1.put("baz", "2017-02-02"); child1.put("qux", Collections.singletonList(grandchild)); final Map<String, Object> child2 = new HashMap<>(); child2.put("foo", "child2"); child2.put("bar", 3); child2.put("baz", "2017-02-03"); child2.put("qux", Collections.emptyList()); final Map<String, Object> root = new HashMap<>(); root.put("foo", "root"); root.put("bar", 4); root.put("baz", "2017-02-04"); root.put("qux", Arrays.asList(child1, child2)); final RequestEntity<Map<String, Object>> requestEntity = RequestEntity .post(new UriTemplate(url).expand(port)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .body(root); final ParameterizedTypeReference<Map<String, Object>> responseType = new ParameterizedTypeReference<Map<String, Object>>() { }; final ResponseEntity<Map<String, Object>> response = restTemplate.exchange(requestEntity, responseType); assertThat(response.getBody(), is(root)); }
private ResponseEntity<Map<String, Object>> doRequest(final Map<String, Object> body) { final RequestEntity<Map<String, Object>> requestEntity = RequestEntity .post(new UriTemplate(url).expand(port)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .body(body); final ParameterizedTypeReference<Map<String, Object>> responseType = new ParameterizedTypeReference<Map<String, Object>>() { }; return restTemplate.exchange(requestEntity, responseType); }
@Override public void registerDelegate(UriTemplate path, RestDelegate delegate, int priority) { if (path == null) { throw new NullPointerException("Argument 'path' is required."); } if (delegate == null) { throw new NullPointerException( "Argument 'delegate' is required."); } logger.debug( "Registering delegate '{}' for path {} with priority {}.", delegate, path, priority); synchronized (mappings) { mappings.add(new RestDelegateMappingEntry(path, delegate, priority)); isSorted = false; } }
/** * Generates an instance of the URI according to the template given by uriTemplate, by expanding the variables * with the values provided by keyValues. * * @param uriTemplate * The URI template * @param keyValues * Dynamic list of string of the form "key:value" * @return The corresponding URI instance */ public static URI expand(final String uriTemplate, final String... keyValues) { UriTemplate template = new UriTemplate(uriTemplate); Map<String, String> uriVariables = new HashMap<>(); for (String kv : keyValues) { String[] keyValue = kv.split(":"); uriVariables.put(keyValue[0], keyValue[1]); } return template.expand(uriVariables); }
private void doTestForURITemplateMatch(final String uriTemplate, final String uri, final Boolean uriTemplateExpectedMatch, final String[] varNames, final String[] varValues) { UriTemplate template = new UriTemplate(uriTemplate); Assert.assertEquals(template.matches(uri), uriTemplateExpectedMatch.booleanValue()); Map<String, String> matchedVariables = template.match(uri); for (int i = 0; i < varNames.length; i++) { // skip variable match if name is "n/a" if (varNames[i].equals("n/a")) { continue; } Assert.assertEquals(matchedVariables.get(varNames[i]), varValues[i]); Assert.assertEquals(matchedVariables.get(varNames[i]), varValues[i]); } }
@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()); }
@Override @Cacheable("changelogs") public Changelog getChangelogFor(ModuleIteration moduleIteration) { Map<String, Object> parameters = newUrlTemplateVariables(); parameters.put("jql", JqlQuery.from(moduleIteration)); parameters.put("fields", "summary,status,resolution,fixVersions"); parameters.put("startAt", 0); URI searchUri = new UriTemplate(SEARCH_TEMPLATE).expand(parameters); logger.log(moduleIteration, "Looking up JIRA issues from %s…", searchUri); JiraIssues issues = operations.getForObject(searchUri, JiraIssues.class); Tickets tickets = issues.stream().map(this::toTicket).collect(Tickets.toTicketsCollector()); logger.log(moduleIteration, "Created changelog with %s entries.", tickets.getOverallTotal()); return Changelog.of(moduleIteration, tickets); }
public AdmAccessToken getAccessToken(AdmRequestToken requestToken) { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(4); params.add(AdmRequestToken.CLIENT_ID, requestToken.getClientId()); params.add(AdmRequestToken.CLIENT_SECRET, requestToken.getClientSecret()); params.add(AdmRequestToken.GRANT_TYPE, requestToken.getGrantType()); params.add(AdmRequestToken.SCOPE, requestToken.getScope()); URI uri = new UriTemplate(TOKEN_URI).expand(); RequestEntity<MultiValueMap<String, String>> request = RequestEntity.post(uri)// .contentType(MediaType.APPLICATION_FORM_URLENCODED)// .body(params); ResponseEntity<AdmAccessToken> response = restTemplate.exchange(request, AdmAccessToken.class); return response.getBody(); }
/** * The <code>options</code> parameter when provided, defines the text * format. Possible values are: * <ul> * <li><b>plain</b> - Text without markup (default value).</li> * <li><b>html</b> - Text in HTML format.</li> * </ul> */ @Override public String detectLanguage(String text, String... options) { LOG.debug("Calling dectectLanguage() with text={}, options={}", text, options); MultiValueMap<String, String> params = new LinkedMultiValueMap<>(3); String format = (options.length > 0) ? options[0] : config.getYandex().getOptions().getFormat(); params.add("key", config.getYandex().getApiKey()); params.add("text", text); params.add("format", format); URI uri = new UriTemplate(DETECT_URI).expand(); RequestEntity<MultiValueMap<String, String>> request = RequestEntity.post(uri)// .contentType(MediaType.APPLICATION_FORM_URLENCODED)// .body(params); ResponseEntity<DetectedLang> response = restTemplate.exchange(request, DetectedLang.class); DetectedLang detectedLang = response.getBody(); return detectedLang.getLang(); }
/** * The <code>options</code> parameter when provided, defines the ui language * used to display supported languages names. Possible values are: * <ul> * <li>en - in English</li> * <li>ru - in Russian</li> * <li>tr - in Turkish</li> * <li>uk - in Ukrainian</li> * </ul> */ @Override public List<String> getSupportedLanguages(String... options) { LOG.debug("Calling getSupportedLanguages() with options={}", (Object[]) options); String ui = (options.length > 0) ? "&ui={ui}" : config.getYandex().getOptions().getUiLang(); URI uri = new UriTemplate(GETLANGS_URI + "?key={key}" + ui).expand(config.getYandex().getApiKey(), options); RequestEntity<Void> request = RequestEntity.get(uri).build(); ResponseEntity<SupportedLangs> response = restTemplate.exchange(request, SupportedLangs.class); SupportedLangs supportedLangs = response.getBody(); return new ArrayList<>(supportedLangs.getLangs().keySet()); }
/** * Initializes a new routing instruction. * * @param method The HTTP method for the instruction. * @param uri The URI for the instruction. * @param target The target for the instruction. * @param description The description of the instruction. * @param source The source file of the instruction. */ protected void initialize(HTTPMethod method, UriTemplate uri, String target, String description, File source) { this.method = method; this.uri = uri; this.target = target; java.util.regex.Matcher matcher = SERVICE_PATTERN.matcher(target); isInvoke = matcher.matches(); if (isInvoke) { service = NSName.create(target); } this.description = description; this.source = source; }
@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()); }
private String geoCodeName(double lat, double lng) { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new IllegalStateException(e); } final ResponseEntity<Map> entity = restTemplate.getForEntity(URL, Map.class, lat, lng); if (entity.getStatusCode().is2xxSuccessful()) { final Map<?, ?> body = entity.getBody(); final Object addressObj = body.get("address"); if (addressObj instanceof Map) { final Object roadObj = ((Map) addressObj).get("road"); final Object suburbObj = ((Map) addressObj).get("suburb"); final Object cityObj = ((Map) addressObj).get("city"); return Joiner.on(", ").skipNulls().join(roadObj, suburbObj, cityObj); } } throw new IllegalStateException(String.format("Unable to reverse geocode %s", new UriTemplate(URL).expand(lat, lng))); }
private WarehouseTask createWarehouseTask(final String targetUri, final HttpMethod httpMethod, final WarehouseS3Credentials s3Credentials, final HttpEntity<MappingJacksonValue> requestEntity, final Object... args) { try { final HttpEntity<WarehouseTask> taskHttpEntity = restTemplate.exchange(targetUri, httpMethod, requestEntity, WarehouseTask.class, args); if (taskHttpEntity == null || taskHttpEntity.getBody() == null) { throw new WarehouseS3CredentialsException(targetUri, format("Empty response when trying to %s S3 credentials via API", httpMethod.name())); } return taskHttpEntity.getBody(); } catch (GoodDataException | RestClientException e) { final String expandedTargetUri = new UriTemplate(targetUri).expand(args).toString(); throw new WarehouseS3CredentialsException(targetUri, format("Unable to %s S3 credentials %s with region: %s, access key: %s", httpMethod.name(), expandedTargetUri, s3Credentials.getRegion(), s3Credentials.getAccessKey()), e); } }
/** * Add all bean properties * from the supplied bean * to the representation * @param value * @return */ public ResponseEntityBuilder<ReadableRepresentation> withPage(Page<?> value, String uriTemplate, String... includeFields) { String[] fields = requestedFields == null ? includeFields : requestedFields; // Extract page data such as size, page number representation.withProperty("size", value.getSize()); representation.withProperty("number", value.getNumber()); representation.withProperty("numberOfElements", value.getNumberOfElements()); representation.withProperty("totalElements", value.getTotalElements()); // Next/back links if (value.hasNextPage()) { buildNextLink(representation, request); } if (value.hasPreviousPage()) { buildPreviousLink(representation, request); } // Build the content of the page for (Object object : value.getContent()) { Representation content = converter.convert(object, new UriTemplate(uriTemplate), fields); this.representation.withRepresentation("content", content); } return this; }
@Test public void testCreation() throws Exception { // Create test objects Customer customer = new Customer(1, "email", "first", new Date(123456789l), "last"); Method accessor = customer.getClass().getMethod("getBaskets"); UriTemplate uriTemplate = new UriTemplate("/basket/{basketId}"); String name = "baskets"; // Create EmbeddedResource EmbeddedResource er = new EmbeddedResource(name, uriTemplate, accessor); // Test Assert.assertEquals(name, er.getName()); Assert.assertEquals(accessor, er.getAccessor()); Assert.assertEquals(uriTemplate, er.getUriTemplate()); Assert.assertEquals(Collection.class, er.getType()); Assert.assertEquals(customer.getBaskets(), er.getValue(customer)); }
@Test public void testConvertEmbeddedManyToOne() { Customer customer = customer(); Basket basket = basket(1); basket.setCustomer(customer); customer.getBaskets().add(basket); Representation representation = converter.convert(basket, new UriTemplate("/basket/{basketId}")); Assert.assertEquals("1", representation.getValue("basketId").toString()); Collection<ReadableRepresentation> reps = representation.getResourceMap().get("customer"); Assert.assertNotNull(reps); Assert.assertTrue(reps.size() == 1); System.out.println(representation.toString("application/hal+xml")); }
@Test public void testBuild() throws SecurityException, NoSuchMethodException { ResourceMetadataBuilder builder = new ResourceMetadataBuilder(); builder.uriTemplate("/customer/{customerId}"); builder.identityProperty("customerId", Customer.class.getMethod("getCustomerId")); builder.simpleProperty("firstName", Customer.class.getMethod("getFirstName")); builder.embeddedResource("baskets", "/basket/{basketId}", Customer.class.getMethod("getBaskets")); ResourceMetadata metadata = builder.build(); Assert.assertEquals(new UriTemplate("/customer/{customerId}").toString(), metadata.getUriTemplate().toString()); Assert.assertEquals(1, metadata.getIdentityProperties().size()); Assert.assertEquals(new IdentityProperty("customerId", Customer.class.getMethod("getCustomerId")), metadata.getIdentityProperties().get(0)); Assert.assertEquals(1, metadata.getSimpleProperties().size()); Assert.assertEquals(new SimpleProperty("firstName", Customer.class.getMethod("getFirstName")), metadata.getSimpleProperties().get(0)); Assert.assertEquals(1, metadata.getEmbeddedResources().size()); // UriTemplate doesn't implement equals very well //Assert.assertEquals(new EmbeddedResource("baskets", new UriTemplate("/basket/{basketId}"), Customer.class.getMethod("getBaskets")), metadata.getEmbeddedResources().get(0)); }
private String buildUrl ( String url, String category ) { if ( !url.startsWith( "http" ) ) { url = getLbUrl() + url; } String resolvedUrl = url; Map<String, String> urlVariables = new HashMap<String, String>(); if ( url.contains( "{appId}" ) ) { urlVariables.put( "appId", getEventDataUser() ); } if ( url.contains( "{life}" ) ) { urlVariables.put( "life", Application.getCurrentLifeCycle() ); } if ( url.contains( "{host}" ) ) { urlVariables.put( "host", Application.getHOST_NAME() ); } if ( url.contains( "{category}" ) ) { urlVariables.put( "category", category ); } if ( url.contains( "{project}" ) ) { urlVariables.put( "project", csapApplication.getActiveModel().getReleasePackageName() ); } try { URI expanded = new UriTemplate( url ).expand( urlVariables ); resolvedUrl = expanded.toURL().toString(); logger.debug( "Url: {}, Resolved: {}", url, resolvedUrl ); } catch (Exception e) { logger.warn( "Failed to build url: " + url, e ); } return resolvedUrl; }
@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")); }
@Override public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor, Object... urlVariables) throws RestClientException { URI expanded = new UriTemplate(url).expand(urlVariables); return doExecute(expanded, method, requestCallback, responseExtractor); }
@Override public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor, Map<String, ?> urlVariables) throws RestClientException { URI expanded = new UriTemplate(url).expand(urlVariables); return doExecute(expanded, method, requestCallback, responseExtractor); }
@Override public <T> ListenableFuture<T> execute(String url, HttpMethod method, AsyncRequestCallback requestCallback, ResponseExtractor<T> responseExtractor, Object... urlVariables) throws RestClientException { URI expanded = new UriTemplate(url).expand(urlVariables); return doExecute(expanded, method, requestCallback, responseExtractor); }
@Override public <T> ListenableFuture<T> execute(String url, HttpMethod method, AsyncRequestCallback requestCallback, ResponseExtractor<T> responseExtractor, Map<String, ?> urlVariables) throws RestClientException { URI expanded = new UriTemplate(url).expand(urlVariables); return doExecute(expanded, method, requestCallback, responseExtractor); }
/** * Resolves one Link from a Collection of Links based on the command invocation matching multiple * relations from the Link Index. * * @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(org.apache.geode.management.internal.cli.CommandRequest) * @see org.apache.geode.management.internal.cli.CommandRequest * @see org.apache.geode.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! Map<String, String> commandParametersCopy = CollectionUtils.removeKeys(new HashMap<>(command.getParameters()), NoValueFilter.INSTANCE); Link resolvedLink = null; int pathVariableCount = 0; for (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; }
/** * @param pathVariable * name of path parameter in the URL * @return path parameter value */ public String uriVariable(final String pathVariable) { if (StringUtils.isEmpty(this.resourceURITemplate) || StringUtils.isEmpty(this.resourceURI) || StringUtils.isEmpty(pathVariable)) { return ""; } UriTemplate template = new UriTemplate(this.resourceURITemplate); Map<String, String> match = template.match(this.resourceURI); String pathVariableValue = match.get(pathVariable); return pathVariableValue != null ? pathVariableValue : ""; }
String resolveResourceURI(final Policy policy) { if (attributeUriTemplateExists(policy)) { String attributeUriTemplate = policy.getTarget().getResource().getAttributeUriTemplate(); UriTemplate uriTemplate = new UriTemplate(attributeUriTemplate); return this.uriTemplateVariableResolver.resolve(this.requestResourceUri, uriTemplate, ATTRIBUTE_URI_TEMPLATE_VARIABLE); } return null; }
protected URI getQuotesURI(final String prependSymbols, final String appendSymbols) { String uri = prependSymbols; for (String symbol : getSymbols()) { uri += "\"" + symbol + "\","; } uri = uri.substring(0, uri.length() - 1); uri += appendSymbols; return new UriTemplate(uri).expand(); }
@Test public void IsSubmittedOrderSaved() { long before = orderRepository.count(); MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); map.add("submit", ""); map.add("customer", Long.toString(customer.getCustomerId())); map.add("orderLine[0].item", Long.toString(item.getItemId())); map.add("orderLine[0].count", "42"); URI uri = restTemplate.postForLocation(orderURL(), map, String.class); UriTemplate uriTemplate = new UriTemplate(orderURL() + "/{id}"); assertEquals(before + 1, orderRepository.count()); }
@Test @Transactional public void IsSubmittedOrderSaved() { long before = orderRepository.count(); MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); map.add("submit", ""); map.add("orderLine[0].itemId", "42"); map.add("orderLine[0].count", "2"); URI uri = restTemplate.postForLocation(orderURL(), map, String.class); UriTemplate uriTemplate = new UriTemplate(orderURL() + "/{id}"); assertEquals(before + 1, orderRepository.count()); }
@Test @Transactional public void IsSubmittedOrderSaved() { long before = orderRepository.count(); MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); map.add("submit", ""); map.add("customerId", Long.toString(customer.getCustomerId())); map.add("orderLine[0].itemId", Long.toString(item.getItemId())); map.add("orderLine[0].count", "42"); URI uri = restTemplate.postForLocation(orderURL(), map, String.class); UriTemplate uriTemplate = new UriTemplate(orderURL() + "/{id}"); assertEquals(before + 1, orderRepository.count()); }
/** * 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; }
/** * 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; }
@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); } } }
@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); } } }
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, "http://start.spring.io"); 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); }
public static Map<String, String> resolveUrlParameter(List<String> urls, Map<String, String> params) { for (String url : urls) { UriTemplate uriTemplate = new UriTemplate(url); if (uriTemplate.getVariableNames().stream().allMatch(params::containsKey)) { params.put("url", uriTemplate.expand(params).toString()); break; } } return params; }
public GatewayFilter apply(String template) { UriTemplate uriTemplate = new UriTemplate(template); return (exchange, chain) -> { PathMatchInfo variables = exchange.getAttribute(URI_TEMPLATE_VARIABLES_ATTRIBUTE); ServerHttpRequest req = exchange.getRequest(); addOriginalRequestUrl(exchange, req.getURI()); Map<String, String> uriVariables; if (variables != null) { uriVariables = variables.getUriVariables(); } else { uriVariables = Collections.emptyMap(); } URI uri = uriTemplate.expand(uriVariables); String newPath = uri.getPath(); exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, uri); ServerHttpRequest request = req.mutate() .path(newPath) .build(); return chain.filter(exchange.mutate().request(request).build()); }; }