Search in sources :

Example 91 with ApiOperation

use of com.wordnik.swagger.annotations.ApiOperation in project ma-modules-public by infiniteautomation.

the class EventsRestController method acknowledgeEvent.

/**
 * Update an event
 * @param vo
 * @param xid
 * @param builder
 * @param request
 * @return
 */
@ApiOperation(value = "Acknowledge an existing event", notes = "")
@RequestMapping(method = RequestMethod.PUT, consumes = { "application/json" }, produces = { "application/json" }, value = "/acknowledge/{id}")
public ResponseEntity<EventInstanceModel> acknowledgeEvent(@PathVariable Integer id, @RequestBody(required = false) TranslatableMessageModel message, UriComponentsBuilder builder, HttpServletRequest request) {
    RestProcessResult<EventInstanceModel> result = new RestProcessResult<EventInstanceModel>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        TranslatableMessage tlm = null;
        if (message != null)
            tlm = new TranslatableMessage(message.getKey(), message.getArgs().toArray());
        EventInstance event = EventDao.instance.get(id);
        if (event == null) {
            result.addRestMessage(getDoesNotExistMessage());
            return result.createResponseEntity();
        } else if (!Permissions.hasEventTypePermission(user, event.getEventType())) {
            result.addRestMessage(getUnauthorizedMessage());
            return result.createResponseEntity();
        }
        Common.eventManager.acknowledgeEventById(id, System.currentTimeMillis(), user, tlm);
        // if event has a different ack timestamp, user or message it was already acked, we could return a different message
        EventInstanceModel model = new EventInstanceModel(event);
        // Put a link to the updated data in the header?
        URI location = builder.path("/v1/events/{id}").buildAndExpand(id).toUri();
        result.addRestMessage(getResourceUpdatedMessage(location));
        return result.createResponseEntity(model);
    }
    // Not logged in
    return result.createResponseEntity();
}
Also used : EventInstanceModel(com.serotonin.m2m2.web.mvc.rest.v1.model.events.EventInstanceModel) EventInstance(com.serotonin.m2m2.rt.event.EventInstance) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) User(com.serotonin.m2m2.vo.User) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) URI(java.net.URI) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 92 with ApiOperation

use of com.wordnik.swagger.annotations.ApiOperation 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 93 with ApiOperation

use of com.wordnik.swagger.annotations.ApiOperation 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 94 with ApiOperation

use of com.wordnik.swagger.annotations.ApiOperation 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 95 with ApiOperation

use of com.wordnik.swagger.annotations.ApiOperation 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)

Aggregations

ApiOperation (com.wordnik.swagger.annotations.ApiOperation)274 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)212 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)125 User (com.serotonin.m2m2.vo.User)115 URI (java.net.URI)59 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)54 ArrayList (java.util.ArrayList)50 Produces (javax.ws.rs.Produces)49 ResponseEntity (org.springframework.http.ResponseEntity)44 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)42 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)41 Path (javax.ws.rs.Path)40 Response (javax.ws.rs.core.Response)38 ApiResponses (com.wordnik.swagger.annotations.ApiResponses)36 DefaultValue (javax.ws.rs.DefaultValue)35 HeaderParam (javax.ws.rs.HeaderParam)35 ListResponse (org.gluu.oxtrust.model.scim2.ListResponse)34 ASTNode (net.jazdw.rql.parser.ASTNode)31 List (java.util.List)29 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)25