栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

geoserver(xml和json带属性互转,获取工作区-图层-样式-更新样式(解决乱码问题))

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

geoserver(xml和json带属性互转,获取工作区-图层-样式-更新样式(解决乱码问题))

这篇代码是我排过n个坑的结果,测试代码,仅供参考

package com.example.geopushstyledemo2.control;

import com.alibaba.fastjson.parser.Feature;
import com.example.geopushstyledemo2.utils.XmlConverUtil3;
import it.geosolutions.geoserver.rest.GeoServerRESTManager;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
import it.geosolutions.geoserver.rest.GeoServerRESTReader;
import it.geosolutions.geoserver.rest.decoder.RESTFeatureType;
import it.geosolutions.geoserver.rest.decoder.RESTLayer;
import net.sf.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.*;


@RestController
public class test1 {

    String URL = "http://192.168.20.3:8090/geoserver";
    String user = "admin";
    String password = "geoserver";
    public GeoServerRESTManager getGeoServer(String URL,String user,String password) {
        // 连接geoServer
        GeoServerRESTManager geoServerRESTManager = null;
        try {
            geoServerRESTManager = new GeoServerRESTManager(new URL(URL), user, password);
        } catch (Exception e) {
            System.out.println("远程连接GeoServer失败...");
            e.printStackTrace();
        }
        return geoServerRESTManager;
    }

    @RequestMapping(value = "/pushStyle", method = RequestMethod.POST)
    public Boolean test1(
            @RequestBody pushStyleDto dto
    ) throws Exception {
        GeoServerRESTManager geoServer = getGeoServer(URL,user,password);
        // shp读写和发布
        assert geoServer != null;
        String styleUrl = null;
        String workSpace = null;
        GeoServerRESTReader restReader = geoServer.getReader();
        GeoServerRESTPublisher restPublisher = geoServer.getPublisher();

        String styleDetail = getStyleDetail(dto.getUrl());

        String styleName = JSONObject.fromObject(styleDetail).getJSonObject("style").getString("name");
        if (JSONObject.fromObject(styleDetail).getJSonObject("style").get("workspace") != null) {
            workSpace = JSONObject.fromObject(styleDetail).getJSonObject("style").getJSonObject("workspace").getString("name");
        }
        if (workSpace != null && workSpace != "") {
            //有工作空间
            styleUrl = URL+"/rest/workspaces/" + workSpace + "/styles/" + styleName + "?raw=true";
        } else {
            //没有工作空间
            styleUrl = URL+"/rest/workspaces/styles/" + styleName + "?raw=true";
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic YWRtaW46Z2Vvc2VydmVy");
        headers.add("Content-type", "application/vnd.ogc.sld+xml");
        HttpEntity entity = new HttpEntity("n" + XmlConverUtil3.JsonToXml(com.alibaba.fastjson.JSONObject.toJSonString(dto.getXmlString())), headers);
        RestTemplate restTemplate = getThirdRestTemplate();

        return restTemplate.exchange(styleUrl, HttpMethod.PUT, entity, String.class).getStatusCode().getReasonPhrase().equals("OK") ? true : false;
    }

    @RequestMapping(value = "/jsontoxml", method = RequestMethod.POST)
    public String jsonToXml(
            @RequestBody String jsonStr
    ) {
        return XmlConverUtil3.JsonToXml(jsonStr);
    }

    @RequestMapping(value = "/xmltojson", method = RequestMethod.GET)
    public String xmlToJson(
            String xmlStr
    ) {
        return XmlConverUtil3.XmlToJson(xmlStr);
    }

    @RequestMapping(value = "/getWorkSpace", method = RequestMethod.GET)
    public Object getWorkSpace(

    ) {
        GeoServerRESTManager geoServer = getGeoServer(URL,user,password);
        // shp读写和发布
        assert geoServer != null;
        GeoServerRESTReader restReader = geoServer.getReader();
        GeoServerRESTPublisher restPublisher = geoServer.getPublisher();
        //获取所有工作空间
        return restReader.getWorkspaceNames();
    }

    @RequestMapping(value = "/getCoverage", method = RequestMethod.GET)
    public Object getCoverage(
            @RequestParam(value = "workSpaceName") String workSpaceName
    ) {
        GeoServerRESTManager geoServer = getGeoServer(URL,user,password);
        // shp读写和发布
        assert geoServer != null;
        GeoServerRESTReader restReader = geoServer.getReader();
        GeoServerRESTPublisher restPublisher = geoServer.getPublisher();
        //获取空间下的图层
        String url = URL+"/rest/workspaces/" + workSpaceName + "/layers";
        HttpHeaders headers = new HttpHeaders();
        // headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Authorization", "Basic YWRtaW46Z2Vvc2VydmVy");
        HttpEntity entity = new HttpEntity(headers);
        RestTemplate restTemplate = getThirdRestTemplate();
        String object = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();
        return JSONObject.fromObject(object);
    }

    @RequestMapping(value = "/getStyle", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object getStyle(
            @RequestParam(value = "url") String url
    ) throws IOException {
        String sld = null;
        String sldUrl = null;
        String workSpace = null;
        GeoServerRESTManager geoServer = getGeoServer(URL,user,password);
        // shp读写和发布
        assert geoServer != null;
        GeoServerRESTReader restReader = geoServer.getReader();
        GeoServerRESTPublisher restPublisher = geoServer.getPublisher();

        //获取图层下的样式
        HttpHeaders headers = new HttpHeaders();
        // headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Authorization", "Basic YWRtaW46Z2Vvc2VydmVy");
        headers.add("Accept", "application/vnd.ogc.sld+xml");
        HttpEntity entity = new HttpEntity(headers);
        RestTemplate restTemplate = getThirdRestTemplate();
        String styleDetail = getStyleDetail(url);
        String styleName = JSONObject.fromObject(styleDetail).getJSonObject("style").getString("name");
        if (JSONObject.fromObject(styleDetail).getJSonObject("style").get("workspace") != null) {
            workSpace = JSONObject.fromObject(styleDetail).getJSonObject("style").getJSonObject("workspace").getString("name");
        }
        if (workSpace != null && workSpace != "") {
            //有工作空间
            sldUrl = URL+"/rest/workspaces/" + workSpace + "/styles/" + styleName;
        } else {
            //没有工作空间
            sldUrl = URL+"/rest/styles/" + styleName;
        }
        String sldXml = restTemplate.exchange(sldUrl, HttpMethod.GET, entity, String.class).getBody();
        String jsonString = XmlConverUtil3.XmlToJson(sldXml);
        com.alibaba.fastjson.JSonObject sldJson = com.alibaba.fastjson.JSONObject.parseObject(jsonString, Feature.OrderedField);
        styleVo styleVo = new styleVo()
                .setName(styleName)
                .setJson(sldJson);
        return styleVo;
    }

    @RequestMapping(value = "/getCoverageProperty", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object getCoverageProperty(
            @RequestParam(value = "workSpaceName") String workSpaceName,
            @RequestParam(value = "coverageName") String coverageName
    ) {
        GeoServerRESTManager geoServer = getGeoServer(URL,user,password);
        // shp读写和发布
        assert geoServer != null;
        GeoServerRESTReader restReader = geoServer.getReader();
        GeoServerRESTPublisher restPublisher = geoServer.getPublisher();
        //获取图层要素
        RESTLayer layer = restReader.getLayer(workSpaceName, coverageName);
        RESTFeatureType cuFeatureType = restReader.getFeatureType(layer);
        List list = new ArrayList<>();
        for (RESTFeatureType.Attribute attribute : cuFeatureType.getAttributes()) {
            list.add(attribute.getName());
        }
        return list;
    }

    
    public RestTemplate getThirdRestTemplate() {
        Charset thirdRequest = Charset.forName("GBK");
        RestTemplate restTemplate = new RestTemplate();
        // 处理请求中文乱码问题
        List> messageConverters = restTemplate.getMessageConverters();
        for (HttpMessageConverter messageConverter : messageConverters) {
            if (messageConverter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) messageConverter).setDefaultCharset(thirdRequest);
            }
            if (messageConverter instanceof MappingJackson2HttpMessageConverter) {
                ((MappingJackson2HttpMessageConverter) messageConverter).setDefaultCharset(thirdRequest);
            }
            if (messageConverter instanceof AllEncompassingFormHttpMessageConverter) {
                ((AllEncompassingFormHttpMessageConverter) messageConverter).setCharset(thirdRequest);
            }
        }
        return restTemplate;
    }

    public static String readFile(String path) throws Exception {
        File file = new File(path);
        FileInputStream fis = new FileInputStream(file);
        FileChannel fc = fis.getChannel();
        ByteBuffer bb = ByteBuffer.allocate(new Long(file.length()).intValue());
        //fc向buffer中读入数据
        fc.read(bb);
        bb.flip();
        String str = new String(bb.array(), "UTF8");
        fc.close();
        fis.close();
        return str;
    }

    public String getStyleDetail(String url) {
        HttpHeaders headers = new HttpHeaders();
        // headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Authorization", "Basic YWRtaW46Z2Vvc2VydmVy");
        headers.add("Accept", "application/vnd.ogc.sld+xml");
        HttpEntity entity = new HttpEntity(headers);
        RestTemplate restTemplate = getThirdRestTemplate();
        String object = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();
        String styleUrl = JSONObject.fromObject(object).getJSonObject("layer").getJSonObject("defaultStyle").getString("href");
        return restTemplate.exchange(styleUrl, HttpMethod.GET, entity, String.class).getBody();
    }
}

xml和json完美互转工具


            de.odysseus.staxon
            staxon
            1.3
        
package com.example.geopushstyledemo2.utils;

import de.odysseus.staxon.json.JsonXMLConfig;
import de.odysseus.staxon.json.JsonXMLConfigBuilder;
import de.odysseus.staxon.json.JsonXMLInputFactory;
import de.odysseus.staxon.json.JsonXMLOutputFactory;
import de.odysseus.staxon.xml.util.PrettyXMLEventWriter;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class XmlConverUtil3 {
    public static void main(String[] args) throws Exception {
        String xmlStr = readFile("D:/xmltest/test.xml");
        String jsonStr = readFile("D:/xmltest/jsonStr.json");
        //System.out.println(XmlToJson(xmlStr));
        System.out.println(JsonToXml(jsonStr));
    }

    public static String XmlToJson(String xmlString) {

        StringReader input = new StringReader(xmlString);
        StringWriter output = new StringWriter();
        JsonXMLConfig config = new JsonXMLConfigBuilder()
                .autoArray(true)
                .autoPrimitive(true)
                .prettyPrint(true)
                .namespaceDeclarations(true)
                .build();
        try {
            XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(input);
            XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output);
            writer.add(reader);
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return output.toString();
    }

    
    public static String JsonToXml(String jsonString) {
        StringReader input = new StringReader(jsonString);
        StringWriter output = new StringWriter();
        JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).repairingNamespaces(false).build();
        try {
            XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
            XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
            writer = new PrettyXMLEventWriter(writer);
            writer.add(reader);
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // remove 
        if (output.toString().length() >= 38) {
            return output.toString().substring(39);
        }
        return output.toString();
    }

    
    public static String JsonToXmlReplaceBlank(String jsonString) {
        String str = XmlConverUtil3.JsonToXml(jsonString);
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\s*|t|r|n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    public static String readFile(String path) throws Exception {
        File file = new File(path);
        FileInputStream fis = new FileInputStream(file);
        FileChannel fc = fis.getChannel();
        ByteBuffer bb = ByteBuffer.allocate(new Long(file.length()).intValue());
        //fc向buffer中读入数据
        fc.read(bb);
        bb.flip();
        String str = new String(bb.array(), "UTF8");
        fc.close();
        fis.close();
        return str;

    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/325451.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号