/**
  * Show an error message
  *
  * @param message
  */
 public static void showErrorMessage(String title, String message) {
   // Need a parent window to display error message
   Component parent = null;
   BundleContext context = PlugInScopeObjectManager.getManager().getBundleContext();
   ServiceReference serviceReference =
       context.getServiceReference(CySwingApplication.class.getName());
   if (serviceReference != null) {
     CySwingApplication cytoscape = (CySwingApplication) context.getService(serviceReference);
     if (cytoscape != null) {
       parent = cytoscape.getJFrame();
     }
   }
   JOptionPane.showMessageDialog(parent, message, title, JOptionPane.ERROR_MESSAGE);
   if (serviceReference != null) { // Unget the service and null serviceReference
     context.ungetService(serviceReference);
     serviceReference = null;
   }
 }
 /**
  * Open an OS web browser to display the passed URL.
  *
  * @param url
  */
 public static void openURL(String url) {
   BundleContext context = PlugInScopeObjectManager.getManager().getBundleContext();
   ServiceReference serviceReference = context.getServiceReference(OpenBrowser.class.getName());
   boolean isOpened = false;
   if (serviceReference != null) {
     OpenBrowser browser = (OpenBrowser) context.getService(serviceReference);
     if (browser != null) {
       browser.openURL(url);
       isOpened = true;
     }
     context.ungetService(serviceReference);
   }
   // In case the passed URL cannot be opened!
   if (!isOpened) {
     showErrorMessage(
         "Error in Opening URL",
         "Error in opening URL: cannot find a configured browser in Cytoscape!");
   }
 }
  private CyNetwork constructFINetwork(Set<String> selectedGenes, String title) throws Exception {
    // Check if a local service should be used
    FINetworkService fiService = PlugInScopeObjectManager.getManager().getNetworkService();
    Set<String> fis = fiService.buildFINetwork(selectedGenes, useLinkers);
    CyNetwork network = null;
    if (fis != null && fis.size() > 0) {

      CyNetworkGenerator generator = new CyNetworkGenerator(networkFactory, tableFactory);
      // Check if any unlinked nodes should be added
      if (showUnlinkedEnabled && showUnlinked) {
        network = generator.constructFINetwork(selectedGenes, fis);
      } else {
        network = generator.constructFINetwork(fis);
      }
    }
    // netManager.addNetwork(network);
    // CyTableManager manager = new CyTableManager();
    // manager.storeDataSetType(network, "Data Set");
    return network;
  }
  @Override
  public void run(TaskMonitor taskMonitor) throws Exception {
    desktopApp.getJFrame().getGlassPane().setVisible(true);
    taskMonitor.setTitle("Gene Set / Mutation Analysis");
    taskMonitor.setStatusMessage("Loading file...");
    taskMonitor.setProgress(.25d);
    try {
      Map<String, Integer> geneToSampleNumber = null;
      Map<String, String> geneToSampleString = null;
      Map<String, Set<String>> sampleToGenes = null;
      Set<String> selectedGenes = null;

      if (format.equals("MAF")) {

        sampleToGenes =
            new MATFileLoader().loadSampleToGenes(file.getAbsolutePath(), chooseHomoGenes);
        selectedGenes =
            CancerAnalysisUtilitites.selectGenesInSamples(sampleCutoffValue, sampleToGenes);
      } else if (format.equals("GeneSample")) {
        geneToSampleNumber = new HashMap<String, Integer>();
        geneToSampleString = new HashMap<String, String>();
        loadGeneSampleFile(file, geneToSampleNumber, geneToSampleString);
        selectedGenes = selectGenesBasedOnSampleCutoff(geneToSampleNumber, sampleCutoffValue);
      } else if (format.equals("GeneSet")) {
        selectedGenes = loadGeneSetFile(file);
      }
      // Check if it is possible to construct the network
      // given the sample size.
      if (useLinkers) {
        taskMonitor.setStatusMessage("Checking FI Network size...");
        FINetworkService fiService = PlugInScopeObjectManager.getManager().getNetworkService();
        Integer cutoff = fiService.getNetworkBuildSizeCutoff();
        if (cutoff != null && selectedGenes.size() >= cutoff) {
          JOptionPane.showMessageDialog(
              desktopApp.getJFrame(),
              "The size of the gene set is too big. Linker genes should not be used!\n"
                  + "Please try again without using linker genes.",
              "Error in Building Network",
              JOptionPane.ERROR_MESSAGE);
          desktopApp.getJFrame().getGlassPane().setVisible(false);
          return;
        }
      }

      CytoPanel controlPane = desktopApp.getCytoPanel(CytoPanelName.WEST);
      int selectedIndex = controlPane.getSelectedIndex();
      taskMonitor.setStatusMessage("Constructing FI Network...");
      taskMonitor.setProgress(.50d);
      CyNetwork network = constructFINetwork(selectedGenes, file.getName());
      network.getDefaultNetworkTable().getRow(network.getSUID()).set("name", file.getName());
      if (network == null) {
        JOptionPane.showMessageDialog(
            desktopApp.getJFrame(),
            "Cannot find any functional interaction among provided genes.\n"
                + "No network can be constructed.\n"
                + "Note: only human gene names are supported.",
            "Empty Network",
            JOptionPane.INFORMATION_MESSAGE);
        desktopApp.getJFrame().getGlassPane().setVisible(false);
        return;
      }
      netManager.addNetwork(network);

      // Fix for missing default value persistence in CyTables
      // Should be remedied in the 3.1 api
      CyTable nodeTable = network.getDefaultNodeTable();
      for (Object name : network.getNodeList()) {
        CyNode node = (CyNode) name;
        Long nodeSUID = node.getSUID();
        nodeTable.getRow(nodeSUID).set("isLinker", false);
      }

      controlPane.setSelectedIndex(selectedIndex);
      if (sampleToGenes != null) {
        geneToSampleNumber = new HashMap<String, Integer>();
        geneToSampleString = new HashMap<String, String>();
        Map<String, Set<String>> geneToSamples =
            InteractionUtilities.switchKeyValues(sampleToGenes);
        geneToSamples.keySet().retainAll(selectedGenes);
        for (String gene : geneToSamples.keySet()) {
          Set<String> samples = geneToSamples.get(gene);
          geneToSampleNumber.put(gene, samples.size());
          geneToSampleString.put(gene, InteractionUtilities.joinStringElements(";", samples));
        }
      }
      taskMonitor.setStatusMessage("Formatting network attributes...");
      taskMonitor.setProgress(.65d);
      CyTableManager tableManager = new CyTableManager();
      CyNetworkView view = viewFactory.createNetworkView(network);
      tableManager.storeFINetworkVersion(view);
      tableManager.storeDataSetType(network, CyTableFormatter.getSampleMutationData());
      viewManager.addNetworkView(view);
      if (geneToSampleNumber != null && !geneToSampleNumber.isEmpty()) {
        tableManager.loadNodeAttributesByName(view, "sampleNumber", geneToSampleNumber);
      }
      if (geneToSampleString != null && !geneToSampleString.isEmpty()) {
        tableManager.loadNodeAttributesByName(view, "samples", geneToSampleString);
      }
      // Check if linker genes are to be used.
      if (useLinkers) {
        taskMonitor.setStatusMessage("Fetching linker genes...");
        Map<String, Boolean> geneToIsLinker = new HashMap<String, Boolean>();
        for (Object name : network.getNodeList()) {
          CyNode node = (CyNode) name;
          Long suid = node.getSUID();
          String nodeName = network.getDefaultNodeTable().getRow(suid).get("name", String.class);
          geneToIsLinker.put(nodeName, !selectedGenes.contains(nodeName));
        }
        tableManager.loadNodeAttributesByName(view, "isLinker", geneToIsLinker);
      }
      if (fetchFIAnnotations) {
        taskMonitor.setStatusMessage("Fetching FI annotations...");
        new FIAnnotationHelper().annotateFIs(view, new RESTFulFIService(), tableManager);
      }
      if (view.getModel().getEdgeCount() != 0) {
        for (CyEdge edge : view.getModel().getEdgeList()) {
          tableManager.storeEdgeName(edge, view);
        }
      }
      BundleContext context = PlugInScopeObjectManager.getManager().getBundleContext();
      ServiceReference visHelperRef = context.getServiceReference(FIVisualStyle.class.getName());
      if (visHelperRef != null) {
        FIVisualStyleImpl styleHelper = (FIVisualStyleImpl) context.getService(visHelperRef);
        styleHelper.setVisualStyle(view);
        styleHelper.setLayout();
      }
      //            BundleContext context =
      // PlugInScopeObjectManager.getManager().getBundleContext();
      //            ServiceReference styleHelperRef =
      // context.getServiceReference(FIVisualStyleImpl.class.getName());
      //            FIVisualStyleImpl styleHelper = (FIVisualStyleImpl)
      // context.getService(styleHelperRef);

      taskMonitor.setProgress(1.0d);
    } catch (Exception e) {
      JOptionPane.showMessageDialog(
          desktopApp.getJFrame(),
          "Error in Loading File: " + e.getMessage(),
          "Error in Loading",
          JOptionPane.ERROR_MESSAGE);
      desktopApp.getJFrame().getGlassPane().setVisible(false);
    }
    desktopApp.getJFrame().getGlassPane().setVisible(false);
  }