From 866d7c4a2ca72be75822fbfc81e74f2332194406 Mon Sep 17 00:00:00 2001 From: YevhenBondarenko <56396344+YevhenBondarenko@users.noreply.github.com> Date: Thu, 28 Nov 2019 14:59:09 +0200 Subject: [PATCH] [WIP] Feature/rest-client (#2208) * added methods from admin-controller, alarm-controller, asset-controller, audit-log-controller * refactored rest client and added methods from auth controller * added methods from component-descriptor-controller * added methods from customer controller * added methods from dashboard controller * added methods from device controller * refactored url pageLink params * added methods from entity relation controller * added methods from entity view controller * refactored * added methods from event controller * added methods from rpc controller * added methods from rule chain controller * added methods from telemetry controller * added methods from tenant controller * added methods from user controller * added methods from widgets bundle controller * added methods from widget type controller --- .../thingsboard/client/tools/RestClient.java | 1693 ++++++++++++++++- 1 file changed, 1682 insertions(+), 11 deletions(-) diff --git a/tools/src/main/java/org/thingsboard/client/tools/RestClient.java b/tools/src/main/java/org/thingsboard/client/tools/RestClient.java index 55a5c4e501..2d789ac706 100644 --- a/tools/src/main/java/org/thingsboard/client/tools/RestClient.java +++ b/tools/src/main/java/org/thingsboard/client/tools/RestClient.java @@ -18,6 +18,7 @@ package org.thingsboard.client.tools; import com.fasterxml.jackson.databind.JsonNode; import lombok.RequiredArgsConstructor; import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpRequest; import org.springframework.http.HttpStatus; @@ -28,23 +29,47 @@ import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.client.support.HttpRequestWrapper; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; +import org.springframework.web.context.request.async.DeferredResult; +import org.thingsboard.server.common.data.AdminSettings; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.EntitySubtype; +import org.thingsboard.server.common.data.EntityView; +import org.thingsboard.server.common.data.Event; +import org.thingsboard.server.common.data.Tenant; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.alarm.Alarm; +import org.thingsboard.server.common.data.alarm.AlarmInfo; +import org.thingsboard.server.common.data.alarm.AlarmSeverity; import org.thingsboard.server.common.data.asset.Asset; +import org.thingsboard.server.common.data.asset.AssetSearchQuery; +import org.thingsboard.server.common.data.audit.AuditLog; +import org.thingsboard.server.common.data.device.DeviceSearchQuery; +import org.thingsboard.server.common.data.entityview.EntityViewSearchQuery; import org.thingsboard.server.common.data.id.AssetId; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DashboardId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.page.TextPageData; +import org.thingsboard.server.common.data.page.TextPageLink; +import org.thingsboard.server.common.data.page.TimePageData; +import org.thingsboard.server.common.data.page.TimePageLink; +import org.thingsboard.server.common.data.plugin.ComponentDescriptor; import org.thingsboard.server.common.data.relation.EntityRelation; +import org.thingsboard.server.common.data.relation.EntityRelationInfo; +import org.thingsboard.server.common.data.relation.EntityRelationsQuery; +import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.common.data.rule.RuleChainMetaData; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.security.DeviceCredentialsType; +import org.thingsboard.server.common.data.widget.WidgetType; +import org.thingsboard.server.common.data.widget.WidgetsBundle; import java.io.IOException; +import java.net.URI; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -61,6 +86,16 @@ public class RestClient implements ClientHttpRequestInterceptor { protected final String baseURL; private String token; + private final static String TIME_PAGE_LINK_URL_PARAMS = "limit={limit}&startTime={startTime}&endTime={endTime}&ascOrder={ascOrder}&offset={offset}"; + private final static String TEXT_PAGE_LINK_URL_PARAMS = "limit={limit}&textSearch{textSearch}&idOffset={idOffset}&textOffset{textOffset}"; + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] bytes, ClientHttpRequestExecution execution) throws IOException { + HttpRequest wrapper = new HttpRequestWrapper(request); + wrapper.getHeaders().set(JWT_TOKEN_HEADER_PARAM, "Bearer " + token); + return execution.execute(wrapper, bytes); + } + public void login(String username, String password) { Map loginRequest = new HashMap<>(); loginRequest.put("username", username); @@ -156,10 +191,6 @@ public class RestClient implements ClientHttpRequestInterceptor { return saveDeviceCredentials(deviceCredentials); } - public DeviceCredentials saveDeviceCredentials(DeviceCredentials deviceCredentials) { - return restTemplate.postForEntity(baseURL + "/api/device/credentials", deviceCredentials, DeviceCredentials.class).getBody(); - } - public Device createDevice(Device device) { return restTemplate.postForEntity(baseURL + "/api/device", device, Device.class).getBody(); } @@ -197,7 +228,7 @@ public class RestClient implements ClientHttpRequestInterceptor { } public Asset assignAsset(CustomerId customerId, AssetId assetId) { - return restTemplate.postForEntity(baseURL + "/api/customer/{customerId}/asset/{assetId}", null, Asset.class, + return restTemplate.postForEntity(baseURL + "/api/customer/{customerId}/asset/{assetId}", HttpEntity.EMPTY, Asset.class, customerId.toString(), assetId.toString()).getBody(); } @@ -244,10 +275,1650 @@ public class RestClient implements ClientHttpRequestInterceptor { return token; } - @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] bytes, ClientHttpRequestExecution execution) throws IOException { - HttpRequest wrapper = new HttpRequestWrapper(request); - wrapper.getHeaders().set(JWT_TOKEN_HEADER_PARAM, "Bearer " + token); - return execution.execute(wrapper, bytes); + public Optional getAdminSettings(String key) { + try { + ResponseEntity adminSettings = restTemplate.getForEntity(baseURL + "/api/admin/settings/{key}", AdminSettings.class, key); + return Optional.ofNullable(adminSettings.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } } -} \ No newline at end of file + + public AdminSettings saveAdminSettings(AdminSettings adminSettings) { + return restTemplate.postForEntity(baseURL + "/api/settings", adminSettings, AdminSettings.class).getBody(); + } + + public void sendTestMail(AdminSettings adminSettings) { + restTemplate.postForEntity(baseURL + "/api/settings/testMail", adminSettings, AdminSettings.class); + } + + //TODO: +// @RequestMapping(value = "/securitySettings", method = RequestMethod.GET) +// public SecuritySettings getSecuritySettings() { +// +// } + //TODO: +// @RequestMapping(value = "/securitySettings", method = RequestMethod.POST) +// public SecuritySettings saveSecuritySettings(SecuritySettings securitySettings) { +// +// } + //TODO: +// @RequestMapping(value = "/updates", method = RequestMethod.GET) +// public UpdateMessage checkUpdates() { +// +// } + + public Optional getAlarmById(String alarmId) { + try { + ResponseEntity alarm = restTemplate.getForEntity(baseURL + "/api/alarm/{alarmId}", Alarm.class, alarmId); + return Optional.ofNullable(alarm.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional getAlarmInfoById(String alarmId) { + try { + ResponseEntity alarmInfo = restTemplate.getForEntity(baseURL + "/api/alarm/info/{alarmId}", AlarmInfo.class, alarmId); + return Optional.ofNullable(alarmInfo.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Alarm saveAlarm(Alarm alarm) { + return restTemplate.postForEntity(baseURL + "/api/alarm", alarm, Alarm.class).getBody(); + } + + public void deleteAlarm(String alarmId) { + restTemplate.delete(baseURL + "/api/alarm/{alarmId}", alarmId); + } + + public void ackAlarm(String alarmId) { + restTemplate.postForObject(baseURL + "/api/alarm/{alarmId}/ack", new Object(), Object.class, alarmId); + } + + public void clearAlarm(String alarmId) { + restTemplate.postForObject(baseURL + "/api/alarm/{alarmId}/clear", new Object(), Object.class, alarmId); + } + + public TimePageData getAlarms(String entityType, String entityId, String searchStatus, String status, TimePageLink pageLink, Boolean fetchOriginator) { + Map params = new HashMap<>(); + params.put("entityType", entityType); + params.put("entityId", entityId); + params.put("searchStatus", searchStatus); + params.put("status", status); + params.put("fetchOriginator", String.valueOf(fetchOriginator)); + addPageLinkToParam(params, pageLink); + + return restTemplate.exchange( + baseURL + "/api/alarm/{entityType}/{entityId}?searchStatus={searchStatus}&status={status}&fetchOriginator={fetchOriginator}&" + TIME_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, params).getBody(); + } + + public Optional getHighestAlarmSeverity(String entityType, String entityId, String searchStatus, String status) { + Map params = new HashMap<>(); + params.put("entityType", entityType); + params.put("entityId", entityId); + params.put("searchStatus", searchStatus); + params.put("status", status); + try { + ResponseEntity alarmSeverity = restTemplate.getForEntity(baseURL + "/api/alarm/highestSeverity/{entityType}/{entityId}?searchStatus={searchStatus}&status={status}", AlarmSeverity.class, params); + return Optional.ofNullable(alarmSeverity.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional getAssetById(String assetId) { + try { + ResponseEntity asset = restTemplate.getForEntity(baseURL + "/api/asset/{assetId}", Asset.class, assetId); + return Optional.ofNullable(asset.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Asset saveAsset(Asset asset) { + return restTemplate.postForEntity(baseURL + "/api/asset", asset, Asset.class).getBody(); + } + + public void deleteAsset(String assetId) { + restTemplate.delete(baseURL + "/api/asset/{assetId}", assetId); + } + + public Optional assignAssetToCustomer(String customerId, + String assetId) { + Map params = new HashMap<>(); + params.put("customerId", customerId); + params.put("assetId", assetId); + + try { + ResponseEntity asset = restTemplate.postForEntity(baseURL + "/api/customer/{customerId}/asset/{assetId}", null, Asset.class, params); + return Optional.ofNullable(asset.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional unassignAssetFromCustomer(String assetId) { + try { + ResponseEntity asset = restTemplate.exchange(baseURL + "/api/customer/asset/{assetId}", HttpMethod.DELETE, HttpEntity.EMPTY, Asset.class, assetId); + return Optional.ofNullable(asset.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional assignAssetToPublicCustomer(String assetId) { + try { + ResponseEntity asset = restTemplate.postForEntity(baseURL + "/api/customer/public/asset/{assetId}", null, Asset.class, assetId); + return Optional.ofNullable(asset.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public TextPageData getTenantAssets(TextPageLink pageLink, String type) { + Map params = new HashMap<>(); + params.put("type", type); + addPageLinkToParam(params, pageLink); + + ResponseEntity> assets = restTemplate.exchange( + baseURL + "/tenant/assets?type={type}&" + TEXT_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params); + return assets.getBody(); + } + + public Optional getTenantAsset(String assetName) { + try { + ResponseEntity asset = restTemplate.getForEntity(baseURL + "/api/tenant/assets?assetName={assetName}", Asset.class, assetName); + return Optional.ofNullable(asset.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public TextPageData getCustomerAssets(String customerId, TextPageLink pageLink, String type) { + Map params = new HashMap<>(); + params.put("customerId", customerId); + params.put("type", type); + addPageLinkToParam(params, pageLink); + + ResponseEntity> assets = restTemplate.exchange( + baseURL + "/customer/{customerId}/assets?type={type}&" + TEXT_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params); + return assets.getBody(); + } + + public List getAssetsByIds(String[] assetIds) { + return restTemplate.exchange( + baseURL + "/api/assets?assetIds={assetIds}", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + assetIds).getBody(); + } + + public List findByQuery(AssetSearchQuery query) { + return restTemplate.exchange( + URI.create(baseURL + "/api/assets"), + HttpMethod.POST, + new HttpEntity<>(query), + new ParameterizedTypeReference>() { + }).getBody(); + } + + public List getAssetTypes() { + return restTemplate.exchange(URI.create( + baseURL + "/api/asset/types"), + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }).getBody(); + } + + public TimePageData getAuditLogsByCustomerId(String customerId, TimePageLink pageLink, String actionTypes) { + Map params = new HashMap<>(); + params.put("customerId", customerId); + params.put("actionTypes", actionTypes); + addPageLinkToParam(params, pageLink); + + ResponseEntity> auditLog = restTemplate.exchange( + baseURL + "/audit/logs/customer/{customerId}?actionTypes={actionTypes}&" + TIME_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params); + return auditLog.getBody(); + } + + public TimePageData getAuditLogsByUserId(String userId, TimePageLink pageLink, String actionTypes) { + Map params = new HashMap<>(); + params.put("userId", userId); + params.put("actionTypes", actionTypes); + addPageLinkToParam(params, pageLink); + + ResponseEntity> auditLog = restTemplate.exchange( + baseURL + "/audit/logs/user/{userId}?actionTypes={actionTypes}&" + TIME_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params); + return auditLog.getBody(); + } + + public TimePageData getAuditLogsByEntityId(String entityType, String entityId, String actionTypes, TimePageLink pageLink) { + Map params = new HashMap<>(); + params.put("entityType", entityType); + params.put("entityId", entityId); + params.put("actionTypes", actionTypes); + addPageLinkToParam(params, pageLink); + + ResponseEntity> auditLog = restTemplate.exchange( + baseURL + "/audit/logs/entity/{entityType}/{entityId}?actionTypes={actionTypes}&" + TIME_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params); + return auditLog.getBody(); + } + + public TimePageData getAuditLogs(TimePageLink pageLink, String actionTypes) { + Map params = new HashMap<>(); + params.put("actionTypes", actionTypes); + addPageLinkToParam(params, pageLink); + + ResponseEntity> auditLog = restTemplate.exchange( + baseURL + "/audit/logs?actionTypes={actionTypes}&" + TIME_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params); + return auditLog.getBody(); + } + + public Optional getUser() { + ResponseEntity user = restTemplate.getForEntity(baseURL + "/auth/user", User.class); + return Optional.ofNullable(user.getBody()); + } + + public void logout() { + restTemplate.exchange(URI.create(baseURL + "/auth/logout"), HttpMethod.POST, HttpEntity.EMPTY, Object.class); + } + + public void changePassword(JsonNode changePasswordRequest) { + restTemplate.exchange(URI.create(baseURL + "/auth/changePassword"), HttpMethod.POST, new HttpEntity<>(changePasswordRequest), Object.class); + } + + //TODO: +// @RequestMapping(value = "/noauth/userPasswordPolicy", method = RequestMethod.GET) +// public UserPasswordPolicy getUserPasswordPolicy() { +// +// } + + + public ResponseEntity checkActivateToken(String activateToken) { + return restTemplate.getForEntity(baseURL + "/noauth/activate?activateToken={activateToken}", String.class, activateToken); + } + + public void requestResetPasswordByEmail(JsonNode resetPasswordByEmailRequest) { + restTemplate.exchange(URI.create(baseURL + "/noauth/resetPasswordByEmail"), HttpMethod.POST, new HttpEntity<>(resetPasswordByEmailRequest), Object.class); + } + + public ResponseEntity checkResetToken(String resetToken) { + return restTemplate.getForEntity(baseURL + "noauth/resetPassword?resetToken={resetToken}", String.class, resetToken); + } + + public Optional activateUser(JsonNode activateRequest) { + try { + ResponseEntity jsonNode = restTemplate.postForEntity(baseURL + "/noauth/activate", activateRequest, JsonNode.class); + return Optional.ofNullable(jsonNode.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional resetPassword(JsonNode resetPasswordRequest) { + try { + ResponseEntity jsonNode = restTemplate.postForEntity(baseURL + "/noauth/resetPassword", resetPasswordRequest, JsonNode.class); + return Optional.ofNullable(jsonNode.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional getComponentDescriptorByClazz(String componentDescriptorClazz) { + try { + ResponseEntity componentDescriptor = restTemplate.getForEntity(baseURL + "/component/{componentDescriptorClazz}", ComponentDescriptor.class); + return Optional.ofNullable(componentDescriptor.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public List getComponentDescriptorsByType(String componentType) { + return restTemplate.exchange( + baseURL + "/components?componentType={componentType}", + HttpMethod.GET, HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + componentType).getBody(); + } + + public List getComponentDescriptorsByTypes(String[] componentTypes) { + return restTemplate.exchange( + baseURL + "/components?componentTypes={componentTypes}", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + componentTypes).getBody(); + } + + public Optional getCustomerById(String customerId) { + try { + ResponseEntity customer = restTemplate.getForEntity(baseURL + "/customer/{customerId}", Customer.class, customerId); + return Optional.ofNullable(customer.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional getShortCustomerInfoById(String customerId) { + try { + ResponseEntity customerInfo = restTemplate.getForEntity(baseURL + "/customer/{customerId}/shortInfo", JsonNode.class, customerId); + return Optional.ofNullable(customerInfo.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public String getCustomerTitleById(String customerId) { + return restTemplate.getForObject(baseURL + "/customer/{customerId}/title", String.class, customerId); + } + + public Customer saveCustomer(Customer customer) { + return restTemplate.postForEntity(baseURL + "/customer", customer, Customer.class).getBody(); + } + + public void deleteCustomer(String customerId) { + restTemplate.delete(baseURL + "/customer/{customerId}", customerId); + } + + public TextPageData getCustomers(TextPageLink pageLink) { + Map params = new HashMap<>(); + addPageLinkToParam(params, pageLink); + + ResponseEntity> customer = restTemplate.exchange( + baseURL + "/customers?" + TEXT_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params); + return customer.getBody(); + } + + public Optional getTenantCustomer(String customerTitle) { + try { + ResponseEntity customer = restTemplate.getForEntity(baseURL + "/tenant/customers?customerTitle={customerTitle}", Customer.class, customerTitle); + return Optional.ofNullable(customer.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Long getServerTime() { + return restTemplate.getForObject(baseURL + "/dashboard/serverTime", Long.class); + } + + public Long getMaxDatapointsLimit() { + return restTemplate.getForObject(baseURL + "/dashboard/maxDatapointsLimit", Long.class); + } + + public Optional getDashboardInfoById(String dashboardId) { + try { + ResponseEntity dashboardInfo = restTemplate.getForEntity(baseURL + "/dashboard/info/{dashboardId}", DashboardInfo.class, dashboardId); + return Optional.ofNullable(dashboardInfo.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional getDashboardById(String dashboardId) { + try { + ResponseEntity dashboard = restTemplate.getForEntity(baseURL + "/dashboard/{dashboardId}", Dashboard.class, dashboardId); + return Optional.ofNullable(dashboard.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Dashboard saveDashboard(Dashboard dashboard) { + return restTemplate.postForEntity(baseURL + "/dashboard", dashboard, Dashboard.class).getBody(); + } + + public void deleteDashboard(String dashboardId) { + restTemplate.delete(baseURL + "/dashboard/{dashboardId}", dashboardId); + } + + public Optional assignDashboardToCustomer(String customerId, String dashboardId) { + try { + ResponseEntity dashboard = restTemplate.postForEntity(baseURL + "/customer/{customerId}/dashboard/{dashboardId}", null, Dashboard.class, customerId, dashboardId); + return Optional.ofNullable(dashboard.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional unassignDashboardFromCustomer(String customerId, String dashboardId) { + try { + ResponseEntity dashboard = restTemplate.exchange(baseURL + "/customer/{customerId}/dashboard/{dashboardId}", HttpMethod.DELETE, HttpEntity.EMPTY, Dashboard.class, customerId, dashboardId); + return Optional.ofNullable(dashboard.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional updateDashboardCustomers(String dashboardId, String[] customerIds) { + try { + ResponseEntity dashboard = restTemplate.postForEntity(baseURL + "/dashboard/{dashboardId}/customers", customerIds, Dashboard.class, dashboardId); + return Optional.ofNullable(dashboard.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional addDashboardCustomers(String dashboardId, String[] customerIds) { + try { + ResponseEntity dashboard = restTemplate.postForEntity(baseURL + "/dashboard/{dashboardId}/customers/add", customerIds, Dashboard.class, dashboardId); + return Optional.ofNullable(dashboard.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional removeDashboardCustomers(String dashboardId, String[] customerIds) { + try { + ResponseEntity dashboard = restTemplate.postForEntity(baseURL + "/dashboard/{dashboardId}/customers/remove", customerIds, Dashboard.class, dashboardId); + return Optional.ofNullable(dashboard.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional assignDashboardToPublicCustomer(String dashboardId) { + try { + ResponseEntity dashboard = restTemplate.postForEntity(baseURL + "/customer/public/dashboard/{dashboardId}", null, Dashboard.class, dashboardId); + return Optional.ofNullable(dashboard.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional unassignDashboardFromPublicCustomer(String dashboardId) { + try { + ResponseEntity dashboard = restTemplate.exchange(baseURL + "/customer/public/dashboard/{dashboardId}", HttpMethod.DELETE, HttpEntity.EMPTY, Dashboard.class, dashboardId); + return Optional.ofNullable(dashboard.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public TextPageData getTenantDashboards(String tenantId, TextPageLink pageLink) { + Map params = new HashMap<>(); + params.put("tenantId", tenantId); + addPageLinkToParam(params, pageLink); + return restTemplate.exchange( + baseURL + "/tenant/{tenantId}/dashboards?" + TEXT_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params + ).getBody(); + } + + public TextPageData getTenantDashboards(TextPageLink pageLink) { + Map params = new HashMap<>(); + addPageLinkToParam(params, pageLink); + return restTemplate.exchange( + baseURL + "/tenant/dashboards?" + TEXT_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params + ).getBody(); + } + + public TimePageData getCustomerDashboards(String customerId, TimePageLink pageLink) { + Map params = new HashMap<>(); + params.put("customerId", customerId); + addPageLinkToParam(params, pageLink); + return restTemplate.exchange( + baseURL + "/customer/{customerId}/dashboards?" + TEXT_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params + ).getBody(); + } + + public Optional getDeviceById(String deviceId) { + try { + ResponseEntity device = restTemplate.getForEntity(baseURL + "/device/{deviceId}", Device.class, deviceId); + return Optional.ofNullable(device.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Device saveDevice(Device device) { + return restTemplate.postForEntity(baseURL + "/device", device, Device.class).getBody(); + } + + public void deleteDevice(String deviceId) { + restTemplate.delete(baseURL + "/device/{deviceId}", deviceId); + } + + public Optional assignDeviceToCustomer(String customerId, String deviceId) { + try { + ResponseEntity device = restTemplate.postForEntity(baseURL + "/customer/{customerId}/device/{deviceId}", null, Device.class, customerId, deviceId); + return Optional.ofNullable(device.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional unassignDeviceFromCustomer(String deviceId) { + try { + ResponseEntity device = restTemplate.exchange(baseURL + "/customer/device/{deviceId}", HttpMethod.DELETE, HttpEntity.EMPTY, Device.class, deviceId); + return Optional.ofNullable(device.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional assignDeviceToPublicCustomer(String deviceId) { + try { + ResponseEntity device = restTemplate.postForEntity(baseURL + "/customer/public/device/{deviceId}", null, Device.class, deviceId); + return Optional.ofNullable(device.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional getDeviceCredentialsByDeviceId(String deviceId) { + try { + ResponseEntity deviceCredentials = restTemplate.getForEntity(baseURL + "/device/{deviceId}/credentials", DeviceCredentials.class, deviceId); + return Optional.ofNullable(deviceCredentials.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public DeviceCredentials saveDeviceCredentials(DeviceCredentials deviceCredentials) { + return restTemplate.postForEntity(baseURL + "/api/device/credentials", deviceCredentials, DeviceCredentials.class).getBody(); + } + + public TextPageData getTenantDevices(String type, TextPageLink pageLink) { + Map params = new HashMap<>(); + params.put("type", type); + addPageLinkToParam(params, pageLink); + return restTemplate.exchange( + baseURL + "/tenant/devices?type={type}&" + TEXT_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params) + .getBody(); + } + + public Optional getTenantDevice(String deviceName) { + try { + ResponseEntity device = restTemplate.getForEntity(baseURL + "/tenant/devices?deviceName={deviceName}", Device.class, deviceName); + return Optional.ofNullable(device.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public TextPageData getCustomerDevices(String customerId, String type, TextPageLink pageLink) { + Map params = new HashMap<>(); + params.put("customerId", customerId); + params.put("type", type); + addPageLinkToParam(params, pageLink); + return restTemplate.exchange( + baseURL + "/customer/{customerId}/devices?type={type}&" + TEXT_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params) + .getBody(); + } + + public List getDevicesByIds(String[] deviceIds) { + return restTemplate.exchange(baseURL + "/devices?deviceIds={deviceIds}", + HttpMethod.GET, + HttpEntity.EMPTY, new ParameterizedTypeReference>() { + }, + deviceIds).getBody(); + } + + public List findByQuery(DeviceSearchQuery query) { + return restTemplate.exchange( + baseURL + "/devices", + HttpMethod.POST, + new HttpEntity<>(query), + new ParameterizedTypeReference>() { + }).getBody(); + } + + public List getDeviceTypes() { + return restTemplate.exchange( + baseURL + "/devices", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }).getBody(); + } + + //TODO: ClaimRequest class +// @RequestMapping(value = "/customer/device/{deviceName}/claim", method = RequestMethod.POST) +// public DeferredResult claimDevice(String deviceName, ClaimRequest claimRequest) { +// return restTemplate.exchange(baseURL + "/customer/device/{deviceName}/claim", HttpMethod.POST, new HttpEntity<>(claimRequest), new ParameterizedTypeReference>() { +// }, deviceName).getBody(); +// } + + public DeferredResult reClaimDevice(String deviceName) { + return restTemplate.exchange( + baseURL + "/customer/device/{deviceName}/claim", + HttpMethod.DELETE, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + deviceName).getBody(); + } + + public void saveRelation(EntityRelation relation) { + restTemplate.postForEntity(baseURL + "/relation", relation, Object.class); + } + + public void deleteRelation(String fromId, String fromType, String relationType, String relationTypeGroup, String toId, String toType) { + Map params = new HashMap<>(); + params.put("fromId", fromId); + params.put("fromType", fromType); + params.put("relationType", relationType); + params.put("relationTypeGroup", relationTypeGroup); + params.put("toId", toId); + params.put("toType", toType); + restTemplate.delete(baseURL + "/relation?fromId={fromId}&fromType={fromType}&relationType={relationType}&relationTypeGroup={relationTypeGroup}&toId={toId}&toType={toType}", params); + } + + public void deleteRelations(String entityId, String entityType) { + restTemplate.delete(baseURL + "/relations?entityId={entityId}&entityType={entityType}", entityId, entityType); + } + + public Optional getRelation(String fromId, String fromType, String relationType, String relationTypeGroup, String toId, String toType) { + Map params = new HashMap<>(); + params.put("fromId", fromId); + params.put("fromType", fromType); + params.put("relationType", relationType); + params.put("relationTypeGroup", relationTypeGroup); + params.put("toId", toId); + params.put("toType", toType); + + try { + ResponseEntity entityRelation = restTemplate.getForEntity( + baseURL + "/relation?fromId={fromId}&fromType={fromType}&relationType={relationType}&relationTypeGroup={relationTypeGroup}&toId={toId}&toType={toType}", + EntityRelation.class, + params); + return Optional.ofNullable(entityRelation.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public List findByFrom(String fromId, String fromType, String relationTypeGroup) { + Map params = new HashMap<>(); + params.put("fromId", fromId); + params.put("fromType", fromType); + params.put("relationTypeGroup", relationTypeGroup); + + return restTemplate.exchange( + baseURL + "/relations?fromId={fromId}&fromType={fromType}&relationTypeGroup={relationTypeGroup}", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params).getBody(); + } + + public List findInfoByFrom(String fromId, String fromType, String relationTypeGroup) { + + Map params = new HashMap<>(); + params.put("fromId", fromId); + params.put("fromType", fromType); + params.put("relationTypeGroup", relationTypeGroup); + + return restTemplate.exchange( + baseURL + "/relations/info?fromId={fromId}&fromType={fromType}&relationTypeGroup={relationTypeGroup}", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params).getBody(); + } + + public List findByFrom(String fromId, String fromType, String relationType, String relationTypeGroup) { + Map params = new HashMap<>(); + params.put("fromId", fromId); + params.put("fromType", fromType); + params.put("relationType", relationType); + params.put("relationTypeGroup", relationTypeGroup); + + return restTemplate.exchange( + baseURL + "/relations?fromId={fromId}&fromType={fromType}&relationType={relationType}&relationTypeGroup={relationTypeGroup}", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params).getBody(); + } + + public List findByTo(String toId, String toType, String relationTypeGroup) { + Map params = new HashMap<>(); + params.put("toId", toId); + params.put("toType", toType); + params.put("relationTypeGroup", relationTypeGroup); + + return restTemplate.exchange( + baseURL + "/relations?toId={toId}&toType={toType}&relationTypeGroup={relationTypeGroup}", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params).getBody(); + } + + public List findInfoByTo(String toId, String toType, String relationTypeGroup) { + Map params = new HashMap<>(); + params.put("toId", toId); + params.put("toType", toType); + params.put("relationTypeGroup", relationTypeGroup); + + return restTemplate.exchange( + baseURL + "/relations?toId={toId}&toType={toType}&relationTypeGroup={relationTypeGroup}", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params).getBody(); + } + + public List findByTo(String toId, String toType, String relationType, String relationTypeGroup) { + Map params = new HashMap<>(); + params.put("toId", toId); + params.put("toType", toType); + params.put("relationType", relationType); + params.put("relationTypeGroup", relationTypeGroup); + + return restTemplate.exchange( + baseURL + "/relations?toId={toId}&toType={toType}&relationType={relationType}&relationTypeGroup={relationTypeGroup}", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params).getBody(); + } + + public List findByQuery(EntityRelationsQuery query) { + return restTemplate.exchange( + baseURL + "/relations", + HttpMethod.POST, + new HttpEntity<>(query), + new ParameterizedTypeReference>() { + }).getBody(); + } + + public List findInfoByQuery(EntityRelationsQuery query) { + return restTemplate.exchange( + baseURL + "/relations", + HttpMethod.POST, + new HttpEntity<>(query), + new ParameterizedTypeReference>() { + }).getBody(); + } + + public Optional getEntityViewById(String entityViewId) { + try { + ResponseEntity entityView = restTemplate.getForEntity(baseURL + "/entityView/{entityViewId}", EntityView.class, entityViewId); + return Optional.ofNullable(entityView.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public EntityView saveEntityView(EntityView entityView) { + return restTemplate.postForEntity(baseURL + "entityView", entityView, EntityView.class).getBody(); + } + + public void deleteEntityView(String entityViewId) { + restTemplate.delete(baseURL + "/entityView/{entityViewId}", entityViewId); + } + + public Optional getTenantEntityView(String entityViewName) { + try { + ResponseEntity entityView = restTemplate.getForEntity(baseURL + "/tenant/entityViews?entityViewName={entityViewName}", EntityView.class, entityViewName); + return Optional.ofNullable(entityView.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional assignEntityViewToCustomer(String customerId, String entityViewId) { + try { + ResponseEntity entityView = restTemplate.postForEntity(baseURL + "/customer/{customerId}/entityView/{entityViewId}", null, EntityView.class, customerId, entityViewId); + return Optional.ofNullable(entityView.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional unassignEntityViewFromCustomer(String entityViewId) { + try { + ResponseEntity entityView = restTemplate.exchange( + baseURL + "/customer/entityView/{entityViewId}", + HttpMethod.DELETE, + HttpEntity.EMPTY, + EntityView.class, entityViewId); + return Optional.ofNullable(entityView.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public TextPageData getCustomerEntityViews(String customerId, String type, TextPageLink pageLink) { + Map params = new HashMap<>(); + params.put("customerId", customerId); + params.put("type", type); + addPageLinkToParam(params, pageLink); + return restTemplate.exchange( + baseURL + "/customer/{customerId}/entityViews?type={type}&" + TEXT_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params).getBody(); + } + + public TextPageData getTenantEntityViews(String type, TextPageLink pageLink) { + Map params = new HashMap<>(); + params.put("type", type); + addPageLinkToParam(params, pageLink); + return restTemplate.exchange( + baseURL + "/tenant/entityViews?type={type}&" + TEXT_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params).getBody(); + } + + public List findByQuery(EntityViewSearchQuery query) { + return restTemplate.exchange(baseURL + "/entityViews", HttpMethod.POST, new HttpEntity<>(query), new ParameterizedTypeReference>() { + }).getBody(); + } + + public List getEntityViewTypes() { + return restTemplate.exchange(baseURL + "/entityView/types", HttpMethod.GET, HttpEntity.EMPTY, new ParameterizedTypeReference>() { + }).getBody(); + } + + public Optional assignEntityViewToPublicCustomer(String entityViewId) { + try { + ResponseEntity entityView = restTemplate.postForEntity(baseURL + "customer/public/entityView/{entityViewId}", null, EntityView.class, entityViewId); + return Optional.ofNullable(entityView.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public TimePageData getEvents(String entityType, String entityId, String eventType, String tenantId, TimePageLink pageLink) { + Map params = new HashMap<>(); + params.put("entityType", entityType); + params.put("entityId", entityId); + params.put("eventType", eventType); + params.put("tenantId", tenantId); + addPageLinkToParam(params, pageLink); + + return restTemplate.exchange( + baseURL + "/events/{entityType}/{entityId}/{eventType}?tenantId={tenantId}&" + TIME_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params).getBody(); + } + + public TimePageData getEvents(String entityType, String entityId, String tenantId, TimePageLink pageLink) { + Map params = new HashMap<>(); + params.put("entityType", entityType); + params.put("entityId", entityId); + params.put("tenantId", tenantId); + addPageLinkToParam(params, pageLink); + + return restTemplate.exchange( + baseURL + "/events/{entityType}/{entityId}?tenantId={tenantId}&" + TIME_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params).getBody(); + } + + public DeferredResult handleOneWayDeviceRPCRequest(String deviceId, String requestBody) { + return restTemplate.exchange( + baseURL + "/oneway/{deviceId}", + HttpMethod.POST, + new HttpEntity<>(requestBody), + new ParameterizedTypeReference>() { + }, + deviceId).getBody(); + } + + public DeferredResult handleTwoWayDeviceRPCRequest(String deviceId, String requestBody) { + return restTemplate.exchange( + baseURL + "/twoway/{deviceId}", + HttpMethod.POST, + new HttpEntity<>(requestBody), + new ParameterizedTypeReference>() { + }, + deviceId).getBody(); + } + + public Optional getRuleChainById(String ruleChainId) { + try { + ResponseEntity ruleChain = restTemplate.getForEntity(baseURL + "/ruleChain/{ruleChainId}", RuleChain.class, ruleChainId); + return Optional.ofNullable(ruleChain.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional getRuleChainMetaData(String ruleChainId) { + try { + ResponseEntity ruleChainMetaData = restTemplate.getForEntity(baseURL + "/ruleChain/{ruleChainId}/metadata", RuleChainMetaData.class, ruleChainId); + return Optional.ofNullable(ruleChainMetaData.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public RuleChain saveRuleChain(RuleChain ruleChain) { + return restTemplate.postForEntity(baseURL + "/ruleChain", ruleChain, RuleChain.class).getBody(); + } + + public Optional setRootRuleChain(String ruleChainId) { + try { + ResponseEntity ruleChain = restTemplate.postForEntity(baseURL + "/ruleChain/{ruleChainId}/root", null, RuleChain.class, ruleChainId); + return Optional.ofNullable(ruleChain.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public RuleChainMetaData saveRuleChainMetaData(RuleChainMetaData ruleChainMetaData) { + return restTemplate.postForEntity(baseURL + "/ruleChain/metadata", ruleChainMetaData, RuleChainMetaData.class).getBody(); + } + + public TextPageData getRuleChains(TextPageLink pageLink) { + Map params = new HashMap<>(); + addPageLinkToParam(params, pageLink); + return restTemplate.exchange( + baseURL + "/ruleChains" + TEXT_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + } + ).getBody(); + } + + public void deleteRuleChain(String ruleChainId) { + restTemplate.delete(baseURL + "/ruleChain/{ruleChainId}", ruleChainId); + } + + public Optional getLatestRuleNodeDebugInput(String ruleNodeId) { + try { + ResponseEntity jsonNode = restTemplate.getForEntity(baseURL + "/ruleNode/{ruleNodeId}/debugIn", JsonNode.class, ruleNodeId); + return Optional.ofNullable(jsonNode.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Optional testScript(JsonNode inputParams) { + try { + ResponseEntity jsonNode = restTemplate.postForEntity(baseURL + "/ruleChain/testScript", inputParams, JsonNode.class); + return Optional.ofNullable(jsonNode.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public DeferredResult getAttributeKeys(String entityType, String entityId) { + return restTemplate.exchange( + baseURL + "/{entityType}/{entityId}/keys/attributes", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + entityType, + entityId).getBody(); + } + + public DeferredResult getAttributeKeysByScope(String entityType, String entityId, String scope) { + return restTemplate.exchange( + baseURL + "/{entityType}/{entityId}/keys/attributes/{scope}", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + entityType, + entityId, + scope).getBody(); + } + + public DeferredResult getAttributesResponseEntity(String entityType, String entityId, String keys) { + return restTemplate.exchange( + baseURL + "/{entityType}/{entityId}/values/attributes?keys={keys}", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + entityType, + entityId, + keys).getBody(); + } + + public DeferredResult getAttributesByScope(String entityType, String entityId, String scope, String keys) { + return restTemplate.exchange( + baseURL + "/{entityType}/{entityId}/values/attributes/{scope}?keys={keys}", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + entityType, + entityId, + scope, + keys).getBody(); + } + + public DeferredResult getTimeseriesKeys(String entityType, String entityId) { + return restTemplate.exchange( + baseURL + "/{entityType}/{entityId}/keys/timeseries", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + entityType, + entityId).getBody(); + } + + public DeferredResult getLatestTimeseries(String entityType, String entityId, String keys) { + return restTemplate.exchange( + baseURL + "/{entityType}/{entityId}/values/timeseries?keys={keys}", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + entityType, + entityId, + keys).getBody(); + } + + + public DeferredResult getTimeseries(String entityType, String entityId, String keys, Long startTs, Long endTs, Long interval, Integer limit, String agg) { + Map params = new HashMap<>(); + params.put("entityType", entityType); + params.put("entityId", entityId); + params.put("keys", keys); + params.put("startTs", startTs.toString()); + params.put("endTs", endTs.toString()); + params.put("interval", interval == null ? "0" : interval.toString()); + params.put("limit", limit == null ? "100" : limit.toString()); + params.put("agg", agg == null ? "NONE" : agg); + + return restTemplate.exchange( + baseURL + "/{entityType}/{entityId}/values/timeseries?keys={keys}&startTs={startTs}&endTs={endTs}&interval={interval}&limit={limit}&agg={agg}", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params).getBody(); + } + + public DeferredResult saveDeviceAttributes(String deviceId, String scope, JsonNode request) { + return restTemplate.exchange( + baseURL + "/{deviceId}/{scope}", + HttpMethod.POST, + new HttpEntity<>(request), + new ParameterizedTypeReference>() { + }, + deviceId, + scope).getBody(); + } + + public DeferredResult saveEntityAttributesV1(String entityType, String entityId, String scope, JsonNode request) { + return restTemplate.exchange( + baseURL + "/{entityType}/{entityId}/{scope}", + HttpMethod.POST, + new HttpEntity<>(request), + new ParameterizedTypeReference>() { + }, + entityType, + entityId, + scope).getBody(); + } + + public DeferredResult saveEntityAttributesV2(String entityType, String entityId, String scope, JsonNode request) { + return restTemplate.exchange( + baseURL + "/{entityType}/{entityId}/attributes/{scope}", + HttpMethod.POST, + new HttpEntity<>(request), + new ParameterizedTypeReference>() { + }, + entityType, + entityId, + scope).getBody(); + } + + public DeferredResult saveEntityTelemetry(String entityType, String entityId, String scope, String requestBody) { + return restTemplate.exchange( + baseURL + "/{entityType}/{entityId}/timeseries/{scope}", + HttpMethod.POST, + new HttpEntity<>(requestBody), + new ParameterizedTypeReference>() { + }, + entityType, + entityId, + scope).getBody(); + } + + public DeferredResult saveEntityTelemetryWithTTL(String entityType, String entityId, String scope, Long ttl, String requestBody) { + return restTemplate.exchange( + baseURL + "/{entityType}/{entityId}/timeseries/{scope}/{ttl}", + HttpMethod.POST, + new HttpEntity<>(requestBody), + new ParameterizedTypeReference>() { + }, + entityType, + entityId, + scope, + ttl).getBody(); + } + + public DeferredResult deleteEntityTimeseries(String entityType, + String entityId, + String keys, + boolean deleteAllDataForKeys, + Long startTs, + Long endTs, + boolean rewriteLatestIfDeleted) { + Map params = new HashMap<>(); + params.put("entityType", entityType); + params.put("entityId", entityId); + params.put("keys", keys); + params.put("deleteAllDataForKeys", String.valueOf(deleteAllDataForKeys)); + params.put("startTs", startTs.toString()); + params.put("endTs", endTs.toString()); + params.put("rewriteLatestIfDeleted", String.valueOf(rewriteLatestIfDeleted)); + + return restTemplate.exchange( + baseURL + "/{entityType}/{entityId}/timeseries/delete?keys={keys}&deleteAllDataForKeys={deleteAllDataForKeys}&startTs={startTs}&endTs={endTs}&rewriteLatestIfDeleted={rewriteLatestIfDeleted}", + HttpMethod.DELETE, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params).getBody(); + } + + public DeferredResult deleteEntityAttributes(String deviceId, String scope, String keys) { + return restTemplate.exchange( + baseURL + "/{deviceId}/{scope}?keys={keys}", + HttpMethod.DELETE, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + deviceId, + scope, + keys).getBody(); + } + + public DeferredResult deleteEntityAttributes(String entityType, String entityId, String scope, String keys) { + return restTemplate.exchange( + baseURL + "/{entityType}/{entityId}/{scope}?keys={keys}", + HttpMethod.DELETE, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + entityType, + entityId, + scope, + keys).getBody(); + } + + public Optional getTenantById(String tenantId) { + try { + ResponseEntity tenant = restTemplate.getForEntity(baseURL + "/tenant/{tenantId}", Tenant.class, tenantId); + return Optional.ofNullable(tenant.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Tenant saveTenant(Tenant tenant) { + return restTemplate.postForEntity(baseURL + "/tenant", tenant, Tenant.class).getBody(); + } + + public void deleteTenant(String tenantId) { + restTemplate.delete(baseURL + "/tenant/{tenantId}", tenantId); + } + + public TextPageData getTenants(TextPageLink pageLink) { + Map params = new HashMap<>(); + addPageLinkToParam(params, pageLink); + return restTemplate.exchange( + baseURL + "/tenants?" + TEXT_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params).getBody(); + } + + public Optional getUserById(String userId) { + try { + ResponseEntity user = restTemplate.getForEntity(baseURL + "/user/{userId}", User.class, userId); + return Optional.ofNullable(user.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public Boolean isUserTokenAccessEnabled() { + return restTemplate.getForEntity(baseURL + "/user/tokenAccessEnabled", Boolean.class).getBody(); + } + + public Optional getUserToken(String userId) { + try { + ResponseEntity userToken = restTemplate.getForEntity(baseURL + "/user/{userId}/token", JsonNode.class, userId); + return Optional.ofNullable(userToken.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public User saveUser(User user, boolean sendActivationMail) { + return restTemplate.postForEntity(baseURL + "/user?sendActivationMail={sendActivationMail}", user, User.class, sendActivationMail).getBody(); + } + + public void sendActivationEmail(String email) { + restTemplate.postForEntity(baseURL + "/user/sendActivationMail?email={email}", null, Object.class, email); + } + + public Optional getActivationLink(String userId) { + try { + ResponseEntity activationLink = restTemplate.getForEntity(baseURL + "/user/{userId}/activationLink", String.class, userId); + return Optional.ofNullable(activationLink.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public void deleteUser(String userId) { + restTemplate.delete(baseURL + "/user/{userId}", userId); + } + + // @RequestMapping(value = "/tenant/{tenantId}/users", params = {"limit"}, method = RequestMethod.GET) + public TextPageData getTenantAdmins(String tenantId, TextPageLink pageLink) { + Map params = new HashMap<>(); + params.put("tenantId", tenantId); + addPageLinkToParam(params, pageLink); + + return restTemplate.exchange( + baseURL + "/tenant/{tenantId}/users?" + TEXT_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params).getBody(); + } + + public TextPageData getCustomerUsers(String customerId, TextPageLink pageLink) { + Map params = new HashMap<>(); + params.put("customerId", customerId); + addPageLinkToParam(params, pageLink); + + return restTemplate.exchange( + baseURL + "/customer/{customerId}/users?" + TEXT_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + params).getBody(); + } + + public void setUserCredentialsEnabled(String userId, boolean userCredentialsEnabled) { + restTemplate.postForEntity( + baseURL + "/user/{userId}/userCredentialsEnabled?serCredentialsEnabled={serCredentialsEnabled}", + null, + Object.class, + userId, + userCredentialsEnabled); + } + + public Optional getWidgetsBundleById(String widgetsBundleId) { + try { + ResponseEntity widgetsBundle = + restTemplate.getForEntity(baseURL + "/widgetsBundle/{widgetsBundleId}", WidgetsBundle.class, widgetsBundleId); + return Optional.ofNullable(widgetsBundle.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public WidgetsBundle saveWidgetsBundle(WidgetsBundle widgetsBundle) { + return restTemplate.postForEntity(baseURL + "/widgetsBundle", widgetsBundle, WidgetsBundle.class).getBody(); + } + + public void deleteWidgetsBundle(String widgetsBundleId) { + restTemplate.delete(baseURL + "/widgetsBundle/{widgetsBundleId}", widgetsBundleId); + } + + public TextPageData getWidgetsBundles(TextPageLink pageLink) { + Map params = new HashMap<>(); + addPageLinkToParam(params, pageLink); + return restTemplate.exchange( + baseURL + "/widgetsBundles?" + TEXT_PAGE_LINK_URL_PARAMS, + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }).getBody(); + } + + public List getWidgetsBundles() { + return restTemplate.exchange( + baseURL + "/widgetsBundles", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }).getBody(); + } + + public Optional getWidgetTypeById(String widgetTypeId) { + try { + ResponseEntity widgetType = + restTemplate.getForEntity(baseURL + "/widgetType/{widgetTypeId}", WidgetType.class, widgetTypeId); + return Optional.ofNullable(widgetType.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + public WidgetType saveWidgetType(WidgetType widgetType) { + return restTemplate.postForEntity(baseURL + "/widgetType", widgetType, WidgetType.class).getBody(); + } + + public void deleteWidgetType(String widgetTypeId) { + restTemplate.delete(baseURL + "/widgetType/{widgetTypeId}", widgetTypeId); + } + + public List getBundleWidgetTypes(boolean isSystem, String bundleAlias) { + return restTemplate.exchange( + baseURL + "/widgetTypes?isSystem={isSystem}&bundleAlias={bundleAlias}", + HttpMethod.GET, + HttpEntity.EMPTY, + new ParameterizedTypeReference>() { + }, + isSystem, + bundleAlias).getBody(); + } + + public Optional getWidgetType(boolean isSystem, String bundleAlias, String alias) { + try { + ResponseEntity widgetType = + restTemplate.getForEntity( + baseURL + "/widgetType?isSystem={isSystem}&bundleAlias={bundleAlias}&alias={alias}", + WidgetType.class, + isSystem, + bundleAlias, + alias); + return Optional.ofNullable(widgetType.getBody()); + } catch (HttpClientErrorException exception) { + if (exception.getStatusCode() == HttpStatus.NOT_FOUND) { + return Optional.empty(); + } else { + throw exception; + } + } + } + + private void addPageLinkToParam(Map params, TimePageLink pageLink) { + params.put("limit", String.valueOf(pageLink.getLimit())); + params.put("startTime", String.valueOf(pageLink.getStartTime())); + params.put("endTime", String.valueOf(pageLink.getEndTime())); + params.put("ascOrder", String.valueOf(pageLink.isAscOrder())); + params.put("offset", pageLink.getIdOffset().toString()); + } + + private void addPageLinkToParam(Map params, TextPageLink pageLink) { + params.put("limit", String.valueOf(pageLink.getLimit())); + params.put("textSearch", pageLink.getTextSearch()); + params.put("idOffset", pageLink.getIdOffset().toString()); + params.put("textOffset", pageLink.getTextOffset()); + } +}