Search in sources :

Example 11 with TranslatableMessage

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

the class JsonConfigImportWebSocketHandler method handleTextMessage.

@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
    try {
        User user = this.getUser(session);
        // TODO Can anyone cancel the import?
        if (user == null) {
            return;
        } else if (!user.isAdmin()) {
            if (session.isOpen()) {
                session.close(MangoWebSocketPublisher.NOT_AUTHORIZED);
            }
            return;
        }
        JsonEmportControlModel model = this.jacksonMapper.readValue(message.getPayload(), JsonEmportControlModel.class);
        if (model != null && model.isCancel()) {
            // Cancel the task if it is running
            this.controller.cancelImport(model.getResourceId());
        }
    } catch (Exception e) {
        try {
            this.sendErrorMessage(session, MangoWebSocketErrorType.SERVER_ERROR, new TranslatableMessage("rest.error.serverError", e.getMessage()));
        } catch (Exception e1) {
            LOG.error(e.getMessage(), e);
        }
    }
}
Also used : User(com.serotonin.m2m2.vo.User) JsonEmportControlModel(com.serotonin.m2m2.web.mvc.rest.v1.model.emport.JsonEmportControlModel) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Example 12 with TranslatableMessage

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

the class EventsWebSocketHandler method handleTextMessage.

@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
    try {
        User user = this.getUser(session);
        if (user == null) {
            return;
        }
        EventRegistrationModel model = this.jacksonMapper.readValue(message.getPayload(), EventRegistrationModel.class);
        Set<String> levels = model.getLevels();
        if (levels == null) {
            levels = Collections.emptySet();
        }
        Set<EventEventTypeEnum> events = model.getEventTypes();
        if (events == null) {
            events = EnumSet.noneOf(EventEventTypeEnum.class);
        }
        boolean emptySubscriptions = levels.isEmpty() || events.isEmpty();
        synchronized (this.lock) {
            if (!this.connectionClosed) {
                if (this.listener != null) {
                    if (emptySubscriptions) {
                        this.listener.terminate();
                        this.listener = null;
                    } else {
                        this.listener.changeLevels(levels);
                        this.listener.changeEvents(events);
                    }
                } else if (!emptySubscriptions) {
                    this.listener = new EventsWebSocketListener(user, levels, events);
                    this.listener.initialize();
                }
            }
        }
    } catch (Exception e) {
        try {
            this.sendErrorMessage(session, MangoWebSocketErrorType.SERVER_ERROR, new TranslatableMessage("rest.error.serverError", e.getMessage()));
        } catch (Exception e1) {
            log.error(e.getMessage(), e);
        }
    }
    if (log.isDebugEnabled())
        log.debug(message.getPayload());
}
Also used : User(com.serotonin.m2m2.vo.User) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) EventRegistrationModel(com.serotonin.m2m2.web.mvc.rest.v1.model.events.EventRegistrationModel) EventEventTypeEnum(com.serotonin.m2m2.web.mvc.rest.v1.model.events.EventEventTypeEnum)

Example 13 with TranslatableMessage

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

the class PointValueWebSocketHandler method handleTextMessage.

@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
    try {
        User user = getUser(session);
        if (user == null) {
            return;
        }
        PointValueRegistrationModel model = this.jacksonMapper.readValue(message.getPayload(), PointValueRegistrationModel.class);
        // Handle message.getPayload() here
        DataPointVO vo = DataPointDao.instance.getByXid(model.getDataPointXid());
        if (vo == null) {
            this.sendErrorMessage(session, MangoWebSocketErrorType.SERVER_ERROR, new TranslatableMessage("rest.error.pointNotFound", model.getDataPointXid()));
            return;
        }
        // Check permissions
        if (!Permissions.hasDataPointReadPermission(user, vo)) {
            this.sendErrorMessage(session, MangoWebSocketErrorType.PERMISSION_DENIED, new TranslatableMessage("permission.exception.readDataPoint", user.getUsername()));
            return;
        }
        Set<PointValueEventType> eventsTypes = model.getEventTypes();
        int dataPointId = vo.getId();
        synchronized (pointIdToListenerMap) {
            if (this.connectionClosed) {
                return;
            }
            PointValueWebSocketListener publisher = pointIdToListenerMap.get(dataPointId);
            if (publisher != null) {
                if (eventsTypes.isEmpty()) {
                    publisher.terminate();
                    pointIdToListenerMap.remove(dataPointId);
                } else {
                    publisher.setEventTypes(eventsTypes);
                }
            } else if (!eventsTypes.isEmpty()) {
                publisher = new PointValueWebSocketListener(vo, eventsTypes);
                publisher.initialize();
                // Immediately send the most recent Point Value and the status of the data point
                publisher.sendPointStatus();
                pointIdToListenerMap.put(dataPointId, publisher);
            }
        }
    } catch (Exception e) {
        // TODO Mango 3.4 add new exception type for closed session and don't try and send error if it was a closed session exception
        try {
            this.sendErrorMessage(session, MangoWebSocketErrorType.SERVER_ERROR, new TranslatableMessage("rest.error.serverError", e.getMessage()));
        } catch (Exception e1) {
            log.error(e.getMessage(), e);
        }
    }
    if (log.isDebugEnabled())
        log.debug(message.getPayload());
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) User(com.serotonin.m2m2.vo.User) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 14 with TranslatableMessage

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

the class PointLinksDwr method validateScript.

@DwrPermission(user = true)
public ProcessResult validateScript(String script, int sourcePointId, int targetPointId, ScriptPermissions permissions, int logLevel) {
    ProcessResult response = new ProcessResult();
    TranslatableMessage message;
    DataPointRT source = Common.runtimeManager.getDataPoint(sourcePointId);
    if (source == null) {
        DataPointVO sourceVo = DataPointDao.instance.getDataPoint(sourcePointId, false);
        if (sourceVo == null) {
            message = new TranslatableMessage("pointLinks.validate.sourceRequired");
            response.addMessage("script", message);
            return response;
        }
        if (sourceVo.getDefaultCacheSize() == 0)
            sourceVo.setDefaultCacheSize(1);
        source = new DataPointRT(sourceVo, sourceVo.getPointLocator().createRuntime(), DataSourceDao.instance.getDataSource(sourceVo.getDataSourceId()), null);
        source.resetValues();
    }
    DataPointRT target = Common.runtimeManager.getDataPoint(targetPointId);
    if (target == null) {
        DataPointVO targetVo = DataPointDao.instance.getDataPoint(targetPointId, false);
        if (targetVo == null) {
            message = new TranslatableMessage("pointLinks.validate.targetRequired");
            response.addMessage("script", message);
            return response;
        }
        if (targetVo.getDefaultCacheSize() == 0)
            targetVo.setDefaultCacheSize(1);
        target = new DataPointRT(targetVo, targetVo.getPointLocator().createRuntime(), DataSourceDao.instance.getDataSource(targetVo.getDataSourceId()), null);
        target.resetValues();
    }
    Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
    context.put(PointLinkRT.CONTEXT_SOURCE_VAR_NAME, source);
    context.put(PointLinkRT.CONTEXT_TARGET_VAR_NAME, target);
    int targetDataType = target.getDataTypeId();
    final StringWriter scriptOut = new StringWriter();
    final PrintWriter scriptWriter = new PrintWriter(scriptOut);
    ScriptLog scriptLog = new ScriptLog(scriptWriter, logLevel);
    final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYY HH:mm:ss");
    ScriptPointValueSetter loggingSetter = new ScriptPointValueSetter(permissions) {

        @Override
        public void set(IDataPointValueSource point, Object value, long timestamp, String annotation) {
            DataPointRT dprt = (DataPointRT) point;
            if (!dprt.getVO().getPointLocator().isSettable()) {
                scriptOut.append("Point " + dprt.getVO().getExtendedName() + " not settable.");
                return;
            }
            if (!Permissions.hasPermission(dprt.getVO().getSetPermission(), permissions.getDataPointSetPermissions())) {
                scriptOut.write(new TranslatableMessage("pointLinks.setTest.permissionDenied", dprt.getVO().getXid()).translate(Common.getTranslations()));
                return;
            }
            scriptOut.append("Setting point " + dprt.getVO().getName() + " to " + value + " @" + sdf.format(new Date(timestamp)) + "\r\n");
        }

        @Override
        protected void setImpl(IDataPointValueSource point, Object value, long timestamp, String annotation) {
        // not really setting
        }
    };
    try {
        CompiledScript compiledScript = CompiledScriptExecutor.compile(script);
        PointValueTime pvt = CompiledScriptExecutor.execute(compiledScript, context, null, System.currentTimeMillis(), targetDataType, -1, permissions, scriptWriter, scriptLog, loggingSetter, null, true);
        if (pvt.getValue() == null)
            message = new TranslatableMessage("event.pointLink.nullResult");
        else if (pvt.getValue() == CompiledScriptExecutor.UNCHANGED)
            message = new TranslatableMessage("pointLinks.validate.successNoValue");
        else if (pvt.getTime() == -1)
            message = new TranslatableMessage("pointLinks.validate.success", pvt.getValue());
        else
            message = new TranslatableMessage("pointLinks.validate.successTs", pvt.getValue(), Functions.getTime(pvt.getTime()));
        // Add the script logging output
        response.addData("out", scriptOut.toString().replaceAll("\n", "<br/>"));
    } catch (ScriptException e) {
        message = new TranslatableMessage("pointLinks.validate.scriptError", e.getMessage());
    } catch (ResultTypeException e) {
        message = e.getTranslatableMessage();
    }
    response.addMessage("script", message);
    return response;
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) CompiledScript(javax.script.CompiledScript) ScriptPointValueSetter(com.serotonin.m2m2.rt.script.ScriptPointValueSetter) HashMap(java.util.HashMap) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) Date(java.util.Date) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) StringWriter(java.io.StringWriter) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) SimpleDateFormat(java.text.SimpleDateFormat) PrintWriter(java.io.PrintWriter) DwrPermission(com.serotonin.m2m2.web.dwr.util.DwrPermission)

Example 15 with TranslatableMessage

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

the class DataImportController method importCsv.

/**
 * The file needs to be in the format:
 *
 * Data Point XID, Device Name, Point name, Time, Value, Rendered, Annotation, Modify(Not used yet)
 *
 * @param reader
 * @param model
 * @return
 * @throws IOException
 * @throws TranslatableException
 */
private void importCsv(CSVReader csvReader, Map<String, Object> model, Translations translations, List<String> errorMessages) throws IOException, TranslatableException {
    DataPointDao dataPointDao = DataPointDao.instance;
    PointValueDao pointValueDao = Common.databaseProxy.newPointValueDao();
    int rowErrors = 0;
    int rowsImported = 0;
    int rowsDeleted = 0;
    // Basic validation of header
    String[] nextLine = csvReader.readNext();
    if (nextLine == null) {
        errorMessages.add(new TranslatableMessage("dataImport.import.noData").translate(translations));
        return;
    }
    if (nextLine.length != ExportCsvStreamer.columns) {
        errorMessages.add(new TranslatableMessage("dataImport.import.invalidHeaders", nextLine.length, ExportCsvStreamer.columns).translate(translations));
        return;
    }
    // Map of XIDs to non-running data points
    Map<String, DataPointVO> voMap = new HashMap<String, DataPointVO>();
    // Map of XIDs to running data points
    Map<String, DataPointRT> rtMap = new HashMap<String, DataPointRT>();
    // Read in all the rows
    int row = 1;
    String xid;
    DataPointVO vo;
    DataPointRT rt;
    long time;
    DataValue value;
    PointValueTime pvt;
    while ((nextLine = csvReader.readNext()) != null) {
        if (nextLine.length != ExportCsvStreamer.columns) {
            errorMessages.add(new TranslatableMessage("dataImport.import.invalidLength", row).translate(translations));
            rowErrors++;
            row++;
            continue;
        }
        // Check XID
        xid = nextLine[0];
        if (StringUtils.isBlank(xid)) {
            errorMessages.add(new TranslatableMessage("dataImport.import.badXid", xid, row).translate(translations));
            rowErrors++;
            row++;
            continue;
        }
        // First Check to see if we already have a point
        vo = voMap.get(xid);
        rt = rtMap.get(xid);
        // We will always have the vo in the map but the RT may be null if the point isn't running
        if (vo == null) {
            vo = dataPointDao.getDataPoint(xid);
            if (vo == null) {
                errorMessages.add(new TranslatableMessage("dataImport.import.xidNotFound", xid, row).translate(translations));
                rowErrors++;
                row++;
                continue;
            }
            rt = Common.runtimeManager.getDataPoint(vo.getId());
            rtMap.put(xid, rt);
            voMap.put(xid, vo);
        }
        // Add or delete or nothing
        String modify = nextLine[7];
        if (StringUtils.equalsIgnoreCase("add", modify)) {
            // Going to insert some data
            time = ExportCsvStreamer.dtf.parseDateTime(nextLine[3]).getMillis();
            value = DataValue.stringToValue(nextLine[4], vo.getPointLocator().getDataTypeId());
            // Get Annotation
            String annotation = nextLine[6];
            if (annotation != null)
                pvt = new AnnotatedPointValueTime(value, time, new TranslatableMessage("common.default", annotation));
            else
                pvt = new PointValueTime(value, time);
            if (rt == null) {
                // Insert Via DAO
                pointValueDao.savePointValueAsync(vo.getId(), pvt, null);
            } else {
                // Insert Via RT
                rt.savePointValueDirectToCache(pvt, null, true, true);
            }
            rowsImported++;
        } else if (StringUtils.equalsIgnoreCase("delete", modify)) {
            // Delete this entry
            time = ExportCsvStreamer.dtf.parseDateTime(nextLine[3]).getMillis();
            rowsDeleted += Common.runtimeManager.purgeDataPointValue(vo.getId(), time);
        }
        row++;
    }
    // Setup results
    model.put("rowsImported", rowsImported);
    model.put("rowsDeleted", rowsDeleted);
    model.put("rowsWithErrors", rowErrors);
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) DataPointDao(com.serotonin.m2m2.db.dao.DataPointDao) HashMap(java.util.HashMap) DataValue(com.serotonin.m2m2.rt.dataImage.types.DataValue) PointValueDao(com.serotonin.m2m2.db.dao.PointValueDao) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) AnnotatedPointValueTime(com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) AnnotatedPointValueTime(com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime) 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