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

📄 xmlreader.java

📁 一个用于排队系统仿真的开源软件,有非常形象的图象仿真过程!
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
/**    
  * Copyright (C) 2006, Laboratorio di Valutazione delle Prestazioni - Politecnico di Milano

  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 2 of the License, or
  * (at your option) any later version.

  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.

  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  */
  
package jmt.gui.common.xml;

import jmt.common.xml.resources.XSDSchemaLoader;
import jmt.gui.common.CommonConstants;
import jmt.gui.common.Defaults;
import jmt.gui.common.definitions.CommonModel;
import jmt.gui.common.distributions.Distribution;
import jmt.gui.common.routingStrategies.ProbabilityRouting;
import jmt.gui.common.routingStrategies.RoutingStrategy;
import jmt.gui.common.serviceStrategies.LDStrategy;
import jmt.gui.common.serviceStrategies.ZeroStrategy;

import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;

/**
 * <p>Title: XML Reader</p>
 * <p>Description: Reads model information from an XML file. This
 * class provide methods for model load. It's designed to be used by both JModel and JSim.</p>
 * 
 * @author Bertoli Marco
 *         Date: 27-lug-2005
 *         Time: 13.59.48
 */
public class XMLReader implements XMLConstantNames, CommonConstants {
    protected static TreeMap classes; // Data structure used to map between class name and its key
    protected static TreeMap stations; // Data structure used to map between station name and its key
    protected static HashMap refStations; // Data structure used to hold classes' reference stations
    protected static HashMap empiricalRouting; // Data structure to save malformed empirical routing tuples

    /*defines matching between engine representation and gui names for drop
    rules.*/
    protected static final HashMap dropRulesNamesMatchings = new HashMap(){
        {
            put("drop", FINITE_DROP);
            put("waiting queue", FINITE_WAITING);
            put("BAS blocking", FINITE_BLOCK);
        }
    };

    // Variables used with caching purpose to improve reading speed
    protected static Map engineToGuiDistr = null;
    protected static Map engineToGuiRouting = null;

    protected static final String queueGetFCFS = "jmt.engine.NetStrategies.QueueGetStrategies.FCFSstrategy";
    protected static final String queueGetLCFS = "jmt.engine.NetStrategies.QueueGetStrategies.LCFSstrategy";
    protected static final String queuePut = "jmt.engine.NetStrategies.QueuePutStrategy";
    protected static final String serviceStrategy = "jmt.engine.NetStrategies.ServiceStrategy";


    /**
     * Restore a model saved in an XML file, given the name of the file. If specified file
     * is a jmodel archive, extracts model informations from it and uses them to reconstruct
     * the model. This method is provided to be used with JSIM
     * @param fileName name of the file to be opened
     * @param model data structure where model should be created (a new data structure
     * is the best choice)
     * @return true iff model was recognized and loaded, false otherwise
     */
    public static boolean loadModel(String fileName, CommonModel model){
        Document doc = loadXML(fileName, XSDSchemaLoader.loadSchema(XSDSchemaLoader.JSIM_MODEL_DEFINITION));
        if (doc.getElementsByTagName(XML_DOCUMENT_ROOT).getLength() != 0) {
            // Document is a simulation model
            parseXML(doc, model);
            return true;
        }
        else if (doc.getElementsByTagName(GuiXMLConstants.XML_ARCHIVE_DOCUMENT_ROOT).getLength() != 0) {
            // Document is an archive
            parseXML(XMLArchiver.getSimFromArchiveDocument(doc), model);
            return true;
        }
        return false;
    }

    /**
     * Restore a model saved in an XML file, given the handler to the file. If specified file
     * is a jmodel archive, extracts model informations from it and uses them to reconstruct
     * the model. This method is provided to be used with JSIM
     * @param xmlFile handler to the file to be opened
     * @param model data structure where model should be created (a new data structure
     * is the best choice)
     * @return true iff model was recognized and loaded, false otherwise
     */
    public static boolean loadModel(File xmlFile, CommonModel model){
        return loadModel(xmlFile.getAbsolutePath(), model);
    }

    /**
     * Parses given Gui XML Document to reconstruct simulation model.
     * @param root root of document to be parsed
     * @param model data model to be elaborated
     */
    public static void parseXML(Element root, CommonModel model) {
        // Gets optional parameter simulation seed
        String seed = root.getAttribute(XML_A_ROOT_SEED);
        if (seed != null && seed != "") {
            model.setUseRandomSeed(false);
            model.setSimulationSeed(new Long(seed));
        }
        else {
            model.setUseRandomSeed(true);
        }
        // Gets optional parameter maximum time
        String maxTime = root.getAttribute(XML_A_ROOT_DURATION);
        if (maxTime != null && maxTime != "")
            model.setMaximumDuration(new Double(maxTime));

        else
            model.setMaximumDuration(new Double(-1));

        // Gets optional parameter polling interval
        String polling = root.getAttribute(XML_A_ROOT_POLLING);
        if (polling != null && polling != "")
            model.setPollingInterval(Double.parseDouble(polling));

        // Gets optional parameter maximum samples
        String maxSamples = root.getAttribute(XML_A_ROOT_MAXSAMPLES);
        if (maxSamples != null && maxSamples != "")
            model.setMaxSimulationSamples(Integer.decode(maxSamples));

        // Gets optional parameter disable statistic
        String disableStatistic = root.getAttribute(XML_A_ROOT_DISABLESTATISTIC);
        if (disableStatistic != null && disableStatistic != "")
            model.setDisableStatistic(Boolean.valueOf(disableStatistic));

        parseClasses(root, model);
        empiricalRouting = new HashMap();
        parseStations(root, model);
        parseMeasures(root, model);
        parseConnections(root, model);
        parseBlockingRegions(root, model);
        parsePreloading(root, model);
        // Set reference station for each class
        Object[] keys = refStations.keySet().toArray();
        for (int i=0; i<keys.length; i++)
            model.setClassRefStation(keys[i], stations.get(refStations.get(keys[i])));
        // Sets correct station key into every empiricalRouting element
        // Now each key is an Object[] where (0) is station key and (1) class key
        keys = empiricalRouting.keySet().toArray();
        for (int i=0; i<keys.length; i++) {
            Object[] dualkey = (Object[]) keys[i];
            RoutingStrategy rs = (RoutingStrategy) model.getRoutingStrategy(dualkey[0], dualkey[1]);
            Map routing = rs.getValues();
            Map values = (Map)empiricalRouting.get(keys[i]);
            Object[] names = values.keySet().toArray();
            // Creates correct hashmap with station key --> probability mapping
            for (int j=0; j<names.length; j++)
                routing.put(stations.get(names[j]), values.get(names[j]));
        }
    }


    /**
     * Parses given Gui XML Document to reconstruct simulation model.
     * @param xml Document to be parsed
     * @param model data model to be elaborated
     */
    public static void parseXML(Document xml, CommonModel model) {
        parseXML(xml.getDocumentElement(), model);
    }

// --- Helper methods ----------------------------------------------------------------------------
    /**
     * Helper method that searches for first text node, between all children of current node
     * and returns its value. (This is needed to garbage out all comments)
     * @param elem root node to begin search
     * @return parsed text if found, otherwise null
     */
    protected static String findText(Node elem) {
        NodeList tmp = elem.getChildNodes();
        for (int j=0; j<tmp.getLength(); j++)
            if (tmp.item(j).getNodeType() == Node.TEXT_NODE)
                return tmp.item(j).getNodeValue();
        return null;
    }
// -----------------------------------------------------------------------------------------------


// --- Class section -----------------------------------------------------------------------------
    /**
     * Parses userclasses information. Note that distributions for open class will be set lately
     * and reference station information is stored into refStations data structure as will
     * be used later
     * @param root root element of XML Document
     * @param model data structure where all properties have to be set
     */
    protected static void parseClasses(Element root, CommonModel model) {
        // Initialize classes and refStations data structure
        classes = new TreeMap();
        refStations = new HashMap();
        NodeList nodeclasses = root.getElementsByTagName(XML_E_CLASS);
        // Now scans all elements
        Element currclass;
        int type, priority;
        Integer customers;
        String name;
        Distribution defaultDistr = (Distribution)Defaults.getAsNewInstance("classDistribution");
        Object key;
        for (int i=0; i<nodeclasses.getLength(); i++) {
            currclass = (Element) nodeclasses.item(i);
            name = currclass.getAttribute(XML_A_CLASS_NAME);
            type = currclass.getAttribute(XML_A_CLASS_TYPE).equals("closed")?CLASS_TYPE_CLOSED:CLASS_TYPE_OPEN;
            customers = new Integer(0);
            priority = 0;

⌨️ 快捷键说明

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