Search in sources :

Example 11 with ProcessMessage

use of com.serotonin.m2m2.i18n.ProcessMessage in project ma-core-public by infiniteautomation.

the class JsonEmportScriptTestUtility method doImportGetStatus.

@Override
public List<ProcessMessage> doImportGetStatus(String json) {
    List<ProcessMessage> result = new ArrayList<>(1);
    result.add(new ProcessMessage(new TranslatableMessage("literal", "Cannot run or test imports during validation.")));
    return result;
}
Also used : ArrayList(java.util.ArrayList) ProcessMessage(com.serotonin.m2m2.i18n.ProcessMessage) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Example 12 with ProcessMessage

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

the class UserRestController method updateUser.

@ApiOperation(value = "Updates a user")
@RequestMapping(method = RequestMethod.PUT, consumes = { "application/json", "text/csv" }, produces = { "application/json", "text/csv" }, value = "/{username}")
public ResponseEntity<UserModel> updateUser(@PathVariable String username, @RequestBody(required = true) UserModel model, UriComponentsBuilder builder, HttpServletRequest request, Authentication authentication) throws RestValidationFailedException {
    RestProcessResult<UserModel> result = new RestProcessResult<UserModel>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        User u = UserDao.instance.getUser(username);
        if (Permissions.hasAdmin(user)) {
            if (u == null) {
                result.addRestMessage(getDoesNotExistMessage());
                return result.createResponseEntity();
            }
            // Cannot make yourself disabled or not admin
            if (user.getId() == u.getId()) {
                if (!(authentication instanceof UsernamePasswordAuthenticationToken)) {
                    throw new AccessDeniedException(new TranslatableMessage("rest.error.usernamePasswordOnly"));
                }
                boolean failed = false;
                if (!model.isAdmin()) {
                    model.addValidationMessage(new ProcessMessage("permissions", new TranslatableMessage("users.validate.adminInvalid")));
                    failed = true;
                }
                if (model.getDisabled()) {
                    model.addValidationMessage(new ProcessMessage("disabled", new TranslatableMessage("users.validate.adminDisable")));
                    failed = true;
                }
                if (failed) {
                    result.addRestMessage(getValidationFailedError());
                    return result.createResponseEntity(model);
                }
            }
            // Cannot Rename a User to an existing Username
            if (!model.getUsername().equals(username)) {
                User existingUser = UserDao.instance.getUser(model.getUsername());
                if (existingUser != null) {
                    model.addValidationMessage(new ProcessMessage("username", new TranslatableMessage("users.validate.usernameInUse")));
                    result.addRestMessage(getValidationFailedError());
                    return result.createResponseEntity(model);
                }
            }
            // Set the ID for the user for validation
            model.getData().setId(u.getId());
            if (!model.validate()) {
                result.addRestMessage(this.getValidationFailedError());
            } else {
                User newUser = model.getData();
                newUser.setId(u.getId());
                if (!StringUtils.isBlank(model.getData().getPassword()))
                    newUser.setPassword(Common.encrypt(model.getData().getPassword()));
                else
                    newUser.setPassword(u.getPassword());
                UserDao.instance.saveUser(newUser);
                sessionRegistry.userUpdated(request, newUser);
            }
            return result.createResponseEntity(model);
        } else {
            if (u.getId() != user.getId()) {
                LOG.warn("Non admin user: " + user.getUsername() + " attempted to update user : " + u.getUsername());
                result.addRestMessage(this.getUnauthorizedMessage());
                return result.createResponseEntity();
            } else {
                if (!(authentication instanceof UsernamePasswordAuthenticationToken)) {
                    throw new AccessDeniedException(new TranslatableMessage("rest.error.usernamePasswordOnly"));
                }
                // Allow users to update themselves
                User newUser = model.getData();
                newUser.setId(u.getId());
                if (!StringUtils.isBlank(model.getData().getPassword()))
                    newUser.setPassword(Common.encrypt(model.getData().getPassword()));
                else
                    newUser.setPassword(u.getPassword());
                // If we are not Admin we cannot modify our own privs
                if (!u.isAdmin()) {
                    if (!StringUtils.equals(u.getPermissions(), newUser.getPermissions())) {
                        model.addValidationMessage(new ProcessMessage("permissions", new TranslatableMessage("users.validate.cannotChangePermissions")));
                        result.addRestMessage(this.getValidationFailedError());
                        return result.createResponseEntity(model);
                    }
                }
                if (!model.validate()) {
                    result.addRestMessage(this.getValidationFailedError());
                } else {
                    // Cannot make yourself disabled admin or not admin
                    boolean failed = false;
                    if (user.getId() == u.getId()) {
                        if (model.getDisabled()) {
                            model.addValidationMessage(new ProcessMessage("disabled", new TranslatableMessage("users.validate.adminDisable")));
                            failed = true;
                        }
                        if (u.isAdmin()) {
                            // We were superadmin, so we must still have it
                            if (!model.getData().isAdmin()) {
                                model.addValidationMessage(new ProcessMessage("permissions", new TranslatableMessage("users.validate.adminInvalid")));
                                failed = true;
                            }
                        } else {
                            // We were not superadmin so we must not have it
                            if (model.getData().isAdmin()) {
                                model.addValidationMessage(new ProcessMessage("permissions", new TranslatableMessage("users.validate.adminGrantInvalid")));
                                failed = true;
                            }
                        }
                        if (failed) {
                            result.addRestMessage(getValidationFailedError());
                            return result.createResponseEntity(model);
                        }
                    }
                    UserDao.instance.saveUser(newUser);
                    sessionRegistry.userUpdated(request, newUser);
                    URI location = builder.path("v1/users/{username}").buildAndExpand(model.getUsername()).toUri();
                    result.addRestMessage(getResourceCreatedMessage(location));
                }
                return result.createResponseEntity(model);
            }
        }
    }
    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) AccessDeniedException(com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException) User(com.serotonin.m2m2.vo.User) ProcessMessage(com.serotonin.m2m2.i18n.ProcessMessage) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) URI(java.net.URI) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 13 with ProcessMessage

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

the class UserModel method validate.

/*
	 * (non-Javadoc)
	 * @see com.serotonin.m2m2.web.mvc.rest.v1.model.AbstractRestModel#validate(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)
	 */
@Override
public boolean validate() {
    ProcessResult validation = new ProcessResult();
    this.data.validate(validation);
    if (validation.getHasMessages()) {
        if (this.messages == null)
            this.messages = new ArrayList<RestValidationMessage>();
        // Add our messages to the list
        for (ProcessMessage message : validation.getMessages()) {
            this.messages.add(new RestValidationMessage(message.getContextualMessage(), RestMessageLevel.ERROR, message.getContextKey()));
        }
        return false;
    } else {
        // Validated ok
        return true;
    }
}
Also used : RestValidationMessage(com.serotonin.m2m2.web.mvc.rest.v1.message.RestValidationMessage) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) ArrayList(java.util.ArrayList) ProcessMessage(com.serotonin.m2m2.i18n.ProcessMessage)

Example 14 with ProcessMessage

use of com.serotonin.m2m2.i18n.ProcessMessage in project ma-core-public by infiniteautomation.

the class MangoTestBase method validate.

/**
 * Validate a vo, fail if invalid
 * @param vo
 */
public void validate(AbstractVO<?> vo) {
    ProcessResult result = new ProcessResult();
    vo.validate(result);
    if (result.getHasMessages()) {
        String messages = new String();
        for (ProcessMessage message : result.getMessages()) messages += message.toString(Common.getTranslations()) + " ";
        fail("Validation of " + vo.getClass().getName() + " failed because " + messages);
    }
}
Also used : ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) ProcessMessage(com.serotonin.m2m2.i18n.ProcessMessage)

Example 15 with ProcessMessage

use of com.serotonin.m2m2.i18n.ProcessMessage in project ma-core-public by infiniteautomation.

the class DataSourceImporter method importImpl.

@Override
protected void importImpl() {
    String xid = json.getString("xid");
    if (StringUtils.isBlank(xid))
        xid = ctx.getDataSourceDao().generateUniqueXid();
    DataSourceVO<?> vo = ctx.getDataSourceDao().getDataSource(xid);
    if (vo == null) {
        String typeStr = json.getString("type");
        if (StringUtils.isBlank(typeStr))
            addFailureMessage("emport.dataSource.missingType", xid, ModuleRegistry.getDataSourceDefinitionTypes());
        else {
            DataSourceDefinition def = ModuleRegistry.getDataSourceDefinition(typeStr);
            if (def == null)
                addFailureMessage("emport.dataSource.invalidType", xid, typeStr, ModuleRegistry.getDataSourceDefinitionTypes());
            else {
                vo = def.baseCreateDataSourceVO();
                vo.setXid(xid);
            }
        }
    }
    if (vo != null) {
        try {
            // The VO was found or successfully created. Finish reading it in.
            ctx.getReader().readInto(vo, json);
            // Now validate it. Use a new response object so we can distinguish errors in this vo from
            // other errors.
            ProcessResult voResponse = new ProcessResult();
            vo.validate(voResponse);
            if (voResponse.getHasMessages())
                setValidationMessages(voResponse, "emport.dataSource.prefix", xid);
            else {
                // Sweet. Save it.
                boolean isnew = vo.isNew();
                if (Common.runtimeManager.getState() == RuntimeManager.RUNNING) {
                    Common.runtimeManager.saveDataSource(vo);
                    addSuccessMessage(isnew, "emport.dataSource.prefix", xid);
                } else {
                    addFailureMessage(new ProcessMessage("Runtime manager not running, data source with xid: " + xid + "not saved."));
                }
            }
        } catch (TranslatableJsonException e) {
            addFailureMessage("emport.dataSource.prefix", xid, e.getMsg());
        } catch (JsonException e) {
            addFailureMessage("emport.dataSource.prefix", xid, getJsonExceptionMessage(e));
        }
    }
}
Also used : TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) JsonException(com.serotonin.json.JsonException) DataSourceDefinition(com.serotonin.m2m2.module.DataSourceDefinition) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) ProcessMessage(com.serotonin.m2m2.i18n.ProcessMessage) TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException)

Aggregations

ProcessMessage (com.serotonin.m2m2.i18n.ProcessMessage)15 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)9 JsonException (com.serotonin.json.JsonException)4 TranslatableJsonException (com.serotonin.m2m2.i18n.TranslatableJsonException)4 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)4 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)3 User (com.serotonin.m2m2.vo.User)3 AbstractPointEventDetectorVO (com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO)3 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)3 UserModel (com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel)3 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)3 ArrayList (java.util.ArrayList)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 AccessDeniedException (com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException)2 DataPointPropertiesTemplateVO (com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO)2 RestValidationMessage (com.serotonin.m2m2.web.mvc.rest.v1.message.RestValidationMessage)2 URI (java.net.URI)2 ValueMonitor (com.infiniteautomation.mango.monitor.ValueMonitor)1 InvalidRQLRestException (com.infiniteautomation.mango.rest.v2.exception.InvalidRQLRestException)1 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)1