Search in sources :

Example 6 with SystemEventType

use of com.serotonin.m2m2.rt.event.type.SystemEventType in project ma-core-public by infiniteautomation.

the class BackupWorkItem method execute.

@Override
public void execute() {
    synchronized (lock) {
        LOG.info("Starting backup WorkItem.");
        // Create the filename
        String filename = "Mango-Configuration";
        String runtimeString = dateFormatter.format(new Date());
        int maxFiles = SystemSettingsDao.getIntValue(SystemSettingsDao.BACKUP_FILE_COUNT);
        // If > 1 then we will use a date in the filename
        if (maxFiles > 1) {
            // Create Mango-Configuration-date.json
            filename += "-";
            filename += runtimeString;
        }
        filename += ".json";
        // Fill the full path
        String fullFilePath = this.backupLocation;
        if (fullFilePath.endsWith(File.separator)) {
            fullFilePath += filename;
        } else {
            fullFilePath += File.separator;
            fullFilePath += filename;
        }
        if (cancelled)
            return;
        // Collect the json backup data
        String jsonData = getBackup();
        // Write to file
        try {
            File file = new File(fullFilePath);
            if (!file.exists())
                if (!file.createNewFile()) {
                    failed = true;
                    LOG.warn("Unable to create backup file: " + fullFilePath);
                    SystemEventType.raiseEvent(new SystemEventType(SystemEventType.TYPE_BACKUP_FAILURE), Common.timer.currentTimeMillis(), false, new TranslatableMessage("event.backup.failure", fullFilePath, "Unable to create backup file"));
                    return;
                }
            // Always replace if exists
            FileWriter fw = new FileWriter(file, false);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(jsonData);
            bw.close();
            // Save the filename
            this.filename = file.getAbsolutePath();
            // Store the last successful backup time
            SystemSettingsDao.instance.setValue(SystemSettingsDao.BACKUP_LAST_RUN_SUCCESS, runtimeString);
            // Clean up old files, keeping the correct number as the history
            File backupDir = new File(this.backupLocation);
            File[] files = backupDir.listFiles(new FilenameFilter() {

                public boolean accept(File dir, String name) {
                    return name.toLowerCase().endsWith(".json");
                }
            });
            // Sort the files by date
            Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
            // Keep the desired history
            for (int i = maxFiles; i < files.length; i++) {
                try {
                    // Remove it
                    files[i].delete();
                } catch (Exception e) {
                    LOG.warn("Unable to delete file: " + files[i].getAbsolutePath(), e);
                }
            }
        } catch (Exception e) {
            LOG.warn(e);
            failed = true;
            SystemEventType.raiseEvent(new SystemEventType(SystemEventType.TYPE_BACKUP_FAILURE), Common.timer.currentTimeMillis(), false, new TranslatableMessage("event.backup.failure", fullFilePath, e.getMessage()));
        } finally {
            this.finished = true;
            LOG.info("Finished backup WorkItem.");
        }
    }
}
Also used : SystemEventType(com.serotonin.m2m2.rt.event.type.SystemEventType) FilenameFilter(java.io.FilenameFilter) FileWriter(java.io.FileWriter) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) File(java.io.File) Date(java.util.Date) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) ParseException(java.text.ParseException) BufferedWriter(java.io.BufferedWriter)

Example 7 with SystemEventType

use of com.serotonin.m2m2.rt.event.type.SystemEventType in project ma-core-public by infiniteautomation.

the class EventInstanceDao method createEventType.

static EventType createEventType(ResultSet rs, int offset) throws SQLException {
    String typeName = rs.getString(offset);
    String subtypeName = rs.getString(offset + 1);
    EventType type;
    if (typeName.equals(EventType.EventTypeNames.DATA_POINT))
        type = new DataPointEventType(rs.getInt(offset + 2), rs.getInt(offset + 3));
    else if (typeName.equals(EventType.EventTypeNames.DATA_SOURCE))
        type = new DataSourceEventType(rs.getInt(offset + 2), rs.getInt(offset + 3));
    else if (typeName.equals(EventType.EventTypeNames.SYSTEM))
        type = new SystemEventType(subtypeName, rs.getInt(offset + 2));
    else if (typeName.equals(EventType.EventTypeNames.PUBLISHER))
        type = new PublisherEventType(rs.getInt(offset + 2), rs.getInt(offset + 3));
    else if (typeName.equals(EventType.EventTypeNames.AUDIT))
        throw new ShouldNeverHappenException("AUDIT events should not exist here. Consider running the SQL: DELETE FROM events WHERE typeName='AUDIT';");
    else {
        EventTypeDefinition def = ModuleRegistry.getEventTypeDefinition(typeName);
        if (def == null) {
            // Create Missing Event Type
            type = new MissingEventType(typeName, null, rs.getInt(offset + 2), rs.getInt(offset + 3));
        } else {
            type = def.createEventType(subtypeName, rs.getInt(offset + 2), rs.getInt(offset + 3));
            if (type == null) {
                // Create Missing Event type
                type = new MissingEventType(typeName, subtypeName, rs.getInt(offset + 2), rs.getInt(offset + 3));
            }
        }
    }
    return type;
}
Also used : DataSourceEventType(com.serotonin.m2m2.rt.event.type.DataSourceEventType) SystemEventType(com.serotonin.m2m2.rt.event.type.SystemEventType) MissingEventType(com.serotonin.m2m2.rt.event.type.MissingEventType) DataSourceEventType(com.serotonin.m2m2.rt.event.type.DataSourceEventType) EventType(com.serotonin.m2m2.rt.event.type.EventType) SystemEventType(com.serotonin.m2m2.rt.event.type.SystemEventType) DataPointEventType(com.serotonin.m2m2.rt.event.type.DataPointEventType) PublisherEventType(com.serotonin.m2m2.rt.event.type.PublisherEventType) MissingEventType(com.serotonin.m2m2.rt.event.type.MissingEventType) PublisherEventType(com.serotonin.m2m2.rt.event.type.PublisherEventType) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) DataPointEventType(com.serotonin.m2m2.rt.event.type.DataPointEventType) EventTypeDefinition(com.serotonin.m2m2.module.EventTypeDefinition)

Example 8 with SystemEventType

use of com.serotonin.m2m2.rt.event.type.SystemEventType in project ma-core-public by infiniteautomation.

the class SetPointHandlerRT method raiseFailureEvent.

private void raiseFailureEvent(TranslatableMessage message, EventType et) {
    if (et != null && et.isSystemMessage()) {
        if (((SystemEventType) et).getSystemEventType().equals(SystemEventType.TYPE_SET_POINT_HANDLER_FAILURE)) {
            // The set point attempt failed for an event that is a set point handler failure in the first place.
            // Do not propagate the event, but rather just write a log message.
            LOG.warn("A set point event due to a set point handler failure itself failed. The failure event " + "has been discarded: " + message.translate(Common.getTranslations()));
            return;
        }
    }
    SystemEventType eventType = new SystemEventType(SystemEventType.TYPE_SET_POINT_HANDLER_FAILURE, vo.getId());
    if (StringUtils.isBlank(vo.getAlias()))
        message = new TranslatableMessage("event.setPointFailed", message);
    else
        message = new TranslatableMessage("event.setPointFailed.alias", vo.getAlias(), message);
    SystemEventType.raiseEvent(eventType, Common.timer.currentTimeMillis(), false, message);
}
Also used : SystemEventType(com.serotonin.m2m2.rt.event.type.SystemEventType) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Example 9 with SystemEventType

use of com.serotonin.m2m2.rt.event.type.SystemEventType in project ma-core-public by infiniteautomation.

the class MangoAuthenticationFailureHandler method saveExceptionImpl.

protected void saveExceptionImpl(HttpServletRequest request, AuthenticationException exception) {
    if (this.isUseForward()) {
        request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
    } else {
        HttpSession session = request.getSession(false);
        if (session != null || this.isAllowSessionCreation()) {
            request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
            // Store for use in the Controller
            String username = request.getParameter("username");
            request.getSession().setAttribute("username", username);
            LOG.warn("Failed login attempt on user '" + username + "' from IP +" + request.getRemoteAddr());
        }
    }
    // Raise the event
    String username = request.getParameter("username");
    SystemEventType.raiseEvent(new SystemEventType(SystemEventType.TYPE_FAILED_USER_LOGIN), Common.timer.currentTimeMillis(), false, new TranslatableMessage("event.failedLogin", username, request.getRemoteAddr()));
}
Also used : SystemEventType(com.serotonin.m2m2.rt.event.type.SystemEventType) HttpSession(javax.servlet.http.HttpSession) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Example 10 with SystemEventType

use of com.serotonin.m2m2.rt.event.type.SystemEventType in project ma-core-public by infiniteautomation.

the class EmailHandlerRT method sendEmail.

private static void sendEmail(EventInstance evt, NotificationType notificationType, Set<String> addresses, String alias, boolean includeSystemInfo, int pointValueCount, boolean includeLogs, String handlerXid, String customTemplate, List<IntStringPair> additionalContext, String script, SetCallback setCallback, ScriptPermissions permissions) {
    if (evt.getEventType().isSystemMessage()) {
        if (((SystemEventType) evt.getEventType()).getSystemEventType().equals(SystemEventType.TYPE_EMAIL_SEND_FAILURE)) {
            // Don't send email notifications about email send failures.
            LOG.info("Not sending email for event raised due to email failure");
            return;
        }
    }
    Translations translations = Common.getTranslations();
    if (StringUtils.isBlank(alias)) {
        // Just set the subject to the message
        alias = evt.getMessage().translate(translations);
        // Strip out the HTML and the &nbsp
        alias = StringEscapeUtils.unescapeHtml4(alias);
        // Since we have <br/> in the code and that isn't proper HTML we need to remove it by hand
        alias = alias.replace("<br/>", "\n");
    }
    // end if alias was blank
    // Determine the subject to use.
    TranslatableMessage subjectMsg;
    TranslatableMessage notifTypeMsg = new TranslatableMessage(notificationType.getKey());
    if (StringUtils.isBlank(alias)) {
        // Make these more descriptive
        if (evt.getId() == Common.NEW_ID)
            subjectMsg = new TranslatableMessage("ftl.subject.default", notifTypeMsg);
        else
            subjectMsg = new TranslatableMessage("ftl.subject.default.id", notifTypeMsg, evt.getId());
    } else {
        if (evt.getId() == Common.NEW_ID)
            subjectMsg = new TranslatableMessage("ftl.subject.alias", alias, notifTypeMsg);
        else
            subjectMsg = new TranslatableMessage("ftl.subject.alias.id", alias, notifTypeMsg, evt.getId());
    }
    String alarmLevel = AlarmLevels.getAlarmLevelMessage(evt.getAlarmLevel()).translate(translations);
    String subject = alarmLevel + " - " + subjectMsg.translate(translations);
    // Trim the subject if its too long
    if (subject.length() > 200)
        subject = subject.substring(0, 200);
    try {
        String[] toAddrs = addresses.toArray(new String[0]);
        UsedImagesDirective inlineImages = new UsedImagesDirective();
        // Send the email.
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("evt", evt);
        if (evt.getContext() != null)
            model.putAll(evt.getContext());
        model.put("img", inlineImages);
        model.put("instanceDescription", SystemSettingsDao.getValue(SystemSettingsDao.INSTANCE_DESCRIPTION));
        if (includeSystemInfo) {
            // Get the Work Items
            List<WorkItemModel> highPriorityWorkItems = Common.backgroundProcessing.getHighPriorityServiceItems();
            model.put("highPriorityWorkItems", highPriorityWorkItems);
            List<WorkItemModel> mediumPriorityWorkItems = Common.backgroundProcessing.getMediumPriorityServiceQueueItems();
            model.put("mediumPriorityWorkItems", mediumPriorityWorkItems);
            List<WorkItemModel> lowPriorityWorkItems = Common.backgroundProcessing.getLowPriorityServiceQueueItems();
            model.put("lowPriorityWorkItems", lowPriorityWorkItems);
            model.put("threadList", getThreadsList());
        }
        int type = SystemSettingsDao.getIntValue(SystemSettingsDao.EMAIL_CONTENT_TYPE);
        // If we are a point event then add the value
        if (evt.getEventType() instanceof DataPointEventType) {
            DataPointVO dp = (DataPointVO) evt.getContext().get("point");
            if (dp != null) {
                DataPointRT rt = Common.runtimeManager.getDataPoint(dp.getId());
                if (rt != null) {
                    List<PointValueTime> pointValues = null;
                    if (pointValueCount > 0)
                        pointValues = rt.getLatestPointValues(pointValueCount);
                    if ((pointValues != null) && (pointValues.size() > 0)) {
                        if (type == MangoEmailContent.CONTENT_TYPE_HTML || type == MangoEmailContent.CONTENT_TYPE_BOTH) {
                            List<RenderedPointValueTime> renderedPointValues = new ArrayList<RenderedPointValueTime>();
                            for (PointValueTime pvt : pointValues) {
                                RenderedPointValueTime rpvt = new RenderedPointValueTime();
                                rpvt.setValue(Functions.getHtmlText(rt.getVO(), pvt));
                                rpvt.setTime(Functions.getFullSecondTime(pvt.getTime()));
                                renderedPointValues.add(rpvt);
                            }
                            model.put("renderedHtmlPointValues", renderedPointValues);
                        }
                        if (type == MangoEmailContent.CONTENT_TYPE_TEXT || type == MangoEmailContent.CONTENT_TYPE_BOTH) {
                            List<RenderedPointValueTime> renderedPointValues = new ArrayList<RenderedPointValueTime>();
                            for (PointValueTime pvt : pointValues) {
                                RenderedPointValueTime rpvt = new RenderedPointValueTime();
                                rpvt.setValue(Functions.getRenderedText(rt.getVO(), pvt));
                                rpvt.setTime(Functions.getFullSecondTime(pvt.getTime()));
                                renderedPointValues.add(rpvt);
                            }
                            model.put("renderedPointValues", renderedPointValues);
                        }
                    }
                }
            }
        }
        // Build the additional context for the email model
        if (additionalContext == null || pointValueCount <= 0)
            model.put("additionalContext", new HashMap<>(0));
        else {
            Map<String, Map<String, Object>> context = new HashMap<>();
            for (IntStringPair pair : additionalContext) {
                Map<String, Object> point = new HashMap<String, Object>();
                DataPointRT rt = Common.runtimeManager.getDataPoint(pair.getKey());
                List<PointValueTime> pointValues;
                List<RenderedPointValueTime> renderedPointValues;
                DataPointVO dpvo;
                if (rt != null) {
                    dpvo = rt.getVO();
                    pointValues = rt.getLatestPointValues(pointValueCount);
                    renderedPointValues = new ArrayList<RenderedPointValueTime>();
                    if (pointValues != null && pointValues.size() > 0)
                        for (PointValueTime pvt : pointValues) {
                            RenderedPointValueTime rpvt = new RenderedPointValueTime();
                            rpvt.setValue(Functions.getRenderedText(rt.getVO(), pvt));
                            rpvt.setTime(Functions.getFullSecondTime(pvt.getTime()));
                            renderedPointValues.add(rpvt);
                        }
                } else {
                    dpvo = DataPointDao.instance.get(pair.getKey());
                    if (dpvo == null)
                        continue;
                    pointValues = Common.databaseProxy.newPointValueDao().getLatestPointValues(pair.getKey(), pointValueCount);
                    renderedPointValues = new ArrayList<RenderedPointValueTime>();
                    for (PointValueTime pvt : pointValues) {
                        RenderedPointValueTime rpvt = new RenderedPointValueTime();
                        rpvt.setValue(Functions.getRenderedText(dpvo, pvt));
                        rpvt.setTime(Functions.getFullSecondTime(pvt.getTime()));
                        renderedPointValues.add(rpvt);
                    }
                }
                point.put("values", renderedPointValues);
                point.put("deviceName", dpvo.getDeviceName());
                point.put("name", dpvo.getName());
                point.put("contextKey", pair.getValue());
                context.put(pair.getValue(), point);
            }
            model.put("additionalContext", context);
        }
        if (!StringUtils.isEmpty(script)) {
            // Okay, a script is defined, let's pass it the model so that it may add to it
            Map<String, Object> modelContext = new HashMap<String, Object>();
            modelContext.put("model", model);
            Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
            for (IntStringPair pair : additionalContext) {
                DataPointRT dprt = Common.runtimeManager.getDataPoint(pair.getKey());
                if (dprt == null) {
                    DataPointVO targetVo = DataPointDao.instance.getDataPoint(pair.getKey(), false);
                    if (targetVo == null) {
                        LOG.warn("Additional context point with ID: " + pair.getKey() + " and context name " + pair.getValue() + " could not be found.");
                        // Not worth aborting the email, just warn it
                        continue;
                    }
                    if (targetVo.getDefaultCacheSize() == 0)
                        targetVo.setDefaultCacheSize(1);
                    dprt = new DataPointRT(targetVo, targetVo.getPointLocator().createRuntime(), DataSourceDao.instance.getDataSource(targetVo.getDataSourceId()), null);
                    dprt.resetValues();
                }
                context.put(pair.getValue(), dprt);
            }
            List<JsonImportExclusion> importExclusions = new ArrayList<JsonImportExclusion>(1);
            importExclusions.add(new JsonImportExclusion("xid", handlerXid) {

                @Override
                public String getImporterType() {
                    return ConfigurationExportData.EVENT_HANDLERS;
                }
            });
            try {
                CompiledScript compiledScript = CompiledScriptExecutor.compile(script);
                CompiledScriptExecutor.execute(compiledScript, context, modelContext, Common.timer.currentTimeMillis(), DataTypes.ALPHANUMERIC, evt.isActive() || !evt.isRtnApplicable() ? evt.getActiveTimestamp() : evt.getRtnTimestamp(), permissions, SetPointHandlerRT.NULL_WRITER, new ScriptLog(SetPointHandlerRT.NULL_WRITER, LogLevel.FATAL), setCallback, importExclusions, false);
            } catch (ScriptPermissionsException | ScriptException | ResultTypeException e) {
                LOG.error("Exception running email handler script: " + e.getMessage(), e);
            }
        }
        MangoEmailContent content;
        if (StringUtils.isEmpty(customTemplate))
            content = new MangoEmailContent(notificationType.getFile(), model, translations, subject, Common.UTF8);
        else
            content = new MangoEmailContent(handlerXid, customTemplate, model, translations, subject);
        PostEmailRunnable[] postEmail = null;
        if (includeLogs) {
            final File logZip = getZippedLogfile(content, new File(Common.getLogsDir(), "ma.log"));
            // Setup To delete the temp files from zip
            if (logZip != null) {
                // See that the temp file(s) gets deleted after the email is sent.
                PostEmailRunnable deleteTempFile = new PostEmailRunnable() {

                    @Override
                    public void run() {
                        if (!logZip.delete())
                            LOG.warn("Temp file " + logZip.getPath() + " not deleted");
                    // Set our state to email failed if necessary
                    // TODO Create an Event to notify of Failed Emails...
                    // if(!this.isSuccess()){}
                    }
                };
                postEmail = new PostEmailRunnable[] { deleteTempFile };
            }
        }
        for (String s : inlineImages.getImageList()) content.addInline(new EmailInline.FileInline(s, Common.getWebPath(s)));
        EmailWorkItem.queueEmail(toAddrs, content, postEmail);
    } catch (Exception e) {
        LOG.error("", e);
    }
}
Also used : CompiledScript(javax.script.CompiledScript) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JsonImportExclusion(com.serotonin.m2m2.rt.script.JsonImportExclusion) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) WorkItemModel(com.serotonin.m2m2.web.mvc.rest.v1.model.workitem.WorkItemModel) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) RenderedPointValueTime(com.serotonin.m2m2.web.dwr.beans.RenderedPointValueTime) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) UsedImagesDirective(com.serotonin.m2m2.email.UsedImagesDirective) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) DataPointEventType(com.serotonin.m2m2.rt.event.type.DataPointEventType) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) IntStringPair(com.serotonin.db.pair.IntStringPair) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) IOException(java.io.IOException) PostEmailRunnable(com.serotonin.m2m2.email.PostEmailRunnable) RenderedPointValueTime(com.serotonin.m2m2.web.dwr.beans.RenderedPointValueTime) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) MangoEmailContent(com.serotonin.m2m2.email.MangoEmailContent) Translations(com.serotonin.m2m2.i18n.Translations) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File)

Aggregations

SystemEventType (com.serotonin.m2m2.rt.event.type.SystemEventType)9 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)6 DataPointEventType (com.serotonin.m2m2.rt.event.type.DataPointEventType)3 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)2 PostEmailRunnable (com.serotonin.m2m2.email.PostEmailRunnable)2 EventTypeDefinition (com.serotonin.m2m2.module.EventTypeDefinition)2 EventInstance (com.serotonin.m2m2.rt.event.EventInstance)2 DataSourceEventType (com.serotonin.m2m2.rt.event.type.DataSourceEventType)2 EventType (com.serotonin.m2m2.rt.event.type.EventType)2 MissingEventType (com.serotonin.m2m2.rt.event.type.MissingEventType)2 PublisherEventType (com.serotonin.m2m2.rt.event.type.PublisherEventType)2 User (com.serotonin.m2m2.vo.User)2 EventTypeVO (com.serotonin.m2m2.vo.event.EventTypeVO)2 File (java.io.File)2 ArrayList (java.util.ArrayList)2 IntStringPair (com.serotonin.db.pair.IntStringPair)1 MangoEmailContent (com.serotonin.m2m2.email.MangoEmailContent)1 UsedImagesDirective (com.serotonin.m2m2.email.UsedImagesDirective)1 Translations (com.serotonin.m2m2.i18n.Translations)1 EventManagerListenerDefinition (com.serotonin.m2m2.module.EventManagerListenerDefinition)1