Search in sources :

Example 1 with PermissionHolder

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

the class ModulesRestController method listModules.

@ApiOperation(value = "List Current Installed Modules", notes = "List all installed")
@RequestMapping(method = RequestMethod.GET, value = "/list")
public List<ModuleModel> listModules(@AuthenticationPrincipal PermissionHolder user) {
    permissionService.ensureAdminRole(user);
    List<ModuleModel> models = new ArrayList<ModuleModel>();
    List<Module> modules = ModuleRegistry.getModules();
    for (Module module : modules) {
        if (module instanceof CoreModule) {
            CoreModuleModel coreModel = new CoreModuleModel(ModuleRegistry.getModule(ModuleRegistry.CORE_MODULE_NAME));
            coreModel.setGuid(Providers.get(ICoreLicense.class).getGuid());
            coreModel.setInstanceDescription(SystemSettingsDao.getInstance().getValue(SystemSettingsDao.INSTANCE_DESCRIPTION));
            coreModel.setDistributor(Common.envProps.getString("distributor"));
            coreModel.setUpgradeVersionState(SystemSettingsDao.getInstance().getIntValue(SystemSettingsDao.UPGRADE_VERSION_STATE));
            coreModel.setStoreUrl(Common.envProps.getString("store.url"));
            models.add(coreModel);
        } else {
            models.add(new ModuleModel(module));
        }
    }
    // Add the unloaded modules at the end?
    List<Module> unloaded = ModuleRegistry.getUnloadedModules();
    for (Module module : unloaded) {
        ModuleModel model = new ModuleModel(module);
        model.setUnloaded(true);
        models.add(model);
    }
    return models;
}
Also used : CoreModuleModel(com.infiniteautomation.mango.rest.latest.model.modules.CoreModuleModel) ArrayList(java.util.ArrayList) CoreModule(com.serotonin.m2m2.module.ModuleRegistry.CoreModule) Module(com.serotonin.m2m2.module.Module) CoreModule(com.serotonin.m2m2.module.ModuleRegistry.CoreModule) InvalidModule(com.infiniteautomation.mango.rest.latest.model.modules.UpgradeUploadResult.InvalidModule) ModuleModel(com.infiniteautomation.mango.rest.latest.model.modules.ModuleModel) CoreModuleModel(com.infiniteautomation.mango.rest.latest.model.modules.CoreModuleModel) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with PermissionHolder

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

the class ModulesRestController method upgrade.

@ApiOperation(value = "Download Upgrades and optionally backup and restart", notes = "Use Modules web socket to track progress")
@RequestMapping(method = RequestMethod.POST, value = "/upgrade")
public ResponseEntity<TranslatableMessage> upgrade(@ApiParam(value = "Perform Backup first", required = false, defaultValue = "false", allowMultiple = false) @RequestParam(required = false, defaultValue = "false") boolean backup, @ApiParam(value = "Restart when completed", required = false, defaultValue = "false", allowMultiple = false) @RequestParam(required = false, defaultValue = "false") boolean restart, @ApiParam(value = "Desired Upgrades", required = true) @RequestBody(required = true) ModuleUpgradesModel model, @AuthenticationPrincipal PermissionHolder user) {
    permissionService.ensureAdminRole(user);
    // Start Downloads
    String status = service.startDownloads(model.fullModulesList(), backup, restart);
    if (status == null) {
        return new ResponseEntity<>(new TranslatableMessage("rest.httpStatus.200"), HttpStatus.OK);
    } else {
        // headers are for compatibility with v1 for the UI
        HttpHeaders headers = new HttpHeaders();
        headers.add("messages", stripAndTrimHeader(status, -1));
        return new ResponseEntity<>(new TranslatableMessage("common.default", status), HttpStatus.NOT_MODIFIED);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) JsonString(com.serotonin.json.type.JsonString) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 3 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 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 4 with PermissionHolder

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

the class EventDetectorsRestController method update.

@ApiOperation(value = "Update an Event Detector", notes = "User must have data source edit permission for source of the point", response = AbstractEventDetectorModel.class)
@RequestMapping(method = RequestMethod.PUT, value = "/{xid}")
public ResponseEntity<AbstractEventDetectorModel<?>> update(@ApiParam(value = "XID of Event Handler to update", required = true, allowMultiple = false) @PathVariable String xid, @ApiParam(value = "Event Handler of update", required = true, allowMultiple = false) @RequestBody AbstractEventDetectorModel<? extends AbstractEventDetectorVO> model, @ApiParam(value = "Restart the source to load in the changes", required = false, defaultValue = "true", allowMultiple = false) @RequestParam(required = false, defaultValue = "true") boolean restart, @AuthenticationPrincipal PermissionHolder user, UriComponentsBuilder builder) {
    AbstractEventDetectorVO vo = service.updateAndReload(xid, model.toVO(), restart);
    URI location = builder.path("/event-detectors/{xid}").buildAndExpand(vo.getXid()).toUri();
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(location);
    return new ResponseEntity<>(map.apply(vo, user), headers, HttpStatus.OK);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) AbstractEventDetectorVO(com.serotonin.m2m2.vo.event.detector.AbstractEventDetectorVO) URI(java.net.URI) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with PermissionHolder

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

the class EventDetectorsRestController method getState.

@ApiOperation(value = "Get Event Detector's internal state", notes = "User must have read permission for the data point", response = AbstractEventDetectorRTModel.class)
@RequestMapping(method = RequestMethod.GET, value = "/runtime/{xid}")
public AbstractEventDetectorRTModel<?> getState(@ApiParam(value = "ID of Event detector", required = true, allowMultiple = false) @PathVariable String xid, @AuthenticationPrincipal PermissionHolder user, UriComponentsBuilder builder) {
    AbstractEventDetectorVO vo = service.get(xid);
    // For now all detectors are data point type
    DataPointRT rt = Common.runtimeManager.getDataPoint(vo.getSourceId());
    if (rt == null) {
        throw new TranslatableIllegalStateException(new TranslatableMessage("rest.error.pointNotEnabled", xid));
    }
    for (PointEventDetectorRT<?> edrt : rt.getEventDetectors()) {
        if (edrt.getVO().getId() == vo.getId()) {
            return modelMapper.map(edrt, AbstractEventDetectorRTModel.class, user);
        }
    }
    throw new NotFoundRestException();
}
Also used : NotFoundRestException(com.infiniteautomation.mango.rest.latest.exception.NotFoundRestException) AbstractEventDetectorVO(com.serotonin.m2m2.vo.event.detector.AbstractEventDetectorVO) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) TranslatableIllegalStateException(com.infiniteautomation.mango.util.exception.TranslatableIllegalStateException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

PermissionHolder (com.serotonin.m2m2.vo.permission.PermissionHolder)120 ApiOperation (io.swagger.annotations.ApiOperation)97 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)97 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)64 ResponseEntity (org.springframework.http.ResponseEntity)53 HttpHeaders (org.springframework.http.HttpHeaders)50 URI (java.net.URI)48 ArrayList (java.util.ArrayList)37 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)34 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)29 List (java.util.List)27 User (com.serotonin.m2m2.vo.User)25 NotFoundException (com.infiniteautomation.mango.util.exception.NotFoundException)24 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)24 BadRequestException (com.infiniteautomation.mango.rest.latest.exception.BadRequestException)19 HashMap (java.util.HashMap)19 ValidationException (com.infiniteautomation.mango.util.exception.ValidationException)18 Common (com.serotonin.m2m2.Common)18 Collectors (java.util.stream.Collectors)17 Role (com.serotonin.m2m2.vo.role.Role)16