Search in sources :

Example 16 with ThingsboardException

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

the class DefaultMailService method sendMail.

private void sendMail(JavaMailSenderImpl mailSender, String mailFrom, String email, String subject, String message) throws ThingsboardException {
    try {
        MimeMessage mimeMsg = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, UTF_8);
        helper.setFrom(mailFrom);
        helper.setTo(email);
        helper.setSubject(subject);
        helper.setText(message, true);
        mailSender.send(helper.getMimeMessage());
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : MimeMessage(javax.mail.internet.MimeMessage) MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper) IncorrectParameterException(org.thingsboard.server.dao.exception.IncorrectParameterException) NestedRuntimeException(org.springframework.core.NestedRuntimeException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException)

Example 17 with ThingsboardException

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

the class DefaultTbResourceService method saveResource.

@Override
public TbResource saveResource(TbResource resource) throws ThingsboardException {
    log.trace("Executing saveResource [{}]", resource);
    if (StringUtils.isEmpty(resource.getData())) {
        throw new DataValidationException("Resource data should be specified!");
    }
    if (ResourceType.LWM2M_MODEL.equals(resource.getResourceType())) {
        try {
            List<ObjectModel> objectModels = ddfFileParser.parse(new ByteArrayInputStream(Base64.getDecoder().decode(resource.getData())), resource.getSearchText());
            if (!objectModels.isEmpty()) {
                ObjectModel objectModel = objectModels.get(0);
                String resourceKey = objectModel.id + LWM2M_SEPARATOR_KEY + objectModel.version;
                String name = objectModel.name;
                resource.setResourceKey(resourceKey);
                if (resource.getId() == null) {
                    resource.setTitle(name + " id=" + objectModel.id + " v" + objectModel.version);
                }
                resource.setSearchText(resourceKey + LWM2M_SEPARATOR_SEARCH_TEXT + name);
            } else {
                throw new DataValidationException(String.format("Could not parse the XML of objectModel with name %s", resource.getSearchText()));
            }
        } catch (InvalidDDFFileException e) {
            log.error("Failed to parse file {}", resource.getFileName(), e);
            throw new DataValidationException("Failed to parse file " + resource.getFileName());
        } catch (IOException e) {
            throw new ThingsboardException(e, ThingsboardErrorCode.GENERAL);
        }
        if (resource.getResourceType().equals(ResourceType.LWM2M_MODEL) && toLwM2mObject(resource, true) == null) {
            throw new DataValidationException(String.format("Could not parse the XML of objectModel with name %s", resource.getSearchText()));
        }
    } else {
        resource.setResourceKey(resource.getFileName());
    }
    return resourceService.saveResource(resource);
}
Also used : DataValidationException(org.thingsboard.server.dao.exception.DataValidationException) ObjectModel(org.eclipse.leshan.core.model.ObjectModel) ByteArrayInputStream(java.io.ByteArrayInputStream) InvalidDDFFileException(org.eclipse.leshan.core.model.InvalidDDFFileException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) IOException(java.io.IOException)

Example 18 with ThingsboardException

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

the class TelemetryController method deleteAttributes.

private DeferredResult<ResponseEntity> deleteAttributes(EntityId entityIdSrc, String scope, String keysStr) throws ThingsboardException {
    List<String> keys = toKeysList(keysStr);
    if (keys.isEmpty()) {
        return getImmediateDeferredResult("Empty keys: " + keysStr, HttpStatus.BAD_REQUEST);
    }
    SecurityUser user = getCurrentUser();
    if (DataConstants.SERVER_SCOPE.equals(scope) || DataConstants.SHARED_SCOPE.equals(scope) || DataConstants.CLIENT_SCOPE.equals(scope)) {
        return accessValidator.validateEntityAndCallback(getCurrentUser(), Operation.WRITE_ATTRIBUTES, entityIdSrc, (result, tenantId, entityId) -> {
            tsSubService.deleteAndNotify(tenantId, entityId, scope, keys, new FutureCallback<Void>() {

                @Override
                public void onSuccess(@Nullable Void tmp) {
                    logAttributesDeleted(user, entityId, scope, keys, null);
                    if (entityIdSrc.getEntityType().equals(EntityType.DEVICE)) {
                        DeviceId deviceId = new DeviceId(entityId.getId());
                        Set<AttributeKey> keysToNotify = new HashSet<>();
                        keys.forEach(key -> keysToNotify.add(new AttributeKey(scope, key)));
                        tbClusterService.pushMsgToCore(DeviceAttributesEventNotificationMsg.onDelete(user.getTenantId(), deviceId, keysToNotify), null);
                    }
                    result.setResult(new ResponseEntity<>(HttpStatus.OK));
                }

                @Override
                public void onFailure(Throwable t) {
                    logAttributesDeleted(user, entityId, scope, keys, t);
                    result.setResult(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
                }
            });
        });
    } else {
        return getImmediateDeferredResult("Invalid attribute scope: " + scope, HttpStatus.BAD_REQUEST);
    }
}
Also used : TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH(org.thingsboard.server.controller.ControllerConstants.TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH) RequestParam(org.springframework.web.bind.annotation.RequestParam) Arrays(java.util.Arrays) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) BaseDeleteTsKvQuery(org.thingsboard.server.common.data.kv.BaseDeleteTsKvQuery) TsData(org.thingsboard.server.service.telemetry.TsData) ENTITY_TYPE_PARAM_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.ENTITY_TYPE_PARAM_DESCRIPTION) SORT_ORDER_ALLOWABLE_VALUES(org.thingsboard.server.controller.ControllerConstants.SORT_ORDER_ALLOWABLE_VALUES) ApiParam(io.swagger.annotations.ApiParam) Autowired(org.springframework.beans.factory.annotation.Autowired) STRICT_DATA_TYPES_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.STRICT_DATA_TYPES_DESCRIPTION) TenantId(org.thingsboard.server.common.data.id.TenantId) Map(java.util.Map) SAVE_ENTITY_TIMESERIES_STATUS_UNAUTHORIZED(org.thingsboard.server.controller.ControllerConstants.SAVE_ENTITY_TIMESERIES_STATUS_UNAUTHORIZED) SAVE_ATTIRIBUTES_STATUS_OK(org.thingsboard.server.controller.ControllerConstants.SAVE_ATTIRIBUTES_STATUS_OK) JsonConverter(org.thingsboard.server.common.transport.adaptor.JsonConverter) INVALID_ENTITY_ID_OR_ENTITY_TYPE_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.INVALID_ENTITY_ID_OR_ENTITY_TYPE_DESCRIPTION) JsonNode(com.fasterxml.jackson.databind.JsonNode) ATTRIBUTES_KEYS_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.ATTRIBUTES_KEYS_DESCRIPTION) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) Set(java.util.Set) RestController(org.springframework.web.bind.annotation.RestController) DeleteTsKvQuery(org.thingsboard.server.common.data.kv.DeleteTsKvQuery) Executors(java.util.concurrent.Executors) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) Slf4j(lombok.extern.slf4j.Slf4j) Operation(org.thingsboard.server.service.security.permission.Operation) BooleanDataEntry(org.thingsboard.server.common.data.kv.BooleanDataEntry) DeferredResult(org.springframework.web.context.request.async.DeferredResult) TELEMETRY_KEYS_BASE_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.TELEMETRY_KEYS_BASE_DESCRIPTION) JsonParser(com.google.gson.JsonParser) DEVICE_ID(org.thingsboard.server.controller.ControllerConstants.DEVICE_ID) ArrayList(java.util.ArrayList) Value(org.springframework.beans.factory.annotation.Value) RequestBody(org.springframework.web.bind.annotation.RequestBody) LinkedHashMap(java.util.LinkedHashMap) EntityIdFactory(org.thingsboard.server.common.data.id.EntityIdFactory) DEVICE_ID_PARAM_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.DEVICE_ID_PARAM_DESCRIPTION) DataType(org.thingsboard.server.common.data.kv.DataType) SAVE_ATTRIBUTES_REQUEST_PAYLOAD(org.thingsboard.server.controller.ControllerConstants.SAVE_ATTRIBUTES_REQUEST_PAYLOAD) Nullable(javax.annotation.Nullable) DataConstants(org.thingsboard.server.common.data.DataConstants) ATTRIBUTES_JSON_REQUEST_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.ATTRIBUTES_JSON_REQUEST_DESCRIPTION) ConstraintValidator(org.thingsboard.server.dao.service.ConstraintValidator) ATTRIBUTES_SCOPE_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.ATTRIBUTES_SCOPE_DESCRIPTION) BaseAttributeKvEntry(org.thingsboard.server.common.data.kv.BaseAttributeKvEntry) FutureCallback(com.google.common.util.concurrent.FutureCallback) HttpStatus(org.springframework.http.HttpStatus) Futures(com.google.common.util.concurrent.Futures) SAVE_ENTITY_ATTRIBUTES_STATUS_UNAUTHORIZED(org.thingsboard.server.controller.ControllerConstants.SAVE_ENTITY_ATTRIBUTES_STATUS_UNAUTHORIZED) ApiResponse(io.swagger.annotations.ApiResponse) MARKDOWN_CODE_BLOCK_START(org.thingsboard.server.controller.ControllerConstants.MARKDOWN_CODE_BLOCK_START) ReadTsKvQuery(org.thingsboard.server.common.data.kv.ReadTsKvQuery) ENTITY_ID_PARAM_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.ENTITY_ID_PARAM_DESCRIPTION) StringDataEntry(org.thingsboard.server.common.data.kv.StringDataEntry) PathVariable(org.springframework.web.bind.annotation.PathVariable) SAVE_ENTITY_ATTRIBUTES_STATUS_INTERNAL_SERVER_ERROR(org.thingsboard.server.controller.ControllerConstants.SAVE_ENTITY_ATTRIBUTES_STATUS_INTERNAL_SERVER_ERROR) SAVE_ENTITY_TIMESERIES_STATUS_INTERNAL_SERVER_ERROR(org.thingsboard.server.controller.ControllerConstants.SAVE_ENTITY_TIMESERIES_STATUS_INTERNAL_SERVER_ERROR) DefaultTenantProfileConfiguration(org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) ApiOperation(io.swagger.annotations.ApiOperation) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) PreDestroy(javax.annotation.PreDestroy) INVALID_STRUCTURE_OF_THE_REQUEST(org.thingsboard.server.controller.ControllerConstants.INVALID_STRUCTURE_OF_THE_REQUEST) EntityType(org.thingsboard.server.common.data.EntityType) TS_STRICT_DATA_EXAMPLE(org.thingsboard.server.controller.ControllerConstants.TS_STRICT_DATA_EXAMPLE) DeviceAttributesEventNotificationMsg(org.thingsboard.rule.engine.api.msg.DeviceAttributesEventNotificationMsg) BaseReadTsKvQuery(org.thingsboard.server.common.data.kv.BaseReadTsKvQuery) DeviceId(org.thingsboard.server.common.data.id.DeviceId) Function(com.google.common.base.Function) MARKDOWN_CODE_BLOCK_END(org.thingsboard.server.controller.ControllerConstants.MARKDOWN_CODE_BLOCK_END) AttributeData(org.thingsboard.server.service.telemetry.AttributeData) MediaType(org.springframework.http.MediaType) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) TimeseriesService(org.thingsboard.server.dao.timeseries.TimeseriesService) ThingsBoardThreadFactory(org.thingsboard.common.util.ThingsBoardThreadFactory) UncheckedApiException(org.thingsboard.server.service.telemetry.exception.UncheckedApiException) LATEST_TS_NON_STRICT_DATA_EXAMPLE(org.thingsboard.server.controller.ControllerConstants.LATEST_TS_NON_STRICT_DATA_EXAMPLE) Collectors(java.util.stream.Collectors) TELEMETRY_KEYS_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.TELEMETRY_KEYS_DESCRIPTION) TELEMETRY_JSON_REQUEST_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.TELEMETRY_JSON_REQUEST_DESCRIPTION) List(java.util.List) KvEntry(org.thingsboard.server.common.data.kv.KvEntry) PostConstruct(javax.annotation.PostConstruct) TELEMETRY_SCOPE_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.TELEMETRY_SCOPE_DESCRIPTION) SAVE_ATTIRIBUTES_STATUS_BAD_REQUEST(org.thingsboard.server.controller.ControllerConstants.SAVE_ATTIRIBUTES_STATUS_BAD_REQUEST) SORT_ORDER_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.SORT_ORDER_DESCRIPTION) LongDataEntry(org.thingsboard.server.common.data.kv.LongDataEntry) JsonParseException(com.google.gson.JsonParseException) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) ATTRIBUTE_DATA_EXAMPLE(org.thingsboard.server.controller.ControllerConstants.ATTRIBUTE_DATA_EXAMPLE) SAVE_TIMESERIES_REQUEST_PAYLOAD(org.thingsboard.server.controller.ControllerConstants.SAVE_TIMESERIES_REQUEST_PAYLOAD) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) SAVE_ENTITY_ATTRIBUTES_STATUS_OK(org.thingsboard.server.controller.ControllerConstants.SAVE_ENTITY_ATTRIBUTES_STATUS_OK) JacksonUtil(org.thingsboard.common.util.JacksonUtil) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ApiResponses(io.swagger.annotations.ApiResponses) JsonElement(com.google.gson.JsonElement) HashSet(java.util.HashSet) TenantProfile(org.thingsboard.server.common.data.TenantProfile) ActionType(org.thingsboard.server.common.data.audit.ActionType) TbCoreComponent(org.thingsboard.server.queue.util.TbCoreComponent) EntityId(org.thingsboard.server.common.data.id.EntityId) UUIDBased(org.thingsboard.server.common.data.id.UUIDBased) DoubleDataEntry(org.thingsboard.server.common.data.kv.DoubleDataEntry) ExecutorService(java.util.concurrent.ExecutorService) AttributeKey(org.thingsboard.server.common.data.kv.AttributeKey) ATTRIBUTES_SCOPE_ALLOWED_VALUES(org.thingsboard.server.controller.ControllerConstants.ATTRIBUTES_SCOPE_ALLOWED_VALUES) AccessValidator(org.thingsboard.server.service.security.AccessValidator) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) Aggregation(org.thingsboard.server.common.data.kv.Aggregation) LATEST_TS_STRICT_DATA_EXAMPLE(org.thingsboard.server.controller.ControllerConstants.LATEST_TS_STRICT_DATA_EXAMPLE) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) SAVE_ENTITY_TIMESERIES_STATUS_OK(org.thingsboard.server.controller.ControllerConstants.SAVE_ENTITY_TIMESERIES_STATUS_OK) InvalidParametersException(org.thingsboard.server.service.telemetry.exception.InvalidParametersException) TimeUnit(java.util.concurrent.TimeUnit) JsonDataEntry(org.thingsboard.server.common.data.kv.JsonDataEntry) ResponseEntity(org.springframework.http.ResponseEntity) ENTITY_ATTRIBUTE_SCOPES(org.thingsboard.server.controller.ControllerConstants.ENTITY_ATTRIBUTE_SCOPES) StringUtils(org.springframework.util.StringUtils) Set(java.util.Set) HashSet(java.util.HashSet) DeviceId(org.thingsboard.server.common.data.id.DeviceId) AttributeKey(org.thingsboard.server.common.data.kv.AttributeKey) ResponseEntity(org.springframework.http.ResponseEntity) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser)

Example 19 with ThingsboardException

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

the class TenantProfileController method setDefaultTenantProfile.

@ApiOperation(value = "Make tenant profile default (setDefaultTenantProfile)", notes = "Makes specified tenant profile to be default. Referencing non-existing tenant profile Id will cause an error. " + SYSTEM_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('SYS_ADMIN')")
@RequestMapping(value = "/tenantProfile/{tenantProfileId}/default", method = RequestMethod.POST)
@ResponseBody
public TenantProfile setDefaultTenantProfile(@ApiParam(value = TENANT_PROFILE_ID_PARAM_DESCRIPTION) @PathVariable("tenantProfileId") String strTenantProfileId) throws ThingsboardException {
    checkParameter("tenantProfileId", strTenantProfileId);
    try {
        TenantProfileId tenantProfileId = new TenantProfileId(toUUID(strTenantProfileId));
        TenantProfile tenantProfile = checkTenantProfileId(tenantProfileId, Operation.WRITE);
        tenantProfileService.setDefaultTenantProfile(getTenantId(), tenantProfileId);
        return tenantProfile;
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : TenantProfileId(org.thingsboard.server.common.data.id.TenantProfileId) TenantProfile(org.thingsboard.server.common.data.TenantProfile) 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 20 with ThingsboardException

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

the class UserController method saveUser.

@ApiOperation(value = "Save Or update User (saveUser)", notes = "Create or update the User. When creating user, platform generates User Id as " + UUID_WIKI_LINK + "The newly created User Id will be present in the response. " + "Specify existing User Id to update the device. " + "Referencing non-existing User Id will cause 'Not Found' error." + "\n\nDevice email is unique for entire platform setup.")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/user", method = RequestMethod.POST)
@ResponseBody
public User saveUser(@ApiParam(value = "A JSON value representing the User.", required = true) @RequestBody User user, @ApiParam(value = "Send activation email (or use activation link)", defaultValue = "true") @RequestParam(required = false, defaultValue = "true") boolean sendActivationMail, HttpServletRequest request) throws ThingsboardException {
    try {
        if (Authority.TENANT_ADMIN.equals(getCurrentUser().getAuthority())) {
            user.setTenantId(getCurrentUser().getTenantId());
        }
        checkEntity(user.getId(), user, Resource.USER);
        boolean sendEmail = user.getId() == null && sendActivationMail;
        User savedUser = checkNotNull(userService.saveUser(user));
        if (sendEmail) {
            SecurityUser authUser = getCurrentUser();
            UserCredentials userCredentials = userService.findUserCredentialsByUserId(authUser.getTenantId(), savedUser.getId());
            String baseUrl = systemSecurityService.getBaseUrl(getTenantId(), getCurrentUser().getCustomerId(), request);
            String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl, userCredentials.getActivateToken());
            String email = savedUser.getEmail();
            try {
                mailService.sendActivationEmail(activateUrl, email);
            } catch (ThingsboardException e) {
                userService.deleteUser(authUser.getTenantId(), savedUser.getId());
                throw e;
            }
        }
        logEntityAction(savedUser.getId(), savedUser, savedUser.getCustomerId(), user.getId() == null ? ActionType.ADDED : ActionType.UPDATED, null);
        sendEntityNotificationMsg(getTenantId(), savedUser.getId(), user.getId() == null ? EdgeEventActionType.ADDED : EdgeEventActionType.UPDATED);
        return savedUser;
    } catch (Exception e) {
        logEntityAction(emptyId(EntityType.USER), user, null, user.getId() == null ? ActionType.ADDED : ActionType.UPDATED, e);
        throw handleException(e);
    }
}
Also used : SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) User(org.thingsboard.server.common.data.User) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) UserCredentials(org.thingsboard.server.common.data.security.UserCredentials) 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)

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