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

📄 dispatcher_jmvaschema.java

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

import jmt.common.exception.LoadException;
import jmt.common.exception.NetException;
import jmt.engine.QueueNet.NetSystem;
import jmt.engine.QueueNet.QueueNetwork;
import jmt.engine.dataAnalysis.Measure;
import jmt.engine.dataAnalysis.TempMeasure;
import jmt.engine.log.JSimLogger;
import jmt.engine.simEngine.SimLoader;
import jmt.engine.simEngine.Simulation;
import jmt.gui.common.definitions.CommonModel;
import jmt.gui.common.definitions.ModelConverter;
import jmt.gui.common.xml.XMLWriter;
import jmt.gui.exact.ExactModel;
import jmt.gui.exact.xml.XMLUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Vector;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * <p><b>Name:</b> Dispatcher_jMVAschema</p> 
 * <p><b>Description:</b> Receives the absolute path of a xml file which describes the model using the
 * JMTmodel.xsd schema.
 * This file is converted into another xml file in order to be passed to the
 * simulator. The simulation results, at the end, are converted and
 * are inserted in the original file.
 * </p>
 * <p><b>Date:</b> 13-lug-2006
 * <b>Time:</b> 11.15.47</p>
 * @author Stefano Omini, Bertoli Marco
 * @version 2.0
 */
public class Dispatcher_jMVAschema {
    private static final String SEPARATOR = System.getProperty("file.separator");

    //xml files containing model definition, simmodel definition and sim results
    File modelDefinition;
    File simModelDefinition;
    File simResults;

    //path of the xml files
    String modelDefinitionPath;
    String simModelDefinitionPath;
    String simResultsPath;

    //if true, deletes the intermediate temp files created to solve the model with jSIM.
    //Only the initial passed file (containing the results)
    boolean deleteIntermediateFiles = false;

    //true if the simulation results have been already obtained, false otherwise
    boolean resultsObtained = false;

    //if true, the simulation seed
    private boolean automaticSeed = true;
    //if true, the simulation seed
    private long simulationSeed;

    private static JSimLogger logger = JSimLogger.getLogger(JSimLogger.STD_LOGGER);

    //used to compute the progress of the simulation
    private boolean simStarted = false;
    private boolean simFinished = false;
    private QueueNetwork net;
    
    // Used to tell if transformer input and output must be validated
    private boolean validate = true;


    //used to store temp measures info
    private TempMeasure[] tempMeasures = null;
    
    //Transformation to be applied to throughputs
    private double[][] transform;


    /**
     * This constructor receives the absolute path of the xml file containing
     * the model to be solved.
     * The model must be described using the JMTmodel.xsd schema
     *
     * @param absolutePath absolute path of the xml file containing the
     * model to be solved
     */
    public Dispatcher_jMVAschema(String absolutePath) {
        modelDefinitionPath = absolutePath;
        modelDefinition = new File(absolutePath);
    }


    /**
     * This constructor receives the absolute path of the xml file containing
     * the model to be solved.
     * The model must be described using the JMTmodel.xsd schema
     *
     * @param model the xml file containing the
     * model to be solved
     */
    public Dispatcher_jMVAschema(File model) {
        modelDefinition = model;
        modelDefinitionPath = model.getAbsolutePath();

    }


    /**
     * By invoking this method, simulation will generate a random simulation seed
     */
    public void automaticSimulationSeed() {
        automaticSeed = true;
    }

    /**
     * Specifies the seed to be used in the simulation.
     * @param seed the simulation seed
     */
    public void setSimulationSeed(long seed) {
        simulationSeed = seed;
        automaticSeed = false;
    }


    /**
     * Determine whether the intermediate files must be deleted or not.
     * @param deleteIntermediateFiles if true, intermediate files will be deleted
     */
    public void setDeleteIntermediateFiles(boolean deleteIntermediateFiles) {
        this.deleteIntermediateFiles = deleteIntermediateFiles;
    }


    public boolean solveModel() {

        boolean transfSuccess = false;


        /*********************DEFINITION MODEL*********************/

        if (!modelDefinition.exists()) {
            //the passed file does not exist
            logger.error("The model file " + modelDefinitionPath + " does not exist...");
            return false;
        } else {
            logger.debug("Model definition path: " + modelDefinitionPath);
        }


        /*********************SIM DEFINITION MODEL*********************/

        //first of all transforms the JMTmodel into SIMmodeldefinition
        ModelTransformer md = new ModelTransformer();
        md.setValidate(validate);
        
        //save the file in the same directory of model file, with the same name preceeded by "sim_"

        String modelDefinitionParent = modelDefinition.getParent();

        if (modelDefinitionParent.endsWith(SEPARATOR)) {
            simModelDefinitionPath = modelDefinitionParent + "sim_" +
                modelDefinition.getName();
        } else {
            simModelDefinitionPath = modelDefinitionParent + SEPARATOR + "sim_" +
                modelDefinition.getName();
        }

        transfSuccess = md.MVAtoSIM_parallel(modelDefinitionPath, simModelDefinitionPath);

        if (!transfSuccess) {
            logger.error("MVA to SIM transformation failed for model file " + modelDefinitionPath);
            return false;
        } else {
            logger.debug("jSIM model definiton path: " + simModelDefinitionPath);
        }


        /*********************SIMULATION LOADING AND RUNNING*********************/

        //sim model successfully created
        //now prepare simulation
        try {
            SimLoader simLoader = new SimLoader(simModelDefinitionPath);
            Simulation sim = simLoader.getSim();
                        
            //sets in the Simulation object the path of the original (i.e. MVA)
            //xml model definition
            sim.setXmlModelDefPath(modelDefinitionPath);

            if (!automaticSeed) {
                //if automaticSeed == false, then a user defined seed is present
                sim.setRandomEngineSeed(simulationSeed);
                sim.initialize();

                logger.debug("jSIM correctly initialized with simulation seed = " + simulationSeed);
            } else {
                sim.initialize();
                logger.debug("jSIM correctly initialized");
            }

            //Avoid saturation
            if (sim.getAllRegions() == null) {
            	//if there are no regions...
            	boolean sufficientProcessingCapacity = checkProcessingCapacity();

                if (!sufficientProcessingCapacity) {
                    logger.warn("Current workload causes system saturation. Simulation will not be started.");
                    return false;
                }
            }
            


            simStarted = true;
            net = sim.getNetwork();


            long start, stop;
            double elapsed;

            //Start time
            start = System.currentTimeMillis();

            sim.run();

            //stop time
            stop = System.currentTimeMillis();
            elapsed = ((double) (stop - start) ) / 1000.0;

            simFinished = true;

            logger.info("Model " + modelDefinitionPath + " solved by jSIM in " + Double.toString(elapsed) + " seconds");

        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return false;
        } catch (LoadException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return false;
        }

        simModelDefinition = new File(simModelDefinitionPath);


        /*********************COPYING SIMULATION RESULTS*********************/

        //the results file has been obtained
        //the file has been saved in the same directory of model file, with the same name preceeded by "res_sim_"



        if (modelDefinitionParent.endsWith(SEPARATOR)) {
            simResultsPath = modelDefinition.getParent() + "res_" +
            simModelDefinition.getName();
        } else {
            simResultsPath = modelDefinition.getParent() + SEPARATOR + "res_" +
            simModelDefinition.getName();
        }

        simResults = new File(simResultsPath);

        logger.debug("jSIM results path: " + simResultsPath);


        //transforms the SIMmodeloutput into JMTmodel

        //resets the transformer
        md = new ModelTransformer();
        md.setValidate(validate);
        //create temp file to contain model definition and results
        File temp = null;
        String tempPath = null;

        try {
            temp = File.createTempFile("~jmt_model", ".xml", modelDefinition.getParentFile());
            tempPath = temp.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            logger.error("Error in creating temp file for model " + modelDefinitionPath);

            return false;
        }

        transfSuccess = md.OUTtoMVAScaling(simResultsPath, tempPath);

        if (!transfSuccess) {
            logger.error("OUT to MVA transformation failed model " + modelDefinitionPath);
            return false;
        } else {
            //if successful, rename to model definition file, after deleting the old version
            if (modelDefinition.exists()) {
                modelDefinition.delete();
            }
            //copy the model with results (rename doesn't work!)

            //if (!temp.renameTo(modelDefinition)){
            if (!copyFile(temp, modelDefinition)){
                logger.error("could not copy results into model " + modelDefinitionPath);
            } else {
                resultsObtained = true;
                logger.debug("jSIM results copied into model " + modelDefinitionPath);
            }

            //delete temp file
            if (!temp.delete()){
                temp.deleteOnExit();
                logger.warn("Could not delete a temp file. Deletion will be retried on JVM exit.");
            }

        }


        /*********************DELETE INTERMEDIATE FILES*********************/

        //if true delete intermediate files
        if (deleteIntermediateFiles) {

            //false if one or more files cannot be deleted
            boolean successfulDelete = true;

            if (simModelDefinition.exists()) {
                if (!simModelDefinition.delete()) {
                    successfulDelete = false;
                    //try in another way
                    simModelDefinition.deleteOnExit();
                }
            }
            if (simResults.exists()) {
                if (!simResults.delete()) {
                    successfulDelete = false;
                    //try in another way
                    simResults.deleteOnExit();
                }
            }

            if (successfulDelete) {
                logger.debug("Intermediate files deleted for model " + modelDefinitionPath);
            } else {
                logger.warn("Could not delete some intermediate files. They will be deleted on JVM exit.");

⌨️ 快捷键说明

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