Search in sources :

Example 16 with JsonValue

use of com.serotonin.json.type.JsonValue in project ma-modules-public by infiniteautomation.

the class ModulesRestController method getUpgrades.

@ApiOperation(value = "Get Available Upgrades", notes = "Check the store for Upgrades")
@RequestMapping(method = RequestMethod.GET, value = "/upgrades-available", produces = { "application/json" })
public ResponseEntity<ModuleUpgradesModel> getUpgrades(HttpServletRequest request) {
    RestProcessResult<ModuleUpgradesModel> result = new RestProcessResult<ModuleUpgradesModel>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        if (Permissions.hasAdmin(user)) {
            // Do the check
            try {
                JsonValue jsonResponse = ModulesDwr.getAvailableUpgrades();
                if (jsonResponse instanceof JsonString) {
                    result.addRestMessage(getInternalServerErrorMessage(jsonResponse.toString()));
                } else {
                    List<ModuleUpgradeModel> upgrades = new ArrayList<>();
                    List<ModuleUpgradeModel> newInstalls = new ArrayList<>();
                    ModuleUpgradesModel model = new ModuleUpgradesModel(upgrades, newInstalls);
                    JsonObject root = jsonResponse.toJsonObject();
                    JsonValue jsonUpgrades = root.get("upgrades");
                    JsonArray jsonUpgradesArray = jsonUpgrades.toJsonArray();
                    Iterator<JsonValue> it = jsonUpgradesArray.iterator();
                    while (it.hasNext()) {
                        JsonValue v = it.next();
                        if (v.getJsonValue("name") == null) {
                            it.remove();
                            continue;
                        }
                        String name = v.getJsonValue("name").toString();
                        Module module = "core".equals(name) ? ModuleRegistry.getCoreModule() : ModuleRegistry.getModule(name);
                        if (module == null) {
                            it.remove();
                            continue;
                        }
                        upgrades.add(new ModuleUpgradeModel(module, v));
                    }
                    JsonValue jsonInstalls = root.get("newInstalls");
                    JsonArray jsonInstallsArray = jsonInstalls.toJsonArray();
                    for (JsonValue v : jsonInstallsArray) {
                        newInstalls.add(new ModuleUpgradeModel(v));
                    }
                    return result.createResponseEntity(model);
                }
            } catch (SocketTimeoutException e) {
                result.addRestMessage(HttpStatus.INTERNAL_SERVER_ERROR, new TranslatableMessage("rest.error.requestTimeout", Common.envProps.getString("store.url")));
            } catch (UnknownHostException e) {
                result.addRestMessage(HttpStatus.INTERNAL_SERVER_ERROR, new TranslatableMessage("rest.error.unknownHost", Common.envProps.getString("store.url")));
            } catch (Exception e) {
                result.addRestMessage(getInternalServerErrorMessage(e.getMessage()));
            }
        } else {
            result.addRestMessage(this.getUnauthorizedMessage());
        }
    }
    return result.createResponseEntity();
}
Also used : User(com.serotonin.m2m2.vo.User) UnknownHostException(java.net.UnknownHostException) JsonValue(com.serotonin.json.type.JsonValue) ArrayList(java.util.ArrayList) JsonObject(com.serotonin.json.type.JsonObject) JsonString(com.serotonin.json.type.JsonString) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException) FileNotFoundException(java.io.FileNotFoundException) ModuleRestV2Exception(com.infiniteautomation.mango.rest.v2.exception.ModuleRestV2Exception) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) JsonArray(com.serotonin.json.type.JsonArray) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) ModuleUpgradeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.modules.ModuleUpgradeModel) SocketTimeoutException(java.net.SocketTimeoutException) ModuleUpgradesModel(com.serotonin.m2m2.web.mvc.rest.v1.model.modules.ModuleUpgradesModel) JsonString(com.serotonin.json.type.JsonString) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) Module(com.serotonin.m2m2.module.Module) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 17 with JsonValue

use of com.serotonin.json.type.JsonValue in project ma-modules-public by infiniteautomation.

the class ModuleUpgradeModel method loadFromStoreJson.

public void loadFromStoreJson(JsonValue v) {
    this.dependencyVersions = new HashMap<>();
    JsonValue sub = v.getJsonValue("name");
    if (sub != null)
        this.name = sub.toString();
    sub = v.getJsonValue("version");
    if (sub != null)
        this.newVersion = sub.toString();
    sub = v.getJsonValue("fullVersion");
    if (sub != null)
        this.newVersion = sub.toString();
    sub = v.getJsonValue("shortDescription");
    if (sub != null)
        this.description = sub.toString();
    sub = v.getJsonValue("longDescription");
    if (sub != null)
        this.longDescription = sub.toString();
    sub = v.getJsonValue("vendorName");
    if (sub != null)
        this.vendor = sub.toString();
    sub = v.getJsonValue("vendorUrl");
    if (sub != null)
        this.vendorUrl = sub.toString();
    sub = v.getJsonValue("releaseNotes");
    if (sub != null)
        this.releaseNotes = sub.toString();
    JsonValue dependencies = v.getJsonValue("dependencies");
    JsonValue fullDependencies = v.getJsonValue("fullDependencies");
    if (dependencies instanceof JsonArray && !(fullDependencies instanceof JsonObject)) {
        dependencies.toList().forEach((obj) -> {
            String moduleName = obj.toString();
            String versionRange = Common.getVersion().getMajorVersion() + "." + Common.getVersion().getMinorVersion();
            this.dependencyVersions.put(moduleName, versionRange);
        });
    }
    if (fullDependencies instanceof JsonObject) {
        fullDependencies.toMap().forEach((key, value) -> {
            this.dependencyVersions.put(key, value.toString());
        });
    }
    this.dependencies = this.dependencyVersions.entrySet().stream().map((entry) -> {
        return entry.getKey() + ":" + entry.getValue();
    }).collect(Collectors.joining(","));
}
Also used : JsonArray(com.serotonin.json.type.JsonArray) JsonValue(com.serotonin.json.type.JsonValue) JsonObject(com.serotonin.json.type.JsonObject)

Example 18 with JsonValue

use of com.serotonin.json.type.JsonValue in project ma-modules-public by infiniteautomation.

the class ReportVO method jsonRead.

/* (non-Javadoc)
	 * @see com.serotonin.json.spi.JsonSerializable#jsonRead(com.serotonin.json.JsonReader, com.serotonin.json.type.JsonObject)
	 */
@Override
public void jsonRead(JsonReader reader, JsonObject jsonObject) throws JsonException {
    super.jsonRead(reader, jsonObject);
    if (jsonObject.containsKey("userId")) {
        userId = jsonObject.getInt("userId");
    } else if (jsonObject.containsKey("user")) {
        String username = jsonObject.getString("user");
        if (org.apache.commons.lang3.StringUtils.isBlank(username))
            throw new TranslatableJsonException("emport.error.missingValue", "user");
        User user = UserDao.instance.getUser(username);
        if (user == null)
            throw new TranslatableJsonException("emport.error.missingUser", username);
        userId = user.getId();
    }
    String text = jsonObject.getString("includeEvents");
    if (text != null) {
        includeEvents = EVENT_CODES.getId(text);
        if (includeEvents == -1)
            throw new TranslatableJsonException("emport.error.invalid", "includeEvents", text, EVENT_CODES.getCodeList());
    }
    text = jsonObject.getString("dateRangeType");
    if (text != null) {
        dateRangeType = DATE_RANGE_TYPES.getId(text);
        if (dateRangeType == -1)
            throw new TranslatableJsonException("emport.error.invalid", "dateRangeType", text, DATE_RANGE_TYPES.getCodeList());
    }
    if (dateRangeType == DATE_RANGE_TYPE_RELATIVE) {
        text = jsonObject.getString("relativeDateType");
        if (text != null) {
            relativeDateType = DATE_RELATIVE_TYPES.getId(text);
            if (relativeDateType == -1)
                throw new TranslatableJsonException("emport.error.invalid", "relativeDateType", text, DATE_RELATIVE_TYPES.getCodeList());
        }
        if (relativeDateType == RELATIVE_DATE_TYPE_PREVIOUS) {
            text = jsonObject.getString("previousPeriodType");
            if (text != null) {
                previousPeriodType = Common.TIME_PERIOD_CODES.getId(text);
                if (previousPeriodType == -1)
                    throw new TranslatableJsonException("emport.error.invalid", "previousPeriodType", text, Common.TIME_PERIOD_CODES.getCodeList());
                previousPeriodCount = jsonObject.getInt("previousPeriods");
            } else {
                // FOR legacy bug where previousPeriodType was misspelled
                text = jsonObject.getString("perviousPeriodType");
                if (text != null) {
                    previousPeriodType = Common.TIME_PERIOD_CODES.getId(text);
                    if (previousPeriodType == -1)
                        throw new TranslatableJsonException("emport.error.invalid", "previousPeriodType", text, Common.TIME_PERIOD_CODES.getCodeList());
                    previousPeriodCount = jsonObject.getInt("previousPeriods");
                }
            }
        } else if (relativeDateType == RELATIVE_DATE_TYPE_PREVIOUS) {
            text = jsonObject.getString("pastPeriodType");
            if (text != null) {
                pastPeriodType = Common.TIME_PERIOD_CODES.getId(text);
                if (pastPeriodType == -1)
                    throw new TranslatableJsonException("emport.error.invalid", "pastPeriodType", text, Common.TIME_PERIOD_CODES.getCodeList());
                pastPeriodCount = jsonObject.getInt("pastPeriods");
            }
        }
    } else if (dateRangeType == DATE_RANGE_TYPE_SPECIFIC) {
        fromNone = jsonObject.getBoolean("fromInception");
        if (!fromNone) {
            fromYear = jsonObject.getInt("fromYear");
            fromMonth = jsonObject.getInt("fromMonth");
            fromDay = jsonObject.getInt("fromDay");
            fromHour = jsonObject.getInt("fromHour");
            fromMinute = jsonObject.getInt("fromMinute");
        }
        toNone = jsonObject.getBoolean("toLatest");
        if (!toNone) {
            toYear = jsonObject.getInt("toYear");
            toMonth = jsonObject.getInt("toMonth");
            toDay = jsonObject.getInt("toDay");
            toHour = jsonObject.getInt("toHour");
            toMinute = jsonObject.getInt("toMinute");
        }
    }
    schedule = jsonObject.getBoolean("schedule");
    if (schedule) {
        text = jsonObject.getString("schedulePeriod");
        if (text != null) {
            schedulePeriod = SCHEDULE_CODES.getId(text);
            if (schedulePeriod == -1)
                throw new TranslatableJsonException("emport.error.invalid", "schedulePeriod", text, SCHEDULE_CODES.getCodeList());
            if (schedulePeriod == SCHEDULE_CRON) {
                scheduleCron = jsonObject.getString("scheduleCron");
                try {
                    new CronTimerTrigger(scheduleCron);
                } catch (ParseException e) {
                    throw new TranslatableJsonException("emport.error.invalid", "scheduleCron", scheduleCron, "cron expressions");
                }
            }
        } else {
            throw new TranslatableJsonException("emport.error.invalid", "schedulePeriod", "null", SCHEDULE_CODES.getCodeList());
        }
    }
    email = jsonObject.getBoolean("email");
    if (email) {
        JsonArray recipientsArray = jsonObject.getJsonArray("recipients");
        boolean add = true;
        if (recipientsArray != null) {
            for (JsonValue jv : recipientsArray) {
                RecipientListEntryBean recipient = new RecipientListEntryBean();
                reader.readInto(recipient, jv);
                for (RecipientListEntryBean existing : recipients) {
                    if (existing.equals(recipient)) {
                        reader.readInto(existing, jv);
                        add = false;
                        break;
                    }
                }
                if (add) {
                    recipients.add(recipient);
                } else {
                    add = true;
                }
            }
        } else {
            throw new TranslatableJsonException("emport.error.invalid", "recipients", "null", "valid users, email addresses or mailing lists");
        }
        includeData = jsonObject.getBoolean("includeData");
        if (includeData)
            zipData = jsonObject.getBoolean("zipData");
    }
    JsonArray pointsArray = jsonObject.getJsonArray("points");
    if (pointsArray != null) {
        points = new ArrayList<ReportPointVO>();
        for (JsonValue jv : pointsArray) {
            ReportPointVO reportPoint = new ReportPointVO();
            reader.readInto(reportPoint, jv);
            // TODO prevent adding the same point twice?
            points.add(reportPoint);
        }
    }
}
Also used : JsonArray(com.serotonin.json.type.JsonArray) User(com.serotonin.m2m2.vo.User) JsonValue(com.serotonin.json.type.JsonValue) TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) CronTimerTrigger(com.serotonin.timer.CronTimerTrigger) ParseException(java.text.ParseException) RecipientListEntryBean(com.serotonin.m2m2.web.dwr.beans.RecipientListEntryBean)

Example 19 with JsonValue

use of com.serotonin.json.type.JsonValue in project ma-modules-public by infiniteautomation.

the class WatchListVO method jsonRead.

@Override
public void jsonRead(JsonReader reader, JsonObject jsonObject) throws JsonException {
    super.jsonRead(reader, jsonObject);
    String username = jsonObject.getString("user");
    if (StringUtils.isBlank(username))
        throw new TranslatableJsonException("emport.error.missingValue", "user");
    User user = UserDao.instance.getUser(username);
    if (user == null)
        throw new TranslatableJsonException("emport.error.missingUser", username);
    userId = user.getId();
    JsonArray jsonDataPoints = jsonObject.getJsonArray("dataPoints");
    if (jsonDataPoints != null) {
        pointList.clear();
        DataPointDao dataPointDao = DataPointDao.instance;
        for (JsonValue jv : jsonDataPoints) {
            String xid = jv.toString();
            DataPointVO dpVO = dataPointDao.getDataPoint(xid);
            if (dpVO == null)
                throw new TranslatableJsonException("emport.error.missingPoint", xid);
            pointList.add(dpVO);
        }
    }
    JsonObject o = jsonObject.getJsonObject("data");
    if (o != null)
        this.data = o.toMap();
}
Also used : JsonArray(com.serotonin.json.type.JsonArray) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) User(com.serotonin.m2m2.vo.User) DataPointDao(com.serotonin.m2m2.db.dao.DataPointDao) JsonValue(com.serotonin.json.type.JsonValue) TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) JsonObject(com.serotonin.json.type.JsonObject)

Example 20 with JsonValue

use of com.serotonin.json.type.JsonValue in project ma-core-public by infiniteautomation.

the class EmportDwr method importData.

@DwrPermission(admin = true)
public ProcessResult importData(String data) {
    ProcessResult response = new ProcessResult();
    Translations translations = getTranslations();
    User user = Common.getHttpUser();
    JsonTypeReader reader = new JsonTypeReader(data);
    try {
        JsonValue value = reader.read();
        if (value instanceof JsonObject) {
            JsonObject root = value.toJsonObject();
            ImportTask importTask = new ImportTask(root, translations, user, true);
            user.setImportTask(importTask);
            response.addData("importStarted", true);
        } else {
            response.addGenericMessage("emport.invalidImportData");
        }
    } catch (ClassCastException e) {
        response.addGenericMessage("emport.parseError", e.getMessage());
    } catch (TranslatableJsonException e) {
        response.addMessage(e.getMsg());
    } catch (IOException e) {
        response.addGenericMessage("emport.parseError", e.getMessage());
    } catch (JsonException e) {
        response.addGenericMessage("emport.parseError", e.getMessage());
    }
    return response;
}
Also used : TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) JsonException(com.serotonin.json.JsonException) User(com.serotonin.m2m2.vo.User) ImportTask(com.serotonin.m2m2.web.dwr.emport.ImportTask) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) JsonValue(com.serotonin.json.type.JsonValue) JsonObject(com.serotonin.json.type.JsonObject) TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) IOException(java.io.IOException) Translations(com.serotonin.m2m2.i18n.Translations) JsonTypeReader(com.serotonin.json.type.JsonTypeReader) DwrPermission(com.serotonin.m2m2.web.dwr.util.DwrPermission)

Aggregations

JsonValue (com.serotonin.json.type.JsonValue)41 JsonArray (com.serotonin.json.type.JsonArray)26 JsonObject (com.serotonin.json.type.JsonObject)21 JsonTypeReader (com.serotonin.json.type.JsonTypeReader)15 TranslatableJsonException (com.serotonin.m2m2.i18n.TranslatableJsonException)15 JsonWriter (com.serotonin.json.JsonWriter)10 StringWriter (java.io.StringWriter)10 HttpPost (org.apache.http.client.methods.HttpPost)10 StringEntity (org.apache.http.entity.StringEntity)10 JsonException (com.serotonin.json.JsonException)8 IOException (java.io.IOException)7 JsonString (com.serotonin.json.type.JsonString)5 DataPointDao (com.serotonin.m2m2.db.dao.DataPointDao)5 User (com.serotonin.m2m2.vo.User)5 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)3 IntStringPair (com.serotonin.db.pair.IntStringPair)3 JsonReader (com.serotonin.json.JsonReader)3 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)3 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)3 Type (java.lang.reflect.Type)3