使用commons-configuration对.xml和.propertias的读写

来源:互联网 发布:银联卡网络支付接口 编辑:程序博客网 时间:2024/05/18 16:16

使用commons-configuration对.xml和.properties的读写

2015/10/27

  • 使用commons-configuration对xml和properties的读写
    • maven依赖
    • 初始化处理
    • 对properties的处理
    • 对xml文件的处理
    • 其他方法对配置文件的操作

完成一个工具需求,对users.prorerties, groups.prorperties, activemq.xml进行修改配置:

  • 新加入用户密码到users中
  • 对组员新加到组中
  • 对新用户加入queue权限或更改时,修改activemq.xml的配置

    考虑到文件中有注释,如果要保存注释,则使用apache下的那些读写配置文件的包。

users.properties示例

## this is just a testuser1=psw1user2=psw2user3=psw3user4=psw4

groups.properties示例

## this is just a testgroup1=user1group2=user2group3=user3,user4

activemq.xml示例

<beans xmlns="http://www.springframework.org/schema/beans">    <bean class="test">        <property name="locations">            <value>value</value>        </property>    </bean>    <managementContext>            <managementContext createConnector="false"/>    </managementContext>    <systemUsage>            <systemUsage>                <memoryUsage>                    <memoryUsage percentOfJvmHeap="70"/>                </memoryUsage>                <storeUsage>                    <storeUsage limit="50 gb"/>                </storeUsage>                <tempUsage>                    <tempUsage limit="1 gb"/>                </tempUsage>            </systemUsage>    </systemUsage>    <plugins>        <runtimeConfigurationPlugin checkPeriod="10000"/>         <jaasAuthenticationPlugin configuration="activemq"/>        <authorizationPlugin>            <map>                <authorizationMap>                    <authorizationEntries>                        <authorizationEntry admin="user1" queue=">" read="user1" write="user1"/>                        <authorizationEntry admin="user1" read="user1" topic=">" write="user1"/>                     </authorizationEntries>                </authorizationMap>            </map>        </authorizationPlugin>    </plugins></beans>

对activemq.xml操作修改的地方为

<authorizationEntry admin="user1" queue="test.queue" read="user1" write="user1"/>

user1用户对队列”test.queue”有admin,read,write权限

要实现的操作是:

1.新增user6=psw6到users.properties中,如果已经存在user6,则对密码的修改;

2.同时将user6加入到组group1即groups.properties中的效果是group1=user1,user6,如果不存在group1,则新增;

3.对user6新加入queue=”user6.test”,使user6有read,write权限,即效果是xml中新加入<authorizationEntry queue="user6.test" read="user6" write="user6"/>,如果已经存在queue=”user6.test”改权限。

maven依赖

    <dependency>        <groupId>commons-configuration</groupId>        <artifactId>commons-configuration</artifactId>        <version>1.10</version>    </dependency>    <dependency>        <groupId>commons-logging</groupId>        <artifactId>commons-logging</artifactId>        <version>1.1.3</version>    </dependency>    <dependency>        <groupId>commons-collections</groupId>        <artifactId>commons-collections</artifactId>        <version>3.2.1</version>    </dependency>

初始化处理

。。。    //配置文件操作类    private PropertiesConfiguration usersProperties;    private PropertiesConfiguration groupsProperties;    private XMLConfiguration activemqXml;    //路径    private String usersPath = "src/main/resources/users.properties";    private String groupsPath = "src/main/resources/groups.properties";    private String activemqXmlPath = "src/main/resources/activemq.xml";    public boolean init(String usersPath, String groupsPath, String activemqXmlPath) {        if (!usersPath.isEmpty()) {            this.usersPath = usersPath;        }        if (!groupsPath.isEmpty()) {            this.groupsPath = groupsPath;        }        if (!activemqXmlPath.isEmpty()) {            this.activemqXmlPath = activemqXmlPath;        }        try {            this.usersProperties = getPropertiesFile(usersPath);            this.groupsProperties = getPropertiesFile(groupsPath);            this.activemqXml = getXML(activemqXmlPath);        } catch (Exception e) {            return false;        }        return true;    }    /**     * 获取加载.properties文件     *      * @param filename     * @return     */    public static PropertiesConfiguration getPropertiesFile(String filename) {        PropertiesConfiguration properties = null;        try {            properties = new PropertiesConfiguration(filename);            // 自动刷新重载入,如果不使用以下一行,则在其他地方对文件操作均无效,            //文件会重新写入当前状态的内容            properties.setReloadingStrategy(new FileChangedReloadingStrategy());        } catch (ConfigurationException e) {            e.printStackTrace();        }        return properties;    }    /**     * 获取加载.xml文件     *      * @param fileName     * @return     */    public static XMLConfiguration getXML(String fileName) {        XMLConfiguration xmlConfig = null;        try {            xmlConfig = new XMLConfiguration(fileName);            xmlConfig.setEncoding("utf-8");            //xml文件同上,自动刷新重载入            xmlConfig.setReloadingStrategy(new FileChangedReloadingStrategy());        } catch (ConfigurationException e) {            e.printStackTrace();        }        return xmlConfig;    }

对.properties的处理

/**     * 添加用户,用户不存在则新增,存在则修改     *      * @param userName     * @param password     */    public void addUser(String userName, String password) {        String oldpsw = (String) usersProperties.getProperty(userName);        if (oldpsw != null) {            usersProperties.setProperty(userName, password);        } else {            usersProperties.addProperty(userName, password);        }        try {            usersProperties.save();        } catch (ConfigurationException e) {            e.printStackTrace();        }    }    /**     * 添加组员,组不存在则新加,存在则在组其他成员之后添加     *      * @param groupName     * @param userName     */    public void addGroup(String groupName, String userName) {        List<Object> list = groupsProperties.getList(groupName);        if (!list.contains(userName)) {            list.add(userName);        }        groupsProperties.setProperty(groupName, list);        try {            groupsProperties.save();        } catch (ConfigurationException e) {            e.printStackTrace();        }    }

对.xml文件的处理

/**     * 更新或添加用户权限     *      * @param type queue or topic     * @param theme queueName or topicName     * @param userName  设置权限的用户     * @param authList  权限有哪些[read,write,admin]     */    public boolean updateUserAuth(String type, String theme, String userName, String[] authArray) {        String path = "plugins.authorizationPlugin.map.authorizationMap.authorizationEntries.authorizationEntry";        List<HierarchicalConfiguration> fields = activemqXml.configurationsAt(path);        boolean isNew = true;        //遍历所有相关authorizationEntry节点,查        for (Iterator<HierarchicalConfiguration> it = fields.iterator(); it.hasNext();) {            HierarchicalConfiguration sub = it.next();            String themexml = (String) sub.getProperty("[@" + type + "]");            //是否存在当然操作用户在已存在的queue或topic中,存在则在原来基础上改            if (themexml != null && theme.equals(themexml)) {                sub.clearProperty("read");                sub.clearProperty("write");                sub.clearProperty("admin");                //重新修改权限                for (String auth : authArray) {                    sub.setProperty("[@" + auth + "]", userName);                }                isNew = false;                break;            }        }        //如果是新添加的,则末尾加        if (isNew) {            activemqXml.addProperty(path + "(" + fields.size() + ")[@" + type + "]", theme);            for (String auth : authArray) {                activemqXml.addProperty(path + "(" + fields.size() + ")[@" + auth + "]", userName);            }        }        try {            activemqXml.save();            // 对转义字符处理。。。把保存后的xml文件内容全部读出,然后replace,然后在写入            File file = new File(activemqXmlPath);            String content = XmlFileUtil.readContent(file, Charset.defaultCharset());            String test = XmlFileUtil.decodeString(content);            XmlFileUtil.writeContent(file, test, Charset.defaultCharset());            return true;        } catch (ConfigurationException | FileNotFoundException e) {            e.printStackTrace();            return false;        }    }

1.在这里存在xml需要注意的是activemqXml.configurationsAt(path);中,path是在root节点beans下的字节点,即plugins.authorizationPlugin.map.authorizationMap.authorizationEntries.authorizationEntry获取到authorizationEntry节点下的内容,以便对此节点进行下一步的操作;

2.在对<authorizationEntry admin="user1" queue=">" read="user1" write="user1"/>中的属性元素如admin=”user1”,进行修改操作时,使用sub.getProperty("[@admin]");获取.

3.在对xml进行操作完毕执行activemqXml.save();保存后,有一个略蛋疼的问题,如果在节点属性中存在特殊字符如queue=">",则在保存后会被转义成queue="&gt;",试了下其他读取xml方法发现还是没办法保持原样,这是由于XML语法检查时会出错,如果编写的XML文件必须包含这些字符,则必须分别成&amp;&lt;&gt;再写入文件中,但是这样就和一开始的xml不一致来。例如,如果在XML文档中使用类似”<” 的字符, 那么解析器将会出现错误,因为解析器会认为这是一个新元素的开始。目前办法是:暴力解决。。字符串strData = replaceString(strData, "&gt;", ">");当然,前提是,仅仅是那些保存后被转义的,如果在原文件中某些地方的url中就已经包含&gt;,那就蛋疼了。

其他方法对配置文件的操作

使用dom4j
这个也是一个工具包,挺好,保留注释。

Java Properties类
在一开始的时候就是使用这个方法,但是发现其操作是,读出来,修改,然后重新读出来并修改后的内容写进去,这样导致注释代码就没了。,然后一般配置文件注释还是很重要的。

0 0
原创粉丝点击