Search in sources :

Example 26 with ValidationException

use of com.infiniteautomation.mango.util.exception.ValidationException in project ma-core-public by infiniteautomation.

the class MangoTestBase method createMockDataSource.

protected MockDataSourceVO createMockDataSource(String name, String xid, boolean enabled, MangoPermission readPermission, MangoPermission editPermission) {
    DataSourceService service = Common.getBean(DataSourceService.class);
    MockDataSourceVO vo = (MockDataSourceVO) ModuleRegistry.getDataSourceDefinition(MockDataSourceDefinition.TYPE_NAME).baseCreateDataSourceVO();
    vo.setXid(name);
    vo.setName(xid);
    vo.setEnabled(enabled);
    vo.setReadPermission(readPermission);
    vo.setEditPermission(editPermission);
    try {
        return (MockDataSourceVO) service.insert(vo);
    } catch (ValidationException e) {
        fail(e.getValidationErrorMessage(Common.getTranslations()));
        return null;
    }
}
Also used : MockDataSourceVO(com.serotonin.m2m2.vo.dataSource.mock.MockDataSourceVO) ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) DataSourceService(com.infiniteautomation.mango.spring.service.DataSourceService)

Example 27 with ValidationException

use of com.infiniteautomation.mango.util.exception.ValidationException in project ma-core-public by infiniteautomation.

the class MangoJavaScriptService method ensureValid.

/**
 * Ensure the script is valid
 */
public void ensureValid(MangoJavaScript vo) throws ValidationException {
    PermissionHolder user = Common.getUser();
    permissionService.ensurePermission(user, dataSourcePermissionDefinition.getPermission());
    ProcessResult result = validate(vo);
    if (!result.isValid())
        throw new ValidationException(result);
}
Also used : ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder)

Example 28 with ValidationException

use of com.infiniteautomation.mango.util.exception.ValidationException in project ma-core-public by infiniteautomation.

the class MangoJavaScriptService method executeScript.

/**
 * The preferred way to execute a script
 */
public MangoJavaScriptResult executeScript(MangoJavaScript vo, ScriptPointValueSetter setter) throws ValidationException, PermissionException {
    PermissionHolder user = Common.getUser();
    ensureValid(vo);
    MangoJavaScriptResult result = new MangoJavaScriptResult();
    final Writer scriptOut;
    final PrintWriter scriptWriter;
    if (vo.isReturnLogOutput()) {
        scriptOut = new StringWriter();
        scriptWriter = new PrintWriter(scriptOut);
    } else {
        NullWriter writer = new NullWriter();
        scriptWriter = new NullPrintWriter(writer);
        scriptOut = writer;
    }
    try {
        try (ScriptLogExtender scriptLog = new ScriptLogExtender("scriptTest-" + user.getPermissionHolderName(), vo.getLogLevel(), scriptWriter, vo.getLog(), vo.isCloseLog())) {
            CompiledMangoJavaScript script = new CompiledMangoJavaScript(vo, setter, scriptLog, result, this, pointValueDao, pointValueCache);
            script.compile(vo.getScript(), vo.isWrapInFunction());
            script.initialize(vo.getContext());
            long time = Common.timer.currentTimeMillis();
            runAs.runAsCallable(script.getPermissionHolder(), () -> {
                if (vo.getResultDataType() != null) {
                    script.execute(time, time, vo.getResultDataType());
                } else {
                    script.execute(time, time);
                }
                return null;
            });
        }
    } catch (ScriptError e) {
        // The script exception should be clean as both compile() and execute() clean it
        result.addError(new MangoJavaScriptError(e.getTranslatableMessage(), e.getLineNumber(), e.getColumnNumber()));
    } catch (ResultTypeException | DataPointStateException e) {
        result.addError(new MangoJavaScriptError(e.getTranslatableMessage()));
    } catch (Exception e) {
        result.addError(new MangoJavaScriptError(e.getMessage()));
    } finally {
        if (vo.isReturnLogOutput())
            result.setScriptOutput(scriptOut.toString());
    }
    return result;
}
Also used : MangoJavaScriptError(com.infiniteautomation.mango.util.script.MangoJavaScriptError) MangoJavaScriptResult(com.infiniteautomation.mango.util.script.MangoJavaScriptResult) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder) NullWriter(com.serotonin.io.NullWriter) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) DataPointStateException(com.serotonin.m2m2.rt.script.DataPointStateException) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) MangoJavaScriptError(com.infiniteautomation.mango.util.script.MangoJavaScriptError) ScriptError(com.serotonin.m2m2.rt.script.ScriptError) StringWriter(java.io.StringWriter) NullPrintWriter(com.serotonin.m2m2.util.log.NullPrintWriter) DataPointStateException(com.serotonin.m2m2.rt.script.DataPointStateException) CompiledMangoJavaScript(com.infiniteautomation.mango.util.script.CompiledMangoJavaScript) NullWriter(com.serotonin.io.NullWriter) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) StringWriter(java.io.StringWriter) NullPrintWriter(com.serotonin.m2m2.util.log.NullPrintWriter) PrintWriter(java.io.PrintWriter) NullPrintWriter(com.serotonin.m2m2.util.log.NullPrintWriter)

Example 29 with ValidationException

use of com.infiniteautomation.mango.util.exception.ValidationException in project ma-modules-public by infiniteautomation.

the class EmailVerificationController method publicRegisterUser.

/**
 * CAUTION: This method is public!
 * However the token's signature is cryptographically verified.
 */
@ApiOperation(value = "Registers a new user if the token's signature can be verified", notes = "The new user is created disabled and must be approved by an administrator.")
@RequestMapping(method = RequestMethod.POST, value = "/public/register")
@AnonymousAccess
public ResponseEntity<UserModel> publicRegisterUser(@RequestBody PublicRegistrationRequest body) {
    body.ensureValid();
    User newUser = body.getUser().toVO();
    try {
        User created = emailVerificationService.publicRegisterNewUser(body.getToken(), newUser);
        return new ResponseEntity<>(new UserModel(created), HttpStatus.OK);
    } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException | MissingClaimException | IncorrectClaimException e) {
        throw new BadRequestException(new TranslatableMessage("rest.error.invalidEmailVerificationToken"), e);
    } catch (ValidationException e) {
        e.getValidationResult().prefixContextKey("user");
        throw e;
    }
}
Also used : User(com.serotonin.m2m2.vo.User) ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) SignatureException(io.jsonwebtoken.SignatureException) IncorrectClaimException(io.jsonwebtoken.IncorrectClaimException) UserModel(com.infiniteautomation.mango.rest.latest.model.user.UserModel) ResponseEntity(org.springframework.http.ResponseEntity) MissingClaimException(io.jsonwebtoken.MissingClaimException) BadRequestException(com.infiniteautomation.mango.rest.latest.exception.BadRequestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) MalformedJwtException(io.jsonwebtoken.MalformedJwtException) UnsupportedJwtException(io.jsonwebtoken.UnsupportedJwtException) AnonymousAccess(com.serotonin.m2m2.web.mvc.spring.security.permissions.AnonymousAccess) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 30 with ValidationException

use of com.infiniteautomation.mango.util.exception.ValidationException in project ma-modules-public by infiniteautomation.

the class EventsRestController method queryForEventsBySourceType.

@ApiOperation(value = "Find Events for a set of sources found by the supplied sourceType RQL query, then query for events with these sources using eventsRql", response = EventQueryResult.class)
@RequestMapping(method = RequestMethod.POST, value = "/query/events-by-source-type")
public StreamedArrayWithTotal queryForEventsBySourceType(@RequestBody EventQueryBySourceType body, @AuthenticationPrincipal PermissionHolder user) {
    ASTNode rql = RQLUtils.parseRQLtoAST(body.getSourceRql());
    ASTNode query = null;
    List<Object> args = new ArrayList<>();
    args.add("typeRef1");
    // Query for the sources
    switch(body.getSourceType()) {
        case "DATA_POINT":
            dataPointService.customizedQuery(rql, (vo) -> args.add(Integer.toString(vo.getId())));
            if (args.size() > 1) {
                query = new ASTNode("in", args);
                query = RQLUtils.addAndRestriction(query, new ASTNode("eq", "typeName", EventTypeNames.DATA_POINT));
            }
            break;
        case "DATA_SOURCE":
            dataSourceService.customizedQuery(rql, (vo) -> args.add(Integer.toString(vo.getId())));
            if (args.size() > 1) {
                query = new ASTNode("in", args);
                query = RQLUtils.addAndRestriction(query, new ASTNode("eq", "typeName", EventTypeNames.DATA_SOURCE));
            }
            break;
        default:
            ProcessResult result = new ProcessResult();
            result.addContextualMessage("sourceType", "validate.invalidValue");
            throw new ValidationException(result);
    }
    // Second query the events
    if (query != null) {
        // Apply the events query
        ASTNode eventQuery = RQLUtils.parseRQLtoAST(body.getEventsRql());
        query = RQLUtils.addAndRestriction(query, eventQuery);
        return doQuery(query, user);
    } else {
        return new StreamedArrayWithTotal() {

            @Override
            public StreamedArray getItems() {
                return null;
            }

            @Override
            public int getTotal() {
                return 0;
            }
        };
    }
}
Also used : ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) ASTNode(net.jazdw.rql.parser.ASTNode) ArrayList(java.util.ArrayList) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) StreamedArrayWithTotal(com.infiniteautomation.mango.rest.latest.model.StreamedArrayWithTotal) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

ValidationException (com.infiniteautomation.mango.util.exception.ValidationException)75 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)31 JsonException (com.serotonin.json.JsonException)22 NotFoundException (com.infiniteautomation.mango.util.exception.NotFoundException)20 TranslatableJsonException (com.serotonin.m2m2.i18n.TranslatableJsonException)16 MangoPermission (com.infiniteautomation.mango.permission.MangoPermission)15 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)15 PermissionHolder (com.serotonin.m2m2.vo.permission.PermissionHolder)14 JsonValue (com.serotonin.json.type.JsonValue)10 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)9 JsonObject (com.serotonin.json.type.JsonObject)8 DataSourceVO (com.serotonin.m2m2.vo.dataSource.DataSourceVO)8 ProcessMessage (com.serotonin.m2m2.i18n.ProcessMessage)7 DataPointService (com.infiniteautomation.mango.spring.service.DataPointService)6 JsonArray (com.serotonin.json.type.JsonArray)6 DataPointWithEventDetectors (com.serotonin.m2m2.vo.dataPoint.DataPointWithEventDetectors)6 AbstractPointEventDetectorVO (com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO)6 ArrayList (java.util.ArrayList)6 ExpectValidationException (com.infiniteautomation.mango.rules.ExpectValidationException)4 PublishedPointService (com.infiniteautomation.mango.spring.service.PublishedPointService)4