Search in sources :

Example 1 with ServerErrorException

use of com.infiniteautomation.mango.rest.latest.exception.ServerErrorException in project ma-modules-public by infiniteautomation.

the class PointValueRestController method putPointValue.

/**
 * Update a point value in the system
 */
@ApiOperation(value = "Update an existing data point's value", notes = "Data point must exist and be enabled")
@RequestMapping(method = RequestMethod.PUT, value = "/{xid}")
public ResponseEntity<LegacyPointValueTimeModel> putPointValue(@RequestBody() LegacyPointValueTimeModel model, @PathVariable String xid, @ApiParam(value = "Return converted value using displayed unit", defaultValue = "false") @RequestParam(required = false, defaultValue = "false") boolean unitConversion, @AuthenticationPrincipal PermissionHolder user, UriComponentsBuilder builder) {
    DataPointVO vo = this.dataPointService.get(xid);
    this.dataPointService.ensureSetPermission(user, vo);
    // Set the time to now if it is not present
    if (model.getTimestamp() == 0) {
        model.setTimestamp(Common.timer.currentTimeMillis());
    }
    // Validate the model's data type for compatibility
    if (model.getDataType() != vo.getPointLocator().getDataType()) {
        throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("event.ds.dataType"));
    }
    // Validate the timestamp for future dated
    if (model.getTimestamp() > Common.timer.currentTimeMillis() + SystemSettingsDao.getInstance().getFutureDateLimit()) {
        throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "Future dated points not acceptable."));
    }
    // Are we converting from the rendered Unit?
    if (unitConversion) {
        if ((model.getDataType() == DataType.NUMERIC) && (model.getValue() instanceof Number)) {
            double value;
            if (model.getValue() instanceof Integer) {
                value = ((Integer) model.getValue());
            } else {
                value = ((Double) model.getValue());
            }
            model.setValue(vo.getRenderedUnit().getConverterTo(vo.getUnit()).convert(value));
        } else {
            throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]Cannot perform unit conversion on Non Numeric data types."));
        }
    }
    // to convert it
    if ((model.getDataType() == DataType.MULTISTATE || model.getDataType() == DataType.NUMERIC) && (model.getValue() instanceof String)) {
        try {
            DataValue value = vo.getTextRenderer().parseText((String) model.getValue(), vo.getPointLocator().getDataType());
            model.setValue(value.getObjectValue());
        } catch (Exception e) {
            // Lots can go wrong here so let the user know
            throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]Unable to convert String representation to any known value."));
        }
    }
    final PointValueTime pvt;
    try {
        DataValue dataValue;
        switch(model.getDataType()) {
            case ALPHANUMERIC:
                dataValue = new AlphanumericValue((String) model.getValue());
                break;
            case BINARY:
                dataValue = new BinaryValue((Boolean) model.getValue());
                break;
            case MULTISTATE:
                dataValue = new MultistateValue(((Number) model.getValue()).intValue());
                break;
            case NUMERIC:
                dataValue = new NumericValue(((Number) model.getValue()).doubleValue());
                break;
            default:
                throw new UnsupportedOperationException("Setting image values not supported");
        }
        if (model.getAnnotation() != null)
            pvt = new AnnotatedPointValueTime(dataValue, model.getTimestamp(), new TranslatableMessage("common.default", model.getAnnotation()));
        else
            pvt = new PointValueTime(dataValue, model.getTimestamp());
    } catch (Exception e) {
        throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]Invalid Format"));
    }
    // one last check to ensure we are inserting the correct data type
    if (pvt.getValue().getDataType() != vo.getPointLocator().getDataType()) {
        throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("event.ds.dataType"));
    }
    final int dataSourceId = vo.getDataSourceId();
    SetPointSource source = null;
    if (model.getAnnotation() != null) {
        source = new SetPointSource() {

            @Override
            public String getSetPointSourceType() {
                return "REST";
            }

            @Override
            public int getSetPointSourceId() {
                return dataSourceId;
            }

            @Override
            public TranslatableMessage getSetPointSourceMessage() {
                return ((AnnotatedPointValueTime) pvt).getSourceMessage();
            }

            @Override
            public void raiseRecursionFailureEvent() {
                log.error("Recursive failure while setting point via REST");
            }
        };
    }
    try {
        Common.runtimeManager.setDataPointValue(vo.getId(), pvt, source);
        // This URI may not always be accurate if the Data Source doesn't use the
        // provided time...
        URI location = builder.path("/point-values/{xid}/{time}").buildAndExpand(xid, pvt.getTime()).toUri();
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(location);
        return new ResponseEntity<>(model, headers, HttpStatus.CREATED);
    } catch (RTException e) {
        // Ok its probably not enabled or settable
        throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]" + e.getMessage()));
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new ServerErrorException(e);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) DataValue(com.serotonin.m2m2.rt.dataImage.types.DataValue) URI(java.net.URI) AnnotatedPointValueTime(com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) BinaryValue(com.serotonin.m2m2.rt.dataImage.types.BinaryValue) SetPointSource(com.serotonin.m2m2.rt.dataImage.SetPointSource) BadRequestException(com.infiniteautomation.mango.rest.latest.exception.BadRequestException) GenericRestException(com.infiniteautomation.mango.rest.latest.exception.GenericRestException) NotFoundRestException(com.infiniteautomation.mango.rest.latest.exception.NotFoundRestException) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) ServerErrorException(com.infiniteautomation.mango.rest.latest.exception.ServerErrorException) RTException(com.serotonin.m2m2.rt.RTException) AbstractRestException(com.infiniteautomation.mango.rest.latest.exception.AbstractRestException) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) MultistateValue(com.serotonin.m2m2.rt.dataImage.types.MultistateValue) RTException(com.serotonin.m2m2.rt.RTException) ResponseEntity(org.springframework.http.ResponseEntity) AlphanumericValue(com.serotonin.m2m2.rt.dataImage.types.AlphanumericValue) AnnotatedPointValueTime(com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime) ServerErrorException(com.infiniteautomation.mango.rest.latest.exception.ServerErrorException) NumericValue(com.serotonin.m2m2.rt.dataImage.types.NumericValue) GenericRestException(com.infiniteautomation.mango.rest.latest.exception.GenericRestException) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with ServerErrorException

use of com.infiniteautomation.mango.rest.latest.exception.ServerErrorException in project ma-modules-public by infiniteautomation.

the class MangoTaskTemporaryResourceManager method scheduleTask.

private void scheduleTask(TemporaryResource<T, AbstractRestException> resource) {
    TaskData tasks = (TaskData) resource.getData();
    // high priority task will start with user that calls this method in the SecurityContext
    tasks.mainTask = new HighPriorityTask("Temporary resource " + resource.getResourceType() + " " + resource.getId()) {

        @Override
        public void run(long runtime) {
            try {
                resource.runTask();
            } catch (Exception e) {
                AbstractRestException error = MangoTaskTemporaryResourceManager.this.mapException(e);
                resource.safeError(error);
            }
        }

        @Override
        public void rejected(RejectedTaskReason reason) {
            super.rejected(reason);
            TranslatableMessage msg = null;
            switch(reason.getCode()) {
                case RejectedTaskReason.POOL_FULL:
                    msg = new TranslatableMessage("rest.error.rejectedTaskPoolFull");
                    break;
                case RejectedTaskReason.TASK_QUEUE_FULL:
                    msg = new TranslatableMessage("rest.error.rejectedTaskQueueFull");
                    break;
                case RejectedTaskReason.CURRENTLY_RUNNING:
                    msg = new TranslatableMessage("rest.error.rejectedTaskAlreadyRunning");
                    break;
            }
            ServerErrorException ex = msg == null ? new ServerErrorException() : new ServerErrorException(msg);
            AbstractRestException error = MangoTaskTemporaryResourceManager.this.mapException(ex);
            resource.safeError(error);
        }
    };
    Common.backgroundProcessing.execute(tasks.mainTask);
    this.scheduleTimeout(resource);
}
Also used : HighPriorityTask(com.serotonin.m2m2.util.timeout.HighPriorityTask) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ServerErrorException(com.infiniteautomation.mango.rest.latest.exception.ServerErrorException) AbstractRestException(com.infiniteautomation.mango.rest.latest.exception.AbstractRestException) StatusUpdateException(com.infiniteautomation.mango.rest.latest.temporaryResource.TemporaryResource.StatusUpdateException) ServerErrorException(com.infiniteautomation.mango.rest.latest.exception.ServerErrorException) AbstractRestException(com.infiniteautomation.mango.rest.latest.exception.AbstractRestException) RejectedTaskReason(com.serotonin.timer.RejectedTaskReason)

Example 3 with ServerErrorException

use of com.infiniteautomation.mango.rest.latest.exception.ServerErrorException in project ma-modules-public by infiniteautomation.

the class WatchListService method getPointEvents.

/**
 */
public void getPointEvents(WatchListVO vo, Integer limit, Integer offset, Consumer<EventInstanceVO> callback) {
    PermissionHolder user = Common.getUser();
    List<Object> args = new ArrayList<>();
    args.add("typeRef1");
    switch(vo.getType()) {
        case STATIC:
            this.dao.getPoints(vo.getId(), (dp) -> {
                if (dataPointService.hasReadPermission(user, dp)) {
                    args.add(Integer.toString(dp.getId()));
                }
            });
            break;
        case QUERY:
            if (vo.getParams().size() > 0)
                throw new ServerErrorException(new TranslatableMessage("watchList.queryParametersNotSupported"));
            ASTNode conditions = RQLUtils.parseRQLtoAST(vo.getQuery());
            dataPointService.customizedQuery(conditions, (dp) -> {
                if (dataPointService.hasReadPermission(user, dp)) {
                    args.add(Integer.toString(dp.getId()));
                }
            });
            break;
        case TAGS:
            throw new ServerErrorException(new TranslatableMessage("watchList.queryParametersNotSupported"));
        default:
            throw new ServerErrorException(new TranslatableMessage("common.default", "unknown watchlist type: " + vo.getType()));
    }
    // Create Event Query for these Points
    if (args.size() > 1) {
        ASTNode query = new ASTNode("in", args);
        if (user.getUser() != null) {
            query = addAndRestriction(query, new ASTNode("eq", "userId", user.getUser().getId()));
        }
        query = addAndRestriction(query, new ASTNode("eq", "typeName", EventTypeNames.DATA_POINT));
        if (limit != null) {
            if (offset == null) {
                offset = 0;
            }
            query = addAndRestriction(query, new ASTNode("limit", limit, offset));
        }
        eventService.customizedQuery(query, (event) -> {
            if (eventService.hasReadPermission(user, event)) {
                callback.accept(event);
            }
        });
    }
}
Also used : ArrayList(java.util.ArrayList) ASTNode(net.jazdw.rql.parser.ASTNode) ServerErrorException(com.infiniteautomation.mango.rest.latest.exception.ServerErrorException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder)

Example 4 with ServerErrorException

use of com.infiniteautomation.mango.rest.latest.exception.ServerErrorException in project ma-modules-public by infiniteautomation.

the class WatchListService method getDataPoints.

/**
 * Get the full data points for a list (TAG_TYPE not supported)
 */
public void getDataPoints(WatchListVO vo, Consumer<DataPointVO> callback) {
    PermissionHolder user = Common.getUser();
    switch(vo.getType()) {
        case STATIC:
            this.dao.getPoints(vo.getId(), (dp) -> {
                if (dataPointService.hasReadPermission(user, dp)) {
                    callback.accept(dp);
                }
            });
            break;
        case QUERY:
            if (vo.getParams().size() > 0)
                throw new ServerErrorException(new TranslatableMessage("watchList.queryParametersNotSupported"));
            ASTNode rql = RQLUtils.parseRQLtoAST(vo.getQuery());
            ConditionSortLimit conditions = dataPointService.rqlToCondition(rql, null, null, null);
            dataPointService.customizedQuery(conditions, callback);
            break;
        case TAGS:
            throw new ServerErrorException(new TranslatableMessage("watchList.queryParametersNotSupported"));
        default:
            throw new ServerErrorException(new TranslatableMessage("common.default", "unknown watchlist type: " + vo.getType()));
    }
}
Also used : ASTNode(net.jazdw.rql.parser.ASTNode) ServerErrorException(com.infiniteautomation.mango.rest.latest.exception.ServerErrorException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder) ConditionSortLimit(com.infiniteautomation.mango.db.query.ConditionSortLimit)

Example 5 with ServerErrorException

use of com.infiniteautomation.mango.rest.latest.exception.ServerErrorException in project ma-modules-public by infiniteautomation.

the class VirtualSerialPortConfigDeserializer method deserialize.

@Override
public VirtualSerialPortConfig deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    JsonNode tree = jp.readValueAsTree();
    String typeName = tree.get("portType").asText();
    Class<?> clazz;
    switch(typeName) {
        case "SERIAL_SOCKET_BRIDGE":
            clazz = SerialSocketBridgeConfig.class;
            break;
        case "SERIAL_SERVER_SOCKET_BRIDGE":
            clazz = SerialServerSocketBridgeConfig.class;
            break;
        default:
            throw new ServerErrorException(new TranslatableMessage("rest.missingModelMapping", VirtualSerialPortConfig.class.getSimpleName(), typeName));
    }
    VirtualSerialPortConfig model = (VirtualSerialPortConfig) mapper.treeToValue(tree, clazz);
    return model;
}
Also used : JsonNode(com.fasterxml.jackson.databind.JsonNode) ServerErrorException(com.infiniteautomation.mango.rest.latest.exception.ServerErrorException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) VirtualSerialPortConfig(com.infiniteautomation.mango.io.serial.virtual.VirtualSerialPortConfig) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

ServerErrorException (com.infiniteautomation.mango.rest.latest.exception.ServerErrorException)10 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)10 ApiOperation (io.swagger.annotations.ApiOperation)3 ArrayList (java.util.ArrayList)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 AbstractRestException (com.infiniteautomation.mango.rest.latest.exception.AbstractRestException)2 BadRequestException (com.infiniteautomation.mango.rest.latest.exception.BadRequestException)2 PermissionHolder (com.serotonin.m2m2.vo.permission.PermissionHolder)2 ASTNode (net.jazdw.rql.parser.ASTNode)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ConditionSortLimit (com.infiniteautomation.mango.db.query.ConditionSortLimit)1 VirtualSerialPortConfig (com.infiniteautomation.mango.io.serial.virtual.VirtualSerialPortConfig)1 GenericRestException (com.infiniteautomation.mango.rest.latest.exception.GenericRestException)1 NotFoundRestException (com.infiniteautomation.mango.rest.latest.exception.NotFoundRestException)1 ValidationFailedRestException (com.infiniteautomation.mango.rest.latest.exception.ValidationFailedRestException)1 CoreModuleModel (com.infiniteautomation.mango.rest.latest.model.modules.CoreModuleModel)1 ModuleModel (com.infiniteautomation.mango.rest.latest.model.modules.ModuleModel)1 ModuleUpgradeModel (com.infiniteautomation.mango.rest.latest.model.modules.ModuleUpgradeModel)1 ModuleUpgradesModel (com.infiniteautomation.mango.rest.latest.model.modules.ModuleUpgradesModel)1