// This method is necessary to know the evaluation procedure to apply on the ICM model
  public HashMap<Integer, Boolean> getScenarioMapFor(ArchEScenario scenario) {
    HashMap<Integer, Boolean> map = new HashMap<Integer, Boolean>();

    if (scenario == null) { // It means to activate all the scenario modes
      for (Iterator<Scenario> itScenarioModes = icmModel.getScenarios().iterator();
          itScenarioModes.hasNext(); )
        map.put(itScenarioModes.next().getNumber(), new Boolean(true));
      return (map);
    }

    // Otherwise, a specific scenario gets activated
    Scenario scenarioMode = null;
    String archeScenarioName = ((ArchEScenarioVO) scenario).getId();
    for (Iterator<Scenario> itScenarioModes = icmModel.getScenarios().iterator();
        itScenarioModes.hasNext(); ) {
      scenarioMode = itScenarioModes.next();
      if (scenarioMode.getName().equals(archeScenarioName)) // The scenario to be analyzed
      map.put(scenarioMode.getNumber(), new Boolean(true));
      else map.put(scenarioMode.getNumber(), new Boolean(false));
    }
    return (map);
  }
  public String getServicePinNameFor(ArchEScenario scenario) {

    ElementInstance elem = null;
    String nameWithoutSpaces = null;

    for (Iterator<ElementInstance> itComponents = icmModel.getElements().iterator();
        itComponents.hasNext(); ) {
      elem = itComponents.next();

      if (elem instanceof IcmService) {
        nameWithoutSpaces = "Service_" + removeSpaces(((ArchEScenarioVO) scenario).getId());
        nameWithoutSpaces = nameWithoutSpaces + ".psource_service";
        return (nameWithoutSpaces.toLowerCase());
      }
    }
    return (null);
  }
  public void setInputInformation(
      String name,
      List<ArchEScenario> scenarios,
      ArchEResponsibilityStructure responsibilityStructure) {

    List<ArchEResponsibility> responsibilities = responsibilityStructure.getResponsibilities();
    ArchECoreResponsibilityStructure coreStructure =
        ((ArchECoreResponsibilityStructure) responsibilityStructure);
    String reactionTypeVO = ArchEResponsibilityReactionRelationVO.class.getName();
    List<ArchERelation> reactions = coreStructure.getRelations(reactionTypeVO);
    String translationTypeVO = ArchETranslationRelationVO.class.getName();
    List<ArchERelation> translations = coreStructure.getRelations(translationTypeVO);

    icmModel = createICM(name, scenarios, responsibilities, reactions, translations);
    // We assume always the first scenario in the ICM file is the one to analyze
    icmModel.setSourceFile(this.saveICMAssembly(icmModel));
  }
  private String saveICMAssembly(AssemblyInstance assembly) {

    // configure this RF with the configuration file
    try {
      URL url =
          FileLocator.find(Platform.getBundle("SEI.ArchE.Performance"), new Path("/temp"), null);
      String tempPathName = FileLocator.resolve(url).getPath();

      ResourceSet resourceSet = new ResourceSetImpl();

      IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
      IPath path = new Path(tempPathName + assembly.getName() + ".icm");

      IFile xmlFile = workspaceRoot.getFile(path);

      // Get the URI of the model file
      URI fileURI = URI.createFileURI(path.toString());

      // Create a resource for this file.
      Resource resource = resourceSet.createResource(fileURI);

      // Add the assembly to the resource contents
      resource.getContents().add(assembly);

      // Save the contents of the resource to the file system.
      String xmlAssemblyFile = null;
      try {
        resource.save(Collections.EMPTY_MAP);
      } catch (IOException e) {
      }

      xmlAssemblyFile = fileURI.toFileString();

      return (path.toPortableString());

    } catch (MalformedURLException e1) {
      e1.printStackTrace();
    } catch (IOException e1) {
      e1.printStackTrace();
    }

    return null; // for error
  }
 public boolean clearICMAssembly() {
   File icmFile = new Path(icmModel.getSourceFile()).toFile();
   boolean ok = icmFile.delete();
   return (ok);
 }
  private static AssemblyInstance createICM(
      String name,
      List<ArchEScenario> scenarios,
      List<ArchEResponsibility> responsibilities,
      List<ArchERelation> reactions,
      List<ArchERelation> translations) {

    // System.out.println("@@@@@CREATION OF ICM WITH REACTIONS: "+reactions.size());

    IcmFactory factory = IcmFactory.eINSTANCE;
    AssemblyInstance assembly = factory.createAssemblyInstance();
    assembly.setName(name);
    assembly.setConnectionOverhead(DEFAULT_CONNECTION_OVERHEAD);
    resetTaskPriority();

    String nameWithoutSpaces = null;

    // Rule 1: Create an ICM component for each responsibility
    IcmComponent comp = null;
    ArchEResponsibilityVO resp = null;
    Hashtable<String, IcmComponent> allComponents = new Hashtable<String, IcmComponent>();
    for (Iterator<ArchEResponsibility> itResponsibilities = responsibilities.iterator();
        itResponsibilities.hasNext(); ) {
      resp = (ArchEResponsibilityVO) (itResponsibilities.next());
      comp = factory.createIcmComponent();
      nameWithoutSpaces = removeSpaces(resp.getName());
      comp.setName(nameWithoutSpaces);
      allComponents.put(nameWithoutSpaces, comp);
      assembly.getElements().add(comp);
    }

    // Rule 2: For each reaction relationship create corresponding source and sink pins
    // in the components associated to the responsibilities involved in the relationship
    IcmComponent component = null;
    SinkPinInstance pinSinkInstance = null;
    SourcePinInstance pinSourceInstance = null;
    ArchEResponsibilityReactionRelationVO reaction = null;
    List<String> connectedComponents = new ArrayList<String>();
    double avgExecutionTime = 0;
    Distribution uniform = null;
    // For connecting the pins within a component
    for (Iterator<ArchERelation> it1 = reactions.iterator(); it1.hasNext(); ) {
      reaction = (ArchEResponsibilityReactionRelationVO) (it1.next());

      // This creates a sink pin for the child responsibility,
      // assuming that parent --> child maps to source_parent --> sink_child
      pinSinkInstance = factory.createSinkPinInstance();
      pinSinkInstance.setMode(DEFAULT_SINKPIN_MODE);
      pinSinkInstance.setPriority(getTaskPriority());
      nameWithoutSpaces = removeSpaces(reaction.getChild().getName());
      pinSinkInstance.setName("psink_" + nameWithoutSpaces);
      try {
        avgExecutionTime =
            reaction
                .getChild()
                .getDoubleParameter(ICMPerformanceReasoningFramework.PARAMETER_EXECUTION_TIME);
        uniform = getUniformDistribution(factory, 1.0, avgExecutionTime);
        pinSinkInstance.setExecTimeDistribution(uniform);
      } catch (ArchEException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      component = allComponents.get(nameWithoutSpaces);
      pinSinkInstance.setElementInstance(component);
      // This saves the names of those components that have at least one sink pin
      // connected, for later.
      if (!connectedComponents.contains(nameWithoutSpaces))
        connectedComponents.add(nameWithoutSpaces);

      // This creates a source pin for the child responsibility
      pinSourceInstance = factory.createSourcePinInstance();
      pinSourceInstance.setMode(DEFAULT_SOURCEPIN_MODE);

      nameWithoutSpaces = removeSpaces(reaction.getParent().getName());
      pinSourceInstance.setName("psource_" + nameWithoutSpaces);
      component = allComponents.get(nameWithoutSpaces);
      pinSourceInstance.setElementInstance(component);

      // This connects the source for the sink to react to
      pinSourceInstance.getSinks().add(pinSinkInstance);
      pinSinkInstance.getLinkSources().add(pinSourceInstance);
    }

    // Rule 3: Create services for each of the scenarios, and then link them
    // to responsibilities (components) that have no incoming reactions (within the same scenario)
    ServiceSourcePinIcm serviceSourcePin = null;
    IcmService service = null;
    IcmComponent initialComponent = null;
    SinkPinInstance serviceSinkPin = null;
    ArchEScenarioVO scItem = null;
    List<IcmComponent> list = null;
    Scenario scenarioMode = null;
    int index = 1;
    Double interarrival = null;
    Distribution constant = null;

    for (Iterator<ArchEScenario> itScenarios = scenarios.iterator(); itScenarios.hasNext(); ) {
      scItem = (ArchEScenarioVO) (itScenarios.next());

      // Rule 4: Create Icm scenarios (modes) for the assembly
      scenarioMode = factory.createScenario();
      scenarioMode.setNumber(index);
      index++;
      nameWithoutSpaces = scItem.getId();
      scenarioMode.setName(
          nameWithoutSpaces); // Check if the number depends on the services (Gabriel)!!
      assembly.getScenarios().add(scenarioMode);

      //				list = getInitialComponentsFor(scItem,translations,markedComponents,allComponents);
      list = getInitialComponentsFor1(scItem, translations, reactions, allComponents);
      if (list.size() > 0) { // The scenario has at least one responsibility
        interarrival = scItem.getStimulusValue();
        if (interarrival == null) interarrival = DEFAULT_EVENT_INTERARRIVAL_TIME;
        constant = getConstantDistribution(factory, interarrival);

        // Create a service for the scenario
        service = factory.createIcmService();
        service.setPriority(getTaskPriority());
        nameWithoutSpaces = removeSpaces(scItem.getId());
        service.setName("Service_" + nameWithoutSpaces);
        assembly.getElements().add(service);

        // Create a source pin for the service
        serviceSourcePin = factory.createServiceSourcePinIcm();
        // The deadline comes from the response of the scenario
        serviceSourcePin.setDeadline(scItem.getMeasureValue());
        serviceSourcePin.setMode(DEFAULT_SOURCEPIN_MODE);
        avgExecutionTime = ICMPerformanceReasoningFramework.DEFAULT_EXECUTION_TIME;
        serviceSourcePin.setEventDistribution(constant);
        uniform = getUniformDistribution(factory, 1.0, avgExecutionTime);
        serviceSourcePin.setExecTimeDistribution(uniform);
        serviceSourcePin.setName("psource_service");
        serviceSourcePin.setElementInstance(service);

        // Create a sink pin for every component that is "initial" for the scenario
        for (Iterator<IcmComponent> itComponents = list.iterator(); itComponents.hasNext(); ) {
          initialComponent = itComponents.next();

          // This saves the names of those components that have at least one sink pin
          // connected, for later.
          if (!connectedComponents.contains(initialComponent.getName())) ;
          connectedComponents.add(initialComponent.getName());

          serviceSinkPin = factory.createSinkPinInstance();
          serviceSinkPin.setMode(DEFAULT_SINKPIN_MODE);
          serviceSinkPin.setPriority(getTaskPriority());
          // avgExecutionTime = ICMPerformanceReasoningFramework.DEFAULT_EXECUTION_TIME;
          avgExecutionTime = retrieveExecutionTimeFor(initialComponent, responsibilities);
          uniform = getUniformDistribution(factory, 1.0, avgExecutionTime);
          serviceSinkPin.setExecTimeDistribution(uniform);
          serviceSinkPin.setName("psink_" + service.getName());
          serviceSinkPin.setElementInstance(initialComponent);

          // This connects the source for the sink to react to
          serviceSourcePin.getSinks().add(serviceSinkPin);
          serviceSinkPin.getLinkSources().add(serviceSourcePin);
        }

        serviceSourcePin.getScenarios().add(scenarioMode);
      } // End if list.size() > 0
    }

    // Rule 5: Create a default scenario for all the remaining "unconnected" components
    //			if (allComponents.size() > connectedComponents.size()) {
    //				scenarioMode = factory.createScenario();
    //				scenarioMode.setNumber(index);
    //				index++;
    //				nameWithoutSpaces = "background";
    //				scenarioMode.setName(nameWithoutSpaces); // Check if the number depends on the services
    // (Gabriel)!!
    //				assembly.getScenarios().add(scenarioMode);
    //
    //				interarrival = DEFAULT_EVENT_INTERARRIVAL_TIME;
    //				constant = getConstantDistribution(factory,interarrival);
    //
    //				// Create a service for the default scenario
    //				service = factory.createIcmService();
    //				service.setPriority(getTaskPriority());
    //				service.setName("Service_background");
    //				assembly.getElements().add(service);
    //
    //				// Create a source pin for the service
    //				serviceSourcePin = factory.createServiceSourcePinIcm();
    //				// The deadline comes from the response of the scenario
    //				serviceSourcePin.setDeadline(100.0); // Some default long value
    //				serviceSourcePin.setMode(DEFAULT_SOURCEPIN_MODE);
    //				avgExecutionTime = ICMPerformanceReasoningFramework.DEFAULT_EXECUTION_TIME;
    //				serviceSourcePin.setEventDistribution(constant);
    //				uniform = getUniformDistribution(factory,1.0, avgExecutionTime);
    //				serviceSourcePin.setExecTimeDistribution(uniform);
    //				serviceSourcePin.setName("psource_service");
    //				serviceSourcePin.setElementInstance(service);
    //
    //				for(Enumeration<IcmComponent> itComponents = allComponents.elements();
    // itComponents.hasMoreElements();) {
    //					initialComponent = itComponents.nextElement();
    //					// This means the component is isolated
    //					if (!connectedComponents.contains(initialComponent.getName())) {
    //						serviceSinkPin = factory.createSinkPinInstance();
    //						serviceSinkPin.setMode(DEFAULT_SINKPIN_MODE);
    //						serviceSinkPin.setPriority(getTaskPriority());
    //						//avgExecutionTime = ICMPerformanceReasoningFramework.DEFAULT_EXECUTION_TIME;
    //						avgExecutionTime = retrieveExecutionTimeFor(initialComponent, responsibilities);
    //						uniform = getUniformDistribution(factory,1.0, avgExecutionTime);
    //						serviceSinkPin.setExecTimeDistribution(uniform);
    //						serviceSinkPin.setName("psink_" + service.getName());
    //						serviceSinkPin.setElementInstance(initialComponent);
    //
    //						// This connects the source for the sink to react to
    //						serviceSourcePin.getSinks().add(serviceSinkPin);
    //						serviceSinkPin.getLinkSources().add(serviceSourcePin);
    //					}
    //				}
    //
    //			}

    for (Enumeration<IcmComponent> itComponents = allComponents.elements();
        itComponents.hasMoreElements(); ) {
      initialComponent = itComponents.nextElement();
      initialComponent.setName("IcmC_" + initialComponent.getName());
    }

    // This prints the assembly just created, for testing purposes
    //			System.out.println("ASSEMBLY ==> "+assembly.getName());
    //			ElementInstance componenti = null;
    //			PinInstance pini = null;
    //			for (Iterator it3 = assembly.getElements().iterator(); it3.hasNext();) {
    //				componenti = (ElementInstance)(it3.next());
    //				System.out.println("    Component: "+ componenti.getName());
    //				for (Iterator it4 = componenti.getPins().iterator(); it4.hasNext();) {
    //					pini = (PinInstance)(it4.next());
    //					System.out.println("        Pin: "+ pini.getName());
    //				}
    //			}

    return (assembly);
  }