Package com.serotonin.m2m2.rt.script

Examples of com.serotonin.m2m2.rt.script.ScriptExecutor


        SerialDataSourceVO ds = (SerialDataSourceVO) Common.getUser().getEditDataSource();
        if(ds.getId() == -1) {
          pr.addContextualMessage("testString", "serial.test.needsSave");
          return pr;
        }
        DataPointDao dpd = new DataPointDao();
        List<DataPointVO> points = dpd.getDataPoints(ds.getId(), null);
        if(ds.getUseTerminator()) {
          if(msg.indexOf(ds.getMessageTerminator()) != -1) {
            msg = msg.substring(0, msg.indexOf(ds.getMessageTerminator())+1);
            Pattern p = Pattern.compile(ds.getMessageRegex());
            Matcher m = p.matcher(msg);
View Full Code Here


        return null;
    }

    private int importCsv(FileItem item) throws IOException, TranslatableException {
        CSVReader csvReader = new CSVReader(new InputStreamReader(item.getInputStream()));
        DataPointDao dataPointDao = new DataPointDao();
        PointValueDao pointValueDao = Common.databaseProxy.newPointValueDao();
        DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss");

        // Basic validation
        String[] nextLine = csvReader.readNext();
        if (nextLine == null)
            throw new TranslatableException(new TranslatableMessage("dataImport.import.noData"));
        if (nextLine.length < 2)
            throw new TranslatableException(new TranslatableMessage("dataImport.import.noPoints"));

        // Find the points by XID
        DataPointVO[] vos = new DataPointVO[nextLine.length - 1];

        for (int i = 1; i < nextLine.length; i++) {
            if (StringUtils.isBlank(nextLine[i]))
                throw new TranslatableException(new TranslatableMessage("dataImport.import.badXid", i));

            DataPointVO vo = dataPointDao.getDataPoint(nextLine[i]);
            if (vo == null)
                throw new TranslatableException(new TranslatableMessage("dataImport.import.xidNotFound", nextLine[i]));

            vos[i - 1] = vo;
        }
View Full Code Here

      Common.runtimeManager.saveDataSource(ds);
    else
      throw new RuntimeException("Invalid data!");
   
   
    DataPointDao dpDao = new DataPointDao();
    //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<PointEventDetectorVO>(0));
View Full Code Here

    }

    private int importCsv(FileItem item) throws IOException, TranslatableException {
        CSVReader csvReader = new CSVReader(new InputStreamReader(item.getInputStream()));
        DataPointDao dataPointDao = new DataPointDao();
        PointValueDao pointValueDao = Common.databaseProxy.newPointValueDao();
        DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss");

        // Basic validation
        String[] nextLine = csvReader.readNext();
        if (nextLine == null)
            throw new TranslatableException(new TranslatableMessage("dataImport.import.noData"));
        if (nextLine.length < 2)
            throw new TranslatableException(new TranslatableMessage("dataImport.import.noPoints"));

        // Find the points by XID
        DataPointVO[] vos = new DataPointVO[nextLine.length - 1];

        for (int i = 1; i < nextLine.length; i++) {
            if (StringUtils.isBlank(nextLine[i]))
                throw new TranslatableException(new TranslatableMessage("dataImport.import.badXid", i));

            DataPointVO vo = dataPointDao.getDataPoint(nextLine[i]);
            if (vo == null)
                throw new TranslatableException(new TranslatableMessage("dataImport.import.xidNotFound", nextLine[i]));

            vos[i - 1] = vo;
        }

        // Find the RTs for the points if they are enabled
        DataPointRT[] rts = new DataPointRT[vos.length];
        for (int i = 0; i < vos.length; i++)
            rts[i] = Common.runtimeManager.getDataPoint(vos[i].getId());

        // Import the data
        int count = 0;
        while ((nextLine = csvReader.readNext()) != null) {
            // The first value is always a date.
            long time = dtf.parseDateTime(nextLine[0]).getMillis();

            // The rest of the values are point samples.
            for (int i = 1; i < nextLine.length; i++) {
                DataValue value = DataValue.stringToValue(nextLine[i], vos[i - 1].getPointLocator().getDataTypeId());
                PointValueTime pvt = new PointValueTime(value, time);

                if (rts[i - 1] != null)
                    rts[i - 1].savePointValueDirectToCache(pvt, null, true, true);
                else
                    // Save directly to the database
                    pointValueDao.savePointValueAsync(vos[i - 1].getId(), pvt, null);
            }

            count++;
        }
View Full Code Here

        pointStatistics = handler.getPointStatistics();
    devices = handler.getDevices();
    pointMap = handler.getStatisticsMap();
        UsedImagesDirective inlineImages = new UsedImagesDirective();
        SubjectDirective subjectDirective = new SubjectDirective(translations);

        // Prepare the model for the content rendering.
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("fmt", new MessageFormatDirective(translations));
        model.put("subject", subjectDirective);
        model.put("img", inlineImages);
        model.put("instance", reportInstance);
        model.put("timezone", timeZone.getID());
        model.put("points", pointStatistics);
        model.put("inline", inlinePrefix == null ? "" : "cid:");
    model.put("devices", devices);
    model.put("mapped", pointMap);

        model.put("ALPHANUMERIC", DataTypes.ALPHANUMERIC);
        model.put("BINARY", DataTypes.BINARY);
        model.put("MULTISTATE", DataTypes.MULTISTATE);
        model.put("NUMERIC", DataTypes.NUMERIC);
        model.put("IMAGE", DataTypes.IMAGE);

        // Create the individual point charts
        for (PointStatistics pointStat : pointStatistics) {
            PointTimeSeriesCollection ptsc = new PointTimeSeriesCollection(timeZone);

            if (pointStat.getNumericTimeSeries() != null)
                ptsc.addNumericTimeSeries(pointStat.getNumericTimeSeries().plainCopy());
            else if (pointStat.getDiscreteTimeSeries() != null)
                ptsc.addDiscreteTimeSeries(pointStat.getDiscreteTimeSeries().plainCopy());

            if (ptsc.hasData()) {
                if (inlinePrefix != null)
                    model.put("chartName", inlinePrefix + pointStat.getChartName());
                pointStat.setImageData(ImageChartUtils.getChartData(ptsc, POINT_IMAGE_WIDTH, POINT_IMAGE_HEIGHT,
                        reportInstance.getReportStartTime(), reportInstance.getReportEndTime()));
            }
        }

        PointTimeSeriesCollection ptsc = handler.getPointTimeSeriesCollection();
        if (ptsc.hasData()) {
            if (inlinePrefix != null)
                model.put("chartName", inlinePrefix + IMAGE_CONTENT_ID);
            else {
                chartName = "r" + reportInstance.getId() + ".png";
                // The path comes from the servlet path definition in web.xml.
                model.put("chartName", IMAGE_SERVLET + chartName);
            }

            imageData = ImageChartUtils.getChartData(ptsc, true, IMAGE_WIDTH, IMAGE_HEIGHT,
                    reportInstance.getReportStartTime(), reportInstance.getReportEndTime());
        }

        List<EventInstance> events = null;
        if (reportInstance.getIncludeEvents() != ReportVO.EVENTS_NONE) {
            events = reportDao.getReportInstanceEvents(reportInstance.getId());
            model.put("includeEvents", true);
            model.put("events", events);
        }
        else
            model.put("includeEvents", false);

        List<ReportUserComment> comments = null;
        if (reportInstance.isIncludeUserComments()) {
            comments = reportDao.getReportInstanceUserComments(reportInstance.getId());

            // Only provide the list of point comments to the report. The event comments have already be correlated
            // into the events list.
            List<ReportUserComment> pointComments = new ArrayList<ReportUserComment>();
            for (ReportUserComment c : comments) {
                if (c.getCommentType() == UserComment.TYPE_POINT)
                    pointComments.add(c);
            }

            model.put("includeUserComments", true);
            model.put("userComments", pointComments);
        }
        else
            model.put("includeUserComments", false);

        // Create the template.
        Template template;
        try {
            template = Common.freemarkerConfiguration.getTemplate(reportInstance.getTemplateFile());
        }
        catch (IOException e) {
            // Couldn't load the template?
            throw new ShouldNeverHappenException(e);
        }

        // Create the content from the template.
        StringWriter writer = new StringWriter();
        try {
            template.process(model, writer);
        }
        catch (Exception e) {
            // Couldn't process the template?
            throw new ShouldNeverHappenException(e);
        }

        // Save the content
        html = writer.toString();
        subject = subjectDirective.getSubject();
        inlineImageList = inlineImages.getImageList();

        // Save the export file (if any)
        exportFile = handler.exportFile;
View Full Code Here

          reportDao.reportInstanceDataNoSQL(reportInstance.getId(), handler);

        pointStatistics = handler.getPointStatistics();
    devices = handler.getDevices();
    pointMap = handler.getStatisticsMap();
        UsedImagesDirective inlineImages = new UsedImagesDirective();
        SubjectDirective subjectDirective = new SubjectDirective(translations);

        // Prepare the model for the content rendering.
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("fmt", new MessageFormatDirective(translations));
        model.put("subject", subjectDirective);
        model.put("img", inlineImages);
        model.put("instance", reportInstance);
        model.put("timezone", timeZone.getID());
        model.put("points", pointStatistics);
        model.put("inline", inlinePrefix == null ? "" : "cid:");
    model.put("devices", devices);
    model.put("mapped", pointMap);

        model.put("ALPHANUMERIC", DataTypes.ALPHANUMERIC);
        model.put("BINARY", DataTypes.BINARY);
        model.put("MULTISTATE", DataTypes.MULTISTATE);
        model.put("NUMERIC", DataTypes.NUMERIC);
        model.put("IMAGE", DataTypes.IMAGE);

        // Create the individual point charts
        for (PointStatistics pointStat : pointStatistics) {
            PointTimeSeriesCollection ptsc = new PointTimeSeriesCollection(timeZone);

            if (pointStat.getNumericTimeSeries() != null)
                ptsc.addNumericTimeSeries(pointStat.getNumericTimeSeries().plainCopy());
            else if (pointStat.getDiscreteTimeSeries() != null)
                ptsc.addDiscreteTimeSeries(pointStat.getDiscreteTimeSeries().plainCopy());

            if (ptsc.hasData()) {
                if (inlinePrefix != null)
                    model.put("chartName", inlinePrefix + pointStat.getChartName());
                pointStat.setImageData(ImageChartUtils.getChartData(ptsc, POINT_IMAGE_WIDTH, POINT_IMAGE_HEIGHT,
                        reportInstance.getReportStartTime(), reportInstance.getReportEndTime()));
            }
        }

        PointTimeSeriesCollection ptsc = handler.getPointTimeSeriesCollection();
        if (ptsc.hasData()) {
            if (inlinePrefix != null)
                model.put("chartName", inlinePrefix + IMAGE_CONTENT_ID);
            else {
                chartName = "r" + reportInstance.getId() + ".png";
                // The path comes from the servlet path definition in web.xml.
                model.put("chartName", IMAGE_SERVLET + chartName);
            }

            imageData = ImageChartUtils.getChartData(ptsc, true, IMAGE_WIDTH, IMAGE_HEIGHT,
                    reportInstance.getReportStartTime(), reportInstance.getReportEndTime());
        }

        List<EventInstance> events = null;
        if (reportInstance.getIncludeEvents() != ReportVO.EVENTS_NONE) {
            events = reportDao.getReportInstanceEvents(reportInstance.getId());
            model.put("includeEvents", true);
            model.put("events", events);
        }
        else
            model.put("includeEvents", false);

        List<ReportUserComment> comments = null;
        if (reportInstance.isIncludeUserComments()) {
            comments = reportDao.getReportInstanceUserComments(reportInstance.getId());

            // Only provide the list of point comments to the report. The event comments have already be correlated
            // into the events list.
            List<ReportUserComment> pointComments = new ArrayList<ReportUserComment>();
            for (ReportUserComment c : comments) {
                if (c.getCommentType() == UserComment.TYPE_POINT)
                    pointComments.add(c);
            }

            model.put("includeUserComments", true);
            model.put("userComments", pointComments);
        }
        else
            model.put("includeUserComments", false);

        // Create the template.
        Template template;
        try {
            template = Common.freemarkerConfiguration.getTemplate(reportInstance.getTemplateFile());
        }
        catch (IOException e) {
            // Couldn't load the template?
            throw new ShouldNeverHappenException(e);
        }

        // Create the content from the template.
        StringWriter writer = new StringWriter();
        try {
            template.process(model, writer);
        }
        catch (Exception e) {
            // Couldn't process the template?
            throw new ShouldNeverHappenException(e);
        }

        // Save the content
        html = writer.toString();
        subject = subjectDirective.getSubject();
        inlineImageList = inlineImages.getImageList();

        // Save the export file (if any)
        exportFile = handler.exportFile;

        if (createExportFile && events != null) {
View Full Code Here

            int fromMonth, int fromDay, int fromHour, int fromMinute, boolean toNone, int toYear, int toMonth,
            int toDay, int toHour, int toMinute, boolean schedule, int schedulePeriod, int runDelayMinutes,
            String scheduleCron, boolean email, boolean includeData, boolean zipData,
            List<RecipientListEntryBean> recipients) {

        ProcessResult response = new ProcessResult();

        // Basic validation
        validateData(response, name, points, dateRangeType, relativeDateType, previousPeriodCount, pastPeriodCount);

        if (schedule) {
            if (schedulePeriod == ReportVO.SCHEDULE_CRON) {
                // Check the cron pattern.
                try {
                    new CronTimerTrigger(scheduleCron);
                }
                catch (Exception e) {
                    response.addContextualMessage("scheduleCron", "reports.validate.cron", e.getMessage());
                }
            }
            else {
                if (runDelayMinutes < 0)
                    response.addContextualMessage("runDelayMinutes", "reports.validate.lessThan0");
                else if (runDelayMinutes > 59)
                    response.addContextualMessage("runDelayMinutes", "reports.validate.greaterThan59");
            }
        }

        if (schedule && email && recipients.isEmpty())
            response.addContextualMessage("recipients", "reports.validate.needRecip");

        if (response.getHasMessages())
            return response;

        User user = Common.getUser();
        ReportDao reportDao = new ReportDao();
        ReportVO report;
        if (id == Common.NEW_ID) {
            report = new ReportVO();
            report.setUserId(user.getId());
        }
        else
            report = reportDao.getReport(id);
       
        ReportCommon.ensureReportPermission(user, report);

        // Update the new values.
        report.setXid(xid);
        report.setName(name);
        report.setPoints(points);
        report.setTemplate(template);
        report.setIncludeEvents(includeEvents);
        report.setIncludeUserComments(includeUserComments);
        report.setDateRangeType(dateRangeType);
        report.setRelativeDateType(relativeDateType);
        report.setPreviousPeriodCount(previousPeriodCount);
        report.setPreviousPeriodType(previousPeriodType);
        report.setPastPeriodCount(pastPeriodCount);
        report.setPastPeriodType(pastPeriodType);
        report.setFromNone(fromNone);
        report.setFromYear(fromYear);
        report.setFromMonth(fromMonth);
        report.setFromDay(fromDay);
        report.setFromHour(fromHour);
        report.setFromMinute(fromMinute);
        report.setToNone(toNone);
        report.setToYear(toYear);
        report.setToMonth(toMonth);
        report.setToDay(toDay);
        report.setToHour(toHour);
        report.setToMinute(toMinute);
        report.setSchedule(schedule);
        report.setSchedulePeriod(schedulePeriod);
        report.setRunDelayMinutes(runDelayMinutes);
        report.setScheduleCron(scheduleCron);
        report.setEmail(email);
        report.setIncludeData(includeData);
        report.setZipData(zipData);
        report.setRecipients(recipients);

        // Save the report
        reportDao.saveReport(report);

        // Conditionally schedule the report.
        ReportJob.scheduleReportJob(report);

        // Send back the report id in case this was new.
        response.addData("reportId", report.getId());
        response.addData("report", report);
        return response;
    }
View Full Code Here

            boolean includeUserComments, int dateRangeType, int relativeDateType, int previousPeriodCount,
            int previousPeriodType, int pastPeriodCount, int pastPeriodType, boolean fromNone, int fromYear,
            int fromMonth, int fromDay, int fromHour, int fromMinute, boolean toNone, int toYear, int toMonth,
            int toDay, int toHour, int toMinute, boolean email, boolean includeData, boolean zipData,
            List<RecipientListEntryBean> recipients) {
        ProcessResult response = new ProcessResult();

        // Basic validation
        //TODO Replace with vo.validate()
        validateData(response, name, points, dateRangeType, relativeDateType, previousPeriodCount, pastPeriodCount);

        if (!response.getHasMessages()) {
            ReportVO report = new ReportVO();
            report.setXid(xid);
            report.setName(name);
            report.setUserId(Common.getUser().getId());
            report.setPoints(points);
View Full Code Here

        return StringEscapeUtils.escapeJava(ds.getMessageTerminator());
      }
     
      @DwrPermission(user = true)
      public ProcessResult testString(String raw) {
        ProcessResult pr = new ProcessResult();
        String msg = StringEscapeUtils.unescapeJava(raw);
        SerialDataSourceVO ds = (SerialDataSourceVO) Common.getUser().getEditDataSource();
        if(ds.getId() == -1) {
          pr.addContextualMessage("testString", "serial.test.needsSave");
          return pr;
        }
        DataPointDao dpd = new DataPointDao();
        List<DataPointVO> points = dpd.getDataPoints(ds.getId(), null);
        if(ds.getUseTerminator()) {
          if(msg.indexOf(ds.getMessageTerminator()) != -1) {
            msg = msg.substring(0, msg.indexOf(ds.getMessageTerminator())+1);
            Pattern p = Pattern.compile(ds.getMessageRegex());
            Matcher m = p.matcher(msg);
            if(!m.matches()) {
              pr.addContextualMessage("testString", "serial.test.noMessageMatch");
              return pr;
            }
            String identifier = m.group(ds.getPointIdentifierIndex());
            for(DataPointVO pnt : points) {
              SerialPointLocatorVO plVo = (SerialPointLocatorVO) pnt.getPointLocator();
              if(identifier.equals(plVo.getPointIdentifier())) {
                Pattern v = Pattern.compile(plVo.getValueRegex());
                Matcher vm = v.matcher(msg);
                if(vm.find())
                  pr.addContextualMessage("testString", "serial.test.consumed", pnt.getName(), vm.group(0));
              }
               
            }
          }
          else {
            pr.addContextualMessage("testString", "serial.test.noTerminator");
            return pr;
          }
        }
        else {
          for(DataPointVO pnt : points) {
            SerialPointLocatorVO plVo = (SerialPointLocatorVO) pnt.getPointLocator();
            Pattern p = Pattern.compile(plVo.getValueRegex());
            Matcher m = p.matcher(msg);
            if(m.find())
              pr.addContextualMessage("testString", "serial.test.consumed", pnt.getName(), m.group(0));         
          }
        }
        return pr;
      }
View Full Code Here

        se.setInactiveHour(inactiveHour);
        se.setInactiveMinute(inactiveMinute);
        se.setInactiveSecond(inactiveSecond);
        se.setInactiveCron(inactiveCron);

        ProcessResult response = new ProcessResult();
        ScheduledEventDao scheduledEventDao = new ScheduledEventDao();

        if (StringUtils.isBlank(xid))
            response.addContextualMessage("xid", "validate.required");
        else if (!scheduledEventDao.isXidUnique(xid, id))
            response.addContextualMessage("xid", "validate.xidUsed");

        se.validate(response);

        // Save the scheduled event
        if (!response.getHasMessages())
            RTMDefinition.instance.saveScheduledEvent(se);

        response.addData("seId", se.getId());
        return response;
    }
View Full Code Here

TOP

Related Classes of com.serotonin.m2m2.rt.script.ScriptExecutor

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.