Search in sources :

Example 31 with ThingsboardException

use of org.thingsboard.server.common.data.exception.ThingsboardException in project thingsboard by thingsboard.

the class TelemetryController method saveTelemetry.

private DeferredResult<ResponseEntity> saveTelemetry(TenantId curTenantId, EntityId entityIdSrc, String requestBody, long ttl) throws ThingsboardException {
    Map<Long, List<KvEntry>> telemetryRequest;
    JsonElement telemetryJson;
    try {
        telemetryJson = new JsonParser().parse(requestBody);
    } catch (Exception e) {
        return getImmediateDeferredResult("Unable to parse timeseries payload: Invalid JSON body!", HttpStatus.BAD_REQUEST);
    }
    try {
        telemetryRequest = JsonConverter.convertToTelemetry(telemetryJson, System.currentTimeMillis());
    } catch (Exception e) {
        return getImmediateDeferredResult("Unable to parse timeseries payload. Invalid JSON body: " + e.getMessage(), HttpStatus.BAD_REQUEST);
    }
    List<TsKvEntry> entries = new ArrayList<>();
    for (Map.Entry<Long, List<KvEntry>> entry : telemetryRequest.entrySet()) {
        for (KvEntry kv : entry.getValue()) {
            entries.add(new BasicTsKvEntry(entry.getKey(), kv));
        }
    }
    if (entries.isEmpty()) {
        return getImmediateDeferredResult("No timeseries data found in request body!", HttpStatus.BAD_REQUEST);
    }
    SecurityUser user = getCurrentUser();
    return accessValidator.validateEntityAndCallback(getCurrentUser(), Operation.WRITE_TELEMETRY, entityIdSrc, (result, tenantId, entityId) -> {
        long tenantTtl = ttl;
        if (!TenantId.SYS_TENANT_ID.equals(tenantId) && tenantTtl == 0) {
            TenantProfile tenantProfile = tenantProfileCache.get(tenantId);
            tenantTtl = TimeUnit.DAYS.toSeconds(((DefaultTenantProfileConfiguration) tenantProfile.getProfileData().getConfiguration()).getDefaultStorageTtlDays());
        }
        tsSubService.saveAndNotify(tenantId, user.getCustomerId(), entityId, entries, tenantTtl, new FutureCallback<Void>() {

            @Override
            public void onSuccess(@Nullable Void tmp) {
                logTelemetryUpdated(user, entityId, entries, null);
                result.setResult(new ResponseEntity(HttpStatus.OK));
            }

            @Override
            public void onFailure(Throwable t) {
                logTelemetryUpdated(user, entityId, entries, t);
                AccessValidator.handleError(t, result, HttpStatus.INTERNAL_SERVER_ERROR);
            }
        });
    });
}
Also used : TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) ArrayList(java.util.ArrayList) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) BaseAttributeKvEntry(org.thingsboard.server.common.data.kv.BaseAttributeKvEntry) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) KvEntry(org.thingsboard.server.common.data.kv.KvEntry) UncheckedApiException(org.thingsboard.server.service.telemetry.exception.UncheckedApiException) JsonParseException(com.google.gson.JsonParseException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) InvalidParametersException(org.thingsboard.server.service.telemetry.exception.InvalidParametersException) ResponseEntity(org.springframework.http.ResponseEntity) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) JsonElement(com.google.gson.JsonElement) ArrayList(java.util.ArrayList) List(java.util.List) TenantProfile(org.thingsboard.server.common.data.TenantProfile) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) DefaultTenantProfileConfiguration(org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration) JsonParser(com.google.gson.JsonParser)

Example 32 with ThingsboardException

use of org.thingsboard.server.common.data.exception.ThingsboardException in project thingsboard by thingsboard.

the class DeviceController method getCustomerDeviceInfos.

@ApiOperation(value = "Get Customer Device Infos (getCustomerDeviceInfos)", notes = "Returns a page of devices info objects assigned to customer. " + PAGE_DATA_PARAMETERS + DEVICE_INFO_DESCRIPTION + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/customer/{customerId}/deviceInfos", params = { "pageSize", "page" }, method = RequestMethod.GET)
@ResponseBody
public PageData<DeviceInfo> getCustomerDeviceInfos(@ApiParam(value = CUSTOMER_ID_PARAM_DESCRIPTION, required = true) @PathVariable("customerId") String strCustomerId, @ApiParam(value = PAGE_SIZE_DESCRIPTION, required = true) @RequestParam int pageSize, @ApiParam(value = PAGE_NUMBER_DESCRIPTION, required = true) @RequestParam int page, @ApiParam(value = DEVICE_TYPE_DESCRIPTION) @RequestParam(required = false) String type, @ApiParam(value = DEVICE_PROFILE_ID_PARAM_DESCRIPTION) @RequestParam(required = false) String deviceProfileId, @ApiParam(value = DEVICE_TEXT_SEARCH_DESCRIPTION) @RequestParam(required = false) String textSearch, @ApiParam(value = SORT_PROPERTY_DESCRIPTION, allowableValues = DEVICE_SORT_PROPERTY_ALLOWABLE_VALUES) @RequestParam(required = false) String sortProperty, @ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES) @RequestParam(required = false) String sortOrder) throws ThingsboardException {
    checkParameter("customerId", strCustomerId);
    try {
        TenantId tenantId = getCurrentUser().getTenantId();
        CustomerId customerId = new CustomerId(toUUID(strCustomerId));
        checkCustomerId(customerId, Operation.READ);
        PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
        if (type != null && type.trim().length() > 0) {
            return checkNotNull(deviceService.findDeviceInfosByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink));
        } else if (deviceProfileId != null && deviceProfileId.length() > 0) {
            DeviceProfileId profileId = new DeviceProfileId(toUUID(deviceProfileId));
            return checkNotNull(deviceService.findDeviceInfosByTenantIdAndCustomerIdAndDeviceProfileId(tenantId, customerId, profileId, pageLink));
        } else {
            return checkNotNull(deviceService.findDeviceInfosByTenantIdAndCustomerId(tenantId, customerId, pageLink));
        }
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : TenantId(org.thingsboard.server.common.data.id.TenantId) DeviceProfileId(org.thingsboard.server.common.data.id.DeviceProfileId) PageLink(org.thingsboard.server.common.data.page.PageLink) TimePageLink(org.thingsboard.server.common.data.page.TimePageLink) CustomerId(org.thingsboard.server.common.data.id.CustomerId) IOException(java.io.IOException) IncorrectParameterException(org.thingsboard.server.dao.exception.IncorrectParameterException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 33 with ThingsboardException

use of org.thingsboard.server.common.data.exception.ThingsboardException in project thingsboard by thingsboard.

the class EdgeController method getEdgesByIds.

@ApiOperation(value = "Get Edges By Ids (getEdgesByIds)", notes = "Requested edges must be owned by tenant or assigned to customer which user is performing the request." + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/edges", params = { "edgeIds" }, method = RequestMethod.GET)
@ResponseBody
public List<Edge> getEdgesByIds(@ApiParam(value = "A list of edges ids, separated by comma ','", required = true) @RequestParam("edgeIds") String[] strEdgeIds) throws ThingsboardException {
    checkArrayParameter("edgeIds", strEdgeIds);
    try {
        SecurityUser user = getCurrentUser();
        TenantId tenantId = user.getTenantId();
        CustomerId customerId = user.getCustomerId();
        List<EdgeId> edgeIds = new ArrayList<>();
        for (String strEdgeId : strEdgeIds) {
            edgeIds.add(new EdgeId(toUUID(strEdgeId)));
        }
        ListenableFuture<List<Edge>> edgesFuture;
        if (customerId == null || customerId.isNullUid()) {
            edgesFuture = edgeService.findEdgesByTenantIdAndIdsAsync(tenantId, edgeIds);
        } else {
            edgesFuture = edgeService.findEdgesByTenantIdCustomerIdAndIdsAsync(tenantId, customerId, edgeIds);
        }
        List<Edge> edges = edgesFuture.get();
        return checkNotNull(edges);
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : TenantId(org.thingsboard.server.common.data.id.TenantId) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) EdgeId(org.thingsboard.server.common.data.id.EdgeId) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) CustomerId(org.thingsboard.server.common.data.id.CustomerId) Edge(org.thingsboard.server.common.data.edge.Edge) IncorrectParameterException(org.thingsboard.server.dao.exception.IncorrectParameterException) DataValidationException(org.thingsboard.server.dao.exception.DataValidationException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) IOException(java.io.IOException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 34 with ThingsboardException

use of org.thingsboard.server.common.data.exception.ThingsboardException in project thingsboard by thingsboard.

the class EdgeController method getTenantEdges.

@ApiOperation(value = "Get Tenant Edges (getTenantEdges)", notes = "Returns a page of edges owned by tenant. " + PAGE_DATA_PARAMETERS + TENANT_AUTHORITY_PARAGRAPH, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/tenant/edges", params = { "pageSize", "page" }, method = RequestMethod.GET)
@ResponseBody
public PageData<Edge> getTenantEdges(@ApiParam(value = PAGE_SIZE_DESCRIPTION, required = true) @RequestParam int pageSize, @ApiParam(value = PAGE_NUMBER_DESCRIPTION, required = true) @RequestParam int page, @ApiParam(value = EDGE_TYPE_DESCRIPTION) @RequestParam(required = false) String type, @ApiParam(value = EDGE_TEXT_SEARCH_DESCRIPTION) @RequestParam(required = false) String textSearch, @ApiParam(value = SORT_PROPERTY_DESCRIPTION, allowableValues = EDGE_SORT_PROPERTY_ALLOWABLE_VALUES) @RequestParam(required = false) String sortProperty, @ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES) @RequestParam(required = false) String sortOrder) throws ThingsboardException {
    try {
        TenantId tenantId = getCurrentUser().getTenantId();
        PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
        if (type != null && type.trim().length() > 0) {
            return checkNotNull(edgeService.findEdgesByTenantIdAndType(tenantId, type, pageLink));
        } else {
            return checkNotNull(edgeService.findEdgesByTenantId(tenantId, pageLink));
        }
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : TenantId(org.thingsboard.server.common.data.id.TenantId) PageLink(org.thingsboard.server.common.data.page.PageLink) IncorrectParameterException(org.thingsboard.server.dao.exception.IncorrectParameterException) DataValidationException(org.thingsboard.server.dao.exception.DataValidationException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) IOException(java.io.IOException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 35 with ThingsboardException

use of org.thingsboard.server.common.data.exception.ThingsboardException in project thingsboard by thingsboard.

the class EdgeController method syncEdge.

@ApiOperation(value = "Sync edge (syncEdge)", notes = "Starts synchronization process between edge and cloud. \n" + "All entities that are assigned to particular edge are going to be send to remote edge service." + TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/edge/sync/{edgeId}", method = RequestMethod.POST)
public void syncEdge(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true) @PathVariable("edgeId") String strEdgeId) throws ThingsboardException {
    checkParameter("edgeId", strEdgeId);
    try {
        if (isEdgesEnabled()) {
            EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
            edgeId = checkNotNull(edgeId);
            SecurityUser user = getCurrentUser();
            TenantId tenantId = user.getTenantId();
            edgeGrpcService.startSyncProcess(tenantId, edgeId);
        } else {
            throw new ThingsboardException("Edges support disabled", ThingsboardErrorCode.GENERAL);
        }
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : TenantId(org.thingsboard.server.common.data.id.TenantId) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) EdgeId(org.thingsboard.server.common.data.id.EdgeId) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) IncorrectParameterException(org.thingsboard.server.dao.exception.IncorrectParameterException) DataValidationException(org.thingsboard.server.dao.exception.DataValidationException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) IOException(java.io.IOException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

ThingsboardException (org.thingsboard.server.common.data.exception.ThingsboardException)225 ApiOperation (io.swagger.annotations.ApiOperation)176 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)176 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)172 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)150 IncorrectParameterException (org.thingsboard.server.dao.exception.IncorrectParameterException)102 TenantId (org.thingsboard.server.common.data.id.TenantId)75 SecurityUser (org.thingsboard.server.service.security.model.SecurityUser)48 CustomerId (org.thingsboard.server.common.data.id.CustomerId)42 EdgeId (org.thingsboard.server.common.data.id.EdgeId)42 DataValidationException (org.thingsboard.server.dao.exception.DataValidationException)42 Customer (org.thingsboard.server.common.data.Customer)39 IOException (java.io.IOException)38 Edge (org.thingsboard.server.common.data.edge.Edge)34 PageLink (org.thingsboard.server.common.data.page.PageLink)34 ResponseStatus (org.springframework.web.bind.annotation.ResponseStatus)30 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)25 MessagingException (javax.mail.MessagingException)25 EntityId (org.thingsboard.server.common.data.id.EntityId)25 TimePageLink (org.thingsboard.server.common.data.page.TimePageLink)25