Search in sources :

Example 36 with TranslatableMessage

use of com.serotonin.m2m2.i18n.TranslatableMessage in project ma-modules-public by infiniteautomation.

the class HelpRestController method getHelp.

@ApiOperation(value = "Get Help", notes = "request help via the internal Mango help id", response = HelpModel.class, responseContainer = "Array")
@RequestMapping(method = RequestMethod.GET, produces = { "application/json" }, value = "/by-id/{helpId}")
public ResponseEntity<HelpModel> getHelp(@PathVariable String helpId, HttpServletRequest request) {
    RestProcessResult<HelpModel> result = new RestProcessResult<HelpModel>(HttpStatus.OK);
    this.checkUser(request, result);
    if (result.isOk()) {
        HelpModel model = new HelpModel();
        DocumentationItem item = Common.documentationManifest.getItem(helpId);
        if (item == null) {
            result.addRestMessage(this.getDoesNotExistMessage());
        } else {
            model.setId(item.getId());
            model.setTitle(new TranslatableMessage(item.getKey()).translate(Common.getTranslations()));
            // Find the file appropriate for the locale.
            Locale locale = ControllerUtils.getLocale(request);
            File file = Common.documentationManifest.getDocumentationFile(item, locale.getLanguage(), locale.getCountry(), locale.getVariant());
            // Read the content.
            try {
                Reader in = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"));
                StringWriter out = new StringWriter();
                StreamUtils.transfer(in, out);
                in.close();
                model.setContent(out.toString());
                List<RelatedHelpItemModel> relatedItems = new ArrayList<RelatedHelpItemModel>();
                for (String relatedId : item.getRelated()) {
                    DocumentationItem relatedItem = Common.documentationManifest.getItem(relatedId);
                    if (relatedItem == null)
                        throw new RuntimeException("Related document '" + relatedId + "' not found");
                    relatedItems.add(new RelatedHelpItemModel(relatedItem.getId(), new TranslatableMessage(relatedItem.getKey()).translate(Common.getTranslations())));
                }
                model.setRelatedList(relatedItems);
                return result.createResponseEntity(model);
            } catch (FileNotFoundException e) {
                result.addRestMessage(HttpStatus.NOT_FOUND, new TranslatableMessage("dox.fileNotFound", file.getPath()));
            } catch (IOException e) {
                result.addRestMessage(HttpStatus.NOT_FOUND, new TranslatableMessage("dox.readError", e.getClass().getName(), e.getMessage()));
            }
        }
    }
    return result.createResponseEntity();
}
Also used : Locale(java.util.Locale) InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) RelatedHelpItemModel(com.serotonin.m2m2.web.mvc.rest.v1.model.help.RelatedHelpItemModel) IOException(java.io.IOException) DocumentationItem(com.serotonin.m2m2.util.DocumentationItem) HelpModel(com.serotonin.m2m2.web.mvc.rest.v1.model.help.HelpModel) FileInputStream(java.io.FileInputStream) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) StringWriter(java.io.StringWriter) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) File(java.io.File) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 37 with TranslatableMessage

use of com.serotonin.m2m2.i18n.TranslatableMessage in project ma-modules-public by infiniteautomation.

the class ScriptUtilRestController method testScript.

@PreAuthorize("isAdmin()")
@ApiOperation(value = "Test a script")
@ApiResponses({ @ApiResponse(code = 401, message = "Unauthorized user access", response = ResponseEntity.class), @ApiResponse(code = 500, message = "Error processing request", response = ResponseEntity.class) })
@RequestMapping(method = RequestMethod.POST, value = { "/test" }, consumes = { "application/json" }, produces = { "application/json" })
public ResponseEntity<ScriptRestResult> testScript(@AuthenticationPrincipal User user, @RequestBody ScriptRestModel scriptModel) {
    if (LOG.isDebugEnabled())
        LOG.debug("Testing script for: " + user.getName());
    Map<String, IDataPointValueSource> context = convertContextModel(scriptModel.getContext(), true);
    try {
        CompiledScript script = CompiledScriptExecutor.compile(scriptModel.getScript());
        final StringWriter scriptOut = new StringWriter();
        final PrintWriter scriptWriter = new PrintWriter(scriptOut);
        int logLevel = ScriptLog.LogLevel.FATAL;
        if (StringUtils.isEmpty(scriptModel.getLogLevel())) {
            int levelId = ScriptLog.LOG_LEVEL_CODES.getId(scriptModel.getLogLevel());
            if (levelId == -1)
                throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, new TranslatableMessage("rest.script.error.unknownLogLevel", scriptModel.getLogLevel()));
            else
                logLevel = levelId;
        }
        ScriptLog scriptLog = new ScriptLog(scriptWriter, logLevel);
        final ScriptPermissions permissions = scriptModel.getPermissions().toPermissions();
        final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYY HH:mm:ss");
        ScriptPointValueSetter loggingSetter = new ScriptPointValueSetter(permissions) {

            @Override
            public void set(IDataPointValueSource point, Object value, long timestamp, String annotation) {
                DataPointRT dprt = (DataPointRT) point;
                if (!dprt.getVO().getPointLocator().isSettable()) {
                    scriptOut.append("Point " + dprt.getVO().getExtendedName() + " not settable.");
                    return;
                }
                if (!Permissions.hasPermission(dprt.getVO().getSetPermission(), permissions.getDataPointSetPermissions())) {
                    scriptOut.write(new TranslatableMessage("pointLinks.setTest.permissionDenied", dprt.getVO().getXid()).translate(Common.getTranslations()));
                    return;
                }
                scriptOut.append("Setting point " + dprt.getVO().getName() + " to " + value + " @" + sdf.format(new Date(timestamp)) + "\r\n");
            }

            @Override
            protected void setImpl(IDataPointValueSource point, Object value, long timestamp, String annotation) {
            // not really setting
            }
        };
        try {
            PointValueTime pvt = CompiledScriptExecutor.execute(script, context, new HashMap<String, Object>(), Common.timer.currentTimeMillis(), DataTypes.ALPHANUMERIC, Common.timer.currentTimeMillis(), permissions, scriptWriter, scriptLog, loggingSetter, null, true);
            if (LOG.isDebugEnabled())
                LOG.debug("Script output: " + scriptOut.toString());
            return new ResponseEntity<>(new ScriptRestResult(scriptOut.toString(), new PointValueTimeModel(pvt)), HttpStatus.OK);
        } catch (ResultTypeException e) {
            throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
        }
    } catch (ScriptException e) {
        throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
}
Also used : CompiledScript(javax.script.CompiledScript) ScriptPointValueSetter(com.serotonin.m2m2.rt.script.ScriptPointValueSetter) PointValueTimeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.PointValueTimeModel) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) ScriptPermissions(com.serotonin.m2m2.rt.script.ScriptPermissions) Date(java.util.Date) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptException(javax.script.ScriptException) ResponseEntity(org.springframework.http.ResponseEntity) StringWriter(java.io.StringWriter) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) SimpleDateFormat(java.text.SimpleDateFormat) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException) PrintWriter(java.io.PrintWriter) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ApiResponses(com.wordnik.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 38 with TranslatableMessage

use of com.serotonin.m2m2.i18n.TranslatableMessage in project ma-modules-public by infiniteautomation.

the class ScriptUtilRestController method runScript.

@PreAuthorize("isAdmin()")
@ApiOperation(value = "Run a script")
@ApiResponses({ @ApiResponse(code = 401, message = "Unauthorized user access", response = ResponseEntity.class), @ApiResponse(code = 500, message = "Error processing request", response = ResponseEntity.class) })
@RequestMapping(method = RequestMethod.POST, value = { "/run" }, consumes = { "application/json" }, produces = { "application/json" })
public ResponseEntity<ScriptRestResult> runScript(@AuthenticationPrincipal User user, @RequestBody ScriptRestModel scriptModel) {
    if (LOG.isDebugEnabled())
        LOG.debug("Running script for: " + user.getName());
    Map<String, IDataPointValueSource> context = convertContextModel(scriptModel.getContext(), false);
    try {
        CompiledScript script = CompiledScriptExecutor.compile(scriptModel.getScript());
        final StringWriter scriptOut = new StringWriter();
        final PrintWriter scriptWriter = new PrintWriter(scriptOut);
        int logLevel = ScriptLog.LogLevel.FATAL;
        if (StringUtils.isEmpty(scriptModel.getLogLevel())) {
            int levelId = ScriptLog.LOG_LEVEL_CODES.getId(scriptModel.getLogLevel());
            if (levelId == -1)
                throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, new TranslatableMessage("rest.script.error.unknownLogLevel", scriptModel.getLogLevel()));
            else
                logLevel = levelId;
        }
        ScriptLog scriptLog = new ScriptLog(scriptWriter, logLevel);
        ScriptPermissions permissions = scriptModel.getPermissions().toPermissions();
        try {
            PointValueTime pvt = CompiledScriptExecutor.execute(script, context, new HashMap<String, Object>(), Common.timer.currentTimeMillis(), DataTypes.ALPHANUMERIC, Common.timer.currentTimeMillis(), permissions, scriptWriter, scriptLog, new SetCallback(permissions, user), null, false);
            if (LOG.isDebugEnabled())
                LOG.debug("Script output: " + scriptOut.toString());
            return new ResponseEntity<>(new ScriptRestResult(scriptOut.toString(), new PointValueTimeModel(pvt)), HttpStatus.OK);
        } catch (ResultTypeException | ScriptPermissionsException e) {
            throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
        }
    } catch (ScriptException e) {
        throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
}
Also used : CompiledScript(javax.script.CompiledScript) PointValueTimeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.PointValueTimeModel) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) ScriptPermissions(com.serotonin.m2m2.rt.script.ScriptPermissions) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptException(javax.script.ScriptException) ResponseEntity(org.springframework.http.ResponseEntity) StringWriter(java.io.StringWriter) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException) PrintWriter(java.io.PrintWriter) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ApiResponses(com.wordnik.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 39 with TranslatableMessage

use of com.serotonin.m2m2.i18n.TranslatableMessage in project ma-modules-public by infiniteautomation.

the class DataPointRestController method updateDataPoint.

@ApiOperation(value = "Update an existing data point")
@RequestMapping(method = RequestMethod.PUT, value = "/{xid}")
public ResponseEntity<DataPointModel> updateDataPoint(@PathVariable String xid, @ApiParam(value = "Updated data point model", required = true) @RequestBody(required = true) DataPointModel model, @AuthenticationPrincipal User user, UriComponentsBuilder builder) {
    DataPointVO dataPoint = DataPointDao.instance.getByXid(xid);
    if (dataPoint == null) {
        throw new NotFoundRestException();
    }
    Permissions.ensureDataSourcePermission(user, dataPoint.getDataSourceId());
    // check if they are trying to move it to another data source
    String newDataSourceXid = model.getDataSourceXid();
    if (newDataSourceXid != null && !newDataSourceXid.isEmpty() && !newDataSourceXid.equals(dataPoint.getDataSourceXid())) {
        throw new BadRequestException(new TranslatableMessage("rest.error.pointChangeDataSource"));
    }
    DataPointPropertiesTemplateVO template = null;
    if (model.isTemplateXidWasSet()) {
        if (model.getTemplateXid() != null) {
            template = (DataPointPropertiesTemplateVO) TemplateDao.instance.getByXid(model.getTemplateXid());
            if (template == null) {
                throw new BadRequestException(new TranslatableMessage("invalidTemplateXid"));
            }
        }
    } else if (dataPoint.getTemplateId() != null) {
        template = (DataPointPropertiesTemplateVO) TemplateDao.instance.get(dataPoint.getTemplateId());
    }
    DataPointDao.instance.loadPartialRelationalData(dataPoint);
    model.copyPropertiesTo(dataPoint);
    // load the template after copying the properties, template properties override the ones in the data point
    if (template != null) {
        dataPoint.withTemplate(template);
    }
    dataPoint.ensureValid();
    // have to load any existing event detectors for the data point as we are about to replace the VO in the runtime manager
    DataPointDao.instance.setEventDetectors(dataPoint);
    Common.runtimeManager.saveDataPoint(dataPoint);
    URI location = builder.path("/v2/data-points/{xid}").buildAndExpand(xid).toUri();
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(location);
    return new ResponseEntity<>(new DataPointModel(dataPoint), headers, HttpStatus.OK);
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) HttpHeaders(org.springframework.http.HttpHeaders) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) ResponseEntity(org.springframework.http.ResponseEntity) DataPointModel(com.infiniteautomation.mango.rest.v2.model.dataPoint.DataPointModel) DataPointPropertiesTemplateVO(com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) URI(java.net.URI) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 40 with TranslatableMessage

use of com.serotonin.m2m2.i18n.TranslatableMessage in project ma-modules-public by infiniteautomation.

the class DataPointRestController method createDataPoint.

@ApiOperation(value = "Create a new data point")
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<DataPointModel> createDataPoint(@ApiParam(value = "Data point model", required = true) @RequestBody(required = true) DataPointModel model, @AuthenticationPrincipal User user, UriComponentsBuilder builder) {
    DataSourceVO<?> dataSource = DataSourceDao.instance.getByXid(model.getDataSourceXid());
    if (dataSource == null) {
        throw new BadRequestException(new TranslatableMessage("rest.error.invalidDataSourceXid"));
    }
    Permissions.ensureDataSourcePermission(user, dataSource);
    DataPointVO dataPoint = new DataPointVO(dataSource);
    model.copyPropertiesTo(dataPoint);
    if (model.getTemplateXid() != null) {
        DataPointPropertiesTemplateVO template = (DataPointPropertiesTemplateVO) TemplateDao.instance.getByXid(model.getTemplateXid());
        if (template == null) {
            throw new BadRequestException(new TranslatableMessage("rest.error.invalidTemplateXid"));
        }
        dataPoint.withTemplate(template);
    }
    dataPoint.ensureValid();
    Common.runtimeManager.saveDataPoint(dataPoint);
    URI location = builder.path("/v2/data-points/{xid}").buildAndExpand(dataPoint.getXid()).toUri();
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(location);
    return new ResponseEntity<>(new DataPointModel(dataPoint), headers, HttpStatus.CREATED);
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) DataPointModel(com.infiniteautomation.mango.rest.v2.model.dataPoint.DataPointModel) DataPointPropertiesTemplateVO(com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) URI(java.net.URI) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)180 User (com.serotonin.m2m2.vo.User)53 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)52 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)52 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)33 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)33 IOException (java.io.IOException)28 HashMap (java.util.HashMap)27 DwrPermission (com.serotonin.m2m2.web.dwr.util.DwrPermission)24 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)22 ArrayList (java.util.ArrayList)22 DataPointRT (com.serotonin.m2m2.rt.dataImage.DataPointRT)20 PointValueTime (com.serotonin.m2m2.rt.dataImage.PointValueTime)20 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)19 BadRequestException (com.infiniteautomation.mango.rest.v2.exception.BadRequestException)18 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)17 File (java.io.File)16 URI (java.net.URI)16 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)12 ResponseEntity (org.springframework.http.ResponseEntity)11