use of com.wordnik.swagger.annotations.ApiResponses in project ma-modules-public by infiniteautomation.
the class UserRestController method createNewUser.
/**
* Create a new User
* @param model
* @param request
* @return
* @throws RestValidationFailedException
*/
@ApiOperation(value = "Create New User", notes = "Cannot save existing user")
@ApiResponses({ @ApiResponse(code = 201, message = "User Created", response = UserModel.class), @ApiResponse(code = 401, message = "Unauthorized Access", response = ResponseEntity.class), @ApiResponse(code = 409, message = "User Already Exists") })
@RequestMapping(method = RequestMethod.POST, consumes = { "application/json", "text/csv" }, produces = { "application/json", "text/csv" })
public ResponseEntity<UserModel> createNewUser(@ApiParam(value = "User to save", required = true) @RequestBody(required = true) UserModel model, UriComponentsBuilder builder, HttpServletRequest request) throws RestValidationFailedException {
RestProcessResult<UserModel> result = new RestProcessResult<UserModel>(HttpStatus.CREATED);
User user = this.checkUser(request, result);
if (result.isOk()) {
User u = UserDao.instance.getUser(model.getUsername());
if (Permissions.hasAdmin(user)) {
if (u == null) {
// Create new user
model.getData().setId(Common.NEW_ID);
if (model.validate()) {
try {
User newUser = model.getData();
newUser.setPassword(Common.encrypt(model.getData().getPassword()));
UserDao.instance.saveUser(newUser);
URI location = builder.path("v1/users/{username}").buildAndExpand(model.getUsername()).toUri();
result.addRestMessage(getResourceCreatedMessage(location));
return result.createResponseEntity(model);
} catch (Exception e) {
result.addRestMessage(getInternalServerErrorMessage(e.getMessage()));
return result.createResponseEntity();
}
} else {
result.addRestMessage(this.getValidationFailedError());
return result.createResponseEntity(model);
}
} else {
model.addValidationMessage(new ProcessMessage("username", new TranslatableMessage("users.validate.usernameInUse")));
result.addRestMessage(getValidationFailedError());
return result.createResponseEntity(model);
}
} else {
LOG.warn("Non admin user: " + user.getUsername() + " attempted to create user : " + model.getUsername());
result.addRestMessage(this.getUnauthorizedMessage());
return result.createResponseEntity();
}
}
return result.createResponseEntity();
}
use of com.wordnik.swagger.annotations.ApiResponses 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.ApiResponses 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.ApiResponses in project ma-modules-public by infiniteautomation.
the class ExampleV2RestController method matchPath.
@PreAuthorize("isAdmin()")
@ApiOperation(value = "Example Path matching", notes = "")
@ApiResponses({ @ApiResponse(code = 401, message = "Unauthorized user access", response = ResponseEntity.class) })
@RequestMapping(method = { RequestMethod.GET }, value = { "/{resourceId}/**" }, produces = { "application/json" })
public ResponseEntity<String> matchPath(@AuthenticationPrincipal User user, @ApiParam(value = "Resource id", required = true, allowMultiple = false) @PathVariable String resourceId, HttpServletRequest request) {
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
AntPathMatcher apm = new AntPathMatcher();
String finalPath = apm.extractPathWithinPattern(bestMatchPattern, path);
return new ResponseEntity<String>(finalPath, HttpStatus.OK);
}
use of com.wordnik.swagger.annotations.ApiResponses in project ma-modules-public by infiniteautomation.
the class SessionExceptionRestV2Controller method clearLatest.
@ApiOperation(value = "Clear Last Exception for your session", notes = "")
@ApiResponses({ @ApiResponse(code = 401, message = "Unauthorized user access", response = ResponseEntity.class), @ApiResponse(code = 404, message = "No Exception exists", response = ResponseEntity.class), @ApiResponse(code = 500, message = "Error processing request", response = ResponseEntity.class) })
@RequestMapping(method = { RequestMethod.PUT }, value = { "/latest" }, produces = { "application/json" })
public ResponseEntity<Map<String, Exception>> clearLatest(HttpServletRequest request) {
RestProcessResult<Map<String, Exception>> result = new RestProcessResult<>(HttpStatus.OK);
// Get latest Session Exception
HttpSession session = request.getSession(false);
if (session == null)
throw new ServerErrorException(new TranslatableMessage("rest.error.noSession"));
Map<String, Exception> exceptionMap = new HashMap<String, Exception>();
for (String key : exceptionKeys) {
exceptionMap.put(key, (Exception) session.getAttribute(key));
session.removeAttribute(key);
}
return result.createResponseEntity(exceptionMap);
}
Aggregations