1

Soy novata con springboot. Estoy usando una bbdd en postgressql con postgis.

En el código que muestro lo que hago es leer el inputStream de un fichero geojson y procesarlo.

Antes guardaba las propiedades del fichero geojson, que es un objeto con campos, como jsonb. Pero ahora quiero obtener cada una de las keys del objeto de las propiedades y su tipo para crear la tabla dinámicamente e insertar la información.

¿Cómo podría hacerlo?

public class ParseGeojsonStream {

    private static final Logger log = LoggerFactory.getLogger(ParseGeojsonStream.class);

    private static Gson gson;

    private static List<String> listKeys;
    private static List<String> listTypes;

    @Bean
    public static ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        return mapper;
    }

    public static void parseJson(final String name, final TableGeoJsonStream tableStream, final InputStream is) throws IOException {

        GsonBuilder builder = new GsonBuilder();
        builder.serializeNulls();
        gson = builder.create();

        // Create and configure an ObjectMapper instance
        ObjectMapper mapper = objectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        // Create a JsonParser instance
        try (JsonParser jsonParser = mapper.getFactory().createParser(is)) {

            // Check the first token
            if (jsonParser.nextToken() != JsonToken.START_OBJECT) {
                throw new IllegalStateException("Expected content to be an object");
            }

            JsonParser featureJson = findFeaturesToken(jsonParser);

            if (featureJson == null) {
                throw new IOException("Expected content to be not null");
            }

            if (featureJson.nextToken() != JsonToken.START_ARRAY) {
                throw new IOException("Expected content to be an array");
            }

            List<Feature> features = new ArrayList<Feature>();

            boolean firstFeature = true;
            // Iterate over the tokens until the end of the array
            while (featureJson.nextToken() != JsonToken.END_ARRAY) {
                // Read a contact instance using ObjectMapper and do something with it
                // De 50 en 50
                Feature feature = mapper.readValue(featureJson, Feature.class);
                features.add(feature);

                if (firstFeature) {
                    firstFeature = false;
                    // create table
                    getKeyAndTypeOfProperties((Map<String, ?>) feature.getProperties());
                    createTableWithFields(tableStream, name);
                }


                if (features.size() == 50) {
                    generateSQLValues(tableStream, features);
                    features.clear();
                }
            }

            // Añadimos el resto que sobra
            if (features.size() > 0) {
                generateSQLValues(tableStream, features);
                features.clear();
            }

        }
    }

    private static void getKeyAndTypeOfProperties(Map<String, ?> objectproperties) {
        listKeys = new ArrayList<String>();
        listTypes = new ArrayList<String>();

        Iterator<String> it = objectproperties.keySet().iterator();
        while(it.hasNext()){
            String key = (String) it.next();
            log.info("KEY: "+ key);
            listKeys.add(key);
            listTypes.add(getTypeOfKey(key, objectproperties.get(key)));
        }
    }

    private static String getTypeOfKey(String key, Object value) {
        String type = "";
        if (value == null) {
            if (key.toLowerCase().contains("id")) {
                type = "int8";
            } else if (key.toLowerCase().contains("fecha") || key.toLowerCase().contains("date")) {
                type = "date";
            } else {
                type = "text";              
            }
        } else if (value instanceof String) {
            type = "text";
        } else if (value instanceof Boolean) {
            type = "boolean";
        } else if (value instanceof Double) {
            type = "decimal";
        } else if (value instanceof Integer) {
            type = "int8";
        } else if (value instanceof Date) {
            type = "date";
        } else {
            type = "text";
        }
        return type;
    }

    private static JsonParser findFeaturesToken(JsonParser jsonParser) throws IOException, NullPointerException {
        JsonParser json = jsonParser;
        try {
            while(true) {
                String text = json.getText().toLowerCase();
                if ( text.equalsIgnoreCase(GEOJSONConstants.ApiJSON.FEATURES.toLowerCase()) ) {
                    return json;
                }
                json.nextToken();               
            }           
        } catch(NullPointerException e) {
            return null;
        }
    }

    private static void createTableWithFields(final TableGeoJsonStream tableStream, final String name) {
        String keys = "";
        for (int i=0; i<listKeys.size(); i++) {
            keys += listKeys.get(i) + " " + listTypes.get(i) + ", ";
        }
        keys = keys + "geom geometry(GeometryZ,4326), primary key (table_id)";
        tableStream.createTableWithColumnsDinamically(name, keys);
    }

    private static void generateSQLValues(final TableGeoJsonStream tableStream, final List<Feature> features) {
        String SQL = "INSERT INTO " + tableStream.getCheckedNameTable(); 
//      String SQL = "INSERT INTO " + checkedNameTable + " ( properties, geom ) VALUES ( '" + property + "', ST_Force3D(ST_SetSRID(ST_GeomFromGeoJSON('" + geometry + "'), 4326) ));"; 
        String keys = "";
        for (int i=0; i<listKeys.size(); i++) {
            keys += listKeys.get(i) + ", ";
        }
        SQL += " ( " + keys + " geom ) VALUES ";

        String allValues = "";
        for (int i=0; i<features.size(); i++) {
            String values = " ( ";
            Feature feature = features.get(i);
            Map<String, ?> properties = (Map<String, ?>) feature.getProperties();
            for (int j=0; j<listKeys.size(); j++) {
                values += properties.get(listKeys.get(j)) + ", ";           
            }
            // añadir campo geometria
            values += feature.getGeometry() + " ";
            values = (i == features.size()) ? values + " ) " : values + " ), ";             
            allValues += values;
        }   
        log.info("All Values: " + allValues);




//      String SQL_BEGIN = "INSERT INTO " + tableStream.getCheckedNameTable() + " ( keys de las propiedades, geom ) VALUES ";
//      String SQL = SQL_BEGIN + SQL_VALUES;
//      tableStream.insertMultipleRows(SQL);
    }

1 respuesta 1

0

He conseguido resolverlo, gracias por vuestra ayuda y apoyo. Espero que le pueda servir a alguien y si alguien puede optimizar el código estaría agradecido.

Saludos

public class ParseGeojsonStream {

private static final Logger log = LoggerFactory.getLogger(ParseGeojsonStream.class);

private static Gson gson;

private static List<String> listKeys;
private static List<String> listTypes;

private static String VALUES;
private static int position;

@Bean
public static ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    return mapper;
}

public static void parseJson(final String name, final TableGeoJsonStream tableStream, final InputStream is) throws IOException {

    GsonBuilder builder = new GsonBuilder();
    builder.serializeNulls();
    gson = builder.create();

    // Create and configure an ObjectMapper instance
    ObjectMapper mapper = objectMapper();
    mapper.registerModule(new JavaTimeModule());
    mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    // Create a JsonParser instance
    try (JsonParser jsonParser = mapper.getFactory().createParser(is)) {

        // Check the first token
        if (jsonParser.nextToken() != JsonToken.START_OBJECT) {
            throw new IllegalStateException("Expected content to be an object");
        }

        JsonParser featureJson = findFeaturesToken(jsonParser);

        if (featureJson == null) {
            throw new IOException("Expected content to be not null");
        }

        if (featureJson.nextToken() != JsonToken.START_ARRAY) {
            throw new IOException("Expected content to be an array");
        }

        List<Feature> features = new ArrayList<Feature>();

        boolean firstFeature = true;
        // Iterate over the tokens until the end of the array
        while (featureJson.nextToken() != JsonToken.END_ARRAY) {
            // Read a contact instance using ObjectMapper and do something with it
            // De 50 en 50
            Feature feature = mapper.readValue(featureJson, Feature.class);
            features.add(feature);

            if (firstFeature) {
                firstFeature = false;
                // create table
                getKeyAndTypeOfProperties((Map<String, ?>) feature.getProperties());
                createTableWithFields(tableStream, name);
            }


            if (features.size() == 50) {
                generateSQLValues(tableStream, features);
                features.clear();
            }
        }

        // Añadimos el resto que sobra
        if (features.size() > 0) {
            generateSQLValues(tableStream, features);
            features.clear();
        }

    }
}

private static void getKeyAndTypeOfProperties(Map<String, ?> objectproperties) {
    listKeys = new ArrayList<String>();
    listTypes = new ArrayList<String>();

    Iterator<String> it = objectproperties.keySet().iterator();
    while(it.hasNext()){
        String key = (String) it.next();
        listKeys.add(key);
        listTypes.add(getTypeOfKey(key, objectproperties.get(key)));
    }
}

private static String getTypeOfKey(String key, Object value) {
    String type = "";
    if (value == null) {
        if (key.toLowerCase().contains("id")) {
            type = "int8";
        } else if (key.toLowerCase().contains("fecha") || key.toLowerCase().contains("date")) {
            type = "date";
        } else {
            type = "text";              
        }
    } else if (value instanceof String) {
        type = "text";
    } else if (value instanceof Boolean) {
        type = "boolean";
    } else if (value instanceof Double) {
        type = "decimal";
    } else if (value instanceof Integer) {
        type = "int8";
    } else if (value instanceof Date) {
        type = "date";
    } else {
        type = "text";
    }
    return type;
}

private static JsonParser findFeaturesToken(JsonParser jsonParser) throws IOException, NullPointerException {
    JsonParser json = jsonParser;
    try {
        while(true) {
            String text = json.getText().toLowerCase();
            if ( text.equalsIgnoreCase(GEOJSONConstants.ApiJSON.FEATURES.toLowerCase()) ) {
                return json;
            }
            json.nextToken();               
        }           
    } catch(NullPointerException e) {
        return null;
    }
}

private static void createTableWithFields(final TableGeoJsonStream tableStream, final String name) {
    String keys = "";
    for (int i=0; i<listKeys.size(); i++) {
        keys += listKeys.get(i) + " " + listTypes.get(i) + ", ";
    }
    tableStream.createTableWithColumnsDinamically(name, keys);
}

private static String createSQLValuesScheme() {
    String valuesScheme = "";
    String keys = "";
    for (int i=0; i<listKeys.size(); i++) {
        keys += listKeys.get(i) + ", ";
    }
    valuesScheme += " ( " + keys + "geom ) VALUES ";
    return valuesScheme;
}

private static String getAllPropertiesFromGson(JsonElement jsonElement) {
    VALUES = "";
    JsonObject jsonProperties = jsonElement.getAsJsonObject();

    int totalValues = jsonProperties.size()-1;
    position = 0;
    jsonProperties.keySet().forEach( keyStr -> {
        Object keyValue = jsonProperties.get(keyStr);
        VALUES = (position == totalValues) ? VALUES + "'" + keyValue.toString().replace("\"", "") + "'" : VALUES + "'" + keyValue.toString().replace("\"", "") + "', ";
        position++;
    });
    return VALUES;
}

private static void generateSQLValues(final TableGeoJsonStream tableStream, final List<Feature> features) {
    String SQL = "INSERT INTO " + tableStream.getCheckedNameTable(); 
    String SCHEME_VALUES = createSQLValuesScheme();

    String VALUES = "";
    for (int i=0; i<features.size(); i++) {
        if (features.size() - 1 == i) {
            VALUES += "(" + getAllPropertiesFromGson( gson.toJsonTree(features.get(i).getProperties()) ) + ", ST_Force3D(ST_SetSRID(ST_GeomFromGeoJSON('" + gson.toJson(features.get(i).getGeometry()) + "'), 4326)));";
        } else {
            VALUES += "(" + getAllPropertiesFromGson( gson.toJsonTree(features.get(i).getProperties()) ) + ", ST_Force3D(ST_SetSRID(ST_GeomFromGeoJSON('" + gson.toJson(features.get(i).getGeometry()) + "'), 4326))), ";

        }
    }
    String SQL_COMPLETE = SQL + SCHEME_VALUES + VALUES;
    tableStream.insertMultipleRows(SQL_COMPLETE);
}

}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.