Search in sources :

Example 61 with PermissionHolder

use of com.serotonin.m2m2.vo.permission.PermissionHolder in project ma-modules-public by infiniteautomation.

the class PointValueWebSocketHandler method handleTextMessage.

@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
    try {
        PermissionHolder user = getUser(session);
        PointValueRegistrationModel model = this.jacksonMapper.readValue(message.getPayload(), PointValueRegistrationModel.class);
        DataPointVO vo;
        try {
            // This will check for not found and permissions
            vo = datapointService.get(model.getDataPointXid());
        } catch (NotFoundException e) {
            // send not found message back
            this.sendErrorMessage(session, MangoWebSocketErrorType.SERVER_ERROR, new TranslatableMessage("rest.error.pointNotFound", model.getDataPointXid()));
            return;
        } catch (PermissionException e) {
            // Send permission denied message here
            this.sendErrorMessage(session, MangoWebSocketErrorType.PERMISSION_DENIED, new TranslatableMessage("permission.exception.readDataPoint", user.getPermissionHolderName()));
            return;
        }
        Set<PointValueEventType> eventsTypes = model.getEventTypes();
        int dataPointId = vo.getId();
        synchronized (pointIdToListenerMap) {
            if (this.connectionClosed) {
                return;
            }
            PointValueWebSocketListener publisher = pointIdToListenerMap.get(dataPointId);
            if (publisher != null) {
                if (eventsTypes.isEmpty()) {
                    publisher.terminate();
                    pointIdToListenerMap.remove(dataPointId);
                } else {
                    publisher.setEventTypes(eventsTypes);
                }
            } else if (!eventsTypes.isEmpty()) {
                publisher = new PointValueWebSocketListener(vo, eventsTypes);
                publisher.initialize();
                // Immediately send the most recent Point Value and the status of the data point
                publisher.sendPointStatus();
                pointIdToListenerMap.put(dataPointId, publisher);
            }
        }
    } catch (WebSocketSendException e) {
        log.warn("Error sending websocket message", e);
    } catch (Exception e) {
        try {
            this.sendErrorMessage(session, MangoWebSocketErrorType.SERVER_ERROR, new TranslatableMessage("rest.error.serverError", e.getMessage()));
        } catch (Exception e1) {
            log.error("An error occurred", e);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(message.getPayload());
    }
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) WebSocketSendException(com.infiniteautomation.mango.rest.latest.websocket.WebSocketSendException) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) WebSocketSendException(com.infiniteautomation.mango.rest.latest.websocket.WebSocketSendException)

Example 62 with PermissionHolder

use of com.serotonin.m2m2.vo.permission.PermissionHolder in project ma-modules-public by infiniteautomation.

the class PointValueRestController method deletePointValues.

@ApiOperation(value = "Delete point values >= from  and < to", notes = "The user must have set permission to the data point. If date is not supplied it defaults to now.")
@RequestMapping(method = RequestMethod.DELETE, value = "/{xid}")
public ResponseEntity<Long> deletePointValues(@ApiParam(value = "Point xids", required = true) @PathVariable String xid, @ApiParam(value = "From time") @RequestParam(value = "from", required = false) @DateTimeFormat(iso = ISO.DATE_TIME) ZonedDateTime from, @ApiParam(value = "To time") @RequestParam(value = "to", required = false) @DateTimeFormat(iso = ISO.DATE_TIME) ZonedDateTime to, @ApiParam(value = "Time zone") @RequestParam(value = "timezone", required = false) String timezone, @AuthenticationPrincipal PermissionHolder user) {
    DataPointVO vo = dataPointService.get(xid);
    dataPointService.ensureSetPermission(user, vo);
    ZoneId zoneId;
    if (timezone == null) {
        if (from != null) {
            zoneId = from.getZone();
        } else if (to != null)
            zoneId = to.getZone();
        else
            zoneId = TimeZone.getDefault().toZoneId();
    } else {
        zoneId = ZoneId.of(timezone);
    }
    // Set the timezone on the from and to dates
    long current = Common.timer.currentTimeMillis();
    if (from != null)
        from = from.withZoneSameInstant(zoneId);
    else
        from = ZonedDateTime.ofInstant(Instant.ofEpochMilli(current), zoneId);
    if (to != null)
        to = to.withZoneSameInstant(zoneId);
    else
        to = ZonedDateTime.ofInstant(Instant.ofEpochMilli(current), zoneId);
    Optional<Long> result = Common.runtimeManager.purgeDataPointValuesBetween(vo, from.toInstant().toEpochMilli(), to.toInstant().toEpochMilli());
    return ResponseEntity.ok().body(result.orElse(null));
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) ZoneId(java.time.ZoneId) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 63 with PermissionHolder

use of com.serotonin.m2m2.vo.permission.PermissionHolder 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 convertedValue = ((Number) model.getValue()).doubleValue();
            UnitConverter inverseConverter = vo.getRenderedUnitConverter().inverse();
            double rawValue = inverseConverter.convert(convertedValue);
            model.setValue(rawValue);
        } 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) UnitConverter(javax.measure.converter.UnitConverter) AnnotatedPointValueTime(com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) IdPointValueTime(com.serotonin.m2m2.rt.dataImage.IdPointValueTime) 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) RTException(com.serotonin.m2m2.rt.RTException) 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) 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 64 with PermissionHolder

use of com.serotonin.m2m2.vo.permission.PermissionHolder in project ma-modules-public by infiniteautomation.

the class PublishedPointsRestController method bulkPublishedPointOperation.

@ApiOperation(value = "Bulk get/create/update/delete published points", notes = "User be superadmin")
@RequestMapping(method = RequestMethod.POST, value = "/bulk")
public ResponseEntity<TemporaryResource<PublishedPointBulkResponse, AbstractRestException>> bulkPublishedPointOperation(@RequestBody PublishedPointBulkRequest requestBody, UriComponentsBuilder builder) {
    VoAction defaultAction = requestBody.getAction();
    AbstractPublishedPointModel<?> defaultBody = requestBody.getBody();
    List<PublishedPointIndividualRequest> requests = requestBody.getRequests();
    if (requests == null) {
        throw new BadRequestException(new TranslatableMessage("rest.error.mustNotBeNull", "requests"));
    } else if (requests.isEmpty()) {
        throw new BadRequestException(new TranslatableMessage("rest.error.cantBeEmpty", "requests"));
    }
    String resourceId = requestBody.getId();
    Long expiration = requestBody.getExpiration();
    Long timeout = requestBody.getTimeout();
    TemporaryResource<PublishedPointBulkResponse, AbstractRestException> responseBody = resourceManager.newTemporaryResource(RESOURCE_TYPE_BULK_PUBLISHED_POINT, resourceId, expiration, timeout, (resource) -> {
        PublishedPointBulkResponse bulkResponse = new PublishedPointBulkResponse();
        int i = 0;
        resource.progressOrSuccess(bulkResponse, i++, requests.size());
        PermissionHolder resourceUser = Common.getUser();
        for (PublishedPointIndividualRequest request : requests) {
            UriComponentsBuilder reqBuilder = UriComponentsBuilder.newInstance();
            PublishedPointIndividualResponse individualResponse = doIndividualRequest(request, defaultAction, defaultBody, resourceUser, reqBuilder);
            bulkResponse.addResponse(individualResponse);
            resource.progressOrSuccess(bulkResponse, i++, requests.size());
        }
        return null;
    });
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(builder.path("/published-points/bulk/{id}").buildAndExpand(responseBody.getId()).toUri());
    return new ResponseEntity<>(responseBody, headers, HttpStatus.CREATED);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) VoAction(com.infiniteautomation.mango.rest.latest.bulk.VoAction) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder) ResponseEntity(org.springframework.http.ResponseEntity) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) BadRequestException(com.infiniteautomation.mango.rest.latest.exception.BadRequestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) AbstractRestException(com.infiniteautomation.mango.rest.latest.exception.AbstractRestException) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 65 with PermissionHolder

use of com.serotonin.m2m2.vo.permission.PermissionHolder in project ma-modules-public by infiniteautomation.

the class PublishedPointsRestController method exportPublishedPoint.

@ApiOperation(value = "Export formatted for Configuration Import")
@RequestMapping(method = RequestMethod.GET, value = "/export/{xid}", produces = MediaTypes.SEROTONIN_JSON_VALUE)
public Map<String, Object> exportPublishedPoint(@ApiParam(value = "Valid published point XID", required = true) @PathVariable String xid, @AuthenticationPrincipal PermissionHolder user) {
    PublishedPointVO vo = service.get(xid);
    Map<String, Object> export = new LinkedHashMap<>();
    export.put("publishedPoints", Collections.singletonList(vo));
    return export;
}
Also used : PublishedPointVO(com.serotonin.m2m2.vo.publish.PublishedPointVO) LinkedHashMap(java.util.LinkedHashMap) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

PermissionHolder (com.serotonin.m2m2.vo.permission.PermissionHolder)205 ApiOperation (io.swagger.annotations.ApiOperation)98 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)98 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)86 ResponseEntity (org.springframework.http.ResponseEntity)53 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)50 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)50 ArrayList (java.util.ArrayList)50 HttpHeaders (org.springframework.http.HttpHeaders)50 URI (java.net.URI)48 List (java.util.List)43 User (com.serotonin.m2m2.vo.User)37 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)35 NotFoundException (com.infiniteautomation.mango.util.exception.NotFoundException)32 Common (com.serotonin.m2m2.Common)31 Collectors (java.util.stream.Collectors)30 Role (com.serotonin.m2m2.vo.role.Role)29 ValidationException (com.infiniteautomation.mango.util.exception.ValidationException)28 Autowired (org.springframework.beans.factory.annotation.Autowired)25 HashMap (java.util.HashMap)24