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();
}
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();
}
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);
}
}
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);
}
}
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);
}
Aggregations