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

📄 simloader.java

📁 一个用于排队系统仿真的开源软件,有非常形象的图象仿真过程!
💻 JAVA
字号:
/**    
  * 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.engine.simEngine;

import jmt.common.exception.LoadException;
import jmt.common.xml.resources.XSDSchemaLoader;
import jmt.engine.NodeSections.InputSection;
import jmt.engine.NodeSections.OutputSection;
import jmt.engine.NodeSections.ServiceSection;
import jmt.engine.QueueNet.JobClass;
import jmt.engine.QueueNet.NodeSection;
import jmt.engine.QueueNet.SimConstants;
import jmt.engine.dataAnalysis.InverseMeasure;
import jmt.engine.dataAnalysis.Measure;
import jmt.engine.dataAnalysis.SimParameters;
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.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Vector;


/**
 * This class contains the methods to load the DOM description of a
 * queueing netwok model from a XML file and then to create a Simulation object
 * from that description.
 *
 * For each node, all parameters and sub-parameters are loaded using the suitable constructors.
 *
 * @author Federico Granata, Stefano Omini, Bertoli Marco
 * @version 26-ago-2003 14.23.27
 *
 */
public class SimLoader {

    //used for debug pourposes
    private static final boolean DEBUG = false;

	//represents the entire XML document. it is the root
    //of the document tree, and provides the primary access to the document's data
    Document document;

    //customer class array
    private JobClass[] jobClasses;
    // simulation object created by this loader
	private Simulation sim;

    //path of the xml file containing the sim model
    private String simModelPath;



    /**
     * Creates a Simulation object, loading all the model definition from the
     * passed xml file
     *
     * @param xmlPath the <em>absolute</em> path of the xml model definition
     */
    public SimLoader(String xmlPath) throws IOException, LoadException {

        //NEW
        //@author Stefano Omini

        simModelPath = xmlPath;
        InputStream is = new BufferedInputStream(new FileInputStream(xmlPath));
        //loads the model and creates a Simulation object
        load(is);

        //end NEW


    }


    private void load(InputStream is) throws LoadException {

        if (is == null)
			throw new LoadException("File not Found");
        InputSource inputSource = new InputSource(is);
		//create a parser
        DOMParser parser = new DOMParser();



		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setValidating(true);
		factory.setNamespaceAware(true);

		try {
            // turn on schema validation ( note need to set both sax and dom validation )
			parser.setFeature("http://xml.org/sax/features/validation", true);
			parser.setFeature("http://apache.org/xml/features/validation/schema", true);
			parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);

            //NEW
            //TODO: setto lo schema xsd con cui fare il parsing
            String externalSchemaLocation = XSDSchemaLoader.loadSchema(XSDSchemaLoader.JSIM_MODEL_DEFINITION);
            parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
                    externalSchemaLocation);
            //end NEW


			try {
                //document parsing
				parser.parse(inputSource);
			} catch (FileNotFoundException e) {
				throw new LoadException("Problems while parsing", e);

			}

            //get the w3c document
			document = parser.getDocument();
			if (DEBUG)
				System.out.println(" created document");
            //gets root
			Element root = document.getDocumentElement();
			if (DEBUG)
				System.out.println("root = " + root.getAttribute("name"));
			//recovers the name of the simulation & creates a getLog with the same
			//name
			if (root.getNodeName() == null)
				throw new LoadException("Problems loading");
            else if (! root.getNodeName().equalsIgnoreCase("sim")) 
                throw new LoadException("Problems loading");
            

            //OLD
            //sim = new Simulation(root.getAttribute("name"), root.getAttribute("debug").equals("true"));

            //NEW
            //@author Stefano Omini

            //default values
            boolean debug = false;
            long seed = -1;
            String simName = "";

            if (root.hasAttribute("name")) {
                simName = root.getAttribute("name");
            }

            //vraiable debug is no longer USED
            if (root.hasAttribute("debug")) {
                debug = (root.getAttribute("debug")).equalsIgnoreCase("true");
            }

            if (root.getAttribute("seed") != "") {
                seed = Long.parseLong(root.getAttribute("seed"));
            }

            if (simName.equalsIgnoreCase("")) {

                //NEW
                //@author Stefano Omini

                //no name specified: uses current time as name
                String datePattern = "yyyyMMdd_HHmmss";
                SimpleDateFormat formatter = new SimpleDateFormat(datePattern);

                Date today = new Date();
                String todayString = formatter.format(today);

                simName = "jSIM_" + todayString;

                //OLD
                //sim = new Simulation(seed, null, debug);
                sim = new Simulation(seed, simName);

                //end NEW

            } else {

                //OLD
                //sim = new Simulation(seed, simName, debug);
                sim = new Simulation(seed, simName);
            }

            sim.setXmlSimModelDefPath(simModelPath);

            //end NEW

            //-------------- SIM PARAMETERS -------------------//

            //TODO: codice per fissare i sim parameters

            // Create a class SimParameter, whose parameters will be shared by all
            // dynamic data analyzer in order to compute confidence intervals.
            // For example, number of batches, batch size, ecc..

            //this constructor will use default values
            SimParameters simParam = new SimParameters();

            //TODO: qui dovrei mettere blocchi tipo if (has attribute("batch")) then set(..) ecc
            //una volta aggiunti nello schema dell'xml, vanno letti e
            //inseriti coi rispettivi metodi set

            // {......}

            //TODO: finita la parte con parsing e set degli attributi, si mette questo metodo
            //(che per il momento si limita a settare i valori di default)

            //sets the reference in sim object
            sim.setSimParameters(simParam);

            //gets the default value of maxsamples
            //(max number of samples for each measure)
            int maxSamples = simParam.getMaxSamples();

            //-------------- end SIM PARAMETERS -------------------//

            // NEW Bertoli Marco -- Read MAX Samples if specified
            if (root.getAttribute("maxSamples") != "") {
                maxSamples = Integer.parseInt(root.getAttribute("maxSamples"));
                simParam.setMaxSamples(maxSamples);
            }
            // END
            
            // NEW Bertoli Marco -- Disables condidence interval as stopping criteria
            if (root.hasAttribute("disableStatisticStop")) {
                simParam.setDisableStatisticStop(root.getAttribute("disableStatisticStop").equalsIgnoreCase(Boolean.TRUE.toString()));
            }
            //END
            

            //Returns a NodeList of all the Elements with a given tag name in the order in which they
            //are encountered in a preorder traversal of the Document tree.
			NodeList nodeList = root.getElementsByTagName("node");
			NodeList classList = root.getElementsByTagName("userClass");
			NodeList measureList = root.getElementsByTagName("measure");
			NodeList connectionList = root.getElementsByTagName("connection");

			//class array creation
			jobClasses = new JobClass[classList.getLength()];
			for (int i = 0; i < classList.getLength(); i++) {
				//OLD
                //jobClasses[i] = new JobClass(((Element) classList.item(i)).getAttribute("name"));

                //NEW
                //@author Stefano Omini

                Element currentJobClass = (Element) classList.item(i);

                //parse class attributes: name, type and priority

                String currentClassName = currentJobClass.getAttribute("name");
                String currentClassType = currentJobClass.getAttribute("type");
                String currentClassPriority = currentJobClass.getAttribute("priority");
                String referenceNode = currentJobClass.getAttribute("referenceSource");

                int type, priority;

                if (currentClassType.equalsIgnoreCase("closed")) {
                    type = JobClass.CLOSED_CLASS;

                    //TODO: al momento non viene letto l'attributo opzionale "customers"
                    //(che comunque non 

⌨️ 快捷键说明

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