List of usage examples for org.springframework.web.client RestTemplate getForObject
@Override @Nullable public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException
From source file:org.springframework.cloud.stream.binder.rabbit.admin.RabbitBindingCleaner.java
@SuppressWarnings("unchecked") private List<String> findExchanges(String adminUri, String vhost, String binderPrefix, String entity, RestTemplate restTemplate) { List<String> removedExchanges = new ArrayList<>(); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api").pathSegment("exchanges", "{vhost}") .buildAndExpand(vhost).encode().toUri(); List<Map<String, Object>> exchanges = restTemplate.getForObject(uri, List.class); String exchangeNamePrefix = adjustPrefix(AbstractBinder.applyPrefix(binderPrefix, entity)); for (Map<String, Object> exchange : exchanges) { String exchangeName = (String) exchange.get("name"); if (exchangeName.startsWith(exchangeNamePrefix)) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "source") .buildAndExpand(vhost, exchangeName).encode().toUri(); List<Map<String, Object>> bindings = restTemplate.getForObject(uri, List.class); if (hasNoForeignBindings(bindings, exchangeNamePrefix)) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "destination") .buildAndExpand(vhost, exchangeName).encode().toUri(); bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { removedExchanges.add((String) exchange.get("name")); } else { throw new RabbitAdminException( "Cannot delete exchange " + exchangeName + "; it is a destination: " + bindings); }// w w w. j ava 2 s . c o m } else { throw new RabbitAdminException( "Cannot delete exchange " + exchangeName + "; it has bindings: " + bindings); } } } return removedExchanges; }
From source file:org.springframework.cloud.stream.binder.rabbit.LocalizedQueueConnectionFactory.java
private ConnectionFactory determineConnectionFactory(String queue) { for (int i = 0; i < this.adminAdresses.length; i++) { String adminUri = this.adminAdresses[i]; RestTemplate template = createRestTemplate(adminUri); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("queues", "{vhost}", "{queue}").buildAndExpand(this.vhost, queue).encode().toUri(); try {/*from w w w.ja v a2 s . c o m*/ @SuppressWarnings("unchecked") Map<String, Object> queueInfo = template.getForObject(uri, Map.class); if (queueInfo != null) { String node = (String) queueInfo.get("node"); if (node != null) { for (int j = 0; j < this.nodes.length; j++) { if (this.nodes[j].equals(node)) { return nodeConnectionFactory(queue, j); } } } } } catch (Exception e) { logger.error("Failed to determine queue location for: " + queue + " at: " + uri.toString(), e); } } logger.warn("Failed to determine queue location for: " + queue); return null; }
From source file:org.springframework.data.hadoop.admin.cli.commands.BaseCommand.java
/** * get JSON from server./*from w w w . j a va2s .c o m*/ * * @return JSON String */ public String getJson() { RestTemplate template = getRestTemplate(); String json = template.getForObject(generateCommandUrl(), String.class); return json; }
From source file:org.springframework.data.hadoop.admin.cli.commands.BaseCommand.java
/** * Download file from server.//from w ww .j a v a2 s. c om */ public void callDownloadFile(String fileName) { try { RestTemplate template = getRestTemplate(); byte[] bytes = template.getForObject(generateCommandUrl(), byte[].class); FileCopyUtils.copy(bytes, new File(fileName)); Log.show("download file successfully. file name is:" + fileName); } catch (Throwable t) { showErrorMsg(t); } }
From source file:org.springframework.data.keyvalue.riak.client.RiakRestClient.java
@SuppressWarnings("unchecked") @Override// w w w.j a v a 2s .com public <T> List<RiakResponse<T>> walkLinks(String bucket, String key, Class<T> clazz, RiakLinkPhase... phases) throws RiakException { List<String> pathParams = new ArrayList<String>(Arrays.asList(bucket, key)); for (RiakLinkPhase phase : phases) pathParams.add(phase.toUrlFormat()); RestTemplate privTemp = new RestTemplate(); privTemp.getMessageConverters().add(new MultipartMixedHttpMessageConverter<T>(clazz)); return (List<RiakResponse<T>>) privTemp.getForObject( getUrl("riak", null, (String[]) pathParams.toArray(new String[pathParams.size()])), List.class); }
From source file:org.thingsboard.demo.loader.data.DemoData.java
public void uploadData(RestTemplate restTemplate, String baseUrl) throws Exception { plugins.forEach(plugin -> {/* ww w. j a v a 2 s. c o m*/ try { String apiToken = plugin.getApiToken(); PluginMetaData savedPlugin = null; try { savedPlugin = restTemplate.getForObject(baseUrl + "/api/plugin/token/" + apiToken, PluginMetaData.class); } catch (HttpClientErrorException e) { if (e.getStatusCode() != HttpStatus.NOT_FOUND) { throw e; } } if (savedPlugin == null) { savedPlugin = restTemplate.postForObject(baseUrl + "/api/plugin", plugin, PluginMetaData.class); } if (savedPlugin.getState() == ComponentLifecycleState.SUSPENDED) { restTemplate.postForLocation( baseUrl + "/api/plugin/" + savedPlugin.getId().getId().toString() + "/activate", null); } } catch (Exception e) { log.error("Unable to upload plugin!"); log.error("Cause:", e); } }); rules.forEach(rule -> { try { RuleMetaData savedRule = null; TextPageData<RuleMetaData> rules; ResponseEntity<TextPageData<RuleMetaData>> entity = restTemplate.exchange( baseUrl + "/api/rule?limit={limit}&textSearch={textSearch}", HttpMethod.GET, null, new ParameterizedTypeReference<TextPageData<RuleMetaData>>() { }, 1000, rule.getName()); rules = entity.getBody(); if (rules.getData().size() > 0) { savedRule = rules.getData().get(0); } if (savedRule == null) { savedRule = restTemplate.postForObject(baseUrl + "/api/rule", rule, RuleMetaData.class); } if (savedRule.getState() == ComponentLifecycleState.SUSPENDED) { restTemplate.postForLocation( baseUrl + "/api/rule/" + savedRule.getId().getId().toString() + "/activate", null); } } catch (Exception e) { log.error("Unable to upload rule!"); log.error("Cause:", e); } }); Map<String, CustomerId> customerIdMap = new HashMap<>(); customers.forEach(customer -> { try { Customer savedCustomer = null; TextPageData<Customer> customers; ResponseEntity<TextPageData<Customer>> entity = restTemplate.exchange( baseUrl + "/api/customers?limit={limit}&textSearch={textSearch}", HttpMethod.GET, null, new ParameterizedTypeReference<TextPageData<Customer>>() { }, 1000, customer.getTitle()); customers = entity.getBody(); if (customers.getData().size() > 0) { savedCustomer = customers.getData().get(0); } if (savedCustomer == null) { savedCustomer = restTemplate.postForObject(baseUrl + "/api/customer", customer, Customer.class); } customerIdMap.put(savedCustomer.getTitle(), savedCustomer.getId()); } catch (Exception e) { log.error("Unable to upload customer!"); log.error("Cause:", e); } }); List<Device> loadedDevices = new ArrayList<>(); Map<String, DeviceId> deviceIdMap = new HashMap<>(); devices.forEach(device -> { try { CustomerId customerId = null; String customerTitle = customerDevices.get(device.getName()); if (customerTitle != null) { customerId = customerIdMap.get(customerTitle); } Device savedDevice = null; TextPageData<Device> devices; if (customerId != null) { ResponseEntity<TextPageData<Device>> entity = restTemplate.exchange( baseUrl + "/api/customer/{customerId}/devices?limit={limit}&textSearch={textSearch}", HttpMethod.GET, null, new ParameterizedTypeReference<TextPageData<Device>>() { }, customerId.getId().toString(), 1000, device.getName()); devices = entity.getBody(); if (devices.getData().size() > 0) { savedDevice = devices.getData().get(0); } } if (savedDevice == null) { ResponseEntity<TextPageData<Device>> entity = restTemplate.exchange( baseUrl + "/api/tenant/devices?limit={limit}&textSearch={textSearch}", HttpMethod.GET, null, new ParameterizedTypeReference<TextPageData<Device>>() { }, 1000, device.getName()); devices = entity.getBody(); if (devices.getData().size() > 0) { savedDevice = devices.getData().get(0); } } if (savedDevice == null) { savedDevice = restTemplate.postForObject(baseUrl + "/api/device", device, Device.class); } if (customerId != null && savedDevice.getCustomerId().isNullUid()) { restTemplate.postForLocation(baseUrl + "/api/customer/{customerId}/device/{deviceId}", null, customerId.getId().toString(), savedDevice.getId().toString()); } String deviceName = savedDevice.getName(); DeviceId deviceId = savedDevice.getId(); deviceIdMap.put(deviceName, deviceId); loadedDevices.add(savedDevice); DeviceCredentials credentials = restTemplate.getForObject( baseUrl + "/api/device/{deviceId}/credentials", DeviceCredentials.class, deviceId.getId().toString()); loadedDevicesCredentialsMap.put(deviceId, credentials); Map<String, JsonNode> attributesMap = devicesAttributes.get(deviceName); if (attributesMap != null) { attributesMap.forEach((k, v) -> { restTemplate.postForObject(baseUrl + "/api/plugins/telemetry/{deviceId}/{attributeScope}", v, Void.class, deviceId.getId().toString(), k); }); } } catch (Exception e) { log.error("Unable to upload device!"); log.error("Cause:", e); } }); devices = loadedDevices; Map<String, Dashboard> pendingDashboards = dashboards.stream() .collect(Collectors.toMap(Dashboard::getTitle, Function.identity())); Map<String, Dashboard> savedDashboards = new HashMap<>(); while (pendingDashboards.size() != 0) { Dashboard savedDashboard = null; for (Dashboard dashboard : pendingDashboards.values()) { savedDashboard = getDashboardByName(restTemplate, baseUrl, dashboard); if (savedDashboard == null) { try { Optional<String> dashboardConfigurationBody = resolveLinks(savedDashboards, dashboard.getConfiguration()); if (dashboardConfigurationBody.isPresent()) { dashboard.setConfiguration(objectMapper.readTree(dashboardConfigurationBody.get())); JsonNode dashboardConfiguration = dashboard.getConfiguration(); JsonNode deviceAliases = dashboardConfiguration.get("deviceAliases"); deviceAliases.forEach(jsonNode -> { String aliasName = jsonNode.get("alias").asText(); DeviceId deviceId = deviceIdMap.get(aliasName); if (deviceId != null) { ((ObjectNode) jsonNode).put("deviceId", deviceId.getId().toString()); } }); savedDashboard = restTemplate.postForObject(baseUrl + "/api/dashboard", dashboard, Dashboard.class); } } catch (Exception e) { log.error("Unable to upload dashboard!"); log.error("Cause:", e); } } if (savedDashboard != null) { break; } } if (savedDashboard != null) { savedDashboards.put(savedDashboard.getTitle(), savedDashboard); pendingDashboards.remove(savedDashboard.getTitle()); } else { log.error("Unable to upload dashboards due to unresolved references!"); break; } } dashboards = new ArrayList<>(savedDashboards.values()); }