⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 putstyles.java

📁 电子地图服务器,搭建自己的地图服务
💻 JAVA
📖 第 1 页 / 共 2 页
字号:

            if (childName == null) {
                childName = child.getNodeName();
            }

            if (childName.equalsIgnoreCase(wantedChildName)) {
                return child;
            }
        }

        return null;
    }

    /**
     * Convenience method to get the value from the specified node.
     *
     * @param node
     * @return
     */
    public String getNodeValue(Node node) {
        return node.getChildNodes().item(0).getNodeValue();
    }

    /**
     * Give a node and the name of a child of that node, find its (string)
     * value. This doesnt do anything complex.
     *
     * @param parentNode
     * @param wantedChildName
     *
     * @return
     */
    public String getNodeChildValue(Node parentNode, String wantedChildName) {
        NodeList children = parentNode.getChildNodes();

        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);

            if ((child == null) || (child.getNodeType() != Node.ELEMENT_NODE)) {
                continue;
            }

            String childName = child.getLocalName();

            if (childName == null) {
                childName = child.getNodeName();
            }

            if (childName.equalsIgnoreCase(wantedChildName)) {
                return child.getChildNodes().item(0).getNodeValue();
            }
        }

        return null;
    }

    /**
     * returns true if this node is named "name".  Ignores case and namespaces.
     *
     * @param n
     * @param name
     *
     * @return
     */
    public boolean nodeNameEqual(Node n, String name) {
        if (n.getNodeName().equalsIgnoreCase(name)) {
            return true;
        }

        String nname = n.getNodeName();
        int idx = nname.indexOf(':');

        if (idx == -1) {
            return false;
        }

        if (nname.substring(idx + 1).equalsIgnoreCase(name)) {
            return true;
        }

        return false;
    }

    /**
     * processSLD:
     *
     * Makes the SLD into a DOM object and validates it.
     * It will then get the layer names and update for each layer.
     *
     * @param sld
     * @param rootNode the root node of the DOM document for parsing
     * @param response
     * @throws IOException
     * @throws WmsException
     */
    private void processSLD(PutStylesRequest serviceRequest, HttpServletRequest request,
        HttpServletResponse response, ServletContext context)
        throws IOException, SldException {
        LOGGER.info("Processing SLD");

        String sld_remote = serviceRequest.getSLD();

        if ((sld_remote != null) && !sld_remote.equals("")) {
            throw new java.lang.UnsupportedOperationException(
                "SLD= param not yet implemented. Use SLD_BODY=");
        }

        String sld_body = serviceRequest.getSldBody(); // the actual SLD body

        if ((sld_body == null) || (sld_body == "")) {
            throw new IllegalArgumentException("The body of the SLD cannot be empty!");
        }

        // write out SLD so we can read it in and validate it
        File temp = File.createTempFile("putStyles", "xml");
        temp.deleteOnExit();

        FileOutputStream fos = new FileOutputStream(temp);
        BufferedOutputStream tempOut = new BufferedOutputStream(fos);

        byte[] bytes = sld_body.getBytes();

        for (int i = 0; i < bytes.length; i++) {
            tempOut.write(bytes[i]);
        }

        tempOut.flush();
        tempOut.close();

        BufferedInputStream fs = new BufferedInputStream(new FileInputStream(temp));

        // finish making our tempory file stream (for SLD validation)
        CharArrayReader xml = new CharArrayReader(sld_body.toCharArray()); // put the xml into a 'Reader'

        Node rootNode = generateDOM(xml);

        // validate the SLD
        SLDValidator validator = new SLDValidator();
        List errors = validator.validateSLD(fs, context);

        if (errors.size() != 0) {
            throw new SldException(SLDValidator.getErrorMessage(xml, errors));
        }

        Node n_namedLayer = getNode(rootNode, "NamedLayer");
        Node n_layerName = getNode(n_namedLayer, "Name");
        Node n_userStyle = getNode(n_namedLayer, "UserStyle");
        Node n_styleName = getNode(n_userStyle, "Name");

        // "ftname_styleLayerName": ignore "_style"
        String layerName = getNodeValue(n_layerName); //.split("_styleLayerName")[0];
        String styleName = getNodeValue(n_styleName);
        LOGGER.info("PutStyles SLD:\nLayer: " + layerName + ", style: " + styleName);

        // store the SLD
        StyleConfig style = new StyleConfig();
        style.setId(styleName);

        // make the SLD file in the data_dir/styles directory
        File data_dir = GeoserverDataDirectory.getGeoserverDataDirectory();
        File style_dir;

        try {
            style_dir = GeoserverDataDirectory.findConfigDir(data_dir, "styles");
        } catch (ConfigurationException cfe) {
            LOGGER.warning("no style dir found, creating new one");
            //if for some bizarre reason we don't fine the dir, make a new one.
            style_dir = new File(data_dir, "styles");
        }

        File styleFile = new File(style_dir, styleName + ".sld"); // styleName.sld
                                                                  //styleFile.createNewFile();

        LOGGER.info("Saving new SLD file to " + styleFile.getPath());

        // populate it with the style code
        StringBuffer sldText = new StringBuffer();
        sldText.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        sldText.append("<StyledLayerDescriptor version=\"1.0.0\"\n");
        sldText.append(
            "	xsi:schemaLocation=\"http://www.opengis.net/sld StyledLayerDescriptor.xsd\"\n");
        sldText.append(
            "	xmlns=\"http://www.opengis.net/sld\" xmlns:ogc=\"http://www.opengis.net/ogc\"\n");
        sldText.append("	xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n");
        sldText.append("	xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n");

        FileOutputStream style_fos = new FileOutputStream(styleFile); // save the sld to a file

        String sldBody = serviceRequest.getSldBody();
        int start = sldBody.indexOf("<NamedLayer>");
        int end = sldBody.indexOf("</NamedLayer>");

        sldText.append(sldBody.substring(start, end));
        sldText.append("</NamedLayer>\n");
        sldText.append("</StyledLayerDescriptor>");
        style_fos.write(sldText.toString().getBytes());
        style_fos.flush();
        style_fos.close();

        style.setFilename(styleFile);

        // update the data config to tell it about our new style
        DataConfig dataConfig = ConfigRequests.getDataConfig(request);
        dataConfig.addStyle(styleName, style);

        // SLD is set up now, so tell the feature type to use it

        // get our featureType by the layerName
        List keys = dataConfig.getFeatureTypeConfigKeys();
        Iterator it = keys.iterator();
        layerName = null;

        while (it.hasNext()) // get the full featureType name that has the datastore prefix
         {
            String o = it.next().toString();
            String[] os = o.split(":");

            if (os[1].equalsIgnoreCase(layerName)) {
                layerName = o;

                break;
            }
        }

        // get the feature type and save the style for it, if the feature type exists yet
        // If there is no FT there that may mean that the user is just creating it.
        if (layerName != null) {
            FeatureTypeConfig featureTypeConfig = dataConfig.getFeatureTypeConfig(layerName);
            featureTypeConfig.setDefaultStyle(styleName);
        }

        // if successful, return "success"
        //response.setContentType(success_mime_type);
        LOGGER.info("sending back result");

        String message = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<sld:success>success</sld:success>";
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        byte[] msg = message.getBytes();
        out.write(msg);
        out.flush();
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -