Search in sources :

Example 1 with ModelDefinition

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

the class PointLocatorModelDeserializer method deserialize.

/* (non-Javadoc)
	 * @see com.fasterxml.jackson.databind.JsonDeserializer#deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext)
	 */
@Override
public PointLocatorModel<?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    JsonNode tree = jp.readValueAsTree();
    if (!tree.hasNonNull("modelType"))
        throw new IOException("No modelType field found for point locator model.");
    ModelDefinition definition = findModelDefinition(tree.get("modelType").asText());
    return (PointLocatorModel<?>) mapper.treeToValue(tree, definition.getModelClass());
}
Also used : ModelDefinition(com.serotonin.m2m2.module.ModelDefinition) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) PointLocatorModel(com.serotonin.m2m2.web.mvc.rest.v1.model.dataPoint.PointLocatorModel) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 2 with ModelDefinition

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

the class SuperclassModelDeserializer method deserialize.

/* (non-Javadoc)
	 * @see com.fasterxml.jackson.databind.JsonDeserializer#deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext)
	 */
@Override
public SuperclassModel<?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    JsonNode tree = jp.readValueAsTree();
    ModelDefinition definition = findModelDefinition(tree.get("type").asText());
    return (SuperclassModel<?>) mapper.treeToValue(tree, definition.getModelClass());
}
Also used : ModelDefinition(com.serotonin.m2m2.module.ModelDefinition) JsonNode(com.fasterxml.jackson.databind.JsonNode) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) SuperclassModel(com.serotonin.m2m2.web.mvc.rest.v1.model.SuperclassModel)

Example 3 with ModelDefinition

use of com.serotonin.m2m2.module.ModelDefinition 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 4 with ModelDefinition

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

the class CSVPojoHandler method buildMapping.

private void buildMapping(String[] line) throws ModelNotFoundException, NoSupportingModelException {
    for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
        if (c.getAnnotation(CSVEntity.class) != null) {
            for (Field field : c.getDeclaredFields()) {
                CSVColumn csvColumn = field.getAnnotation(CSVColumn.class);
                if (csvColumn == null)
                    continue;
                // hidden)
                if (!Modifier.isTransient(field.getModifiers()) && (csvColumn == null || !csvColumn.hidden())) {
                    PropertyEditor editor;
                    try {
                        // Try to determine PropertyEditor for field
                        editor = (csvColumn == null || csvColumn.editor() == CSVPropertyEditor.class) ? PropertyEditorManager.findEditor(field.getType()) : csvColumn.editor().newInstance();
                    } catch (InstantiationException ex) {
                        throw new InstantiationError(ex.getLocalizedMessage());
                    } catch (IllegalAccessException ex) {
                        throw new IllegalAccessError(ex.getLocalizedMessage());
                    }
                    if (editor != null) {
                        String header = (csvColumn != null && csvColumn.header().length() > 0) ? csvColumn.header() : field.getName();
                        CSVFieldHandler handler = new CSVFieldHandler(csvColumn.order(), header, field, editor);
                        handlers.add(handler);
                        mapping.put(header, handler);
                    } else {
                        // If no default or specified editor available check
                        // if this is CSVEntity child class
                        CSVEntity csvEntity = field.getType().getAnnotation(CSVEntity.class);
                        if (csvEntity != null) {
                            CSVPojoHandler handler = new CSVPojoHandler();
                            PojoChildField child = new PojoChildField(csvColumn.header(), csvColumn.order(), field, handler, csvEntity);
                            handler.initialize(line, field.getType());
                            children.add(child);
                        }
                    }
                }
            }
            // Sort the Getters and Setters Into a map with Col Order for them
            Map<Integer, CSVColumnMethodAnnotations> methodMap = new HashMap<Integer, CSVColumnMethodAnnotations>();
            for (Method method : c.getDeclaredMethods()) {
                CSVColumnGetter csvColumnGetter = method.getAnnotation(CSVColumnGetter.class);
                if (csvColumnGetter == null)
                    continue;
                boolean isCSVEntity = false;
                if (method.getReturnType().getAnnotation(CSVEntity.class) != null) {
                    isCSVEntity = true;
                }
                CSVColumnMethodAnnotations annos = methodMap.get(csvColumnGetter.order());
                if (annos != null) {
                    annos.setGetterAnnotation(csvColumnGetter);
                    annos.setGetter(method);
                    annos.setCSVEntity(isCSVEntity);
                } else {
                    // Create new one
                    annos = new CSVColumnMethodAnnotations(csvColumnGetter, method, null, null, isCSVEntity);
                    methodMap.put(csvColumnGetter.order(), annos);
                }
            }
            for (Method method : c.getDeclaredMethods()) {
                CSVColumnSetter csvColumnSetter = method.getAnnotation(CSVColumnSetter.class);
                if (csvColumnSetter == null)
                    continue;
                boolean isCSVEntity = false;
                if (method.getReturnType().getAnnotation(CSVEntity.class) != null) {
                    isCSVEntity = true;
                }
                CSVColumnMethodAnnotations annos = methodMap.get(csvColumnSetter.order());
                if (annos != null) {
                    annos.setSetterAnnotation(csvColumnSetter);
                    annos.setSetter(method);
                } else {
                    // Create new one
                    annos = new CSVColumnMethodAnnotations(null, null, csvColumnSetter, method, isCSVEntity);
                    methodMap.put(csvColumnSetter.order(), annos);
                }
            }
            // Now map the matched methods
            Iterator<Integer> it = methodMap.keySet().iterator();
            while (it.hasNext()) {
                Integer order = it.next();
                CSVColumnMethodAnnotations method = methodMap.get(order);
                CSVColumnGetter csvColumnGetter = method.getGetterAnnotation();
                CSVColumnSetter csvColumnSetter = method.getSetterAnnotation();
                if (csvColumnGetter != null) {
                    // Getter First
                    if (!Modifier.isTransient(method.getGetter().getModifiers()) && (csvColumnGetter == null || !csvColumnGetter.hidden())) {
                        PropertyEditor editor;
                        try {
                            // Try to determine PropertyEditor for field
                            editor = (csvColumnGetter == null || csvColumnGetter.editor() == CSVPropertyEditor.class) ? PropertyEditorManager.findEditor(method.getGetter().getReturnType()) : csvColumnGetter.editor().newInstance();
                        } catch (InstantiationException ex) {
                            throw new InstantiationError(ex.getLocalizedMessage());
                        } catch (IllegalAccessException ex) {
                            throw new IllegalAccessError(ex.getLocalizedMessage());
                        }
                        if (editor != null) {
                            String header = (csvColumnGetter != null && csvColumnGetter.header().length() > 0) ? csvColumnGetter.header() : method.getGetter().getName();
                            CSVMethodHandler handler = new CSVMethodHandler(csvColumnGetter.order(), header, method.getGetter(), method.getSetter(), editor);
                            handlers.add(handler);
                            mapping.put(header, handler);
                        } else {
                            // If no default or specified editor available check
                            // if this is CSVEntity child class
                            CSVEntity csvEntity = method.getGetter().getReturnType().getAnnotation(CSVEntity.class);
                            if (csvEntity != null) {
                                CSVPojoHandler handler = new CSVPojoHandler();
                                PojoChildMethod child = new PojoChildMethod(csvColumnGetter.header(), order, method.getGetter(), method.getSetter(), handler, csvEntity);
                                children.add(child);
                                // Check Runtime Type for return value
                                if (csvEntity.derived()) {
                                    ModelDefinition definition = null;
                                    if (line.length > method.getGetterAnnotation().order())
                                        definition = this.findModelDefinition(line[method.getGetterAnnotation().order()]);
                                    if (definition != null) {
                                        handler.initialize(line, definition.createModel());
                                        editor = new CsvEntityAnnotationPropertyEditor(csvEntity.typeName());
                                        CSVMethodHandler methodHandler = new CSVMethodHandler(csvColumnGetter.order(), csvColumnGetter.header(), method.getGetter(), method.getSetter(), editor);
                                        handlers.add(methodHandler);
                                        mapping.put(csvColumnGetter.header(), methodHandler);
                                    }
                                } else {
                                    if (!csvEntity.typeName().equals("")) {
                                        ModelDefinition definition = this.findModelDefinition(csvEntity.typeName());
                                        handler.initialize(line, definition.createModel());
                                        editor = new CsvEntityAnnotationPropertyEditor(csvEntity.typeName());
                                        CSVMethodHandler methodHandler = new CSVMethodHandler(csvColumnGetter.order(), csvColumnGetter.header(), method.getGetter(), method.getSetter(), editor);
                                        handlers.add(methodHandler);
                                        mapping.put(csvColumnGetter.header(), methodHandler);
                                    }
                                }
                            } else {
                                throw new IllegalArgumentException("The method: " + c.getName() + "." + method.getGetter().getName() + " of type: " + method.getGetter().getReturnType().getName() + " is not a CSVEntity or has no PropertyEditor available.");
                            }
                        }
                    }
                }
            // End if getter != null
            }
        }
    }
    // Sort children so we always output them in the same order
    Collections.sort(this.children);
}
Also used : HashMap(java.util.HashMap) Field(java.lang.reflect.Field) Method(java.lang.reflect.Method) ModelDefinition(com.serotonin.m2m2.module.ModelDefinition) PropertyEditor(java.beans.PropertyEditor)

Example 5 with ModelDefinition

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

the class CSVPojoReader method readNext.

/**
 * Read the next pojo from the csv file
 *
 * @return The next pojo from the csv file or null if end of file
 * @throws IOException
 */
public T readNext() throws IOException {
    if (headers == null) {
        headers = reader.readNext();
        if (headers == null)
            return null;
        // Make sure we don't have any accidental whitespaces
        for (int i = 0; i < headers.length; i++) {
            headers[i] = headers[i].trim();
        }
        if (headers.length > 0) {
            if (!headers[0].equalsIgnoreCase("modelType"))
                throw new IOException("Invalid header format, first column must be modelType.");
        } else {
            throw new IOException("No headers provided.");
        }
    }
    String[] line = reader.readNext();
    T pojo = null;
    if (line != null) {
        if (line.length != headers.length) {
            String columnString = new String();
            for (String col : line) columnString += col + ",";
            if (line.length > headers.length) {
                throw new IOException("Header and row length must match.\nRow has too many columns.\n" + columnString);
            } else {
                throw new IOException("Header and row length must match.\nRow has too few columns.\n" + columnString);
            }
        }
        if (!pojoHandler.isInitialized()) {
            // Always needs to be
            String typeName = line[0];
            // Find the model
            ModelDefinition definition = null;
            List<ModelDefinition> definitions = ModuleRegistry.getModelDefinitions();
            for (ModelDefinition d : definitions) {
                if (d.getModelTypeName().equalsIgnoreCase(typeName)) {
                    definition = d;
                    break;
                }
            }
            if (definition == null)
                throw new ModelNotFoundException(typeName);
            else
                pojoHandler.initialize(line, definition.createModel());
        }
        pojo = (T) pojoHandler.newInstance();
        for (int i = 1; i < headers.length; i++) {
            try {
                pojoHandler.setField(pojo, headers[i], line[i].trim());
            } catch (CSVException e) {
                throw new CSVException("Row " + i + " column '" + headers[i] + "' " + e.getMessage());
            }
        }
    }
    return pojo;
}
Also used : ModelNotFoundException(com.serotonin.m2m2.web.mvc.rest.v1.exception.ModelNotFoundException) ModelDefinition(com.serotonin.m2m2.module.ModelDefinition) IOException(java.io.IOException)

Aggregations

ModelDefinition (com.serotonin.m2m2.module.ModelDefinition)5 IOException (java.io.IOException)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 HashMap (java.util.HashMap)2 JsonException (com.serotonin.json.JsonException)1 JsonReader (com.serotonin.json.JsonReader)1 JsonObject (com.serotonin.json.type.JsonObject)1 JsonTypeReader (com.serotonin.json.type.JsonTypeReader)1 JsonValue (com.serotonin.json.type.JsonValue)1 ModelNotFoundException (com.serotonin.m2m2.web.mvc.rest.v1.exception.ModelNotFoundException)1 RestErrorModelDefinition (com.serotonin.m2m2.web.mvc.rest.v1.model.RestErrorModelDefinition)1 SuperclassModel (com.serotonin.m2m2.web.mvc.rest.v1.model.SuperclassModel)1 PointLocatorModel (com.serotonin.m2m2.web.mvc.rest.v1.model.dataPoint.PointLocatorModel)1 PropertyEditor (java.beans.PropertyEditor)1 InputStreamReader (java.io.InputStreamReader)1 Field (java.lang.reflect.Field)1 Method (java.lang.reflect.Method)1 LinkedHashMap (java.util.LinkedHashMap)1