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.*;

/**
 * @author: xxxg
 * @date: 2021/10/8 14:36
 */
@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<String> entity = new HttpEntity<String>("<?xml version=\"1.0\" encoding=\"GBK\"?>\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<String> entity = new HttpEntity<String>(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<String> entity = new HttpEntity<String>(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<String> list = new ArrayList<>();
        for (RESTFeatureType.Attribute attribute : cuFeatureType.getAttributes()) {
            list.add(attribute.getName());
        }
        return list;
    }

    /**
     * 描述:处理中文乱码问题
     * date: 2020年4月8日 上午9:10:38
     *
     * @return
     * @author wuyechun2010@163.com
     * @since JDK 1.8
     */
    public RestTemplate getThirdRestTemplate() {
        Charset thirdRequest = Charset.forName("GBK");
        RestTemplate restTemplate = new RestTemplate();
        // 处理请求中文乱码问题
        List<HttpMessageConverter<?>> 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<String> entity = new HttpEntity<String>(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完美互转工具

<dependency>
            <groupId>de.odysseus.staxon</groupId>
            <artifactId>staxon</artifactId>
            <version>1.3</version>
        </dependency>
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;

/**
 * @author: xxxg
 * @date: 2021/10/9 12:45
 */
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();
    }

    /**
     * @Description: json convert to xml
     * @author xxxg
     */
    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 <?xml version="1.0" encoding="UTF-8"?>
        if (output.toString().length() >= 38) {
            return output.toString().substring(39);
        }
        return output.toString();
    }

    /**
     * @Description: 去掉xml中的换行和空格
     * @author @author xxxg
     */
    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;

    }
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值