Search in sources :

Example 1 with TranslatableMessage

use of com.serotonin.m2m2.i18n.TranslatableMessage in project ma-modules-public by infiniteautomation.

the class ScheduledEventVO method getDescription.

public TranslatableMessage getDescription() {
    TranslatableMessage message;
    if (!StringUtils.isBlank(alias))
        message = new TranslatableMessage("common.default", alias);
    else if (scheduleType == TYPE_ONCE) {
        if (returnToNormal)
            message = new TranslatableMessage("event.schedule.onceUntil", Functions.getTime(new DateTime(activeYear, activeMonth, activeDay, activeHour, activeMinute, activeSecond, 0).getMillis()), Functions.getTime(new DateTime(inactiveYear, inactiveMonth, inactiveDay, inactiveHour, inactiveMinute, inactiveSecond, 0).getMillis()));
        else
            message = new TranslatableMessage("event.schedule.onceAt", Functions.getTime(new DateTime(activeYear, activeMonth, activeDay, activeHour, activeMinute, activeSecond, 0).getMillis()));
    } else if (scheduleType == TYPE_HOURLY) {
        String activeTime = StringUtils.leftPad(Integer.toString(activeMinute), 2, '0') + ":" + StringUtils.leftPad(Integer.toString(activeSecond), 2, '0');
        if (returnToNormal)
            message = new TranslatableMessage("event.schedule.hoursUntil", activeTime, StringUtils.leftPad(Integer.toString(inactiveMinute), 2, '0') + ":" + StringUtils.leftPad(Integer.toString(inactiveSecond), 2, '0'));
        else
            message = new TranslatableMessage("event.schedule.hoursAt", activeTime);
    } else if (scheduleType == TYPE_DAILY) {
        if (returnToNormal)
            message = new TranslatableMessage("event.schedule.dailyUntil", activeTime(), inactiveTime());
        else
            message = new TranslatableMessage("event.schedule.dailyAt", activeTime());
    } else if (scheduleType == TYPE_WEEKLY) {
        if (returnToNormal)
            message = new TranslatableMessage("event.schedule.weeklyUntil", weekday(true), activeTime(), weekday(false), inactiveTime());
        else
            message = new TranslatableMessage("event.schedule.weeklyAt", weekday(true), activeTime());
    } else if (scheduleType == TYPE_MONTHLY) {
        if (returnToNormal)
            message = new TranslatableMessage("event.schedule.monthlyUntil", monthday(true), activeTime(), monthday(false), inactiveTime());
        else
            message = new TranslatableMessage("event.schedule.monthlyAt", monthday(true), activeTime());
    } else if (scheduleType == TYPE_YEARLY) {
        if (returnToNormal)
            message = new TranslatableMessage("event.schedule.yearlyUntil", monthday(true), month(true), activeTime(), monthday(false), month(false), inactiveTime());
        else
            message = new TranslatableMessage("event.schedule.yearlyAt", monthday(true), month(true), activeTime());
    } else if (scheduleType == TYPE_CRON) {
        if (returnToNormal)
            message = new TranslatableMessage("event.schedule.cronUntil", activeCron, inactiveCron);
        else
            message = new TranslatableMessage("event.schedule.cronAt", activeCron);
    } else
        throw new ShouldNeverHappenException("Unknown schedule type: " + scheduleType);
    return message;
}
Also used : ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) DateTime(org.joda.time.DateTime)

Example 2 with TranslatableMessage

use of com.serotonin.m2m2.i18n.TranslatableMessage in project ma-modules-public by infiniteautomation.

the class SerialDataSourceRT method serialEvent.

@Override
public void serialEvent(SerialPortProxyEvent evt) {
    // Keep a lock on the buffer while we do this
    synchronized (this.buffer) {
        // If our port is dead, say so
        if (this.port == null) {
            raiseEvent(POINT_READ_EXCEPTION_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.serial.readFailedPortNotSetup"));
            return;
        }
        // String msg = null;
        try {
            // Don't read during timeout events as there could be no data and this would block till there is
            if (!(evt instanceof TimeoutSerialEvent)) {
                InputStream in = this.port.getInputStream();
                int data;
                // this may not be the full message, or may read multiple messages
                while ((data = in.read()) > -1) {
                    if (buffer.size() >= this.vo.getMaxMessageSize()) {
                        buffer.popAll();
                        raiseEvent(POINT_READ_EXCEPTION_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.serial.readFailed", "Max message size reached!"));
                        // Give up
                        return;
                    }
                    buffer.push(data);
                }
                // Log our buffer contents
                byte[] logMsg = buffer.peekAll();
                if (this.vo.isLogIO()) {
                    if (this.vo.isHex())
                        this.ioLog.log(true, logMsg);
                    else
                        this.ioLog.log("I: " + new String(logMsg, Common.UTF8_CS));
                }
                // Serial Event so setup a Timeout Task to fire after the message timeout
                if (this.buffer.size() > 0)
                    this.timeoutTask = new TimeoutTask(this.vo.getReadTimeout(), new SerialTimeoutClient(this));
            }
            // We either use a terminator and timeout OR just a Timeout
            if (vo.getUseTerminator()) {
                // If timeout then process the buffer
                // If serial event then read input and process buffer
                // "!([A-Z0-9]{3,3})([a-zA-Z])(.*);";
                String messageRegex = vo.getMessageRegex();
                // DS Information
                int pointIdentifierIndex = vo.getPointIdentifierIndex();
                // Create a String so we can use Regex and matching
                String msg = null;
                if (this.vo.isHex()) {
                    msg = convertFromHex(buffer.peekAll());
                } else {
                    msg = new String(buffer.peekAll(), Common.UTF8_CS);
                }
                // Now we have a string that contains the entire contents of the buffer,
                // split on terminator, keep it on the end of the message and process any full messages
                // and pop them from the buffer
                String[] messages = splitMessages(msg, this.vo.getMessageTerminator());
                for (String message : messages) {
                    // potentially be one incomplete message.
                    if (canProcessTerminatedMessage(message, this.vo.getMessageTerminator())) {
                        // Pop off this message
                        this.buffer.pop(message.length());
                        if (LOG.isDebugEnabled())
                            LOG.debug("Matching will use String: " + message);
                        final AtomicBoolean matcherFailed = new AtomicBoolean(false);
                        pointListChangeLock.readLock().lock();
                        try {
                            for (final DataPointRT dp : this.dataPoints) {
                                SerialPointLocatorVO plVo = dp.getVO().getPointLocator();
                                MatchCallback callback = new MatchCallback() {

                                    @Override
                                    public void onMatch(String pointIdentifier, PointValueTime value) {
                                        if (!updatePointValue(value, dp)) {
                                            matcherFailed.set(true);
                                            raiseEvent(POINT_READ_PATTERN_MISMATCH_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.serial.invalidValue", dp.getVO().getXid()));
                                        }
                                    }

                                    @Override
                                    public void pointPatternMismatch(String message, String messageRegex) {
                                    // Ignore as this just isn't a message we care about
                                    }

                                    @Override
                                    public void messagePatternMismatch(String message, String messageRegex) {
                                        raiseEvent(POINT_READ_PATTERN_MISMATCH_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.serial.patternMismatch", messageRegex, message));
                                        matcherFailed.set(true);
                                    }

                                    @Override
                                    public void pointNotIdentified(String message, String messageRegex, int pointIdentifierIndex) {
                                    // Don't Care
                                    }

                                    @Override
                                    public void matchGeneralFailure(Exception e) {
                                        raiseEvent(POINT_READ_EXCEPTION_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.serial.readFailed", e.getMessage()));
                                        matcherFailed.set(true);
                                    }
                                };
                                try {
                                    matchPointValue(message, messageRegex, pointIdentifierIndex, plVo, vo.isHex(), LOG, callback);
                                } catch (Exception e) {
                                    callback.matchGeneralFailure(e);
                                }
                            }
                        } finally {
                            pointListChangeLock.readLock().unlock();
                        }
                        // If no failures...
                        if (!matcherFailed.get())
                            returnToNormal(POINT_READ_PATTERN_MISMATCH_EVENT, System.currentTimeMillis());
                        returnToNormal(POINT_READ_EXCEPTION_EVENT, System.currentTimeMillis());
                    }
                    if (evt instanceof TimeoutSerialEvent) {
                        // Clear the buffer
                        this.buffer.popAll();
                    } else {
                        // Check to see if we have remaining data, if not cancel timeout
                        if (this.buffer.size() == 0)
                            this.timeoutTask.cancel();
                    }
                }
                return;
            } else {
                // Do we have a timeout generated message?
                if (evt instanceof TimeoutSerialEvent) {
                    String msg = null;
                    // We are a timeout event so we have a timeout, pop everything into the message and assume its a message
                    if (this.vo.isHex()) {
                        msg = convertFromHex(buffer.popAll());
                    } else {
                        msg = new String(buffer.popAll(), Common.UTF8_CS);
                    }
                    // Just do a match on the Entire Message because we are not using Terminator
                    // String messageRegex = ".*"; //Match everything
                    // int pointIdentifierIndex = 0; //Whole message
                    // "!([A-Z0-9]{3,3})([a-zA-Z])(.*);";
                    String messageRegex = vo.getMessageRegex();
                    // DS Information
                    int pointIdentifierIndex = vo.getPointIdentifierIndex();
                    if (LOG.isDebugEnabled())
                        LOG.debug("Matching will use String: " + msg);
                    final AtomicBoolean matcherFailed = new AtomicBoolean(false);
                    synchronized (pointListChangeLock) {
                        for (final DataPointRT dp : this.dataPoints) {
                            SerialPointLocatorVO plVo = dp.getVO().getPointLocator();
                            MatchCallback callback = new MatchCallback() {

                                @Override
                                public void onMatch(String pointIdentifier, PointValueTime pvt) {
                                    if (!updatePointValue(pvt, dp)) {
                                        matcherFailed.set(true);
                                        raiseEvent(POINT_READ_PATTERN_MISMATCH_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.serial.invalidValue", dp.getVO().getXid()));
                                    }
                                    // Ensure we clear out the buffer...
                                    buffer.popAll();
                                }

                                @Override
                                public void pointPatternMismatch(String message, String messageRegex) {
                                // Ignore as this just isn't a message we care about
                                }

                                @Override
                                public void messagePatternMismatch(String message, String messageRegex) {
                                    raiseEvent(POINT_READ_PATTERN_MISMATCH_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.serial.patternMismatch", messageRegex, message));
                                    matcherFailed.set(true);
                                }

                                @Override
                                public void pointNotIdentified(String message, String messageRegex, int pointIdentifierIndex) {
                                // Don't Care
                                }

                                @Override
                                public void matchGeneralFailure(Exception e) {
                                    raiseEvent(POINT_READ_EXCEPTION_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.serial.readFailed", e.getMessage()));
                                    matcherFailed.set(true);
                                }
                            };
                            try {
                                matchPointValue(msg, messageRegex, pointIdentifierIndex, plVo, vo.isHex(), LOG, callback);
                            } catch (Exception e) {
                                callback.matchGeneralFailure(e);
                            }
                        }
                    }
                    // If no failures...
                    if (!matcherFailed.get())
                        returnToNormal(POINT_READ_PATTERN_MISMATCH_EVENT, System.currentTimeMillis());
                    returnToNormal(POINT_READ_EXCEPTION_EVENT, System.currentTimeMillis());
                }
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            // Ensure we clear out the buffer...
            this.buffer.popAll();
            raiseEvent(POINT_READ_EXCEPTION_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.serial.readFailed", e.getMessage()));
        }
    }
// End synch
}
Also used : InputStream(java.io.InputStream) MatchCallback(com.infiniteautomation.mango.regex.MatchCallback) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) SerialPortException(com.infiniteautomation.mango.io.serial.SerialPortException) IOException(java.io.IOException) TimeoutTask(com.serotonin.m2m2.util.timeout.TimeoutTask) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) SerialPointLocatorVO(com.infiniteautomation.serial.vo.SerialPointLocatorVO) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Example 3 with TranslatableMessage

use of com.serotonin.m2m2.i18n.TranslatableMessage in project ma-modules-public by infiniteautomation.

the class SerialDataSourceRT method connect.

/**
 * Connect to a serial port
 * @param portName
 * @throws Exception
 */
public boolean connect() {
    if (Common.serialPortManager.portOwned(vo.getCommPortId())) {
        raiseEvent(DATA_SOURCE_EXCEPTION_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.serial.portInUse", vo.getCommPortId()));
        return false;
    } else {
        try {
            this.port = Common.serialPortManager.open("Mango Serial Data Source", vo.getCommPortId(), vo.getBaudRate(), vo.getFlowControlIn(), vo.getFlowControlOut(), vo.getDataBits(), vo.getStopBits(), vo.getParity());
            this.port.addEventListener(this);
            return true;
        } catch (Exception e) {
            raiseEvent(DATA_SOURCE_EXCEPTION_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.serial.portError", vo.getCommPortId(), e.getLocalizedMessage()));
            return false;
        }
    }
}
Also used : TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) SerialPortException(com.infiniteautomation.mango.io.serial.SerialPortException) IOException(java.io.IOException)

Example 4 with TranslatableMessage

use of com.serotonin.m2m2.i18n.TranslatableMessage in project ma-modules-public by infiniteautomation.

the class SerialDataSourceRT method initialize.

@Override
public void initialize() {
    boolean connected = false;
    try {
        if (this.vo.isLogIO()) {
            // PrintWriter log = new PrintWriter(new FileWriter(file, true));
            int fileSize = (int) (vo.getIoLogFileSizeMBytes() * 1000000f);
            int maxFiles = vo.getMaxHistoricalIOLogs();
            ioLog = new RollingIOLog(getIOLogFileName(vo.getId()), Common.getLogsDir(), fileSize, maxFiles);
            ioLog.log("Data source started");
        }
        connected = this.connect();
    } catch (Exception e) {
        LOG.debug("Error while initializing data source", e);
        String msg = e.getMessage();
        if (msg == null) {
            msg = "Unknown";
        }
        raiseEvent(DATA_SOURCE_EXCEPTION_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.serial.connectFailed", msg));
    }
    if (connected) {
        returnToNormal(DATA_SOURCE_EXCEPTION_EVENT, System.currentTimeMillis());
    }
    super.initialize();
}
Also used : RollingIOLog(com.serotonin.log.RollingIOLog) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) SerialPortException(com.infiniteautomation.mango.io.serial.SerialPortException) IOException(java.io.IOException)

Example 5 with TranslatableMessage

use of com.serotonin.m2m2.i18n.TranslatableMessage in project ma-modules-public by infiniteautomation.

the class ReportsDwr method saveReport.

@DwrPermission(custom = ReportPermissionDefinition.PERMISSION)
public ProcessResult saveReport(int id, String name, String xid, List<ReportPointVO> points, String template, int includeEvents, 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 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);
    // Validate XID
    if (StringUtils.isBlank(xid))
        response.addContextualMessage("xid", "validate.required");
    else if (StringValidation.isLengthGreaterThan(xid, 50))
        response.addMessage("xid", new TranslatableMessage("validate.notLongerThan", 50));
    else if (!ReportDao.instance.isXidUnique(xid, id))
        response.addContextualMessage("xid", "validate.xidUsed");
    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 (email && recipients.isEmpty())
        response.addContextualMessage("recipients", "reports.validate.needRecip");
    if (response.getHasMessages())
        return response;
    User user = Common.getUser();
    ReportDao reportDao = ReportDao.instance;
    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.
    String host = "";
    WebContext webContext = WebContextFactory.get();
    int port;
    if (webContext != null) {
        HttpServletRequest req = webContext.getHttpServletRequest();
        host = req.getServerName();
        port = req.getLocalPort();
    } else {
        port = Common.envProps.getInt("web.port", 8080);
    }
    ReportJob.scheduleReportJob(host, port, report);
    // Send back the report id in case this was new.
    response.addData("reportId", report.getId());
    response.addData("report", report);
    return response;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) User(com.serotonin.m2m2.vo.User) WebContext(org.directwebremoting.WebContext) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) CronTimerTrigger(com.serotonin.timer.CronTimerTrigger) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ReportVO(com.serotonin.m2m2.reports.vo.ReportVO) ReportDao(com.serotonin.m2m2.reports.ReportDao) InvalidArgumentException(com.serotonin.InvalidArgumentException) DwrPermission(com.serotonin.m2m2.web.dwr.util.DwrPermission)

Aggregations

TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)180 User (com.serotonin.m2m2.vo.User)53 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)52 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)52 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)33 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)33 IOException (java.io.IOException)28 HashMap (java.util.HashMap)27 DwrPermission (com.serotonin.m2m2.web.dwr.util.DwrPermission)24 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)22 ArrayList (java.util.ArrayList)22 DataPointRT (com.serotonin.m2m2.rt.dataImage.DataPointRT)20 PointValueTime (com.serotonin.m2m2.rt.dataImage.PointValueTime)20 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)19 BadRequestException (com.infiniteautomation.mango.rest.v2.exception.BadRequestException)18 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)17 File (java.io.File)16 URI (java.net.URI)16 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)12 ResponseEntity (org.springframework.http.ResponseEntity)11