GeoServerService.java 7.28 KB
package com.sigem.gis.service;

import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class GeoServerService {

    private final String GS_URL = "http://proyecto-geoserver-1:8080/geoserver/rest";
    private final String GS_USER = "admin";
    private final String GS_PASS = "geoserver";

    private final RestTemplate restTemplate;

    public GeoServerService() {
        org.springframework.http.client.SimpleClientHttpRequestFactory factory = new org.springframework.http.client.SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(2000);
        factory.setReadTimeout(2000);
        this.restTemplate = new RestTemplate(factory);
    }

    public void ensureStyleExists(String styleName) {
        String url = GS_URL + "/styles/" + styleName;
        try {
            restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(createHeaders()), String.class);
        } catch (Exception e) {
            String sldBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                    "<StyledLayerDescriptor version=\"1.0.0\" xmlns=\"http://www.opengis.net/sld\">" +
                    "<NamedLayer><Name>morosidad_style_wms</Name><UserStyle><FeatureTypeStyle>" +
                    "<Rule><Title>Verde</Title><ogc:Filter xmlns:ogc=\"http://www.opengis.net/ogc\"><ogc:PropertyIsEqualTo><ogc:PropertyName>ultimo_pago</ogc:PropertyName><ogc:Literal>2026</ogc:Literal></ogc:PropertyIsEqualTo></ogc:Filter><PolygonSymbolizer><Fill><CssParameter name=\"fill\">#71de75</CssParameter></Fill><Stroke><CssParameter name=\"stroke\">#000000</CssParameter><CssParameter name=\"stroke-width\">0.2</CssParameter></Stroke></PolygonSymbolizer></Rule>" +
                    "<Rule><Title>Ambar</Title><ogc:Filter xmlns:ogc=\"http://www.opengis.net/ogc\"><ogc:PropertyIsGreaterThanOrEqualTo><ogc:PropertyName>ultimo_pago</ogc:PropertyName><ogc:Literal>2024</ogc:Literal></ogc:PropertyIsGreaterThanOrEqualTo></ogc:Filter><PolygonSymbolizer><Fill><CssParameter name=\"fill\">#ffaa00</CssParameter></Fill><Stroke><CssParameter name=\"stroke\">#000000</CssParameter><CssParameter name=\"stroke-width\">0.2</CssParameter></Stroke></PolygonSymbolizer></Rule>" +
                    "<Rule><Title>Rojo</Title><ogc:Filter xmlns:ogc=\"http://www.opengis.net/ogc\"><ogc:PropertyIsLessThanOrEqualTo><ogc:PropertyName>ultimo_pago</ogc:PropertyName><ogc:Literal>2023</ogc:Literal></ogc:PropertyIsLessThanOrEqualTo></ogc:Filter><PolygonSymbolizer><Fill><CssParameter name=\"fill\">#f87171</CssParameter></Fill><Stroke><CssParameter name=\"stroke\">#000000</CssParameter><CssParameter name=\"stroke-width\">0.2</CssParameter></Stroke></PolygonSymbolizer></Rule>" +
                    "<Rule><ElseFilter/><PolygonSymbolizer><Fill><CssParameter name=\"fill\">#94a3b8</CssParameter><CssParameter name=\"fill-opacity\">0.4</CssParameter></Fill></PolygonSymbolizer></Rule>" +
                    "</FeatureTypeStyle></UserStyle></NamedLayer></StyledLayerDescriptor>";

            try {
                // Crear el estilo
                String createJson = String.format("{\"style\": {\"name\": \"%s\", \"filename\": \"%s.sld\"}}", styleName, styleName);
                HttpHeaders h = createHeaders();
                h.setContentType(MediaType.APPLICATION_JSON);
                restTemplate.postForEntity(GS_URL + "/styles", new HttpEntity<>(createJson, h), String.class);

                // Subir el SLD
                HttpHeaders sldHeaders = createHeaders();
                sldHeaders.setContentType(MediaType.parseMediaType("application/vnd.ogc.sld+xml"));
                restTemplate.exchange(url, HttpMethod.PUT, new HttpEntity<>(sldBody, sldHeaders), String.class);
            } catch (Exception ex) {
                System.err.println("Error creando estilo: " + ex.getMessage());
            }
        }
    }

    public void publishLayer(String layerName, String viewName, String styleName, String boundNo, String boundSe) {
        ensureInfrastructureExists();
        if (styleName != null) ensureStyleExists(styleName);

        String workspace = "sigem";
        String datastore = "sigem_db";
        String url = String.format("%s/workspaces/%s/datastores/%s/featuretypes/%s", GS_URL, workspace, datastore, layerName);

        String jsonBody = String.format("{\"featureType\": {\"name\": \"%s\", \"nativeName\": \"%s\", \"srs\": \"EPSG:4326\"}}", layerName, viewName);
        HttpHeaders headers = createHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        
        try {
            restTemplate.exchange(url, HttpMethod.PUT, new HttpEntity<>(jsonBody, headers), String.class);
        } catch (Exception e) {
            String postUrl = String.format("%s/workspaces/%s/datastores/%s/featuretypes", GS_URL, workspace, datastore);
            try { restTemplate.postForEntity(postUrl, new HttpEntity<>(jsonBody, headers), String.class); } catch (Exception ex) {}
        }

        if (styleName != null) {
            String layerUrl = String.format("%s/layers/sigem:%s", GS_URL, layerName);
            String layerJson = String.format("{\"layer\": {\"defaultStyle\": {\"name\": \"%s\"}}}", styleName);
            try { restTemplate.exchange(layerUrl, HttpMethod.PUT, new HttpEntity<>(layerJson, headers), String.class); } catch (Exception e) {}
        }
    }

    private void ensureInfrastructureExists() {
        String workspace = "sigem";
        String datastore = "sigem_db";
        try {
            restTemplate.exchange(GS_URL + "/workspaces/" + workspace, HttpMethod.GET, new HttpEntity<>(createHeaders()), String.class);
        } catch (Exception e) {
            String wsJson = String.format("{\"workspace\": {\"name\": \"%s\"}}", workspace);
            HttpHeaders h = createHeaders(); h.setContentType(MediaType.APPLICATION_JSON);
            try { restTemplate.postForEntity(GS_URL + "/workspaces", new HttpEntity<>(wsJson, h), String.class); } catch (Exception ex) {}
        }

        try {
            restTemplate.exchange(GS_URL + "/workspaces/" + workspace + "/datastores/" + datastore, HttpMethod.GET, new HttpEntity<>(createHeaders()), String.class);
        } catch (Exception e) {
            String dsJson = String.format("{\"dataStore\": {\"name\": \"%s\", \"connectionParameters\": {\"host\": \"proyecto-postgres-1\", \"port\": \"5432\", \"database\": \"sigem\", \"user\": \"sigem_user\", \"passwd\": \"sigem_pass\", \"dbtype\": \"postgis\"}}}", datastore);
            HttpHeaders h = createHeaders(); h.setContentType(MediaType.APPLICATION_JSON);
            try { restTemplate.postForEntity(GS_URL + "/workspaces/" + workspace + "/datastores", new HttpEntity<>(dsJson, h), String.class); } catch (Exception ex) {}
        }
    }

    public void truncateCache(String layerName) {
        String url = "http://proyecto-geoserver-1:8080/geoserver/gwc/rest/masstruncate";
        String xmlBody = String.format("<truncateLayer><layerName>sigem:%s</layerName></truncateLayer>", layerName);
        HttpHeaders h = createHeaders(); h.setContentType(MediaType.TEXT_XML);
        try { restTemplate.postForEntity(url, new HttpEntity<>(xmlBody, h), String.class); } catch (Exception e) {}
    }

    private HttpHeaders createHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setBasicAuth(GS_USER, GS_PASS);
        return headers;
    }
}
GitLab Appliance - Powered by TurnKey Linux