Search in sources :

Example 1 with ValidationException

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

the class WorkItemRestController method getWorkItemsByPriority.

@ApiOperation(value = "Get list of work items by classname", notes = "Returns the Work Item specified by the given classname and priority")
@RequestMapping(method = RequestMethod.GET, value = "/by-priority/{priority}")
public List<WorkItemInfo> getWorkItemsByPriority(@ApiParam(value = "priority", required = true, allowMultiple = false) @PathVariable String priority, @RequestParam(value = "classname", required = false, defaultValue = "") String classname, @AuthenticationPrincipal PermissionHolder user) {
    permissionService.ensureAdminRole(user);
    List<WorkItemInfo> list;
    if (priority.equalsIgnoreCase("HIGH")) {
        list = Common.backgroundProcessing.getHighPriorityServiceItems();
    } else if (priority.equalsIgnoreCase("MEDIUM")) {
        list = Common.backgroundProcessing.getMediumPriorityServiceQueueItems();
    } else if (priority.equalsIgnoreCase("LOW")) {
        list = Common.backgroundProcessing.getLowPriorityServiceQueueItems();
    } else {
        ProcessResult result = new ProcessResult();
        result.addContextualMessage("priority", "validate.invalidValue");
        throw new ValidationException(result);
    }
    // Filter if we need to
    if (StringUtils.isNotEmpty(classname)) {
        List<WorkItemInfo> modelList = new ArrayList<>();
        for (WorkItemInfo model : list) {
            if (model.getClassname().equalsIgnoreCase(classname)) {
                modelList.add(model);
            }
        }
        return modelList;
    } else {
        return list;
    }
}
Also used : ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) ArrayList(java.util.ArrayList) WorkItemInfo(com.infiniteautomation.mango.util.WorkItemInfo) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with ValidationException

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

the class InternalLifecycle method maybeInstallSystemMonitor.

/**
 */
private void maybeInstallSystemMonitor(boolean safe) {
    DataSourceVO ds = DataSourceDao.getInstance().getByXid(SYSTEM_DATASOURCE_XID);
    if (ds == null) {
        // Create Data Source
        DataSourceDefinition<InternalDataSourceVO> def = ModuleRegistry.getDataSourceDefinition(InternalDataSourceDefinition.DATA_SOURCE_TYPE);
        ds = def.baseCreateDataSourceVO();
        InternalDataSourceVO vo = (InternalDataSourceVO) ds;
        vo.setXid(SYSTEM_DATASOURCE_XID);
        vo.setName(SYSTEM_DATASOURCE_DEVICE_NAME);
        vo.setUpdatePeriods(10);
        vo.setUpdatePeriodType(TimePeriods.SECONDS);
        try {
            DataSourceDao.getInstance().insert(vo);
            // Setup the Points
            maybeCreatePoints(safe, ds);
            // Enable the data source
            InternalDataSourceVO existing = (InternalDataSourceVO) ds.copy();
            if (!safe) {
                vo.setEnabled(true);
                Common.getBean(DataSourceService.class).update(existing.getId(), vo);
            }
        } catch (ValidationException e) {
            for (ProcessMessage message : e.getValidationResult().getMessages()) {
                LOG.error(message.toString(Common.getTranslations()));
            }
        }
    } else {
        // Ensure all points are added
        maybeCreatePoints(safe, ds);
    }
}
Also used : DataSourceVO(com.serotonin.m2m2.vo.dataSource.DataSourceVO) ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) ProcessMessage(com.serotonin.m2m2.i18n.ProcessMessage) DataSourceService(com.infiniteautomation.mango.spring.service.DataSourceService)

Example 3 with ValidationException

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

the class DataPointModel method toVO.

@Override
public DataPointVO toVO() {
    DataPointVO point = new DataPointVO();
    if (xid != null) {
        point.setXid(xid);
    }
    if (name != null) {
        point.setName(name);
    }
    if (enabled != null) {
        point.setEnabled(enabled);
    }
    if (deviceName != null) {
        point.setDeviceName(deviceName);
    }
    // TODO Use ModelMapper.unmap
    if (readPermission != null) {
        point.setReadPermission(readPermission.getPermission());
    }
    // TODO Use ModelMapper.unmap
    if (editPermission != null) {
        point.setEditPermission(editPermission.getPermission());
    }
    // TODO Use ModelMapper.unmap
    if (setPermission != null) {
        point.setSetPermission(setPermission.getPermission());
    }
    // TODO Use ModelMapper.unmap
    if (StringUtils.isNotEmpty(dataSourceXid)) {
        DataSourceVO ds = DataSourceDao.getInstance().getByXid(dataSourceXid);
        if (ds != null) {
            point.setDataSourceId(ds.getId());
            point.setDataSourceName(ds.getName());
            point.setDataSourceXid(ds.getXid());
            point.setDataSourceTypeName(ds.getDefinition().getDataSourceTypeName());
        }
    }
    // TODO Use ModelMapper.unmap
    if (point.getDataSourceId() <= 0 && dataSourceId != null && dataSourceId > 0) {
        point.setDataSourceId(dataSourceId);
    }
    if (purgeOverride != null) {
        point.setPurgeOverride(purgeOverride);
        // Ensure that a purge period must be supplied
        if (purgeOverride) {
            point.setPurgePeriod(-1);
            point.setPurgeType(-1);
        }
    }
    if (purgePeriod != null) {
        point.setPurgePeriod(purgePeriod.getPeriods());
        point.setPurgeType(Common.TIME_PERIOD_CODES.getId(purgePeriod.getPeriodType()));
    }
    if (unit != null) {
        try {
            point.setUnit(JUnitUtil.parseLocal(unit));
        } catch (IllegalArgumentException e) {
            // TODO unmap
            ProcessResult result = new ProcessResult();
            result.addContextualMessage("unit", "validate.unitInvalid", e.getMessage());
            throw new ValidationException(result);
        }
    }
    if (useIntegralUnit != null) {
        point.setUseIntegralUnit(useIntegralUnit);
    }
    if (integralUnit != null) {
        try {
            point.setIntegralUnit(JUnitUtil.parseLocal(integralUnit));
        } catch (IllegalArgumentException e) {
            // TODO unmap
            ProcessResult result = new ProcessResult();
            result.addContextualMessage("integralUnit", "validate.unitInvalid", e.getMessage());
            throw new ValidationException(result);
        }
    }
    if (useRenderedUnit != null) {
        point.setUseRenderedUnit(useRenderedUnit);
    }
    if (this.renderedUnit != null) {
        try {
            point.setRenderedUnit(JUnitUtil.parseLocal(renderedUnit));
        } catch (IllegalArgumentException e) {
            // TODO unmap
            ProcessResult result = new ProcessResult();
            result.addContextualMessage("renderedUnit", "validate.unitInvalid", e.getMessage());
            throw new ValidationException(result);
        }
    }
    if (chartColour != null) {
        point.setChartColour(chartColour);
    }
    if (plotType != null) {
        point.setPlotType(DataPointVO.PLOT_TYPE_CODES.getId(plotType));
    }
    if (this.tags != null) {
        Map<String, String> existingTags = point.getTags();
        if (!this.mergeTags || existingTags == null) {
            // existingTags is only null if someone tried to use mergeTags when creating a data point
            point.setTags(this.tags);
        } else {
            Map<String, String> mergedTags = new HashMap<>(existingTags);
            for (Entry<String, String> entry : this.tags.entrySet()) {
                String tagKey = entry.getKey();
                String tagValue = entry.getValue();
                if (tagValue == null) {
                    mergedTags.remove(tagKey);
                } else {
                    mergedTags.put(tagKey, tagValue);
                }
            }
            point.setTags(mergedTags);
        }
    } else {
        // TODO unmap
        if (id != null && id > 0) {
            point.setTags(DataPointTagsDao.getInstance().getTagsForDataPointId(id));
        } else if (xid != null) {
            Integer id = DataPointDao.getInstance().getIdByXid(xid);
            if (id != null) {
                point.setTags(DataPointTagsDao.getInstance().getTagsForDataPointId(id));
            }
        }
    }
    if (this.loggingProperties != null) {
        loggingProperties.copyPropertiesTo(point);
    }
    if (this.textRenderer != null) {
        point.setTextRenderer(textRenderer.toVO());
    }
    if (pointLocator != null) {
        point.setPointLocator(pointLocator.toVO());
    }
    if (this.rollup != null) {
        point.setRollup(Common.ROLLUP_CODES.getId(this.rollup));
    }
    if (this.simplifyType != null) {
        point.setSimplifyType(DataPointVO.SIMPLIFY_TYPE_CODES.getId(this.simplifyType));
    }
    if (this.simplifyTolerance != null) {
        point.setSimplifyTolerance(simplifyTolerance);
    }
    if (this.simplifyTarget != null) {
        point.setSimplifyTarget(simplifyTarget);
    }
    if (this.preventSetExtremeValues != null) {
        point.setPreventSetExtremeValues(this.preventSetExtremeValues);
    }
    if (this.setExtremeLowLimit != null) {
        point.setSetExtremeLowLimit(this.setExtremeLowLimit);
    }
    if (this.setExtremeHighLimit != null) {
        point.setSetExtremeHighLimit(this.setExtremeHighLimit);
    }
    if (this.data != null) {
        point.setData(data);
    }
    return point;
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) DataSourceVO(com.serotonin.m2m2.vo.dataSource.DataSourceVO) ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) HashMap(java.util.HashMap) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult)

Example 4 with ValidationException

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

the class MangoPasswordAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!(authentication instanceof UsernamePasswordAuthenticationToken)) {
        return null;
    }
    if (!(authentication.getDetails() instanceof WebAuthenticationDetails)) {
        throw new InternalAuthenticationServiceException("Expected authentication details to be instance of WebAuthenticationDetails");
    }
    String username = authentication.getName();
    WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
    String ip = details.getRemoteAddress();
    try {
        boolean ipRateExceeded = this.ipRateLimiter != null && this.ipRateLimiter.checkRateExceeded(ip);
        boolean usernameRateExceeded = this.usernameRateLimiter != null && this.usernameRateLimiter.checkRateExceeded(username);
        if (ipRateExceeded) {
            throw new IpAddressAuthenticationRateException(ip);
        }
        if (usernameRateExceeded) {
            throw new UsernameAuthenticationRateException(username);
        }
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
        if (!(userDetails instanceof User)) {
            throw new InternalAuthenticationServiceException("Expected user details to be instance of User");
        }
        User user = (User) userDetails;
        String newPassword = null;
        if (authentication instanceof PasswordResetAuthenticationToken) {
            newPassword = ((PasswordResetAuthenticationToken) authentication).getNewPassword();
        }
        try {
            this.userDetailsChecker.check(user);
        } catch (CredentialsExpiredException e) {
            if (newPassword == null) {
                throw e;
            }
        }
        String credentials = (String) authentication.getCredentials();
        // Validating the password against the database.
        if (!Common.checkPassword(credentials, user.getPassword())) {
            throw new BadCredentialsException(Common.translate("login.validation.invalidLogin"));
        }
        if (newPassword != null) {
            if (newPassword.equals(credentials)) {
                throw new PasswordChangeException(new TranslatableMessage("rest.exception.samePassword"));
            }
            final String password = newPassword;
            runAs.runAs(user, () -> {
                try {
                    usersService.updatePassword(user, password);
                } catch (ValidationException e) {
                    throw new PasswordChangeException(new TranslatableMessage("rest.exception.complexityRequirementsFailed"));
                }
                return null;
            });
        }
        return new UsernamePasswordAuthenticationToken(user, user.getPassword(), Collections.unmodifiableCollection(user.getAuthorities()));
    } catch (AuthenticationException e) {
        if (this.ipRateLimiter != null) {
            this.ipRateLimiter.hit(ip);
        }
        if (this.usernameRateLimiter != null) {
            this.usernameRateLimiter.hit(username);
        }
        throw e;
    }
}
Also used : User(com.serotonin.m2m2.vo.User) ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) CredentialsExpiredException(org.springframework.security.authentication.CredentialsExpiredException) AuthenticationException(org.springframework.security.core.AuthenticationException) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) UserDetails(org.springframework.security.core.userdetails.UserDetails) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Example 5 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)

Aggregations

ValidationException (com.infiniteautomation.mango.util.exception.ValidationException)43 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)19 JsonException (com.serotonin.json.JsonException)12 NotFoundException (com.infiniteautomation.mango.util.exception.NotFoundException)11 MangoPermission (com.infiniteautomation.mango.permission.MangoPermission)9 TranslatableJsonException (com.serotonin.m2m2.i18n.TranslatableJsonException)9 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)8 PermissionHolder (com.serotonin.m2m2.vo.permission.PermissionHolder)7 JsonObject (com.serotonin.json.type.JsonObject)5 JsonValue (com.serotonin.json.type.JsonValue)5 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)5 DataSourceVO (com.serotonin.m2m2.vo.dataSource.DataSourceVO)5 ProcessMessage (com.serotonin.m2m2.i18n.ProcessMessage)4 ApiOperation (io.swagger.annotations.ApiOperation)4 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)4 DataPointService (com.infiniteautomation.mango.spring.service.DataPointService)3 JsonArray (com.serotonin.json.type.JsonArray)3 DataPointWithEventDetectors (com.serotonin.m2m2.vo.dataPoint.DataPointWithEventDetectors)3 AbstractPointEventDetectorVO (com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO)3 ArrayList (java.util.ArrayList)3