use of com.serotonin.m2m2.db.dao.DataPointDao 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());
}
use of com.serotonin.m2m2.db.dao.DataPointDao in project ma-modules-public by infiniteautomation.
the class ReportsDwr method createReportFromWatchlist.
@DwrPermission(custom = ReportPermissionDefinition.PERMISSION)
public ReportVO createReportFromWatchlist(String name, int[] dataPointIds) {
ReportVO report = new ReportVO();
User user = Common.getUser();
report.setName(new TranslatableMessage("common.copyPrefix", name).translate(getTranslations()));
report.setXid(Common.generateXid("REP_"));
DataPointDao dataPointDao = DataPointDao.instance;
for (int id : dataPointIds) {
DataPointVO dp = dataPointDao.getDataPoint(id, false);
if (dp == null || !Permissions.hasDataPointReadPermission(user, dp))
continue;
ReportPointVO rp = new ReportPointVO();
rp.setPointId(dp.getId());
rp.setPointKey("p" + dp.getId());
rp.setColour(dp.getChartColour());
rp.setConsolidatedChart(true);
rp.setPlotType(dp.getPlotType());
report.getPoints().add(rp);
}
return report;
}
use of com.serotonin.m2m2.db.dao.DataPointDao in project ma-modules-public by infiniteautomation.
the class ReportsDwr method validateData.
private void validateData(ProcessResult response, String name, List<ReportPointVO> points, int dateRangeType, int relativeDateType, int previousPeriodCount, int pastPeriodCount) {
if (StringUtils.isBlank(name))
response.addContextualMessage("name", "reports.validate.required");
if (StringValidation.isLengthGreaterThan(name, 100))
response.addContextualMessage("name", "reports.validate.longerThan100");
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");
User user = Common.getUser();
DataPointDao dataPointDao = DataPointDao.instance;
for (ReportPointVO point : points) {
Permissions.ensureDataPointReadPermission(user, dataPointDao.getDataPoint(point.getPointId(), false));
try {
if (!StringUtils.isBlank(point.getColour()))
ColorUtils.toColor(point.getColour());
} catch (InvalidArgumentException e) {
response.addContextualMessage("points", "reports.validate.colour", point.getColour());
}
if (point.getWeight() <= 0)
response.addContextualMessage("points", "reports.validate.weight");
}
}
use of com.serotonin.m2m2.db.dao.DataPointDao in project ma-modules-public by infiniteautomation.
the class SerialEditDwr method testString.
@DwrPermission(user = true)
public ProcessResult testString(String raw, int dsId, String messageRegex, String messageTerminator, int pointIdentifierIndex, boolean isHex, boolean useTerminator) {
final ProcessResult pr = new ProcessResult();
// Message we will work with
String msg;
if (dsId == -1) {
pr.addContextualMessage("testString", "serial.test.needsSave");
return pr;
}
msg = StringEscapeUtils.unescapeJava(raw);
messageRegex = StringEscapeUtils.unescapeJava(messageRegex);
messageTerminator = StringEscapeUtils.unescapeJava(messageTerminator);
// Are we a hex string
if (isHex) {
if (!msg.matches("[0-9A-Fa-f]+")) {
pr.addContextualMessage("testString", "serial.validate.notHex");
return pr;
}
}
// Map to store the values vs the points they are for
final List<Map<String, String>> results = new ArrayList<Map<String, String>>();
pr.addData("results", results);
DataPointDao dpd = DataPointDao.instance;
List<DataPointVO> points = dpd.getDataPoints(dsId, null);
if (useTerminator) {
// Convert the message
String[] messages = SerialDataSourceRT.splitMessages(msg, messageTerminator);
for (String message : messages) {
if (SerialDataSourceRT.canProcessTerminatedMessage(message, messageTerminator)) {
if (LOG.isDebugEnabled())
LOG.debug("Matching will use String: " + message);
// Check all the points
for (final DataPointVO vo : points) {
final Map<String, String> result = new HashMap<String, String>();
MatchCallback callback = new MatchCallback() {
@Override
public void onMatch(String pointIdentifier, PointValueTime pvt) {
result.put("name", vo.getName());
result.put("value", pvt.toString());
result.put("identifier", pointIdentifier);
result.put("success", "true");
}
@Override
public void pointPatternMismatch(String message, String messageRegex) {
result.put("success", "false");
result.put("name", vo.getName());
result.put("error", new TranslatableMessage("serial.test.noPointRegexMatch").translate(Common.getTranslations()));
}
@Override
public void messagePatternMismatch(String message, String messageRegex) {
result.put("success", "false");
result.put("name", vo.getName());
result.put("error", new TranslatableMessage("serial.test.noMessageMatch").translate(Common.getTranslations()));
}
@Override
public void pointNotIdentified(String message, String messageRegex, int pointIdentifierIndex) {
result.put("success", "false");
result.put("name", vo.getName());
result.put("error", new TranslatableMessage("serial.test.noIdentifierFound").translate(Common.getTranslations()));
}
/* (non-Javadoc)
* @see com.infiniteautomation.mango.regex.MatchCallback#matchGeneralFailure(java.lang.Exception)
*/
@Override
public void matchGeneralFailure(Exception e) {
result.put("success", "false");
result.put("name", vo.getName());
result.put("error", new TranslatableMessage("common.default", e.getMessage()).translate(Common.getTranslations()));
}
};
try {
SerialDataSourceRT.matchPointValue(message, messageRegex, pointIdentifierIndex, (SerialPointLocatorVO) vo.getPointLocator(), isHex, LOG, callback);
} catch (Exception e) {
callback.matchGeneralFailure(e);
}
if (result.size() > 0) {
result.put("message", message);
results.add(result);
}
}
} else {
Map<String, String> result = new HashMap<String, String>();
result.put("success", "false");
result.put("message", message);
result.put("error", new TranslatableMessage("serial.test.noTerminator").translate(Common.getTranslations()));
results.add(result);
}
}
} else {
if (LOG.isDebugEnabled())
LOG.debug("Matching will use String: " + msg);
// Check all the points
for (final DataPointVO vo : points) {
final Map<String, String> result = new HashMap<String, String>();
MatchCallback callback = new MatchCallback() {
@Override
public void onMatch(String pointIdentifier, PointValueTime pvt) {
result.put("name", vo.getName());
result.put("value", pvt.toString());
result.put("identifier", pointIdentifier);
result.put("success", "true");
}
@Override
public void pointPatternMismatch(String message, String messageRegex) {
result.put("success", "false");
result.put("name", vo.getName());
result.put("error", new TranslatableMessage("serial.test.noPointRegexMatch").translate(Common.getTranslations()));
}
@Override
public void messagePatternMismatch(String message, String messageRegex) {
result.put("success", "false");
result.put("name", vo.getName());
result.put("error", new TranslatableMessage("serial.test.noMessageMatch").translate(Common.getTranslations()));
}
@Override
public void pointNotIdentified(String message, String messageRegex, int pointIdentifierIndex) {
result.put("success", "false");
result.put("name", vo.getName());
result.put("error", new TranslatableMessage("serial.test.noIdentifierFound").translate(Common.getTranslations()));
}
/* (non-Javadoc)
* @see com.infiniteautomation.mango.regex.MatchCallback#matchGeneralFailure(java.lang.Exception)
*/
@Override
public void matchGeneralFailure(Exception e) {
result.put("success", "false");
result.put("name", vo.getName());
result.put("error", new TranslatableMessage("common.default", e.getMessage()).translate(Common.getTranslations()));
}
};
try {
SerialDataSourceRT.matchPointValue(msg, messageRegex, pointIdentifierIndex, (SerialPointLocatorVO) vo.getPointLocator(), isHex, LOG, callback);
} catch (Exception e) {
callback.matchGeneralFailure(e);
}
if (result.size() > 0) {
result.put("message", msg);
results.add(result);
}
}
}
return pr;
}
use of com.serotonin.m2m2.db.dao.DataPointDao in project ma-modules-public by infiniteautomation.
the class VirtualEditDwr method createTestSource.
/**
* Test Method for debugging system.
*/
@DwrPermission(admin = true)
public void createTestSource() {
VirtualDataSourceVO ds = new VirtualDataSourceVO();
DataSourceDefinition def = ModuleRegistry.getDataSourceDefinition("VIRTUAL");
ds = (VirtualDataSourceVO) def.baseCreateDataSourceVO();
ds.setId(Common.NEW_ID);
ds.setXid(DataSourceDao.instance.generateUniqueXid());
ds.setName("Test Virtual");
ds.setEnabled(true);
ds.setUpdatePeriods(5);
ds.setUpdatePeriodType(TimePeriods.SECONDS);
ds.setPolling(true);
ProcessResult response = new ProcessResult();
ds.validate(response);
if (!response.getHasMessages())
Common.runtimeManager.saveDataSource(ds);
else
throw new RuntimeException("Invalid data!");
DataPointDao dpDao = DataPointDao.instance;
// Create Test Points
for (int i = 0; i < 10; i++) {
VirtualPointLocatorVO pointLocator = ds.createPointLocator();
// Create a Random Points
pointLocator.setDataTypeId(DataTypes.NUMERIC);
pointLocator.setChangeTypeId(ChangeTypeVO.Types.RANDOM_ANALOG);
pointLocator.getRandomAnalogChange().setMin(0);
pointLocator.getRandomAnalogChange().setMax(100);
pointLocator.getRandomAnalogChange().setStartValue("1");
pointLocator.setSettable(true);
DataPointVO dp = new DataPointVO();
dp.setXid(dpDao.generateUniqueXid());
dp.setName("Virtual Random " + i);
dp.setDataSourceId(ds.getId());
dp.setDataSourceTypeName(ds.getDefinition().getDataSourceTypeName());
dp.setDeviceName(ds.getName());
dp.setEventDetectors(new ArrayList<AbstractPointEventDetectorVO<?>>(0));
dp.defaultTextRenderer();
// Setup the Chart Renderer
ImageChartRenderer chartRenderer = new ImageChartRenderer(TimePeriods.DAYS, 5);
dp.setChartRenderer(chartRenderer);
dp.setPointLocator(pointLocator);
dp.setEnabled(true);
dp.setSettable(true);
dp.setDefaultCacheSize(0);
dp.validate(response);
if (!response.getHasMessages())
Common.runtimeManager.saveDataPoint(dp);
else
throw new RuntimeException("Invalid data!");
}
}
Aggregations