Search in sources :

Example 16 with Module

use of com.serotonin.m2m2.module.Module in project ma-core-public by infiniteautomation.

the class BaseDwr method doLongPoll.

@DwrPermission(anonymous = true)
public Map<String, Object> doLongPoll(int pollSessionId) {
    Map<String, Object> response = new HashMap<>();
    HttpServletRequest httpRequest = WebContextFactory.get().getHttpServletRequest();
    User user = Common.getUser(httpRequest);
    EventDao eventDao = EventDao.instance;
    LongPollData data = getLongPollData(pollSessionId, false);
    data.updateTimestamp();
    LongPollRequest pollRequest = data.getRequest();
    // One minute
    long expireTime = Common.timer.currentTimeMillis() + 60000;
    LongPollState state = data.getState();
    int waitTime = SystemSettingsDao.getIntValue(SystemSettingsDao.UI_PERFORMANCE);
    // For users that log in on multiple machines (or browsers), reset the
    // last alarm timestamp so that it always
    // gets reset with at least each new poll. For now this beats writing
    // user-specific event change tracking code.
    state.setLastAlarmLevelChange(0);
    while (!pollRequest.isTerminated() && Common.timer.currentTimeMillis() < expireTime) {
        if (Providers.get(IMangoLifecycle.class).isTerminated()) {
            pollRequest.setTerminated(true);
            break;
        }
        if (pollRequest.isMaxAlarm() && user != null) {
            // Track the last alarm count to see if we need to update the
            // alarm toaster
            Integer lastUnsilencedAlarmCount = (Integer) data.getState().getAttribute("lastUnsilencedAlarmCount");
            // Ensure we have one, as we won't on first run
            if (lastUnsilencedAlarmCount == null)
                lastUnsilencedAlarmCount = 0;
            // Sort into lists for the different types
            List<EventInstance> events = Common.eventManager.getAllActiveUserEvents(user.getId());
            int currentUnsilencedAlarmCount = events.size();
            int lifeSafetyTotal = 0;
            EventInstance lifeSafetyEvent = null;
            int criticalTotal = 0;
            EventInstance criticalEvent = null;
            int urgentTotal = 0;
            EventInstance urgentEvent = null;
            int warningTotal = 0;
            EventInstance warningEvent = null;
            int importantTotal = 0;
            EventInstance importantEvent = null;
            int informationTotal = 0;
            EventInstance informationEvent = null;
            int noneTotal = 0;
            EventInstance noneEvent = null;
            int doNotLogTotal = 0;
            EventInstance doNotLogEvent = null;
            for (EventInstance event : events) {
                switch(event.getAlarmLevel()) {
                    case AlarmLevels.LIFE_SAFETY:
                        lifeSafetyTotal++;
                        lifeSafetyEvent = event;
                        break;
                    case AlarmLevels.CRITICAL:
                        criticalTotal++;
                        criticalEvent = event;
                        break;
                    case AlarmLevels.URGENT:
                        urgentTotal++;
                        urgentEvent = event;
                        break;
                    case AlarmLevels.WARNING:
                        warningTotal++;
                        warningEvent = event;
                        break;
                    case AlarmLevels.IMPORTANT:
                        importantTotal++;
                        importantEvent = event;
                        break;
                    case AlarmLevels.INFORMATION:
                        informationTotal++;
                        informationEvent = event;
                        break;
                    case AlarmLevels.NONE:
                        noneTotal++;
                        noneEvent = event;
                        break;
                    case AlarmLevels.DO_NOT_LOG:
                        doNotLogTotal++;
                        doNotLogEvent = event;
                        break;
                }
            }
            // If we have some new information we should show it
            if (lastUnsilencedAlarmCount != currentUnsilencedAlarmCount) {
                data.getState().setAttribute("lastUnsilencedAlarmCount", // Update the value
                currentUnsilencedAlarmCount);
                // Indicate to UI that
                response.put("alarmsUpdated", true);
                // there is a new
                // alarm
                response.put("alarmsDoNotLog", doNotLogTotal);
                if (doNotLogTotal == 1)
                    response.put("doNotLogEvent", doNotLogEvent);
                response.put("alarmsNone", noneTotal);
                if (noneTotal == 1)
                    response.put("noneEvent", noneEvent);
                response.put("alarmsInformation", informationTotal);
                if (informationTotal == 1)
                    response.put("informationEvent", informationEvent);
                response.put("alarmsImportant", importantTotal);
                if (importantTotal == 1)
                    response.put("importantEvent", importantEvent);
                response.put("alarmsWarning", warningTotal);
                if (warningTotal == 1)
                    response.put("warningEvent", warningEvent);
                response.put("alarmsUrgent", urgentTotal);
                if (urgentTotal == 1)
                    response.put("urgentEvent", urgentEvent);
                response.put("alarmsCritical", criticalTotal);
                if (criticalTotal == 1)
                    response.put("criticalEvent", criticalEvent);
                response.put("alarmsLifeSafety", lifeSafetyTotal);
                if (lifeSafetyTotal == 1)
                    response.put("lifeSafetyEvent", lifeSafetyEvent);
            } else {
            // end if new alarm toaster info
            // response.put("alarmsUpdated",false);
            }
            // The events have changed. See if the user's particular max
            // alarm level has changed.
            int maxAlarmLevel = AlarmLevels.DO_NOT_LOG;
            if (lifeSafetyTotal > 0)
                maxAlarmLevel = AlarmLevels.LIFE_SAFETY;
            else if (criticalTotal > 0)
                maxAlarmLevel = AlarmLevels.CRITICAL;
            else if (urgentTotal > 0)
                maxAlarmLevel = AlarmLevels.URGENT;
            else if (warningTotal > 0)
                maxAlarmLevel = AlarmLevels.WARNING;
            else if (importantTotal > 0)
                maxAlarmLevel = AlarmLevels.IMPORTANT;
            else if (informationTotal > 0)
                maxAlarmLevel = AlarmLevels.INFORMATION;
            else if (noneTotal > 0)
                maxAlarmLevel = AlarmLevels.NONE;
            if (maxAlarmLevel != state.getMaxAlarmLevel()) {
                response.put("highestUnsilencedAlarmLevel", maxAlarmLevel);
                state.setMaxAlarmLevel(maxAlarmLevel);
            }
            // Check the max alarm. First check if the events have changed
            // since the last time this request checked.
            long lastEMUpdate = Common.eventManager.getLastAlarmTimestamp();
            // If there is a new alarm then do stuff
            if (state.getLastAlarmLevelChange() < lastEMUpdate) {
                state.setLastAlarmLevelChange(lastEMUpdate);
            } else {
            // end no new alarms
            // Don't add data for nothing, this will cause tons of
            // polls. response.put("alarmsUpdated",false);
            }
        }
        if (pollRequest.isPointDetails() && user != null) {
            PointDetailsState newState = DataPointDetailsDwr.getPointData();
            PointDetailsState responseState;
            PointDetailsState oldState = state.getPointDetailsState();
            if (oldState == null)
                responseState = newState;
            else {
                responseState = newState.clone();
                responseState.removeEqualValue(oldState);
            }
            if (!responseState.isEmpty()) {
                response.put("pointDetailsState", responseState);
                state.setPointDetailsState(newState);
            }
        }
        // TODO This code is used on the legacy alarms page
        if (pollRequest.isPendingAlarms() && user != null) {
            // Create the list of most current pending alarm content.
            Map<String, Object> model = new HashMap<>();
            model.put(MODEL_ATTR_EVENTS, eventDao.getPendingEvents(user.getId()));
            model.put("pendingEvents", true);
            model.put("noContentWhenEmpty", true);
            String currentContent = generateContent(httpRequest, "eventList.jsp", model);
            currentContent = com.serotonin.util.StringUtils.trimWhitespace(currentContent);
            if (!StringUtils.equals(currentContent, state.getPendingAlarmsContent())) {
                response.put("newAlarms", true);
                response.put("pendingAlarmsContent", currentContent);
                state.setPendingAlarmsContent(currentContent);
            } else {
                response.put("newAlarms", false);
            }
        }
        // Module handlers
        for (int i = 0; i < longPollHandlers.size(); i++) {
            LongPollHandler handler = longPollHandlers.get(i);
            handler.handleLongPoll(data, response, user);
        }
        if (!response.isEmpty())
            break;
        synchronized (pollRequest) {
            try {
                pollRequest.wait(waitTime);
            } catch (InterruptedException e) {
            // no op
            }
        }
    }
    if (pollRequest.isTerminated())
        response.put("terminated", true);
    return response;
}
Also used : EventInstance(com.serotonin.m2m2.rt.event.EventInstance) LongPollState(com.serotonin.m2m2.web.dwr.longPoll.LongPollState) User(com.serotonin.m2m2.vo.User) HashMap(java.util.HashMap) LongPollData(com.serotonin.m2m2.web.dwr.longPoll.LongPollData) LongPollHandler(com.serotonin.m2m2.web.dwr.longPoll.LongPollHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) EventDao(com.serotonin.m2m2.db.dao.EventDao) IMangoLifecycle(com.serotonin.m2m2.IMangoLifecycle) LongPollRequest(com.serotonin.m2m2.web.dwr.longPoll.LongPollRequest) PointDetailsState(com.serotonin.m2m2.web.dwr.beans.PointDetailsState) DwrPermission(com.serotonin.m2m2.web.dwr.util.DwrPermission)

Example 17 with Module

use of com.serotonin.m2m2.module.Module in project ma-core-public by infiniteautomation.

the class ModulesDwr method startDownloads.

@DwrPermission(admin = true)
public static String startDownloads(List<StringStringPair> modules, boolean backup, boolean restart) {
    synchronized (UPGRADE_DOWNLOADER_LOCK) {
        if (UPGRADE_DOWNLOADER != null)
            return Common.translate("modules.versionCheck.occupied");
    }
    // Check if the selected modules will result in a version-consistent system.
    try {
        // Create the request
        Map<String, Object> json = new HashMap<>();
        Map<String, String> jsonModules = new HashMap<>();
        json.put("modules", jsonModules);
        Version coreVersion = Common.getVersion();
        jsonModules.put("core", coreVersion.toString());
        for (StringStringPair module : modules) jsonModules.put(module.getKey(), module.getValue());
        StringWriter stringWriter = new StringWriter();
        new JsonWriter(Common.JSON_CONTEXT, stringWriter).writeObject(json);
        String requestData = stringWriter.toString();
        // Send the request
        String baseUrl = Common.envProps.getString("store.url");
        baseUrl += "/servlet/consistencyCheck";
        HttpPost post = new HttpPost(baseUrl);
        post.setEntity(new StringEntity(requestData));
        String responseData = HttpUtils4.getTextContent(Common.getHttpClient(), post, 1);
        // Parse the response
        JsonTypeReader jsonReader = new JsonTypeReader(responseData);
        String result = jsonReader.read().toString();
        if (!"ok".equals(result))
            return result;
    } catch (Exception e) {
        LOG.error("", e);
        return e.getMessage();
    }
    synchronized (UPGRADE_DOWNLOADER_LOCK) {
        // Ensure that 2 downloads cannot start at the same time.
        if (UPGRADE_DOWNLOADER == null) {
            UPGRADE_DOWNLOADER = new UpgradeDownloader(modules, backup, restart, Common.getHttpUser());
            // Clear out common info
            resetUpgradeStatus();
            Common.backgroundProcessing.execute(UPGRADE_DOWNLOADER);
        } else
            return Common.translate("modules.versionCheck.occupied");
    }
    return null;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringStringPair(com.serotonin.db.pair.StringStringPair) HashMap(java.util.HashMap) JsonString(com.serotonin.json.type.JsonString) JsonWriter(com.serotonin.json.JsonWriter) JsonException(com.serotonin.json.JsonException) HttpException(org.apache.http.HttpException) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) StringEntity(org.apache.http.entity.StringEntity) StringWriter(java.io.StringWriter) Version(com.github.zafarkhaja.semver.Version) JsonObject(com.serotonin.json.type.JsonObject) JsonTypeReader(com.serotonin.json.type.JsonTypeReader) DwrPermission(com.serotonin.m2m2.web.dwr.util.DwrPermission)

Example 18 with Module

use of com.serotonin.m2m2.module.Module in project ma-core-public by infiniteautomation.

the class ModulesDwr method getAvailableUpgrades.

public static JsonValue getAvailableUpgrades() throws JsonException, IOException, HttpException {
    // Create the request
    List<Module> modules = ModuleRegistry.getModules();
    Module.sortByName(modules);
    Map<String, Object> json = new HashMap<>();
    json.put("guid", Providers.get(ICoreLicense.class).getGuid());
    json.put("description", SystemSettingsDao.getValue(SystemSettingsDao.INSTANCE_DESCRIPTION));
    json.put("distributor", Common.envProps.getString("distributor"));
    json.put("upgradeVersionState", SystemSettingsDao.getIntValue(SystemSettingsDao.UPGRADE_VERSION_STATE));
    Properties props = new Properties();
    File propFile = new File(Common.MA_HOME + File.separator + "release.properties");
    int versionState = UpgradeVersionState.DEVELOPMENT;
    if (propFile.exists()) {
        InputStream in = new FileInputStream(propFile);
        try {
            props.load(in);
        } finally {
            in.close();
        }
        String currentVersionState = props.getProperty("versionState");
        try {
            if (currentVersionState != null)
                versionState = Integer.valueOf(currentVersionState);
        } catch (NumberFormatException e) {
        }
    }
    json.put("currentVersionState", versionState);
    Map<String, String> jsonModules = new HashMap<>();
    json.put("modules", jsonModules);
    Version coreVersion = Common.getVersion();
    jsonModules.put("core", coreVersion.toString());
    for (Module module : modules) if (!module.isMarkedForDeletion())
        jsonModules.put(module.getName(), module.getVersion().toString());
    // Add in the unloaded modules so we don't re-download them if we don't have to
    for (Module module : ModuleRegistry.getUnloadedModules()) if (!module.isMarkedForDeletion())
        jsonModules.put(module.getName(), module.getVersion().toString());
    StringWriter stringWriter = new StringWriter();
    new JsonWriter(Common.JSON_CONTEXT, stringWriter).writeObject(json);
    String requestData = stringWriter.toString();
    // Send the request
    String baseUrl = Common.envProps.getString("store.url");
    baseUrl += "/servlet/versionCheck";
    HttpPost post = new HttpPost(baseUrl);
    post.setEntity(new StringEntity(requestData));
    String responseData = HttpUtils4.getTextContent(Common.getHttpClient(), post, 1);
    // Parse the response
    JsonTypeReader jsonReader = new JsonTypeReader(responseData);
    return jsonReader.read();
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HashMap(java.util.HashMap) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JsonString(com.serotonin.json.type.JsonString) Properties(java.util.Properties) JsonWriter(com.serotonin.json.JsonWriter) FileInputStream(java.io.FileInputStream) StringEntity(org.apache.http.entity.StringEntity) StringWriter(java.io.StringWriter) Version(com.github.zafarkhaja.semver.Version) JsonObject(com.serotonin.json.type.JsonObject) Module(com.serotonin.m2m2.module.Module) File(java.io.File) JsonTypeReader(com.serotonin.json.type.JsonTypeReader)

Example 19 with Module

use of com.serotonin.m2m2.module.Module in project ma-core-public by infiniteautomation.

the class MangoRestSpringConfiguration method createNewObjectMapper.

/**
 * Create an instance of the Object Mapper.
 * Used locally when starting Spring but may also be used for testing.
 *
 * Note: This is NOT the same Object Mapper instance used within a running Mango.
 * XXX J.W. Seems to be used inside the REST controller to me?
 *
 * @return
 */
public static ObjectMapper createNewObjectMapper() {
    // For raw Jackson
    ObjectMapper objectMapper = new ObjectMapper();
    if (Common.envProps.getBoolean("rest.indentJSON", false))
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    // JScience
    JScienceModule jScienceModule = new JScienceModule();
    objectMapper.registerModule(jScienceModule);
    // Mango Core JSON Modules
    MangoCoreModule mangoCore = new MangoCoreModule();
    objectMapper.registerModule(mangoCore);
    MangoRestV2JacksonModule mangoCoreV2 = new MangoRestV2JacksonModule();
    objectMapper.registerModule(mangoCoreV2);
    // Setup Module Defined JSON Modules
    List<JacksonModuleDefinition> defs = ModuleRegistry.getDefinitions(JacksonModuleDefinition.class);
    for (JacksonModuleDefinition def : defs) {
        if (def.getSourceMapperType() == JacksonModuleDefinition.ObjectMapperSource.REST)
            objectMapper.registerModule(def.getJacksonModule());
    }
    // Always output dates in ISO 8601
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
    objectMapper.setDateFormat(dateFormat);
    objectMapper.registerModule(new JavaTimeModule());
    // Set to system tz
    objectMapper.setTimeZone(TimeZone.getDefault());
    // This will allow messy JSON to be imported even if all the properties in it are part of the POJOs
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return objectMapper;
}
Also used : JScienceModule(com.serotonin.m2m2.web.mvc.rest.v1.mapping.JScienceModule) MangoCoreModule(com.serotonin.m2m2.web.mvc.rest.v1.mapping.MangoCoreModule) JacksonModuleDefinition(com.serotonin.m2m2.module.JacksonModuleDefinition) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) JavaTimeModule(com.fasterxml.jackson.datatype.jsr310.JavaTimeModule) MangoRestV2JacksonModule(com.infiniteautomation.mango.rest.v2.mapping.MangoRestV2JacksonModule) SimpleDateFormat(java.text.SimpleDateFormat) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 20 with Module

use of com.serotonin.m2m2.module.Module in project ma-core-public by infiniteautomation.

the class ModuleRegistry method ensureModelDefinitions.

private static void ensureModelDefinitions() {
    if (MODEL_DEFINITIONS == null) {
        synchronized (LOCK) {
            if (MODEL_DEFINITIONS == null) {
                Map<String, ModelDefinition> map = new HashMap<String, ModelDefinition>();
                for (ModelDefinition def : Module.getDefinitions(preDefaults, ModelDefinition.class)) {
                    map.put(def.getModelTypeName(), def);
                }
                for (Module module : MODULES.values()) {
                    for (ModelDefinition def : module.getDefinitions(ModelDefinition.class)) map.put(def.getModelTypeName(), def);
                }
                for (ModelDefinition def : Module.getDefinitions(postDefaults, ModelDefinition.class)) {
                    map.put(def.getModelTypeName(), def);
                }
                MODEL_DEFINITIONS = map;
            }
        }
    }
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) RestErrorModelDefinition(com.serotonin.m2m2.web.mvc.rest.v1.model.RestErrorModelDefinition)

Aggregations

HashMap (java.util.HashMap)9 Module (com.serotonin.m2m2.module.Module)8 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)7 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)7 User (com.serotonin.m2m2.vo.User)6 JsonString (com.serotonin.json.type.JsonString)5 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)5 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)5 JsonObject (com.serotonin.json.type.JsonObject)4 File (java.io.File)4 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)3 JsonWriter (com.serotonin.json.JsonWriter)3 CoreModuleModel (com.serotonin.m2m2.web.mvc.rest.v1.model.modules.CoreModuleModel)3 FileInputStream (java.io.FileInputStream)3 IOException (java.io.IOException)3 StringWriter (java.io.StringWriter)3 ArrayList (java.util.ArrayList)3 LinkedHashMap (java.util.LinkedHashMap)3 Version (com.github.zafarkhaja.semver.Version)2 BadRequestException (com.infiniteautomation.mango.rest.v2.exception.BadRequestException)2