자바XML 환경파일 로드 클래스 구성 (XML파싱)

황제낙엽 2007.01.05 12:49 조회 수 : 62 추천:161

sitelink1  
sitelink2  
sitelink3  
sitelink4  
sitelink5  
sitelink6  
프로젝트를 진행하다보면 공통상수 및 환경변수들이 생성됩니다.
이러한 변수들은 보통 xml 또는 properties형태로 화일에 기록됩니다.
이렇게 저장된 환경변수들을 읽어 처리하는 방식의 예제를 분석해 보도록 합니다.
다음의 예제는 분석용으로 사용하기 위해 실제 프로젝트에서 사용한 클래스의 일부를 추출한 내용으로써
완전체가 아님에 주의해야 합니다.

관련 클래스는 다음과 같습니다.

1. ProjectEnv : 프로젝트 환경변수를 담고 있습니다.
/**
 * Copyright(C) NEC Soft, Ltd. 2006.12
 * All rights reserved
 * NEC Soft Confidential and Proprietary
 *
 * @author Lee
 * @version 1.0
 * @since csv R1.0
 */

package com.nec.csv.env;

import java.util.Hashtable;
import com.nec.csv.app.CMainApp;
import com.nec.csv.common.CTradeTrace;
import com.nec.csv.manager.CProcessManager;

public class ProjectEnv {
    // LOG出力用
    static CTradeTrace trace = new CTradeTrace(CMainApp.class.getName());

    public final static String X1197_MIT = "REQKOU02.00";        // 購買見積依?
    public final static String X1197_KAI = "QUOKIK02.00";        // 購買見積回答
    public final static String X1197_CYU = "ORDERS02.00";        // 確定注文
    public final static String X1197_UKE = "ORDRSP02.00";        // 注文請け
    public final static String X1197_DYO = "DEKADV02.00";        // 出?高要請
    public final static String X1197_DHO = "DEKDAK02.00";        // 出?高報告
    public final static String X1197_DKA = "DEKRSP02.00";        // 出?高確認
    public static String commandMsg = "";
    public static String descript = "";
    public static String method = "";
    // environment.xmlの格納場所
    private Hashtable envTable = new Hashtable();

    /**
     * プロパティ情報をセットする。
     *
     */
    public void setEnvironment(String propertyName, String propertyValue) {
        envTable.put(propertyName, propertyValue);
    }    

    /**
     * プロパティ情報を取得する。
     *
     * @return プロパティの値を返却します。
     */
    public String getEnvironment(String propertyName) {
        return (String)envTable.get(propertyName);
    }

    ... ... (기타 get, set 메서드들)
}


2. EnvInitialize : 프로젝트에서 사용하는 xml파일들의 경로등의 정보를 가지고 있습니다.

/**
 * Copyright(C) NEC Soft, Ltd. 2006.12
 * All rights reserved
 * NEC Soft Confidential and Proprietary
 *
 * @author Lee
 * @version 1.0
 * @since csv R1.0
 */
package com.nec.csv.common;

import java.io.File;
import org.apache.log4j.xml.DOMConfigurator;

public class EnvInitialize {
    // LOG出力用
    static CTradeTrace trace = new CTradeTrace(CInitialize.class.getName());

    public static void initialize() {
       //ログファイル設定
        String log4j_filename = "trace.xml";
        //環境ファイル設定
        String config_filename = "config.xml";
        //ファイル?分文字取得
        String file_separator = System.getProperty("file.separator");
        //ユ?ザディレクトリ取得
        String user_dir = System.getProperty("user.dir");
        // Log4j filepath
        String log4j_xmlfile = user_dir + file_separator + log4j_filename;
        //Config XML filepath
        String config_xmlfile = user_dir + file_separator + config_filename;

        try{
           DOMConfigurator.configure(log4j_xmlfile);
           File log4j_conf_file = new File(log4j_xmlfile);
           File env_conf_file = new File(config_xmlfile);
           if (log4j_conf_file.canRead()) {
               CTradeTrace.initalize(log4j_xmlfile);
           }else{
               System.out.println("error - trace.xml file not exist!");
           }
           if (env_conf_file.canRead()) {
               CLoadXml loadXml = new CLoadXml(config_xmlfile);
               loadXml.init();
           }else{
               trace.debug("config.xml file not exist!");
           }
           startLog();
       }catch(Exception e){
           trace.error(e.getMessage());
       }
    }

    /**
     * プログラムの開始を記?
     */
    private static void startLog() {
        trace.debug("--------------------------------------> csvXcsv start ");
    }
}


3. LoadXml : XML화일을 읽어 Env클래스 환경변수를 초기화 합니다.

/**
 * Copyright(C) NEC Soft, Ltd. 2006.12
 * All rights reserved
 * NEC Soft Confidential and Proprietary
 *
 * @author     Lee
 * @version    1.0
 * @since        csv R1.0
 */

 

package com.nec.csv.common;

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.nec.csv.env.CCommand;
import com.nec.csv.env.CEnv;

/**
 * テ?ブルの設定ファイル(XML)を?み?む
 */
public class LoadXml {
    // LOG出力用
    static CTradeTrace trace = new CTradeTrace(CLoadXml.class.getName());
    // ファイルオブジェクトを生成
    File config_file;

    /**
     * 生成者
     * 生成者が呼び出される時共通ファイルオブジェクトも生成される
     * @param confile    XML設定ファイル
     */
    public CLoadXml(String confile) throws Exception{
        // ファイルオブジェクトを生成
        config_file = new File(confile);
        // ファイルの有?性チェック
        if((config_file == null) || (config_file.canRead() == false)){
            // ファイルが存在しないか、?み?み?がありません。
            throw new IOException(confile+"ファイルが存在しないか、?み?み?がありません");
        }
    }

    public void init() {
        // ファイルを?み?む
        try {
            // ドキュメントパ?シン
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document document = docBuilder.parse(config_file);
            // ル?トノ?ドの取得
            Node root_node = document.getDocumentElement();
            // ノ?ドの有?性チェック
            if(root_node == null){
                if (trace.isDebugEnabled())
                    trace.debug("無?なXMLファイルです。");
                return;
            }
            // ル?トノ?ドの値を取得
            String root_nodename = root_node.getNodeName();
            // ル?トノ?ドの確認
            if (!root_nodename.equals("env")) {
                if (trace.isDebugEnabled())
                    trace.debug("ファイルの形式が違います。");
                return;
            }

            // ル?トノ?ドの子ノ?ドリストを取得
            NodeList nodeList = root_node.getChildNodes();
            // ノ?ドリストの有?チェック
            if (nodeList != null) {

                // 1Level子ノ?ドリスト?分ル?プ
                for (int i = 0; i < nodeList.getLength(); i++) {
                    // ノ?ドの取得
                    Node parent_node = nodeList.item(i);
                    // 有?ノ?ドチェック
                    if((parent_node == null) || (parent_node.getNodeType() != Node.ELEMENT_NODE))
                        continue;

                    // "command"ノ?ドの場合
                    if (parent_node.getNodeName().equals("command")) {
                            getCommand(parent_node);
                    }

                    // "filepath"ノ?ドの場合
                    if (parent_node.getNodeName().equals("filepath")) {
                        getFilepath(parent_node);
                    }

                    // "sendprog"ノ?ドの場合
                    if (parent_node.getNodeName().equals("sendprog")) {
                        getSendprog(parent_node);
                    }

                }// End For
            }

        } catch (Exception e) {
            if (trace.isDebugEnabled())
                trace.debug(e.getMessage());
        }
    }

    private void getCommand(Node parent_node) {
        // ?性ノ?ドの取得("id"の値を取得するため)
        String id = getAttNodeValue(parent_node, "id");

        // 選?された場合
        if (id != null && !id.equals("")) {
            // 子ノ?ドを取得して選?可否を判?
            NodeList subList = parent_node.getChildNodes();
            // ノ?ドの有?性チェック
            if (subList != null) {
                CCommand command = new CCommand();
                command.setId(id);

                // メッセ?ジの種類を格納
                int _pos = id.indexOf("_") + 1;
                command.setMessagekind(id.substring(_pos, _pos+3));

                // メッセ?ジの部分名(鑑、明細)を格納
                command.setMessagepart(id.substring(_pos+4, _pos+10));

                // 子ノ?ド分ル?プ
                for (int j = 0; j < subList.getLength(); j++) {
                    // 子ノ?ド項目値を取得
                    Node child_node = subList.item(j);
                    // ノ?ドの有?性チェック
                    if((child_node == null) || (child_node.getNodeType() != Node.ELEMENT_NODE))
                        continue;

                    // 命令の?明取得
                    if(child_node.getNodeName().equals("descript")) {
                        command.setDescript(getTextNodeValue(child_node));
                    }
                    // 命令の?行プロセス取得
                    if(child_node.getNodeName().equals("processor")) {
                        command.setProcessor(getTextNodeValue(child_node));
                    }
                    // 命令のメソッド取得
                    if(child_node.getNodeName().equals("method")) {
                        command.setMethod(getTextNodeValue(child_node));
                    }
                }// End For

                CEnv.processor.put(id, command);
            }
        }
    }

    private void getFilepath(Node parent_node) {
        // 子ノ?ドを取得して各ファイルパ?スを取得
        NodeList subList = parent_node.getChildNodes();
        // ノ?ドの有?性チェック
        if (subList != null) {
            // 子ノ?ド分ル?プ
            for (int j = 0; j < subList.getLength(); j++) {
                // 子ノ?ド項目値を取得
                Node child_node = subList.item(j);
                // ノ?ドの有?性チェック
                if((child_node == null) || (child_node.getNodeType() != Node.ELEMENT_NODE))
                    continue;

                // indexパ?スの取得
                if(child_node.getNodeName().equals("index")) {
                    CEnv.filepath_index = getTextNodeValue(child_node);
                }
                // source
                if(child_node.getNodeName().equals("source")) {
                    CEnv.filepath_source = getTextNodeValue(child_node);
                }
                // target
                if(child_node.getNodeName().equals("target")) {
                    CEnv.filepath_target = getTextNodeValue(child_node);
                }
            }// End For
        }
    }

    private void getSendprog(Node parent_node) {
        // ?性ノ?ドの取得("select"の値を取得するため)
        String select = getAttNodeValue(parent_node, "execute");
        // 選?された場合
        if (select.equals("true")) {
            // ?換の後送信プログラムの?行可否設定
            CEnv.send_program_exe = true;
            // 子ノ?ドを取得して各ファイルパ?スを取得
            NodeList subList = parent_node.getChildNodes();
            // ノ?ドの有?性チェック
            if (subList != null) {
                // 子ノ?ド分ル?プ
                for (int j = 0; j < subList.getLength(); j++) {
                    // 子ノ?ド項目値を取得
                    Node child_node = subList.item(j);
                    // ノ?ドの有?性チェック
                    if((child_node == null) || (child_node.getNodeType() != Node.ELEMENT_NODE))
                        continue;

                    // nameの取得
                    if(child_node.getNodeName().equals("name")) {
                        CEnv.send_program_name = getTextNodeValue(child_node);
                    }
                    // url
                    if(child_node.getNodeName().equals("url")) {
                        CEnv.send_program_url = getTextNodeValue(child_node);
                    }
                    // port
                    if(child_node.getNodeName().equals("port")) {
                         CEnv.send_program_port = getTextNodeValue(child_node);
                    }
                    // page
                    if(child_node.getNodeName().equals("page")) {
                        CEnv.send_program_page = getTextNodeValue(child_node);
                    }
                    // userid
                    if(child_node.getNodeName().equals("userid")) {
                        CEnv.send_program_userid = getTextNodeValue(child_node);
                    }
                    // userpw
                    if(child_node.getNodeName().equals("userpw")) {
                        CEnv.send_program_userpw = getTextNodeValue(child_node);
                    }
                    // file
                    if(child_node.getNodeName().equals("file")) {
                        CEnv.send_program_file = getTextNodeValue(child_node);
                    }
                }// End For
            }
        }
    }

    /**
     * ノ?ドの?性値を取得して返却する
     * @param node           ?象になるノ?ド
     * @param attName  ?性名
     * @return        ?性値
     */
    private String getAttNodeValue(Node node, String attName) {
        // ?性値を格納する文字??
        String attValue = "";
        // ノ?ドの有?性チェック
        if(node == null) return attValue;

        // ?象ノ?ドの?性ノ?ドを取得
        NamedNodeMap nmd = node.getAttributes();
        // ノ?ドの有?性チェック
        if (nmd != null) {
            // ?性ノ?ド?分ル?プ
            for (int j = 0; j < nmd.getLength(); j++) {
                // ?性ノ?ド取得
                Node attNode = nmd.item(j);
                // ノ?ドの有?性チェック
                if ((attNode != null) && (attNode.getNodeType() == Node.ATTRIBUTE_NODE)) {
                    // ノ?ド名比較
                    if (attNode.getNodeName().equals(attName)) {
                        // ノ?ド値を取得
                        attValue = attNode.getNodeValue();
                    }
                }
            }
        }
        // ノ?ド値を返却
        return attValue;
    }

    private String getTextNodeValue(Node node) {
        String nodeValue;

        if (node.getFirstChild() != null) {
            nodeValue = node.getFirstChild().getNodeValue();
        }else{
            nodeValue = "";
        }

        return nodeValue;
    }
}


4. config.xml : 환경변수를 담고있는 설정화일.

<?xml version="1.0" encoding="Shift_JIS"?>
<env>
    <command id="arusha_mit_kagami">
        <descript>サンプル?社見積依?鑑部</descript>
        <processor>com.nec.csv.process.CProcessorZ</processor>
        <method>arusha_mit_kagami</method>
    </command>
    <command id="arusha_mit_meisai">
        <descript>サンプル?社見積依?明細部</descript>
        <processor>com.nec.csv.process.CProcessorZ</processor>
        <method>arusha_mit_meisai</method>
    </command>

 

    <filepath>
        <index>D:NECProjectcsvXcsvindex</index>
        <source>D:NECProjectcsvXcsvoriginal</source>
        <target>D:NECProjectcsvXcsvconvert</target>
    </filepath>

    <sendprog execute="true">       
        <name>fileSend.exe</name>
        <url>localhost</url>
        <port>8080</port>
        <page>/index.jsp</page>
        <userid>admin</userid>
        <userpw>1234</userpw>
        <file></file>
    </sendprog>
</env>