Search in sources :

Example 81 with TranslatableMessage

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

the class DataPointDetailsController method handleRequest.

@Override
public View handleRequest(HttpServletRequest request, HttpServletResponse response, Map<String, Object> model) throws Exception {
    User user = Common.getHttpUser();
    int id = -1;
    if (user.getEditPoint() != null)
        id = user.getEditPoint().getId();
    DataPointDao dataPointDao = DataPointDao.instance;
    String idStr = request.getParameter("dpid");
    DataPointVO point = null;
    if (StringUtils.equals(idStr, "exception"))
        throw new IOException("testing");
    else if (StringUtils.equals(idStr, "permission-exception"))
        throw new PermissionException(new TranslatableMessage("common.default", "Testing"), user);
    if (StringUtils.isBlank(idStr)) {
        // Check for pedid (point event detector id)
        String pedStr = request.getParameter("pedid");
        if (StringUtils.isBlank(pedStr)) {
            // Check if an XID was provided.
            String xid = request.getParameter("dpxid");
            if (!StringUtils.isBlank(xid)) {
                model.put("currentXid", xid);
                point = dataPointDao.getDataPoint(xid);
                id = point == null ? -2 : point.getId();
            }
        } else {
            int pedid = Integer.parseInt(pedStr);
            id = EventDetectorDao.instance.getSourceId(pedid, EventType.EventTypeNames.DATA_POINT);
        }
    } else
        id = Integer.parseInt(idStr);
    // Find accessible points for the goto list
    List<DataPointSummary> userPoints = ControllerUtils.addPointListDataToModel(user, id, model);
    // Get the point.
    if (point == null && id != -1)
        point = dataPointDao.getDataPoint(id);
    if (point == null && id != -2 && /* -2 means an explicit XID was provided but not found */
    !userPoints.isEmpty()) {
        // Load at least 1 point, there may be many points but some might not actually load if thier data source DNE anymore
        for (DataPointSummary userPoint : userPoints) {
            point = dataPointDao.getDataPoint(userPoint.getId());
            if (point != null)
                break;
        }
    }
    if (point != null) {
        // Check permissions
        Permissions.ensureDataPointReadPermission(user, point);
        // Put the point in the model.
        model.put("point", point);
        // Get the users that have access to this point.
        List<User> allUsers = UserDao.instance.getUsers();
        List<Map<String, Object>> users = new LinkedList<>();
        Map<String, Object> userData;
        int accessType;
        for (User mangoUser : allUsers) {
            accessType = Permissions.getDataPointAccessType(mangoUser, point);
            if (accessType != Permissions.DataPointAccessTypes.NONE) {
                userData = new HashMap<>();
                userData.put("user", mangoUser);
                userData.put("accessType", accessType);
                users.add(userData);
            }
        }
        model.put("users", users);
        // Determine whether the link to edit the point should be displayed
        model.put("pointEditor", Permissions.hasDataSourcePermission(user, point.getDataSourceId()));
        // Put the events in the model.
        model.put("events", EventDao.instance.getEventsForDataPoint(id, user.getId()));
        // Put the default history table count into the model. Default to 10.
        int historyLimit = 10;
        if (point.getChartRenderer() instanceof TableChartRenderer)
            historyLimit = ((TableChartRenderer) point.getChartRenderer()).getLimit();
        else if (point.getChartRenderer() instanceof ImageFlipbookRenderer)
            historyLimit = ((ImageFlipbookRenderer) point.getChartRenderer()).getLimit();
        model.put("historyLimit", historyLimit);
        // Determine our image chart rendering capabilities.
        if (ImageChartRenderer.getDefinition().supports(point.getPointLocator().getDataTypeId())) {
            // This point can render an image chart. Carry on...
            int periodType = Common.TimePeriods.DAYS;
            int periodCount = 1;
            if (point.getChartRenderer() instanceof ImageChartRenderer) {
                ImageChartRenderer r = (ImageChartRenderer) point.getChartRenderer();
                periodType = r.getTimePeriod();
                periodCount = r.getNumberOfPeriods();
            }
            model.put("periodType", periodType);
            model.put("periodCount", periodCount);
        }
        // Determine out flipbook rendering capabilities
        if (ImageFlipbookRenderer.getDefinition().supports(point.getPointLocator().getDataTypeId()))
            model.put("flipbookLimit", 10);
        // Set the point in the session for the dwr.
        user.setEditPoint(point);
        model.put("currentXid", point.getXid());
        model.put("hierPath", CollectionUtils.implode(dataPointDao.getPointHierarchy(true).getPath(id), " &raquo; "));
    }
    return null;
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) TableChartRenderer(com.serotonin.m2m2.view.chart.TableChartRenderer) DataPointSummary(com.serotonin.m2m2.vo.DataPointSummary) User(com.serotonin.m2m2.vo.User) DataPointDao(com.serotonin.m2m2.db.dao.DataPointDao) IOException(java.io.IOException) ImageChartRenderer(com.serotonin.m2m2.view.chart.ImageChartRenderer) LinkedList(java.util.LinkedList) ImageFlipbookRenderer(com.serotonin.m2m2.view.chart.ImageFlipbookRenderer) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) HashMap(java.util.HashMap) Map(java.util.Map)

Example 82 with TranslatableMessage

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

the class FileUploadController method parseFile.

/**
 * Parse the Import Files
 * @param input
 * @param model
 * @param translations
 */
protected void parseFile(InputStream input, Map<String, Object> model, Translations translations, HttpServletRequest request) {
    // Get the filename
    String filename = (String) model.get("filename");
    SpreadsheetEmporter emporter;
    if (filename == null)
        return;
    else {
        if (filename.toLowerCase().endsWith(".xls"))
            emporter = new SpreadsheetEmporter(FileType.XLS);
        else if (filename.toLowerCase().endsWith(".xlsx"))
            emporter = new SpreadsheetEmporter(FileType.XLSX);
        else
            return;
    }
    // Switch on the type
    String dataType = (String) model.get("dataType");
    if (dataType != null) {
        if (dataType.equals("pointValue")) {
            // List the sheets and create sheet emporters for each
            for (Sheet sheet : emporter.listSheets(input)) emporter.doImport(input, new PointValueEmporter(sheet.getSheetName()));
        } else
            throw new ShouldNeverHappenException("Unsupported data.");
    }
    model.put("hasImportErrors", emporter.hasErrors());
    // Get the messages
    if (emporter.hasErrors()) {
        List<String> errorMessages = new ArrayList<String>();
        for (TranslatableMessage msg : emporter.getErrorMessages()) {
            errorMessages.add(msg.translate(translations));
        }
        model.put("errorMessages", errorMessages);
    }
    model.put("rowsImported", emporter.getRowsAdded());
    model.put("rowsDeleted", emporter.getRowsDeleted());
    model.put("rowsWithErrors", emporter.getRowErrors());
}
Also used : PointValueEmporter(com.serotonin.m2m2.rt.dataImage.PointValueEmporter) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) ArrayList(java.util.ArrayList) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) SpreadsheetEmporter(com.serotonin.m2m2.vo.emport.SpreadsheetEmporter) Sheet(org.apache.poi.ss.usermodel.Sheet)

Example 83 with TranslatableMessage

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

the class SystemEventType method raiseEvent.

public static void raiseEvent(SystemEventType type, long time, boolean rtn, TranslatableMessage message) {
    EventTypeVO vo = getEventType(type.getSystemEventType());
    if (vo == null) {
        LOG.warn("Unkown event type null");
        return;
    }
    int alarmLevel = vo.getAlarmLevel();
    Common.eventManager.raiseEvent(type, time, rtn, alarmLevel, message, null);
}
Also used : EventTypeVO(com.serotonin.m2m2.vo.event.EventTypeVO)

Example 84 with TranslatableMessage

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

the class JsonEmportScriptTestUtility method doImportGetStatus.

@Override
public List<ProcessMessage> doImportGetStatus(String json) {
    List<ProcessMessage> result = new ArrayList<>(1);
    result.add(new ProcessMessage(new TranslatableMessage("literal", "Cannot run or test imports during validation.")));
    return result;
}
Also used : ArrayList(java.util.ArrayList) ProcessMessage(com.serotonin.m2m2.i18n.ProcessMessage) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Example 85 with TranslatableMessage

use of com.serotonin.m2m2.i18n.TranslatableMessage 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)

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