Search in sources :

Example 1 with LicenseViolatedException

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

the class DataSourceEditDwr method validatePoint.

protected ProcessResult validatePoint(int id, String xid, String name, PointLocatorVO<?> locator, DataPointDefaulter defaulter, boolean includePointList) {
    ProcessResult response = new ProcessResult();
    // This saving of the point into the User is a bad idea, need to rework to
    // pass the point back and forth to page.
    DataPointVO dp = getPoint(id, defaulter);
    dp.setXid(xid);
    dp.setName(name);
    dp.setPointLocator(locator);
    // Confirm that we are assinging a point to the correct data source
    DataSourceVO<?> ds = DataSourceDao.instance.get(dp.getDataSourceId());
    PointLocatorVO<?> plvo = ds.createPointLocator();
    if (plvo.getClass() != locator.getClass()) {
        response.addGenericMessage("validate.invalidType");
        return response;
    }
    // If we are a new point then only validate the basics
    if (id == Common.NEW_ID) {
        if (StringUtils.isBlank(xid))
            response.addContextualMessage("xid", "validate.required");
        else if (StringValidation.isLengthGreaterThan(xid, 50))
            response.addMessage("xid", new TranslatableMessage("validate.notLongerThan", 50));
        else if (!DataPointDao.instance.isXidUnique(xid, id))
            response.addContextualMessage("xid", "validate.xidUsed");
        if (StringUtils.isBlank(name))
            response.addContextualMessage("name", "validate.required");
        // Load in the default Template
        DataPointPropertiesTemplateVO template = TemplateDao.instance.getDefaultDataPointTemplate(locator.getDataTypeId());
        if (template != null) {
            template.updateDataPointVO(dp);
        }
        // Should really be done elsewhere
        dp.setEventDetectors(new ArrayList<AbstractPointEventDetectorVO<?>>());
    } else if (id == DataPointDwr.COPY_ID) {
        dp.setId(Common.NEW_ID);
        if (StringUtils.isBlank(xid))
            response.addContextualMessage("xid", "validate.required");
        else if (StringValidation.isLengthGreaterThan(xid, 50))
            response.addMessage("xid", new TranslatableMessage("validate.notLongerThan", 50));
        else if (!DataPointDao.instance.isXidUnique(xid, id))
            response.addContextualMessage("xid", "validate.xidUsed");
        if (StringUtils.isBlank(name))
            response.addContextualMessage("name", "validate.required");
    } else {
        // New validation on save for all settings on existing points
        dp.validate(response);
        if (dp.getChartRenderer() != null)
            dp.getChartRenderer().validate(response);
        if (dp.getTextRenderer() != null)
            dp.getTextRenderer().validate(response);
    }
    // Validate Locator
    locator.validate(response, dp);
    if (!response.getHasMessages()) {
        try {
            Common.runtimeManager.saveDataPoint(dp);
        } catch (DuplicateKeyException e) {
            response.addGenericMessage("pointEdit.detectors.duplicateXid");
            return response;
        } catch (LicenseViolatedException e) {
            response.addMessage(e.getErrorMessage());
            return response;
        }
        if (defaulter != null)
            defaulter.postSave(dp);
        response.addData("id", dp.getId());
        response.addData("vo", dp);
        if (includePointList)
            response.addData("points", getPoints());
        // Set the User Point
        Common.getUser().setEditPoint(dp);
    }
    return response;
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) AbstractPointEventDetectorVO(com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO) LicenseViolatedException(com.serotonin.m2m2.LicenseViolatedException) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) DataPointPropertiesTemplateVO(com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) DuplicateKeyException(org.springframework.dao.DuplicateKeyException)

Example 2 with LicenseViolatedException

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

the class DataPointImporter method importImpl.

@Override
protected void importImpl() {
    String xid = json.getString("xid");
    DataPointVO vo = null;
    DataSourceVO<?> dsvo = null;
    if (StringUtils.isBlank(xid))
        xid = ctx.getDataPointDao().generateUniqueXid();
    else
        vo = ctx.getDataPointDao().getDataPoint(xid);
    if (vo == null) {
        // Locate the data source for the point.
        String dsxid = json.getString("dataSourceXid");
        dsvo = ctx.getDataSourceDao().getDataSource(dsxid);
        if (dsvo == null)
            addFailureMessage("emport.dataPoint.badReference", xid);
        else {
            vo = new DataPointVO();
            vo.setXid(xid);
            vo.setDataSourceId(dsvo.getId());
            vo.setDataSourceXid(dsxid);
            vo.setPointLocator(dsvo.createPointLocator());
            vo.setEventDetectors(new ArrayList<AbstractPointEventDetectorVO<?>>(0));
        // Not needed as it will be set via the template or JSON or it exists in the DB already: vo.setTextRenderer(new PlainRenderer());
        }
    }
    if (vo != null) {
        try {
            DataPointPropertiesTemplateVO template = null;
            if (json.containsKey("templateXid")) {
                String templateXid = json.getString("templateXid");
                if (!StringUtils.isEmpty(templateXid))
                    template = (DataPointPropertiesTemplateVO) TemplateDao.instance.getByXid(templateXid);
            }
            // Read into the VO to get all properties
            ctx.getReader().readInto(vo, json);
            // Override the settings if we need to
            if (template != null) {
                template.updateDataPointVO(vo);
            }
            // If the name is not provided, default to the XID
            if (StringUtils.isBlank(vo.getName()))
                vo.setName(xid);
            // If the chart colour is null provide default of '' to handle legacy code that sets colour to null
            if (vo.getChartColour() == null)
                vo.setChartColour("");
            // Now validate it. Use a new response object so we can distinguish errors in this vo from
            // other errors.
            ProcessResult voResponse = new ProcessResult();
            vo.validate(voResponse);
            if (voResponse.getHasMessages())
                setValidationMessages(voResponse, "emport.dataPoint.prefix", xid);
            else {
                // We will always override the DS Info with the one from the XID Lookup
                dsvo = ctx.getDataSourceDao().getDataSource(vo.getDataSourceXid());
                if (dsvo == null)
                    addFailureMessage("emport.dataPoint.badReference", xid);
                else {
                    // Compare this point to the existing point in DB to ensure
                    // that we aren't moving a point to a different type of Data Source
                    DataPointVO oldPoint = ctx.getDataPointDao().getDataPoint(vo.getId(), false);
                    // Does the old point have a different data source?
                    if (oldPoint != null && (oldPoint.getDataSourceId() != dsvo.getId())) {
                        vo.setDataSourceId(dsvo.getId());
                        vo.setDataSourceName(dsvo.getName());
                    }
                }
                boolean isNew = vo.isNew();
                try {
                    if (Common.runtimeManager.getState() == RuntimeManager.RUNNING) {
                        Common.runtimeManager.saveDataPoint(vo);
                        if (hierarchyList != null && json.containsKey(PATH)) {
                            String path = json.getString(PATH);
                            if (StringUtils.isNotEmpty(path))
                                hierarchyList.add(new DataPointSummaryPathPair(new DataPointSummary(vo), path));
                        }
                        addSuccessMessage(isNew, "emport.dataPoint.prefix", xid);
                    } else {
                        addFailureMessage(new ProcessMessage("Runtime Manager not running point with xid: " + xid + " not saved."));
                    }
                } catch (LicenseViolatedException e) {
                    addFailureMessage(new ProcessMessage(e.getErrorMessage()));
                }
            }
        } catch (TranslatableJsonException e) {
            addFailureMessage("emport.dataPoint.prefix", xid, e.getMsg());
        } catch (JsonException e) {
            addFailureMessage("emport.dataPoint.prefix", xid, getJsonExceptionMessage(e));
        }
    }
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) JsonException(com.serotonin.json.JsonException) DataPointSummary(com.serotonin.m2m2.vo.DataPointSummary) AbstractPointEventDetectorVO(com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO) LicenseViolatedException(com.serotonin.m2m2.LicenseViolatedException) DataPointPropertiesTemplateVO(com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) ProcessMessage(com.serotonin.m2m2.i18n.ProcessMessage)

Example 3 with LicenseViolatedException

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

the class DataPointDao method checkAddPoint.

public void checkAddPoint() {
    IMangoLifecycle lifecycle = Providers.get(IMangoLifecycle.class);
    Integer limit = lifecycle.dataPointLimit();
    if (limit != null && this.countMonitor.getValue() >= limit) {
        String licenseType;
        if (Common.license() != null)
            licenseType = Common.license().getLicenseType();
        else
            licenseType = "Free";
        throw new LicenseViolatedException(new TranslatableMessage("license.dataPointLimit", licenseType, limit));
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) LicenseViolatedException(com.serotonin.m2m2.LicenseViolatedException) IMangoLifecycle(com.serotonin.m2m2.IMangoLifecycle) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Example 4 with LicenseViolatedException

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

the class DataPointRestController method saveDataPoint.

@ApiOperation(value = "Create a data point", notes = "Content may be CSV or JSON")
@RequestMapping(method = RequestMethod.POST, consumes = { "application/json", "text/csv", "application/sero-json" }, produces = { "application/json", "text/csv", "application/sero-json" })
public ResponseEntity<DataPointModel> saveDataPoint(@ApiParam(value = "Data point model", required = true) @RequestBody(required = true) DataPointModel model, UriComponentsBuilder builder, HttpServletRequest request) {
    RestProcessResult<DataPointModel> result = new RestProcessResult<DataPointModel>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        boolean contentTypeCsv = false;
        if (request.getContentType().toLowerCase().contains("text/csv"))
            contentTypeCsv = true;
        DataPointVO vo = model.getData();
        // Check to see if the point already exists
        if (!StringUtils.isEmpty(vo.getXid())) {
            DataPointVO existing = this.dao.getByXid(vo.getXid());
            if (existing != null) {
                result.addRestMessage(HttpStatus.CONFLICT, new TranslatableMessage("rest.exception.alreadyExists", model.getXid()));
                return result.createResponseEntity();
            }
        }
        // Ensure ds exists
        DataSourceVO<?> dataSource = DataSourceDao.instance.getByXid(model.getDataSourceXid());
        // We will always override the DS Info with the one from the XID Lookup
        if (dataSource == null) {
            result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("emport.dataPoint.badReference", model.getDataSourceXid()));
            return result.createResponseEntity();
        } else {
            vo.setDataSourceId(dataSource.getId());
            vo.setDataSourceName(dataSource.getName());
        }
        // Check permissions
        try {
            if (!Permissions.hasDataSourcePermission(user, vo.getDataSourceId())) {
                result.addRestMessage(getUnauthorizedMessage());
                return result.createResponseEntity();
            }
        } catch (PermissionException e) {
            result.addRestMessage(getUnauthorizedMessage());
            return result.createResponseEntity();
        }
        if (vo.getTextRenderer() == null) {
            vo.setTextRenderer(new PlainRenderer());
        }
        if (vo.getChartColour() == null) {
            vo.setChartColour("");
        }
        // Check the Template and see if we need to use it
        if (model.getTemplateXid() != null) {
            DataPointPropertiesTemplateVO template = (DataPointPropertiesTemplateVO) TemplateDao.instance.getByXid(model.getTemplateXid());
            if (template == null) {
                model.addValidationMessage("validate.invalidReference", RestMessageLevel.ERROR, "templateXid");
                result.addRestMessage(new RestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("emport.dataPoint.badReference", model.getTemplateXid())));
            }
        } else {
            if (contentTypeCsv) {
                model.addValidationMessage("validate.required", RestMessageLevel.ERROR, "templateXid");
                result.addRestMessage(this.getValidationFailedError());
                return result.createResponseEntity(model);
            }
        }
        if (StringUtils.isEmpty(vo.getXid()))
            vo.setXid(DataPointDao.instance.generateUniqueXid());
        // allow empty string, but if its null use the data source name
        if (vo.getDeviceName() == null) {
            vo.setDeviceName(dataSource.getName());
        }
        if (!model.validate()) {
            result.addRestMessage(this.getValidationFailedError());
            return result.createResponseEntity(model);
        } else {
            try {
                Common.runtimeManager.saveDataPoint(vo);
            } catch (LicenseViolatedException e) {
                result.addRestMessage(HttpStatus.METHOD_NOT_ALLOWED, e.getErrorMessage());
            }
        }
        // Put a link to the updated data in the header?
        URI location = builder.path("/v1/data-points/{xid}").buildAndExpand(vo.getXid()).toUri();
        result.addRestMessage(getResourceUpdatedMessage(location));
        return result.createResponseEntity(model);
    }
    // Not logged in
    return result.createResponseEntity();
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) DataPointModel(com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel) User(com.serotonin.m2m2.vo.User) PlainRenderer(com.serotonin.m2m2.view.text.PlainRenderer) LicenseViolatedException(com.serotonin.m2m2.LicenseViolatedException) DataPointPropertiesTemplateVO(com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO) URI(java.net.URI) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) RestMessage(com.serotonin.m2m2.web.mvc.rest.v1.message.RestMessage) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with LicenseViolatedException

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

the class ReportWorkItem method execute.

@Override
public void execute() {
    try {
        ReportLicenseChecker.checkLicense();
    } catch (LicenseViolatedException e) {
        LOG.error("Your core license doesn't permit you to use the reports module.");
        reportInstance.setReportStartTime(Common.timer.currentTimeMillis());
        reportInstance.setReportEndTime(Common.timer.currentTimeMillis());
        reportInstance.setRecordCount(-1);
        reportDao.saveReportInstance(reportInstance);
        return;
    }
    LOG.debug("Running report with id " + reportConfig.getId() + ", instance id " + reportInstance.getId());
    reportInstance.setRunStartTime(System.currentTimeMillis());
    reportDao.saveReportInstance(reportInstance);
    Translations translations = Common.getTranslations();
    // Create a list of DataPointVOs to which the user has permission.
    DataPointDao dataPointDao = DataPointDao.instance;
    List<ReportDao.PointInfo> points = new ArrayList<ReportDao.PointInfo>(reportConfig.getPoints().size());
    for (ReportPointVO reportPoint : reportConfig.getPoints()) {
        DataPointVO point = dataPointDao.getDataPoint(reportPoint.getPointId());
        if (point != null && Permissions.hasDataPointReadPermission(user, point)) {
            String colour = null;
            try {
                if (!StringUtils.isBlank(reportPoint.getColour()))
                    colour = ColorUtils.toHexString(reportPoint.getColour()).substring(1);
            } catch (InvalidArgumentException e) {
            // Should never happen since the colour would have been validated on save, so just let it go
            // as null.
            }
            points.add(new ReportDao.PointInfo(point, colour, reportPoint.getWeight(), reportPoint.isConsolidatedChart(), reportPoint.getPlotType()));
        }
    }
    int recordCount = 0;
    try {
        if (!points.isEmpty()) {
            if (Common.databaseProxy.getNoSQLProxy() == null)
                recordCount = reportDao.runReportSQL(reportInstance, points);
            else
                recordCount = reportDao.runReportNoSQL(reportInstance, points);
        }
    } catch (RuntimeException e) {
        recordCount = -1;
        throw e;
    } catch (Throwable e) {
        recordCount = -1;
        throw new RuntimeException("Report instance failed", e);
    } finally {
        reportInstance.setRunEndTime(System.currentTimeMillis());
        reportInstance.setRecordCount(recordCount);
        reportDao.saveReportInstance(reportInstance);
    }
    if (reportConfig.isEmail()) {
        String inlinePrefix = "R" + System.currentTimeMillis() + "-" + reportInstance.getId() + "-";
        // TODO should we create different instances of the email based upon language and timezone?
        // We are creating an email from the result. Create the content.
        final ReportChartCreator creator = new ReportChartCreator(translations, TimeZone.getDefault());
        creator.createContent(host, port, reportInstance, reportDao, inlinePrefix, reportConfig.isIncludeData());
        // Create the to list
        Set<String> addresses = MailingListDao.instance.getRecipientAddresses(reportConfig.getRecipients(), new DateTime(reportInstance.getReportStartTime()));
        String[] toAddrs = addresses.toArray(new String[0]);
        // Create the email content object.
        EmailContent emailContent = new EmailContent(null, creator.getHtml(), Common.UTF8);
        // Add the consolidated chart
        if (creator.getImageData() != null)
            emailContent.addInline(new EmailInline.ByteArrayInline(inlinePrefix + ReportChartCreator.IMAGE_CONTENT_ID, creator.getImageData(), ImageChartUtils.getContentType()));
        // Add the point charts
        for (PointStatistics pointStatistics : creator.getPointStatistics()) {
            if (pointStatistics.getImageData() != null)
                emailContent.addInline(new EmailInline.ByteArrayInline(inlinePrefix + pointStatistics.getChartName(), pointStatistics.getImageData(), ImageChartUtils.getContentType()));
        }
        // Add optional images used by the template.
        for (String s : creator.getInlineImageList()) addImage(emailContent, s);
        // Check if we need to attach the data.
        if (reportConfig.isIncludeData()) {
            addFileAttachment(emailContent, reportInstance.getName() + ".csv", creator.getExportFile());
            addFileAttachment(emailContent, reportInstance.getName() + "Events.csv", creator.getEventFile());
            addFileAttachment(emailContent, reportInstance.getName() + "Comments.csv", creator.getCommentFile());
        }
        PostEmailRunnable[] postEmail = null;
        if (reportConfig.isIncludeData()) {
            // See that the temp file(s) gets deleted after the email is sent.
            PostEmailRunnable deleteTempFile = new PostEmailRunnable() {

                @Override
                public void run() {
                    for (File file : filesToDelete) {
                        if (!file.delete())
                            LOG.warn("Temp file " + file.getPath() + " not deleted");
                    }
                }
            };
            postEmail = new PostEmailRunnable[] { deleteTempFile };
        }
        try {
            TranslatableMessage lm = new TranslatableMessage("ftl.scheduledReport", reportConfig.getName());
            String subject = creator.getSubject();
            if (subject == null)
                subject = lm.translate(translations);
            EmailWorkItem.queueEmail(toAddrs, subject, emailContent, postEmail);
        } catch (AddressException e) {
            LOG.error(e);
        }
        if (reportConfig.isSchedule()) {
            // Delete the report instance.
            reportDao.deleteReportInstance(reportInstance.getId(), user.getId());
        }
    }
    LOG.debug("Finished running report with id " + reportConfig.getId() + ", instance id " + reportInstance.getId());
}
Also used : LicenseViolatedException(com.serotonin.m2m2.LicenseViolatedException) ArrayList(java.util.ArrayList) EmailContent(com.serotonin.web.mail.EmailContent) DateTime(org.joda.time.DateTime) InvalidArgumentException(com.serotonin.InvalidArgumentException) AddressException(javax.mail.internet.AddressException) ReportPointVO(com.serotonin.m2m2.reports.vo.ReportPointVO) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) DataPointDao(com.serotonin.m2m2.db.dao.DataPointDao) PointStatistics(com.serotonin.m2m2.reports.web.ReportChartCreator.PointStatistics) PostEmailRunnable(com.serotonin.m2m2.email.PostEmailRunnable) ReportDao(com.serotonin.m2m2.reports.ReportDao) Translations(com.serotonin.m2m2.i18n.Translations) File(java.io.File)

Aggregations

LicenseViolatedException (com.serotonin.m2m2.LicenseViolatedException)6 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)5 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)4 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)3 AbstractPointEventDetectorVO (com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO)3 DataPointPropertiesTemplateVO (com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO)3 JsonException (com.serotonin.json.JsonException)2 TranslatableJsonException (com.serotonin.m2m2.i18n.TranslatableJsonException)2 ArrayList (java.util.ArrayList)2 DuplicateKeyException (org.springframework.dao.DuplicateKeyException)2 InvalidArgumentException (com.serotonin.InvalidArgumentException)1 JsonArray (com.serotonin.json.type.JsonArray)1 IMangoLifecycle (com.serotonin.m2m2.IMangoLifecycle)1 DataPointDao (com.serotonin.m2m2.db.dao.DataPointDao)1 PostEmailRunnable (com.serotonin.m2m2.email.PostEmailRunnable)1 ProcessMessage (com.serotonin.m2m2.i18n.ProcessMessage)1 Translations (com.serotonin.m2m2.i18n.Translations)1 ReportDao (com.serotonin.m2m2.reports.ReportDao)1 ReportPointVO (com.serotonin.m2m2.reports.vo.ReportPointVO)1 PointStatistics (com.serotonin.m2m2.reports.web.ReportChartCreator.PointStatistics)1