Search in sources :

Example 91 with Permissions

use of com.serotonin.m2m2.vo.permission.Permissions in project ma-core-public by infiniteautomation.

the class MangoCustomMethodSecurityExpressionRoot method hasAnyPermission.

/**
 * Does the user have at least 1 of the supplied permissions
 * @param permissions
 * @return
 */
public boolean hasAnyPermission(String... permissions) {
    User user = (User) this.getPrincipal();
    Set<String> userPermissions = Permissions.explodePermissionGroups(user.getPermissions());
    // TODO Use Intersect (See Permissions)
    for (String permission : permissions) {
        if (userPermissions.contains(permission))
            return true;
    }
    return false;
}
Also used : User(com.serotonin.m2m2.vo.User)

Example 92 with Permissions

use of com.serotonin.m2m2.vo.permission.Permissions in project ma-core-public by infiniteautomation.

the class SystemSettingsDwr method getSettings.

@DwrPermission(admin = true)
public Map<String, Object> getSettings() {
    Map<String, Object> settings = new HashMap<>();
    // Info
    settings.put(SystemSettingsDao.INSTANCE_DESCRIPTION, SystemSettingsDao.getValue(SystemSettingsDao.INSTANCE_DESCRIPTION));
    // Email
    settings.put(SystemSettingsDao.EMAIL_SMTP_HOST, SystemSettingsDao.getValue(SystemSettingsDao.EMAIL_SMTP_HOST));
    settings.put(SystemSettingsDao.EMAIL_SMTP_PORT, SystemSettingsDao.getIntValue(SystemSettingsDao.EMAIL_SMTP_PORT));
    settings.put(SystemSettingsDao.EMAIL_FROM_ADDRESS, SystemSettingsDao.getValue(SystemSettingsDao.EMAIL_FROM_ADDRESS));
    settings.put(SystemSettingsDao.EMAIL_FROM_NAME, SystemSettingsDao.getValue(SystemSettingsDao.EMAIL_FROM_NAME));
    settings.put(SystemSettingsDao.EMAIL_AUTHORIZATION, SystemSettingsDao.getBooleanValue(SystemSettingsDao.EMAIL_AUTHORIZATION));
    settings.put(SystemSettingsDao.EMAIL_SMTP_USERNAME, SystemSettingsDao.getValue(SystemSettingsDao.EMAIL_SMTP_USERNAME));
    settings.put(SystemSettingsDao.EMAIL_SMTP_PASSWORD, SystemSettingsDao.getValue(SystemSettingsDao.EMAIL_SMTP_PASSWORD));
    settings.put(SystemSettingsDao.EMAIL_TLS, SystemSettingsDao.getBooleanValue(SystemSettingsDao.EMAIL_TLS));
    settings.put(SystemSettingsDao.EMAIL_CONTENT_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.EMAIL_CONTENT_TYPE));
    // System event types
    settings.put("systemEventTypes", SystemEventType.EVENT_TYPES);
    // System event types
    settings.put("auditEventTypes", AuditEventType.EVENT_TYPES);
    // Http
    settings.put(SystemSettingsDao.HTTP_CLIENT_USE_PROXY, SystemSettingsDao.getBooleanValue(SystemSettingsDao.HTTP_CLIENT_USE_PROXY));
    settings.put(SystemSettingsDao.HTTP_CLIENT_PROXY_SERVER, SystemSettingsDao.getValue(SystemSettingsDao.HTTP_CLIENT_PROXY_SERVER));
    settings.put(SystemSettingsDao.HTTP_CLIENT_PROXY_PORT, SystemSettingsDao.getIntValue(SystemSettingsDao.HTTP_CLIENT_PROXY_PORT));
    settings.put(SystemSettingsDao.HTTP_CLIENT_PROXY_USERNAME, SystemSettingsDao.getValue(SystemSettingsDao.HTTP_CLIENT_PROXY_USERNAME));
    settings.put(SystemSettingsDao.HTTP_CLIENT_PROXY_PASSWORD, SystemSettingsDao.getValue(SystemSettingsDao.HTTP_CLIENT_PROXY_PASSWORD));
    // Misc
    settings.put(SystemSettingsDao.POINT_DATA_PURGE_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.POINT_DATA_PURGE_PERIOD_TYPE));
    settings.put(SystemSettingsDao.POINT_DATA_PURGE_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.POINT_DATA_PURGE_PERIODS));
    settings.put(DataPurge.ENABLE_POINT_DATA_PURGE, SystemSettingsDao.getBooleanValue(DataPurge.ENABLE_POINT_DATA_PURGE, true));
    settings.put(SystemSettingsDao.POINT_DATA_PURGE_COUNT, SystemSettingsDao.getBooleanValue(SystemSettingsDao.POINT_DATA_PURGE_COUNT));
    settings.put(SystemSettingsDao.DATA_POINT_EVENT_PURGE_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.DATA_POINT_EVENT_PURGE_PERIOD_TYPE));
    settings.put(SystemSettingsDao.DATA_POINT_EVENT_PURGE_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.DATA_POINT_EVENT_PURGE_PERIODS));
    settings.put(SystemSettingsDao.DATA_SOURCE_EVENT_PURGE_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.DATA_SOURCE_EVENT_PURGE_PERIOD_TYPE));
    settings.put(SystemSettingsDao.DATA_SOURCE_EVENT_PURGE_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.DATA_SOURCE_EVENT_PURGE_PERIODS));
    settings.put(SystemSettingsDao.SYSTEM_EVENT_PURGE_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.SYSTEM_EVENT_PURGE_PERIOD_TYPE));
    settings.put(SystemSettingsDao.SYSTEM_EVENT_PURGE_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.SYSTEM_EVENT_PURGE_PERIODS));
    settings.put(SystemSettingsDao.PUBLISHER_EVENT_PURGE_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.PUBLISHER_EVENT_PURGE_PERIOD_TYPE));
    settings.put(SystemSettingsDao.PUBLISHER_EVENT_PURGE_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.PUBLISHER_EVENT_PURGE_PERIODS));
    settings.put(SystemSettingsDao.AUDIT_EVENT_PURGE_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.AUDIT_EVENT_PURGE_PERIOD_TYPE));
    settings.put(SystemSettingsDao.AUDIT_EVENT_PURGE_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.AUDIT_EVENT_PURGE_PERIODS));
    settings.put(SystemSettingsDao.NONE_ALARM_PURGE_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.NONE_ALARM_PURGE_PERIOD_TYPE));
    settings.put(SystemSettingsDao.NONE_ALARM_PURGE_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.NONE_ALARM_PURGE_PERIODS));
    settings.put(SystemSettingsDao.INFORMATION_ALARM_PURGE_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.INFORMATION_ALARM_PURGE_PERIOD_TYPE));
    settings.put(SystemSettingsDao.INFORMATION_ALARM_PURGE_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.INFORMATION_ALARM_PURGE_PERIODS));
    settings.put(SystemSettingsDao.IMPORTANT_ALARM_PURGE_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.IMPORTANT_ALARM_PURGE_PERIOD_TYPE));
    settings.put(SystemSettingsDao.IMPORTANT_ALARM_PURGE_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.IMPORTANT_ALARM_PURGE_PERIODS));
    settings.put(SystemSettingsDao.WARNING_ALARM_PURGE_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.WARNING_ALARM_PURGE_PERIOD_TYPE));
    settings.put(SystemSettingsDao.WARNING_ALARM_PURGE_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.WARNING_ALARM_PURGE_PERIODS));
    settings.put(SystemSettingsDao.URGENT_ALARM_PURGE_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.URGENT_ALARM_PURGE_PERIOD_TYPE));
    settings.put(SystemSettingsDao.URGENT_ALARM_PURGE_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.URGENT_ALARM_PURGE_PERIODS));
    settings.put(SystemSettingsDao.CRITICAL_ALARM_PURGE_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.CRITICAL_ALARM_PURGE_PERIOD_TYPE));
    settings.put(SystemSettingsDao.CRITICAL_ALARM_PURGE_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.CRITICAL_ALARM_PURGE_PERIODS));
    settings.put(SystemSettingsDao.LIFE_SAFETY_ALARM_PURGE_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.LIFE_SAFETY_ALARM_PURGE_PERIOD_TYPE));
    settings.put(SystemSettingsDao.LIFE_SAFETY_ALARM_PURGE_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.LIFE_SAFETY_ALARM_PURGE_PERIODS));
    settings.put(SystemSettingsDao.EVENT_PURGE_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.EVENT_PURGE_PERIOD_TYPE));
    settings.put(SystemSettingsDao.EVENT_PURGE_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.EVENT_PURGE_PERIODS));
    settings.put(SystemSettingsDao.UI_PERFORMANCE, SystemSettingsDao.getIntValue(SystemSettingsDao.UI_PERFORMANCE));
    settings.put(SystemSettingsDao.FUTURE_DATE_LIMIT_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.FUTURE_DATE_LIMIT_PERIOD_TYPE));
    settings.put(SystemSettingsDao.FUTURE_DATE_LIMIT_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.FUTURE_DATE_LIMIT_PERIODS));
    // Language
    settings.put(SystemSettingsDao.LANGUAGE, SystemSettingsDao.getValue(SystemSettingsDao.LANGUAGE));
    // Colours
    settings.put(SystemSettingsDao.CHART_BACKGROUND_COLOUR, SystemSettingsDao.getValue(SystemSettingsDao.CHART_BACKGROUND_COLOUR));
    settings.put(SystemSettingsDao.PLOT_BACKGROUND_COLOUR, SystemSettingsDao.getValue(SystemSettingsDao.PLOT_BACKGROUND_COLOUR));
    settings.put(SystemSettingsDao.PLOT_GRIDLINE_COLOUR, SystemSettingsDao.getValue(SystemSettingsDao.PLOT_GRIDLINE_COLOUR));
    // Backup Settings
    settings.put(SystemSettingsDao.BACKUP_FILE_LOCATION, SystemSettingsDao.getValue(SystemSettingsDao.BACKUP_FILE_LOCATION));
    settings.put(SystemSettingsDao.BACKUP_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.BACKUP_PERIOD_TYPE));
    settings.put(SystemSettingsDao.BACKUP_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.BACKUP_PERIODS));
    try {
        SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy HH:mm:ss");
        String lastRunString = SystemSettingsDao.getValue(SystemSettingsDao.BACKUP_LAST_RUN_SUCCESS);
        if (lastRunString != null) {
            Date lastRunDate = BackupWorkItem.dateFormatter.parse(lastRunString);
            lastRunString = sdf.format(lastRunDate);
            settings.put(SystemSettingsDao.BACKUP_LAST_RUN_SUCCESS, lastRunString);
        } else {
            settings.put(SystemSettingsDao.BACKUP_LAST_RUN_SUCCESS, "unknown");
        }
    } catch (Exception e) {
        settings.put(SystemSettingsDao.BACKUP_LAST_RUN_SUCCESS, "unknown");
    }
    settings.put(SystemSettingsDao.BACKUP_HOUR, SystemSettingsDao.getIntValue(SystemSettingsDao.BACKUP_HOUR));
    settings.put(SystemSettingsDao.BACKUP_MINUTE, SystemSettingsDao.getIntValue(SystemSettingsDao.BACKUP_MINUTE));
    settings.put(SystemSettingsDao.BACKUP_FILE_COUNT, SystemSettingsDao.getIntValue(SystemSettingsDao.BACKUP_FILE_COUNT));
    // Have to have a default value due to the lack of use of DEFAULT_VALUES for bools
    settings.put(SystemSettingsDao.BACKUP_ENABLED, SystemSettingsDao.getBooleanValue(SystemSettingsDao.BACKUP_ENABLED));
    // Have to have a default value due to the lack of use of DEFAULT_VALUES for bools
    settings.put(SystemSettingsDao.ALLOW_ANONYMOUS_CHART_VIEW, SystemSettingsDao.getBooleanValue(SystemSettingsDao.ALLOW_ANONYMOUS_CHART_VIEW, false));
    // Database Backup Settings
    settings.put(SystemSettingsDao.DATABASE_BACKUP_FILE_LOCATION, SystemSettingsDao.getValue(SystemSettingsDao.DATABASE_BACKUP_FILE_LOCATION));
    settings.put(SystemSettingsDao.DATABASE_BACKUP_PERIOD_TYPE, SystemSettingsDao.getIntValue(SystemSettingsDao.DATABASE_BACKUP_PERIOD_TYPE));
    settings.put(SystemSettingsDao.DATABASE_BACKUP_PERIODS, SystemSettingsDao.getIntValue(SystemSettingsDao.DATABASE_BACKUP_PERIODS));
    try {
        SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy HH:mm:ss");
        String lastRunString = SystemSettingsDao.getValue(SystemSettingsDao.DATABASE_BACKUP_LAST_RUN_SUCCESS);
        if (lastRunString != null) {
            Date lastRunDate = BackupWorkItem.dateFormatter.parse(lastRunString);
            lastRunString = sdf.format(lastRunDate);
            settings.put(SystemSettingsDao.DATABASE_BACKUP_LAST_RUN_SUCCESS, lastRunString);
        } else {
            settings.put(SystemSettingsDao.DATABASE_BACKUP_LAST_RUN_SUCCESS, "unknown");
        }
    } catch (Exception e) {
        settings.put(SystemSettingsDao.DATABASE_BACKUP_LAST_RUN_SUCCESS, "unknown");
    }
    settings.put(SystemSettingsDao.DATABASE_BACKUP_HOUR, SystemSettingsDao.getIntValue(SystemSettingsDao.DATABASE_BACKUP_HOUR));
    settings.put(SystemSettingsDao.DATABASE_BACKUP_MINUTE, SystemSettingsDao.getIntValue(SystemSettingsDao.DATABASE_BACKUP_MINUTE));
    settings.put(SystemSettingsDao.DATABASE_BACKUP_FILE_COUNT, SystemSettingsDao.getIntValue(SystemSettingsDao.DATABASE_BACKUP_FILE_COUNT));
    // Have to have a default value due to the lack of use of DEFAULT_VALUES for bools
    settings.put(SystemSettingsDao.DATABASE_BACKUP_ENABLED, SystemSettingsDao.getBooleanValue(SystemSettingsDao.DATABASE_BACKUP_ENABLED));
    // Permissions
    settings.put(SystemSettingsDao.PERMISSION_DATASOURCE, SystemSettingsDao.getValue(SystemSettingsDao.PERMISSION_DATASOURCE, ""));
    List<Map<String, String>> modulePermissions = new ArrayList<>();
    settings.put("modulePermissions", modulePermissions);
    for (PermissionDefinition def : ModuleRegistry.getDefinitions(PermissionDefinition.class)) {
        if (!def.getPermissionTypeName().equals(SuperadminPermissionDefinition.PERMISSION)) {
            Map<String, String> permission = new HashMap<>();
            permission.put("name", def.getPermissionTypeName());
            permission.put("label", Translations.getTranslations(Common.getLocale()).translate(def.getPermissionKey()));
            permission.put("value", SystemSettingsDao.getValue(def.getPermissionTypeName()));
            modulePermissions.add(permission);
        }
    }
    // Thread Pool Settings
    settings.put(SystemSettingsDao.HIGH_PRI_CORE_POOL_SIZE, SystemSettingsDao.getIntValue(SystemSettingsDao.HIGH_PRI_CORE_POOL_SIZE));
    settings.put(SystemSettingsDao.HIGH_PRI_MAX_POOL_SIZE, SystemSettingsDao.getIntValue(SystemSettingsDao.HIGH_PRI_MAX_POOL_SIZE));
    settings.put(SystemSettingsDao.MED_PRI_CORE_POOL_SIZE, SystemSettingsDao.getIntValue(SystemSettingsDao.MED_PRI_CORE_POOL_SIZE));
    settings.put(SystemSettingsDao.LOW_PRI_CORE_POOL_SIZE, SystemSettingsDao.getIntValue(SystemSettingsDao.LOW_PRI_CORE_POOL_SIZE));
    // Virtual Serial Ports
    settings.put("virtualSerialPorts", VirtualSerialPortConfigDao.instance.getAll());
    // Site analytics
    settings.put(SystemSettingsDao.SITE_ANALYTICS_HEAD, SystemSettingsDao.getValue(SystemSettingsDao.SITE_ANALYTICS_HEAD));
    settings.put(SystemSettingsDao.SITE_ANALYTICS_BODY, SystemSettingsDao.getValue(SystemSettingsDao.SITE_ANALYTICS_BODY));
    // Upgrade states
    settings.put(SystemSettingsDao.UPGRADE_VERSION_STATE, SystemSettingsDao.getIntValue(SystemSettingsDao.UPGRADE_VERSION_STATE));
    // Point Hierarchy
    settings.put(SystemSettingsDao.EXPORT_HIERARCHY_PATH, SystemSettingsDao.getBooleanValue(SystemSettingsDao.EXPORT_HIERARCHY_PATH));
    settings.put(SystemSettingsDao.HIERARCHY_PATH_SEPARATOR, SystemSettingsDao.getValue(SystemSettingsDao.HIERARCHY_PATH_SEPARATOR));
    return settings;
}
Also used : SuperadminPermissionDefinition(com.serotonin.m2m2.module.definitions.permissions.SuperadminPermissionDefinition) PermissionDefinition(com.serotonin.m2m2.module.PermissionDefinition) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SimpleDateFormat(java.text.SimpleDateFormat) HashMap(java.util.HashMap) Map(java.util.Map) Date(java.util.Date) InvalidArgumentException(com.serotonin.InvalidArgumentException) DwrPermission(com.serotonin.m2m2.web.dwr.util.DwrPermission)

Example 93 with Permissions

use of com.serotonin.m2m2.vo.permission.Permissions 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)

Example 94 with Permissions

use of com.serotonin.m2m2.vo.permission.Permissions in project ma-core-public by infiniteautomation.

the class DataPointQuery method query.

/**
 * Perform a query on the data points table
 * @param query
 * @return
 */
public List<DataPointWrapper> query(String query) {
    ASTNode root = parser.parse(query);
    List<DataPointVO> dataPoints = new ArrayList<>();
    ConditionSortLimitWithTagKeys conditions = DataPointDao.instance.rqlToCondition(root);
    DataPointDao.instance.customizedQuery(conditions, new MappedRowCallback<DataPointVO>() {

        @Override
        public void row(DataPointVO item, int index) {
            dataPoints.add(item);
        }
    });
    List<DataPointWrapper> results = new ArrayList<DataPointWrapper>();
    // Filter on permissions
    DataPointRT rt = null;
    AbstractPointWrapper wrapper = null;
    for (DataPointVO dp : dataPoints) {
        // Can we read or write to this point?
        if (Permissions.hasDataPointSetPermission(permissions.getDataPointSetPermissions(), dp) || Permissions.hasDataPointReadPermission(permissions.getDataPointReadPermissions(), dp)) {
            rt = Common.runtimeManager.getDataPoint(dp.getId());
            if (rt != null)
                wrapper = ScriptUtils.wrapPoint(engine, rt, setter);
            else
                wrapper = null;
            results.add(new DataPointWrapper(dp, wrapper));
        }
    }
    return results;
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) ASTNode(net.jazdw.rql.parser.ASTNode) ArrayList(java.util.ArrayList) ConditionSortLimitWithTagKeys(com.infiniteautomation.mango.db.query.ConditionSortLimitWithTagKeys)

Example 95 with Permissions

use of com.serotonin.m2m2.vo.permission.Permissions in project ma-core-public by infiniteautomation.

the class ScriptExecutor method prepareEngine.

/**
 * Prepare the engine by creating the context
 * @param engine
 * @param context
 * @param additionalContext
 * @param runtime
 * @param permissions
 * @param scriptWriter
 * @return
 */
protected static Bindings prepareEngine(ScriptEngine engine, Map<String, IDataPointValueSource> context, Map<String, Object> additionalContext, long runtime, long timestamp, ScriptPermissions permissions, PrintWriter scriptWriter, ScriptLog log, ScriptPointValueSetter setter, List<JsonImportExclusion> importExclusions, boolean testRun) {
    ScriptUtils.prepareEngine(engine);
    ScriptUtils.wrapperContext(engine, new WrapperContext(runtime, timestamp));
    Bindings engineScope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    // TODO Bubble PointValueSetter back up to top
    if (permissions != null)
        ScriptUtils.prepareUtilities(permissions, engine, engineScope, setter, importExclusions, testRun);
    if (additionalContext != null) {
        Set<Entry<String, Object>> entries = additionalContext.entrySet();
        for (Entry<String, Object> entry : entries) engineScope.put(entry.getKey(), entry.getValue());
    }
    // Put the context variables into the engine with engine scope.
    for (String varName : context.keySet()) {
        IDataPointValueSource point = context.get(varName);
        engineScope.put(varName, ScriptUtils.wrapPoint(engine, point, setter));
    }
    engineScope.put(ScriptUtils.POINTS_MAP_KEY, context);
    // Set the print writer if necessary
    if (scriptWriter != null) {
        engine.getContext().setWriter(scriptWriter);
        engineScope.put(ScriptLog.CONTEXT_KEY, log);
    }
    return engineScope;
}
Also used : Entry(java.util.Map.Entry) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) Bindings(javax.script.Bindings)

Aggregations

User (com.serotonin.m2m2.vo.User)61 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)43 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)43 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)40 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)36 ArrayList (java.util.ArrayList)27 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)20 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)17 DwrPermission (com.serotonin.m2m2.web.dwr.util.DwrPermission)16 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)15 HashMap (java.util.HashMap)15 List (java.util.List)14 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)10 ASTNode (net.jazdw.rql.parser.ASTNode)10 PointValueTime (com.serotonin.m2m2.rt.dataImage.PointValueTime)9 RestValidationFailedException (com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException)8 DataPointModel (com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel)8 URI (java.net.URI)8 Map (java.util.Map)8 ResponseEntity (org.springframework.http.ResponseEntity)7