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

📄 xmlproperties.java

📁 基于Jabber协议的即时消息服务器
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        String childName = propName[propName.length - 1];        // We found matching property, clear all children.        List toRemove = new ArrayList();        Iterator iter = element.elementIterator(childName);        while (iter.hasNext()) {            toRemove.add(iter.next());        }        for (iter = toRemove.iterator(); iter.hasNext();) {            element.remove((Element)iter.next());        }        // Add the new children.        for (String value : values) {            Element childElement = element.addElement(childName);            if (value.startsWith("<![CDATA[")) {                Iterator it = childElement.nodeIterator();                while (it.hasNext()) {                    Node node = (Node) it.next();                    if (node instanceof CDATA) {                        childElement.remove(node);                        break;                    }                }                childElement.addCDATA(value.substring(9, value.length()-3));            }            else {                childElement.setText(value);            }        }        saveProperties();        // Generate event.        Map<String, Object> params = new HashMap<String, Object>();        params.put("value", values);        PropertyEventDispatcher.dispatchEvent(name,                PropertyEventDispatcher.EventType.xml_property_set, params);    }    /**     * Return all children property names of a parent property as a String array,     * or an empty array if the if there are no children. For example, given     * the properties <tt>X.Y.A</tt>, <tt>X.Y.B</tt>, and <tt>X.Y.C</tt>, then     * the child properties of <tt>X.Y</tt> are <tt>A</tt>, <tt>B</tt>, and     * <tt>C</tt>.     *     * @param parent the name of the parent property.     * @return all child property values for the given parent.     */    public String[] getChildrenProperties(String parent) {        String[] propName = parsePropertyName(parent);        // Search for this property by traversing down the XML heirarchy.        Element element = document.getRootElement();        for (int i = 0; i < propName.length; i++) {            element = element.element(propName[i]);            if (element == null) {                // This node doesn't match this part of the property name which                // indicates this property doesn't exist so return empty array.                return new String[]{};            }        }        // We found matching property, return names of children.        List children = element.elements();        int childCount = children.size();        String[] childrenNames = new String[childCount];        for (int i = 0; i < childCount; i++) {            childrenNames[i] = ((Element)children.get(i)).getName();        }        return childrenNames;    }    /**     * Sets the value of the specified property. If the property doesn't     * currently exist, it will be automatically created.     *     * @param name  the name of the property to set.     * @param value the new value for the property.     */    public synchronized void setProperty(String name, String value) {        if (name == null) {            return;        }        if (value == null) {            value = "";        }        // Set cache correctly with prop name and value.        propertyCache.put(name, value);        String[] propName = parsePropertyName(name);        // Search for this property by traversing down the XML heirarchy.        Element element = document.getRootElement();        for (int i = 0; i < propName.length; i++) {            // If we don't find this part of the property in the XML heirarchy            // we add it as a new node            if (element.element(propName[i]) == null) {                element.addElement(propName[i]);            }            element = element.element(propName[i]);        }        // Set the value of the property in this node.        if (value.startsWith("<![CDATA[")) {            Iterator it = element.nodeIterator();            while (it.hasNext()) {                Node node = (Node) it.next();                if (node instanceof CDATA) {                    element.remove(node);                    break;                }            }            element.addCDATA(value.substring(9, value.length()-3));        }        else {            element.setText(value);        }        // Write the XML properties to disk        saveProperties();        // Generate event.        Map<String, String> params = new HashMap<String,String>();        params.put("value", value);        PropertyEventDispatcher.dispatchEvent(name,                PropertyEventDispatcher.EventType.xml_property_set, params);    }    /**     * Deletes the specified property.     *     * @param name the property to delete.     */    public synchronized void deleteProperty(String name) {        // Remove property from cache.        propertyCache.remove(name);        String[] propName = parsePropertyName(name);        // Search for this property by traversing down the XML heirarchy.        Element element = document.getRootElement();        for (int i = 0; i < propName.length - 1; i++) {            element = element.element(propName[i]);            // Can't find the property so return.            if (element == null) {                return;            }        }        // Found the correct element to remove, so remove it...        element.remove(element.element(propName[propName.length - 1]));        // .. then write to disk.        saveProperties();        // Generate event.        PropertyEventDispatcher.dispatchEvent(name,                PropertyEventDispatcher.EventType.xml_property_deleted, Collections.emptyMap());    }    /**     * Builds the document XML model up based the given reader of XML data.     */    private void buildDoc(Reader in) throws IOException {        try {            SAXReader xmlReader = new SAXReader();            xmlReader.setEncoding("UTF-8");            document = xmlReader.read(in);        }        catch (Exception e) {            Log.error("Error reading XML properties", e);            throw new IOException(e.getMessage());        }        finally {            if (in != null) {                in.close();            }        }    }    /**     * Saves the properties to disk as an XML document. A temporary file is     * used during the writing process for maximum safety.     */    private synchronized void saveProperties() {        boolean error = false;        // Write data out to a temporary file first.        File tempFile = null;        Writer writer = null;        try {            tempFile = new File(file.getParentFile(), file.getName() + ".tmp");            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8"));            OutputFormat prettyPrinter = OutputFormat.createPrettyPrint();            XMLWriter xmlWriter = new XMLWriter(writer, prettyPrinter);            xmlWriter.write(document);        }        catch (Exception e) {            Log.error(e);            // There were errors so abort replacing the old property file.            error = true;        }        finally {            if (writer != null) {                try {                    writer.close();                }                catch (IOException e1) {                    Log.error(e1);                    error = true;                }            }        }        // No errors occured, so delete the main file.        if (!error) {            // Delete the old file so we can replace it.            if (!file.delete()) {                Log.error("Error deleting property file: " + file.getAbsolutePath());                return;            }            // Copy new contents to the file.            try {                copy(tempFile, file);            }            catch (Exception e) {                Log.error(e);                // There were errors so abort replacing the old property file.                error = true;            }            // If no errors, delete the temp file.            if (!error) {                tempFile.delete();            }        }    }    /**     * Returns an array representation of the given Jive property. Jive     * properties are always in the format "prop.name.is.this" which would be     * represented as an array of four Strings.     *     * @param name the name of the Jive property.     * @return an array representation of the given Jive property.     */    private String[] parsePropertyName(String name) {        List<String> propName = new ArrayList<String>(5);        // Use a StringTokenizer to tokenize the property name.        StringTokenizer tokenizer = new StringTokenizer(name, ".");        while (tokenizer.hasMoreTokens()) {            propName.add(tokenizer.nextToken());        }        return propName.toArray(new String[propName.size()]);    }    public void setProperties(Map<String, String> propertyMap) {        for (String propertyName : propertyMap.keySet()) {            String propertyValue = propertyMap.get(propertyName);            setProperty(propertyName, propertyValue);        }    }    /**     * Copies the inFile to the outFile.     *     * @param inFile  The file to copy from     * @param outFile The file to copy to     * @throws IOException If there was a problem making the copy     */    private static void copy(File inFile, File outFile) throws IOException {        FileInputStream fin = null;        FileOutputStream fout = null;        try {            fin = new FileInputStream(inFile);            fout = new FileOutputStream(outFile);            copy(fin, fout);        }        finally {            try {                if (fin != null) fin.close();            }            catch (IOException e) {                // do nothing            }            try {                if (fout != null) fout.close();            }            catch (IOException e) {                // do nothing            }        }    }    /**     * Copies data from an input stream to an output stream     *     * @param in the stream to copy data from.     * @param out the stream to copy data to.     * @throws IOException if there's trouble during the copy.     */    private static void copy(InputStream in, OutputStream out) throws IOException {        // Do not allow other threads to intrude on streams during copy.        synchronized (in) {            synchronized (out) {                byte[] buffer = new byte[256];                while (true) {                    int bytesRead = in.read(buffer);                    if (bytesRead == -1) break;                    out.write(buffer, 0, bytesRead);                }            }        }    }}

⌨️ 快捷键说明

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