Search in sources :

Example 61 with TranslatableMessage

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

the class AsciiFileEditDwr method testString.

@DwrPermission(user = true)
public ProcessResult testString(int dsId, String raw) {
    final ProcessResult pr = new ProcessResult();
    // Message we will work with
    String msg;
    if (dsId == -1) {
        pr.addContextualMessage("testString", "dsEdit.file.test.needsSave");
        return pr;
    }
    msg = StringEscapeUtils.unescapeJava(raw);
    // Map to store the values vs the points they are for
    final List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
    pr.addData("results", results);
    DataPointDao dpd = DataPointDao.instance;
    List<DataPointVO> points = dpd.getDataPoints(dsId, null);
    for (final DataPointVO vo : points) {
        final Map<String, Object> result = new HashMap<String, Object>();
        MatchCallback callback = new MatchCallback() {

            @Override
            public void onMatch(String pointIdentifier, PointValueTime value) {
                result.put("success", "true");
                result.put("name", vo.getName());
                result.put("identifier", pointIdentifier);
                result.put("value", value != null ? value.toString() : "null");
            }

            @Override
            public void pointPatternMismatch(String message, String pointValueRegex) {
                result.put("success", "false");
                result.put("name", vo.getName());
                result.put("error", new TranslatableMessage("dsEdit.file.test.noPointRegexMatch").translate(Common.getTranslations()));
            }

            @Override
            public void messagePatternMismatch(String message, String messageRegex) {
            }

            @Override
            public void pointNotIdentified(String message, String messageRegex, int pointIdentifierIndex) {
                result.put("success", "false");
                result.put("name", vo.getName());
                result.put("error", new TranslatableMessage("dsEdit.file.test.noIdentifierFound").translate(Common.getTranslations()));
            }

            @Override
            public void matchGeneralFailure(Exception e) {
                result.put("success", "false");
                result.put("name", vo.getName());
                result.put("error", new TranslatableMessage("common.default", e.getMessage()).translate(Common.getTranslations()));
            }
        };
        AsciiFilePointLocatorVO locator = vo.getPointLocator();
        AsciiFileDataSourceRT.matchPointValueTime(msg, Pattern.compile(locator.getValueRegex()), locator.getPointIdentifier(), locator.getPointIdentifierIndex(), locator.getDataTypeId(), locator.getValueIndex(), locator.getHasTimestamp(), locator.getTimestampIndex(), locator.getTimestampFormat(), callback);
        if (result.size() > 0) {
            results.add(result);
        }
    }
    return pr;
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) DataPointDao(com.serotonin.m2m2.db.dao.DataPointDao) HashMap(java.util.HashMap) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) ArrayList(java.util.ArrayList) MatchCallback(com.infiniteautomation.mango.regex.MatchCallback) AsciiFilePointLocatorVO(com.infiniteautomation.asciifile.vo.AsciiFilePointLocatorVO) IOException(java.io.IOException) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) HashMap(java.util.HashMap) Map(java.util.Map) DwrPermission(com.serotonin.m2m2.web.dwr.util.DwrPermission)

Example 62 with TranslatableMessage

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

the class EnvCanDataSourceRT method getData.

private String getData(String url, int timeoutSeconds, int retries) throws TranslatableException {
    // Try to get the data.
    String data;
    while (true) {
        HttpClient client = Common.getHttpClient(timeoutSeconds * 1000);
        HttpGet request = null;
        TranslatableMessage message;
        try {
            request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // data = HttpUtils4.readResponseBody(response);
                data = readResponseBody(response);
                break;
            }
            message = new TranslatableMessage("event.http.response", url, response.getStatusLine().getStatusCode());
        } catch (Exception e) {
            message = DataSourceRT.getExceptionMessage(e);
        } finally {
            request.reset();
        }
        if (retries <= 0)
            throw new TranslatableException(message);
        retries--;
        // Take a little break instead of trying again immediately.
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        // no op
        }
    }
    return data;
}
Also used : TranslatableException(com.serotonin.m2m2.i18n.TranslatableException) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) TranslatableException(com.serotonin.m2m2.i18n.TranslatableException) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException)

Example 63 with TranslatableMessage

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

the class EventManagerImpl method acknowledgeEvent.

/**
 * Added to allow Acknowledge Events to be fired
 * @param evt
 * @param time
 * @param userId
 * @param alternateAckSource
 */
private boolean acknowledgeEvent(EventInstance evt, long time, User ackUser, TranslatableMessage alternateAckSource) {
    boolean acked;
    if (ackUser != null)
        acked = eventDao.ackEvent(evt.getId(), time, ackUser.getId(), alternateAckSource);
    else
        acked = eventDao.ackEvent(evt.getId(), time, 0, alternateAckSource);
    // event was already acknowledged or doesn't exist
    if (!acked) {
        return false;
    }
    // Fill in the info if someone on the other end wants it
    if (ackUser != null) {
        evt.setAcknowledgedByUserId(ackUser.getId());
        evt.setAcknowledgedByUsername(ackUser.getUsername());
    }
    evt.setAcknowledgedTimestamp(time);
    evt.setAlternateAckSource(alternateAckSource);
    for (User user : userDao.getActiveUsers()) {
        // user should be skipped.
        if (evt.getEventType().excludeUser(user))
            continue;
        if (Permissions.hasEventTypePermission(user, evt.getEventType())) {
            // Notify All User Event Listeners of the new event
            for (UserEventListener l : this.userEventListeners) {
                if (l.getUserId() == user.getId()) {
                    Common.backgroundProcessing.addWorkItem(new EventNotifyWorkItem(user, l, evt, false, false, false, true));
                }
            }
            this.userEventCache.removeEvent(user.getId(), evt);
        }
    }
    return true;
}
Also used : User(com.serotonin.m2m2.vo.User) UserEventListener(com.serotonin.m2m2.rt.event.UserEventListener)

Example 64 with TranslatableMessage

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

the class EventManagerImpl method raiseEvent.

// 
// 
// Basic event management.
// 
/**
 * Raise Event
 * @param type
 * @param time
 * @param rtnApplicable - does this event return to normal?
 * @param alarmLevel
 * @param message
 * @param context
 */
public void raiseEvent(EventType type, long time, boolean rtnApplicable, int alarmLevel, TranslatableMessage message, Map<String, Object> context) {
    if (state != RUNNING)
        return;
    if (alarmLevel == AlarmLevels.IGNORE)
        return;
    // Check if there is an event for this type already active.
    EventInstance dup = get(type);
    if (dup != null) {
        // Check the duplicate handling.
        boolean discard = canDiscard(type, message);
        if (discard)
            return;
    // Otherwise we just continue...
    } else if (!rtnApplicable) {
        // Check if we've already seen this type recently.
        boolean recent = isRecent(type, message);
        if (recent)
            return;
    }
    // Determine if the event should be suppressed.
    TranslatableMessage autoAckMessage = null;
    for (EventManagerListenerDefinition l : listeners) {
        autoAckMessage = l.autoAckEventWithMessage(type);
        if (autoAckMessage != null)
            break;
    }
    EventInstance evt = new EventInstance(type, time, rtnApplicable, alarmLevel, message, context);
    if (autoAckMessage == null)
        setHandlers(evt);
    // Check to see if we are Not Logging these
    if (alarmLevel != AlarmLevels.DO_NOT_LOG) {
        eventDao.saveEvent(evt);
    }
    // Create user alarm records for all applicable users
    List<Integer> eventUserIds = new ArrayList<Integer>();
    Set<String> emailUsers = new HashSet<String>();
    for (User user : userDao.getActiveUsers()) {
        // user should be skipped.
        if (type.excludeUser(user))
            continue;
        if (Permissions.hasEventTypePermission(user, type)) {
            eventUserIds.add(user.getId());
            if (user.getReceiveAlarmEmails() > AlarmLevels.IGNORE && alarmLevel >= user.getReceiveAlarmEmails() && !StringUtils.isEmpty(user.getEmail()))
                emailUsers.add(user.getEmail());
            // Notify All User Event Listeners of the new event
            if ((alarmLevel != AlarmLevels.DO_NOT_LOG) && (!evt.getEventType().getEventType().equals(EventType.EventTypeNames.AUDIT))) {
                for (UserEventListener l : this.userEventListeners) {
                    if (l.getUserId() == user.getId()) {
                        Common.backgroundProcessing.addWorkItem(new EventNotifyWorkItem(user, l, evt, true, false, false, false));
                    }
                }
                // Add to the UserEventCache if the user has recently accessed their events
                this.userEventCache.addEvent(user.getId(), evt);
            }
        }
    }
    DateTime now = new DateTime(Common.timer.currentTimeMillis());
    for (MailingList ml : MailingListDao.instance.getAlarmMailingLists(alarmLevel)) {
        ml.appendAddresses(emailUsers, now);
    }
    // No Audit or Do Not Log events are User Events
    if ((eventUserIds.size() > 0) && (alarmLevel != AlarmLevels.DO_NOT_LOG) && (!evt.getEventType().getEventType().equals(EventType.EventTypeNames.AUDIT))) {
        eventDao.insertUserEvents(evt.getId(), eventUserIds, true);
        if (autoAckMessage == null)
            lastAlarmTimestamp = Common.timer.currentTimeMillis();
    }
    if (evt.isRtnApplicable()) {
        activeEventsLock.writeLock().lock();
        try {
            activeEvents.add(evt);
        } finally {
            activeEventsLock.writeLock().unlock();
        }
    } else if (evt.getEventType().isRateLimited()) {
        recentEventsLock.writeLock().lock();
        try {
            recentEvents.add(evt);
        } finally {
            recentEventsLock.writeLock().unlock();
        }
    }
    if ((autoAckMessage != null) && (alarmLevel != AlarmLevels.DO_NOT_LOG) && (!evt.getEventType().getEventType().equals(EventType.EventTypeNames.AUDIT)))
        this.acknowledgeEvent(evt, time, null, autoAckMessage);
    else {
        if (evt.isRtnApplicable()) {
            if (alarmLevel > highestActiveAlarmLevel) {
                int oldValue = highestActiveAlarmLevel;
                highestActiveAlarmLevel = alarmLevel;
                SystemEventType.raiseEvent(new SystemEventType(SystemEventType.TYPE_MAX_ALARM_LEVEL_CHANGED), time, false, getAlarmLevelChangeMessage("event.alarmMaxIncreased", oldValue));
            }
        }
        // Call raiseEvent handlers.
        handleRaiseEvent(evt, emailUsers);
        if (log.isDebugEnabled())
            log.trace("Event raised: type=" + type + ", message=" + message.translate(Common.getTranslations()));
    }
}
Also used : EventInstance(com.serotonin.m2m2.rt.event.EventInstance) SystemEventType(com.serotonin.m2m2.rt.event.type.SystemEventType) User(com.serotonin.m2m2.vo.User) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) MailingList(com.serotonin.m2m2.vo.mailingList.MailingList) DateTime(org.joda.time.DateTime) UserEventListener(com.serotonin.m2m2.rt.event.UserEventListener) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) EventManagerListenerDefinition(com.serotonin.m2m2.module.EventManagerListenerDefinition) HashSet(java.util.HashSet)

Example 65 with TranslatableMessage

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

the class ModuleRegistry method getCoreModule.

/**
 * Helper Method to create a Module with Core Information
 * @return
 */
public static Module getCoreModule() {
    Module core = new Module("core", Common.getVersion(), new TranslatableMessage("modules.core.description"), "Infinite Automation Systems, Inc.", "https://www.infiniteautomation.com", null, -1, Common.isCoreSigned());
    if (Common.isInvalid())
        core.setLicenseType("Invalid");
    else
        core.setLicenseType(Common.license() == null ? null : Common.license().getLicenseType());
    core.addDefinition((LicenseDefinition) Providers.get(ICoreLicense.class));
    return core;
}
Also used : TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

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