use of com.serotonin.InvalidArgumentException in project ma-core-public by infiniteautomation.
the class SystemSettingsDao method validate.
/**
* Validate the system settings passed in, only validating settings that exist in the map.
*
* @param settings
* @param voResponse
*/
public void validate(Map<String, Object> settings, ProcessResult response) {
Object setting = null;
try {
setting = settings.get(EMAIL_CONTENT_TYPE);
if (setting != null) {
if (setting instanceof Number) {
int emailContentType = ((Number) setting).intValue();
switch(emailContentType) {
case MangoEmailContent.CONTENT_TYPE_BOTH:
case MangoEmailContent.CONTENT_TYPE_HTML:
case MangoEmailContent.CONTENT_TYPE_TEXT:
break;
default:
response.addContextualMessage(EMAIL_CONTENT_TYPE, "validate.invalideValue");
}
} else {
// String Code
if (MangoEmailContent.CONTENT_TYPE_CODES.getId((String) setting) < 0)
response.addContextualMessage(EMAIL_CONTENT_TYPE, "emport.error.invalid", EMAIL_CONTENT_TYPE, (String) setting, MangoEmailContent.CONTENT_TYPE_CODES.getCodeList());
}
}
} catch (NumberFormatException e) {
response.addContextualMessage(EMAIL_CONTENT_TYPE, "validate.illegalValue");
}
validatePeriodType(POINT_DATA_PURGE_PERIOD_TYPE, settings, response);
validatePeriodType(DATA_POINT_EVENT_PURGE_PERIOD_TYPE, settings, response);
validatePeriodType(DATA_SOURCE_EVENT_PURGE_PERIOD_TYPE, settings, response);
validatePeriodType(SYSTEM_EVENT_PURGE_PERIOD_TYPE, settings, response);
validatePeriodType(PUBLISHER_EVENT_PURGE_PERIOD_TYPE, settings, response);
validatePeriodType(AUDIT_EVENT_PURGE_PERIOD_TYPE, settings, response);
validatePeriodType(NONE_ALARM_PURGE_PERIOD_TYPE, settings, response);
validatePeriodType(INFORMATION_ALARM_PURGE_PERIOD_TYPE, settings, response);
validatePeriodType(IMPORTANT_ALARM_PURGE_PERIOD_TYPE, settings, response);
validatePeriodType(WARNING_ALARM_PURGE_PERIOD_TYPE, settings, response);
validatePeriodType(URGENT_ALARM_PURGE_PERIOD_TYPE, settings, response);
validatePeriodType(CRITICAL_ALARM_PURGE_PERIOD_TYPE, settings, response);
validatePeriodType(LIFE_SAFETY_ALARM_PURGE_PERIOD_TYPE, settings, response);
validatePeriodType(EVENT_PURGE_PERIOD_TYPE, settings, response);
validatePeriodType(FUTURE_DATE_LIMIT_PERIOD_TYPE, settings, response);
try {
setting = settings.get(CHART_BACKGROUND_COLOUR);
if (setting != null)
ColorUtils.toColor((String) setting);
} catch (InvalidArgumentException e) {
response.addContextualMessage(CHART_BACKGROUND_COLOUR, "systemSettings.validation.invalidColour");
}
try {
setting = settings.get(PLOT_BACKGROUND_COLOUR);
if (setting != null)
ColorUtils.toColor((String) setting);
} catch (InvalidArgumentException e) {
response.addContextualMessage(PLOT_BACKGROUND_COLOUR, "systemSettings.validation.invalidColour");
}
try {
setting = settings.get(PLOT_GRIDLINE_COLOUR);
if (setting != null)
ColorUtils.toColor((String) setting);
} catch (InvalidArgumentException e) {
response.addContextualMessage(PLOT_GRIDLINE_COLOUR, "systemSettings.validation.invalidColour");
}
setting = settings.get(BACKUP_FILE_LOCATION);
if (setting != null) {
File tmp = new File((String) setting);
if (!tmp.exists()) {
// Doesn't exist, push up message
response.addContextualMessage(BACKUP_FILE_LOCATION, "systemSettings.validation.backupLocationNotExists");
}
if (!tmp.canWrite()) {
response.addContextualMessage(BACKUP_FILE_LOCATION, "systemSettings.validation.cannotWriteToBackupFileLocation");
}
}
// Validate the Hour and Minute
Integer backupHour = getIntValue(BACKUP_HOUR, settings);
if (backupHour != null)
if ((backupHour > 23) || (backupHour < 0)) {
response.addContextualMessage(BACKUP_HOUR, "systemSettings.validation.backupHourInvalid");
}
Integer backupMinute = getIntValue(BACKUP_MINUTE, settings);
if (backupMinute != null)
if ((backupMinute > 59) || (backupMinute < 0)) {
response.addContextualMessage(BACKUP_MINUTE, "systemSettings.validation.backupMinuteInvalid");
}
validatePeriodType(BACKUP_PERIOD_TYPE, settings, response);
// Validate the number of backups to keep
Integer backupFileCount = getIntValue(BACKUP_FILE_COUNT, settings);
if (backupFileCount != null)
if (backupFileCount < 1) {
response.addContextualMessage(BACKUP_FILE_COUNT, "systemSettings.validation.backupFileCountInvalid");
}
// Validate
setting = settings.get(DATABASE_BACKUP_FILE_LOCATION);
if (setting != null) {
File tmp = new File((String) setting);
if (!tmp.exists()) {
// Doesn't exist, push up message
response.addContextualMessage(DATABASE_BACKUP_FILE_LOCATION, "systemSettings.validation.databaseBackupLocationNotExists");
}
if (!tmp.canWrite()) {
response.addContextualMessage(DATABASE_BACKUP_FILE_LOCATION, "systemSettings.validation.cannotWriteToDatabaseBackupFileLocation");
}
}
// Validate the Hour and Minute
Integer databaseBackupHour = getIntValue(DATABASE_BACKUP_HOUR, settings);
if (databaseBackupHour != null)
if ((databaseBackupHour > 23) || (databaseBackupHour < 0)) {
response.addContextualMessage(DATABASE_BACKUP_HOUR, "systemSettings.validation.databaseBackupHourInvalid");
}
Integer databaseBackupMinute = getIntValue(DATABASE_BACKUP_MINUTE, settings);
if (databaseBackupMinute != null)
if ((databaseBackupMinute > 59) || (databaseBackupMinute < 0)) {
response.addContextualMessage(DATABASE_BACKUP_MINUTE, "systemSettings.validation.databaseBackupMinuteInvalid");
}
validatePeriodType(DATABASE_BACKUP_PERIOD_TYPE, settings, response);
// Validate the number of backups to keep
Integer databaseBackupFileCount = getIntValue(DATABASE_BACKUP_FILE_COUNT, settings);
if (databaseBackupFileCount != null)
if (databaseBackupFileCount < 1) {
response.addContextualMessage(DATABASE_BACKUP_FILE_COUNT, "systemSettings.validation.databaseBackupFileCountInvalid");
}
// Thread Pool Sizes
Integer corePoolSize = getIntValue(HIGH_PRI_CORE_POOL_SIZE, settings);
Integer maxPoolSize = getIntValue(HIGH_PRI_MAX_POOL_SIZE, settings);
if ((corePoolSize != null) && (corePoolSize < 0)) {
response.addContextualMessage(HIGH_PRI_CORE_POOL_SIZE, "validate.greaterThanOrEqualTo", 0);
}
if ((maxPoolSize != null) && (maxPoolSize < BackgroundProcessing.HIGH_PRI_MAX_POOL_SIZE_MIN)) {
response.addContextualMessage(HIGH_PRI_MAX_POOL_SIZE, "validate.greaterThanOrEqualTo", BackgroundProcessing.HIGH_PRI_MAX_POOL_SIZE_MIN);
}
if ((maxPoolSize != null) && (maxPoolSize < corePoolSize)) {
response.addContextualMessage(HIGH_PRI_MAX_POOL_SIZE, "systemSettings.threadPools.validate.maxPoolMustBeGreaterThanCorePool");
}
// For Medium and Low the Max has no effect because they use a LinkedBlockingQueue and will just block until a
// core pool thread is available
corePoolSize = getIntValue(MED_PRI_CORE_POOL_SIZE, settings);
if (corePoolSize < BackgroundProcessing.MED_PRI_MAX_POOL_SIZE_MIN) {
response.addContextualMessage(MED_PRI_CORE_POOL_SIZE, "validate.greaterThanOrEqualTo", BackgroundProcessing.MED_PRI_MAX_POOL_SIZE_MIN);
}
corePoolSize = getIntValue(LOW_PRI_CORE_POOL_SIZE, settings);
if (corePoolSize < BackgroundProcessing.LOW_PRI_MAX_POOL_SIZE_MIN) {
response.addContextualMessage(LOW_PRI_CORE_POOL_SIZE, "validate.greaterThanOrEqualTo", BackgroundProcessing.LOW_PRI_MAX_POOL_SIZE_MIN);
}
// Validate Upgrade Version State
setting = settings.get(UPGRADE_VERSION_STATE);
if (setting != null) {
if (setting instanceof Number) {
// Legacy Integer Value
try {
int value = ((Number) setting).intValue();
switch(value) {
case UpgradeVersionState.DEVELOPMENT:
case UpgradeVersionState.ALPHA:
case UpgradeVersionState.BETA:
case UpgradeVersionState.RELEASE_CANDIDATE:
case UpgradeVersionState.PRODUCTION:
break;
default:
response.addContextualMessage(UPGRADE_VERSION_STATE, "validate.invalidValue");
break;
}
} catch (NumberFormatException e) {
response.addContextualMessage(UPGRADE_VERSION_STATE, "validate.illegalValue");
}
} else {
// Must be a code
if (Common.VERSION_STATE_CODES.getId((String) setting) < 0)
response.addContextualMessage(UPGRADE_VERSION_STATE, "emport.error.invalid", UPGRADE_VERSION_STATE, (String) setting, Common.VERSION_STATE_CODES.getCodeList());
}
}
// Validate point hierarchy settings
setting = settings.get(HIERARCHY_PATH_SEPARATOR);
if (setting != null) {
if (StringUtils.isEmpty((String) setting))
response.addContextualMessage(HIERARCHY_PATH_SEPARATOR, "validate.cannotContainEmptyString");
}
// Validate the Module Settings
for (SystemSettingsDefinition def : ModuleRegistry.getSystemSettingsDefinitions()) def.validateSettings(settings, response);
// Ensure no one can change the superadmin permission
if (settings.get(SuperadminPermissionDefinition.PERMISSION) != null)
response.addContextualMessage(SuperadminPermissionDefinition.PERMISSION, "validate.readOnly");
}
use of com.serotonin.InvalidArgumentException in project ma-core-public by infiniteautomation.
the class ColorUtils method toColor.
public static Color toColor(String s) throws InvalidArgumentException {
if (s.startsWith("#"))
return hexToColor(s);
Object o = colorMap.get(s.toLowerCase());
if (o != null) {
if (o instanceof String) {
Color c = hexToColor((String) o);
colorMap.put(s, c);
return c;
}
return (Color) o;
}
throw new InvalidArgumentException("Invalid color format: " + s);
}
use of com.serotonin.InvalidArgumentException in project ma-modules-public by infiniteautomation.
the class ReportVO method validate.
@Override
public void validate(ProcessResult response) {
super.validate(response);
if (points.isEmpty())
response.addContextualMessage("points", "reports.validate.needPoint");
if (dateRangeType != ReportVO.DATE_RANGE_TYPE_RELATIVE && dateRangeType != ReportVO.DATE_RANGE_TYPE_SPECIFIC)
response.addGenericMessage("reports.validate.invalidDateRangeType");
if (relativeDateType != ReportVO.RELATIVE_DATE_TYPE_PAST && relativeDateType != ReportVO.RELATIVE_DATE_TYPE_PREVIOUS)
response.addGenericMessage("reports.validate.invalidRelativeDateType");
if (previousPeriodCount < 1)
response.addContextualMessage("previousPeriodCount", "reports.validate.periodCountLessThan1");
if (pastPeriodCount < 1)
response.addContextualMessage("pastPeriodCount", "reports.validate.periodCountLessThan1");
UserDao dao = UserDao.instance;
User user = dao.getUser(userId);
if (user == null) {
response.addContextualMessage("userId", "reports.validate.userDNE");
}
File t = ReportCommon.instance.getTemplateFile(template);
if (!t.isFile())
response.addContextualMessage("template", "reports.validate.template");
DataPointDao dataPointDao = DataPointDao.instance;
for (ReportPointVO point : points) {
DataPointVO vo = dataPointDao.getDataPoint(point.getPointId(), false);
String pointXid = "unknown";
if (vo != null) {
pointXid = vo.getXid();
try {
Permissions.ensureDataPointReadPermission(user, dataPointDao.getDataPoint(point.getPointId(), false));
} catch (PermissionException e) {
response.addContextualMessage("points", "reports.vaildate.pointDNE");
}
} else {
response.addContextualMessage("points", "reports.validate.pointPermissions", user.getUsername(), pointXid);
}
try {
if (!StringUtils.isBlank(point.getColour()))
ColorUtils.toColor(point.getColour());
} catch (InvalidArgumentException e) {
response.addContextualMessage("points", "reports.validate.colour", point.getColour(), pointXid);
}
if (point.getWeight() <= 0)
response.addContextualMessage("points", "reports.validate.weight");
}
// Validate the schedule
if (schedule) {
if (schedulePeriod == SCHEDULE_CRON) {
try {
new CronTimerTrigger(scheduleCron);
} catch (ParseException e) {
response.addContextualMessage("scheduleCron", "validate.invalidValue");
}
}
}
}
use of com.serotonin.InvalidArgumentException in project ma-modules-public by infiniteautomation.
the class ReportPointValueTimeSerializer method getObject.
/* (non-Javadoc)
* @see com.serotonin.m2m2.db.dao.nosql.NoSQLDataSerializer#getObject(byte[], long)
*/
@Override
public ITime getObject(ByteArrayBuilder b, long ts, String seriesId) {
// Get the data type
int dataType = b.getShort();
DataValue dataValue = null;
// Second put in the data value
switch(dataType) {
case DataTypes.ALPHANUMERIC:
String s = b.getString();
dataValue = new AlphanumericValue(s);
break;
case DataTypes.BINARY:
boolean bool = b.getBoolean();
dataValue = new BinaryValue(bool);
break;
case DataTypes.IMAGE:
try {
dataValue = new ImageValue(b.getString());
} catch (InvalidArgumentException e1) {
// Probably no file
}
break;
case DataTypes.MULTISTATE:
int i = b.getInt();
dataValue = new MultistateValue(i);
break;
case DataTypes.NUMERIC:
double d = b.getDouble();
dataValue = new NumericValue(d);
break;
default:
throw new ShouldNeverHappenException("Data type of " + dataType + " is not supported");
}
// Get the annotation
String annotation = b.getString();
if (annotation != null) {
try {
return new AnnotatedPointValueTime(dataValue, ts, TranslatableMessage.deserialize(annotation));
} catch (Exception e) {
throw new ShouldNeverHappenException(e);
}
} else {
return new PointValueTime(dataValue, ts);
}
}
use of com.serotonin.InvalidArgumentException in project ma-modules-public by infiniteautomation.
the class ReportWorkItem method execute.
@Override
public void execute() {
try {
ReportLicenseChecker.checkLicense();
} catch (LicenseViolatedException e) {
LOG.error("Your core license doesn't permit you to use the reports module.");
reportInstance.setReportStartTime(Common.timer.currentTimeMillis());
reportInstance.setReportEndTime(Common.timer.currentTimeMillis());
reportInstance.setRecordCount(-1);
reportDao.saveReportInstance(reportInstance);
return;
}
LOG.debug("Running report with id " + reportConfig.getId() + ", instance id " + reportInstance.getId());
reportInstance.setRunStartTime(System.currentTimeMillis());
reportDao.saveReportInstance(reportInstance);
Translations translations = Common.getTranslations();
// Create a list of DataPointVOs to which the user has permission.
DataPointDao dataPointDao = DataPointDao.instance;
List<ReportDao.PointInfo> points = new ArrayList<ReportDao.PointInfo>(reportConfig.getPoints().size());
for (ReportPointVO reportPoint : reportConfig.getPoints()) {
DataPointVO point = dataPointDao.getDataPoint(reportPoint.getPointId());
if (point != null && Permissions.hasDataPointReadPermission(user, point)) {
String colour = null;
try {
if (!StringUtils.isBlank(reportPoint.getColour()))
colour = ColorUtils.toHexString(reportPoint.getColour()).substring(1);
} catch (InvalidArgumentException e) {
// Should never happen since the colour would have been validated on save, so just let it go
// as null.
}
points.add(new ReportDao.PointInfo(point, colour, reportPoint.getWeight(), reportPoint.isConsolidatedChart(), reportPoint.getPlotType()));
}
}
int recordCount = 0;
try {
if (!points.isEmpty()) {
if (Common.databaseProxy.getNoSQLProxy() == null)
recordCount = reportDao.runReportSQL(reportInstance, points);
else
recordCount = reportDao.runReportNoSQL(reportInstance, points);
}
} catch (RuntimeException e) {
recordCount = -1;
throw e;
} catch (Throwable e) {
recordCount = -1;
throw new RuntimeException("Report instance failed", e);
} finally {
reportInstance.setRunEndTime(System.currentTimeMillis());
reportInstance.setRecordCount(recordCount);
reportDao.saveReportInstance(reportInstance);
}
if (reportConfig.isEmail()) {
String inlinePrefix = "R" + System.currentTimeMillis() + "-" + reportInstance.getId() + "-";
// TODO should we create different instances of the email based upon language and timezone?
// We are creating an email from the result. Create the content.
final ReportChartCreator creator = new ReportChartCreator(translations, TimeZone.getDefault());
creator.createContent(host, port, reportInstance, reportDao, inlinePrefix, reportConfig.isIncludeData());
// Create the to list
Set<String> addresses = MailingListDao.instance.getRecipientAddresses(reportConfig.getRecipients(), new DateTime(reportInstance.getReportStartTime()));
String[] toAddrs = addresses.toArray(new String[0]);
// Create the email content object.
EmailContent emailContent = new EmailContent(null, creator.getHtml(), Common.UTF8);
// Add the consolidated chart
if (creator.getImageData() != null)
emailContent.addInline(new EmailInline.ByteArrayInline(inlinePrefix + ReportChartCreator.IMAGE_CONTENT_ID, creator.getImageData(), ImageChartUtils.getContentType()));
// Add the point charts
for (PointStatistics pointStatistics : creator.getPointStatistics()) {
if (pointStatistics.getImageData() != null)
emailContent.addInline(new EmailInline.ByteArrayInline(inlinePrefix + pointStatistics.getChartName(), pointStatistics.getImageData(), ImageChartUtils.getContentType()));
}
// Add optional images used by the template.
for (String s : creator.getInlineImageList()) addImage(emailContent, s);
// Check if we need to attach the data.
if (reportConfig.isIncludeData()) {
addFileAttachment(emailContent, reportInstance.getName() + ".csv", creator.getExportFile());
addFileAttachment(emailContent, reportInstance.getName() + "Events.csv", creator.getEventFile());
addFileAttachment(emailContent, reportInstance.getName() + "Comments.csv", creator.getCommentFile());
}
PostEmailRunnable[] postEmail = null;
if (reportConfig.isIncludeData()) {
// See that the temp file(s) gets deleted after the email is sent.
PostEmailRunnable deleteTempFile = new PostEmailRunnable() {
@Override
public void run() {
for (File file : filesToDelete) {
if (!file.delete())
LOG.warn("Temp file " + file.getPath() + " not deleted");
}
}
};
postEmail = new PostEmailRunnable[] { deleteTempFile };
}
try {
TranslatableMessage lm = new TranslatableMessage("ftl.scheduledReport", reportConfig.getName());
String subject = creator.getSubject();
if (subject == null)
subject = lm.translate(translations);
EmailWorkItem.queueEmail(toAddrs, subject, emailContent, postEmail);
} catch (AddressException e) {
LOG.error(e);
}
if (reportConfig.isSchedule()) {
// Delete the report instance.
reportDao.deleteReportInstance(reportInstance.getId(), user.getId());
}
}
LOG.debug("Finished running report with id " + reportConfig.getId() + ", instance id " + reportInstance.getId());
}
Aggregations