Search in sources :

Example 26 with JsonException

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

the class SerotoninJsonMessageConverter method readInternal.

/* (non-Javadoc)
	 * @see org.springframework.http.converter.AbstractHttpMessageConverter#readInternal(java.lang.Class, org.springframework.http.HttpInputMessage)
	 */
@Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    InputStreamReader isReader = new InputStreamReader(inputMessage.getBody());
    JsonTypeReader typeReader = new JsonTypeReader(isReader);
    try {
        JsonValue value = typeReader.read();
        if (clazz.equals(JsonValue.class))
            return value;
        // First get the definition for the model so we can create a real object
        ModelDefinition def = findModelDefinition(clazz);
        AbstractRestModel<?> model = def.createModel();
        JsonReader reader = new JsonReader(Common.JSON_CONTEXT, value);
        if (value instanceof JsonObject) {
            // TODO Should do some pre-validation or something to ensure we are
            // importing the right thing?
            JsonObject root = value.toJsonObject();
            if (model != null) {
                Object data = model.getData();
                reader.readInto(data, root);
                return model;
            } else {
                // Catchall
                return root.toNative();
            }
        } else {
            throw new IOException("Huh?");
        }
    } catch (JsonException e) {
        throw new IOException(e);
    }
}
Also used : JsonException(com.serotonin.json.JsonException) InputStreamReader(java.io.InputStreamReader) JsonValue(com.serotonin.json.type.JsonValue) ModelDefinition(com.serotonin.m2m2.module.ModelDefinition) JsonReader(com.serotonin.json.JsonReader) JsonObject(com.serotonin.json.type.JsonObject) JsonObject(com.serotonin.json.type.JsonObject) IOException(java.io.IOException) JsonTypeReader(com.serotonin.json.type.JsonTypeReader)

Example 27 with JsonException

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

the class JsonSerializableUtility method findProperties.

public List<SerializableProperty> findProperties(Class<?> clazz) throws JsonException {
    // 
    // Introspect the class.
    List<SerializableProperty> properties = new ArrayList<>();
    boolean jsonSerializable = JsonSerializable.class.isAssignableFrom(clazz);
    if (!jsonSerializable) {
        // Is it a semi-primative
        if (clazz.isAssignableFrom(Boolean.class) || clazz.isAssignableFrom(Byte.class) || clazz.isAssignableFrom(Short.class) || clazz.isAssignableFrom(Integer.class) || clazz.isAssignableFrom(Long.class) || clazz.isAssignableFrom(Float.class) || clazz.isAssignableFrom(Double.class) || clazz.isAssignableFrom(BigInteger.class) || clazz.isAssignableFrom(BigDecimal.class) || clazz.isAssignableFrom(String.class) || clazz.isAssignableFrom(Object.class))
            return properties;
    }
    BeanInfo info;
    try {
        info = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException e) {
        throw new JsonException(e);
    }
    PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
    // Annotations or beans
    Class<?> currentClazz = clazz;
    while (currentClazz != Object.class) {
        boolean annotationsFound = addAnnotatedProperties(currentClazz, descriptors, properties);
        // Serotonin JSON searches for POJO properties here, we don't want to.
        if (!annotationsFound && !currentClazz.isAnnotationPresent(JsonEntity.class) && !jsonSerializable)
            addPojoProperties(currentClazz, descriptors, properties);
        currentClazz = currentClazz.getSuperclass();
    }
    return properties;
}
Also used : JsonException(com.serotonin.json.JsonException) JsonEntity(com.serotonin.json.spi.JsonEntity) PropertyDescriptor(java.beans.PropertyDescriptor) SerializableProperty(com.serotonin.json.util.SerializableProperty) BeanInfo(java.beans.BeanInfo) ArrayList(java.util.ArrayList) IntrospectionException(java.beans.IntrospectionException) BigDecimal(java.math.BigDecimal) JsonObject(com.serotonin.json.type.JsonObject)

Example 28 with JsonException

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

the class SubclassTest method main.

public static void main(String[] args) throws Exception {
    JsonContext context = new JsonContext();
    context.addResolver(new TypeResolver() {

        @Override
        public Class<?> resolve(JsonValue jsonValue) throws JsonException {
            if (jsonValue.toJsonObject().containsKey("sub1Value"))
                return Subclass1.class;
            if (jsonValue.toJsonObject().containsKey("sub2Value"))
                return Subclass2.class;
            throw new JsonException("Unknown BaseClass: " + jsonValue);
        }
    }, BaseClass.class);
    // context.addFactory(new ObjectFactory() {
    // @Override
    // public Object create(JsonValue jsonValue) throws JsonException {
    // if (jsonValue.toJsonObject().hasProperty("sub1Value"))
    // return new Subclass1();
    // if (jsonValue.toJsonObject().hasProperty("sub2Value"))
    // return new Subclass2();
    // throw new JsonException("Unknown BaseClass: " + jsonValue);
    // }
    // }, BaseClass.class);
    // List<BaseClass> list = new ArrayList<BaseClass>();
    // list.add(new Subclass1());
    // list.add(new Subclass2());
    // 
    // String json = JsonWriter.writeToString(context, list);
    // 
    // System.out.println(json);
    String json = "[{\"id\":\"Subclass1\",\"sub1Value\":\"a\",\"baseValue\":\"b\"},{\"myId\":\"Subclass2\",\"sub2Value\":\"c\",\"baseValue\":\"d\"}]";
    JsonReader reader = new JsonReader(context, json);
    TypeDefinition type = new TypeDefinition(List.class, BaseClass.class);
    Object read = reader.read(type);
    System.out.println(read);
}
Also used : JsonException(com.serotonin.json.JsonException) JsonContext(com.serotonin.json.JsonContext) TypeResolver(com.serotonin.json.spi.TypeResolver) JsonValue(com.serotonin.json.type.JsonValue) JsonReader(com.serotonin.json.JsonReader) TypeDefinition(com.serotonin.json.util.TypeDefinition)

Example 29 with JsonException

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

the class DataSourceImporter method importImpl.

@Override
protected void importImpl() {
    String xid = json.getString("xid");
    if (StringUtils.isBlank(xid))
        xid = ctx.getDataSourceDao().generateUniqueXid();
    DataSourceVO<?> vo = ctx.getDataSourceDao().getDataSource(xid);
    if (vo == null) {
        String typeStr = json.getString("type");
        if (StringUtils.isBlank(typeStr))
            addFailureMessage("emport.dataSource.missingType", xid, ModuleRegistry.getDataSourceDefinitionTypes());
        else {
            DataSourceDefinition def = ModuleRegistry.getDataSourceDefinition(typeStr);
            if (def == null)
                addFailureMessage("emport.dataSource.invalidType", xid, typeStr, ModuleRegistry.getDataSourceDefinitionTypes());
            else {
                vo = def.baseCreateDataSourceVO();
                vo.setXid(xid);
            }
        }
    }
    if (vo != null) {
        try {
            // The VO was found or successfully created. Finish reading it in.
            ctx.getReader().readInto(vo, json);
            // 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.dataSource.prefix", xid);
            else {
                // Sweet. Save it.
                boolean isnew = vo.isNew();
                if (Common.runtimeManager.getState() == RuntimeManager.RUNNING) {
                    Common.runtimeManager.saveDataSource(vo);
                    addSuccessMessage(isnew, "emport.dataSource.prefix", xid);
                } else {
                    addFailureMessage(new ProcessMessage("Runtime manager not running, data source with xid: " + xid + "not saved."));
                }
            }
        } catch (TranslatableJsonException e) {
            addFailureMessage("emport.dataSource.prefix", xid, e.getMsg());
        } catch (JsonException e) {
            addFailureMessage("emport.dataSource.prefix", xid, getJsonExceptionMessage(e));
        }
    }
}
Also used : TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) JsonException(com.serotonin.json.JsonException) DataSourceDefinition(com.serotonin.m2m2.module.DataSourceDefinition) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) ProcessMessage(com.serotonin.m2m2.i18n.ProcessMessage) TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException)

Example 30 with JsonException

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

the class EventDetectorImporter method importImpl.

@Override
protected void importImpl() {
    String dataPointXid = json.getString("dataPointXid");
    DataPointVO dpvo;
    // Everyone is in the same thread so no synchronization on dataPointMap required.
    if (dataPointMap.containsKey(dataPointXid))
        dpvo = dataPointMap.get(dataPointXid);
    else if (StringUtils.isEmpty(dataPointXid) || (dpvo = DataPointDao.instance.getByXid(dataPointXid)) == null) {
        addFailureMessage("emport.error.missingPoint", dataPointXid);
        return;
    } else {
        dataPointMap.put(dataPointXid, dpvo);
        // We're only going to use this to house event detectors imported in the eventDetectors object.
        dpvo.setEventDetectors(new ArrayList<AbstractPointEventDetectorVO<?>>());
    }
    String typeStr = json.getString("type");
    if (typeStr == null)
        addFailureMessage("emport.error.ped.missingAttr", "type");
    EventDetectorDefinition<?> def = ModuleRegistry.getEventDetectorDefinition(typeStr);
    if (def == null) {
        addFailureMessage("emport.error.ped.invalid", "type", typeStr, ModuleRegistry.getEventDetectorDefinitionTypes());
        return;
    }
    JsonArray handlerXids = json.getJsonArray("handlers");
    if (handlerXids != null)
        for (int k = 0; k < handlerXids.size(); k += 1) {
            AbstractEventHandlerVO<?> eh = EventHandlerDao.instance.getByXid(handlerXids.getString(k));
            if (eh == null) {
                addFailureMessage("emport.eventHandler.missing", handlerXids.getString(k));
                return;
            }
        }
    AbstractEventDetectorVO<?> importing = def.baseCreateEventDetectorVO();
    importing.setDefinition(def);
    String xid = json.getString("xid");
    // Create a new one
    importing.setId(Common.NEW_ID);
    importing.setXid(xid);
    AbstractPointEventDetectorVO<?> dped = (AbstractPointEventDetectorVO<?>) importing;
    dped.njbSetDataPoint(dpvo);
    dpvo.getEventDetectors().add(dped);
    try {
        ctx.getReader().readInto(importing, json);
    // try {
    // if(Common.runtimeManager.getState() == RuntimeManager.RUNNING){
    // Common.runtimeManager.saveDataPoint(dpvo);
    // addSuccessMessage(isNew, "emport.eventDetector.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.eventDetector.prefix", xid, e.getMsg());
    } catch (JsonException e) {
        addFailureMessage("emport.eventDetector.prefix", xid, getJsonExceptionMessage(e));
    }
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) JsonArray(com.serotonin.json.type.JsonArray) TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) JsonException(com.serotonin.json.JsonException) AbstractPointEventDetectorVO(com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO) ArrayList(java.util.ArrayList) TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) AbstractEventHandlerVO(com.serotonin.m2m2.vo.event.AbstractEventHandlerVO)

Aggregations

JsonException (com.serotonin.json.JsonException)40 TranslatableJsonException (com.serotonin.m2m2.i18n.TranslatableJsonException)22 JsonObject (com.serotonin.json.type.JsonObject)18 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)17 IOException (java.io.IOException)17 JsonValue (com.serotonin.json.type.JsonValue)6 JsonWriter (com.serotonin.json.JsonWriter)5 JsonReader (com.serotonin.json.JsonReader)4 HashMap (java.util.HashMap)4 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)3 JsonArray (com.serotonin.json.type.JsonArray)3 JsonTypeReader (com.serotonin.json.type.JsonTypeReader)3 SerializableProperty (com.serotonin.json.util.SerializableProperty)3 ProcessMessage (com.serotonin.m2m2.i18n.ProcessMessage)3 JsonSerializableUtility (com.serotonin.m2m2.util.JsonSerializableUtility)3 StringWriter (java.io.StringWriter)3 Method (java.lang.reflect.Method)3 ArrayList (java.util.ArrayList)3 JsonContext (com.serotonin.json.JsonContext)2 TypeDefinition (com.serotonin.json.util.TypeDefinition)2