Search in sources :

Example 16 with ApiResponses

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();
}
Also used : UserModel(com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) User(com.serotonin.m2m2.vo.User) ProcessMessage(com.serotonin.m2m2.i18n.ProcessMessage) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) URI(java.net.URI) RestValidationFailedException(com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException) InvalidRQLRestException(com.infiniteautomation.mango.rest.v2.exception.InvalidRQLRestException) AccessDeniedException(com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) ApiResponses(com.wordnik.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 17 with ApiResponses

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);
    }
}
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 18 with ApiResponses

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);
    }
}
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 19 with ApiResponses

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);
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) AntPathMatcher(org.springframework.util.AntPathMatcher) 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 20 with ApiResponses

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);
}
Also used : RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) ServerErrorException(com.infiniteautomation.mango.rest.v2.exception.ServerErrorException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) HashMap(java.util.HashMap) Map(java.util.Map) ServerErrorException(com.infiniteautomation.mango.rest.v2.exception.ServerErrorException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) ApiResponses(com.wordnik.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

ApiResponses (com.wordnik.swagger.annotations.ApiResponses)47 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)44 Path (javax.ws.rs.Path)21 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)19 Produces (javax.ws.rs.Produces)17 POST (javax.ws.rs.POST)14 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)13 IOException (java.io.IOException)10 User (com.serotonin.m2m2.vo.User)9 Consumes (javax.ws.rs.Consumes)9 GET (javax.ws.rs.GET)9 ArrayList (java.util.ArrayList)8 WebApplicationException (javax.ws.rs.WebApplicationException)8 CertificateEncodingException (java.security.cert.CertificateEncodingException)6 GluuSAMLTrustRelationship (org.gluu.oxtrust.model.GluuSAMLTrustRelationship)6 BaseMappingException (org.gluu.persist.exception.mapping.BaseMappingException)6 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)5 ResponseEntity (org.springframework.http.ResponseEntity)5 SingularityRequestWithState (com.hubspot.singularity.SingularityRequestWithState)4 InvalidRQLRestException (com.infiniteautomation.mango.rest.v2.exception.InvalidRQLRestException)4