/**
   * Opens a file chooser for importing method settings.
   *
   * @param evt
   */
  private void browseConfigButtonActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_browseConfigButtonActionPerformed

    if (txtConfigurationFileLocation.getText().length() > 0) {
      newDialog
          .getReporterGui()
          .getLastSelectedFolder()
          .setLastSelectedFolder(txtConfigurationFileLocation.getText());
    }

    File selectedFile =
        Util.getUserSelectedFile(
            this,
            ".xml",
            "Reporter Method File (*.xml)",
            "Select Settings File",
            newDialog.getReporterGui().getLastSelectedFolder().getLastSelectedFolder(),
            null,
            true);

    if (selectedFile != null) {
      try {
        methodsFactory.importMethods(selectedFile);
        newDialog.setSelectedMethod(newDialog.getMethod(newDialog.getSelectedMethod().getName()));
        newDialog.setReagents(newDialog.getSelectedMethod().getReagentsSortedByMass());
        refresh();
        txtConfigurationFileLocation.setText(selectedFile.getAbsolutePath());
        newDialog.setMethodsFile(selectedFile);
        newDialog
            .getReporterGui()
            .getLastSelectedFolder()
            .setLastSelectedFolder(selectedFile.getPath());
      } catch (IOException e) {
        JOptionPane.showMessageDialog(
            null,
            "File " + selectedFile.getAbsolutePath() + " not found.",
            "File Not Found",
            JOptionPane.WARNING_MESSAGE);
      } catch (XmlPullParserException e) {
        JOptionPane.showMessageDialog(
            null,
            "An error occurred while parsing "
                + selectedFile.getAbsolutePath()
                + " at line "
                + e.getLineNumber()
                + ".",
            "Parsing Error",
            JOptionPane.WARNING_MESSAGE);
        e.printStackTrace();
      }
    }
  } // GEN-LAST:event_browseConfigButtonActionPerformed
  /**
   * Save the method settings.
   *
   * @param evt
   */
  private void saveConfigButtonActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_saveConfigButtonActionPerformed

    String tempFileName = null;
    if (txtConfigurationFileLocation.getText().length() > 0) {
      newDialog
          .getReporterGui()
          .getLastSelectedFolder()
          .setLastSelectedFolder(txtConfigurationFileLocation.getText());
      tempFileName = new File(txtConfigurationFileLocation.getText()).getName();
    }

    File selectedFile =
        Util.getUserSelectedFile(
            this,
            ".xml",
            "Reporter Method File (*.xml)",
            "Save Settings File",
            newDialog.getReporterGui().getLastSelectedFolder().getLastSelectedFolder(),
            tempFileName,
            false);

    if (selectedFile != null) {
      try {
        methodsFactory.saveFile(selectedFile);
        newDialog.setMethodsFile(selectedFile);
        txtConfigurationFileLocation.setText(selectedFile.getAbsolutePath());
        valuesChanged = false;
        JOptionPane.showMessageDialog(
            null,
            "Settings saved to " + selectedFile.getAbsolutePath() + ".",
            "Settings Saved",
            JOptionPane.INFORMATION_MESSAGE);
      } catch (IOException ex) {
        JOptionPane.showMessageDialog(
            null,
            "An error occured when saving the file.",
            "File Error",
            JOptionPane.WARNING_MESSAGE);
        ex.printStackTrace();
      }
    }
  } // GEN-LAST:event_saveConfigButtonActionPerformed
  /** Clears the database folder. */
  private void clearDatabaseFolder() {

    boolean databaseClosed = true;

    // close the database connection
    if (identification != null) {

      try {
        identification.close();
        identification = null;
      } catch (SQLException e) {
        databaseClosed = false;
        e.printStackTrace();
        JOptionPane.showMessageDialog(
            null, "Failed to close the database.", "Database Error", JOptionPane.WARNING_MESSAGE);
      }
    }

    // empty the matches folder
    if (databaseClosed) {
      File matchFolder = new File(resource, PeptideShaker.SERIALIZATION_DIRECTORY);

      if (matchFolder.exists()) {

        File[] tempFiles = matchFolder.listFiles();

        if (tempFiles != null) {
          for (File currentFile : tempFiles) {
            Util.deleteDir(currentFile);
          }
        }

        if (matchFolder.listFiles() != null && matchFolder.listFiles().length > 0) {
          JOptionPane.showMessageDialog(
              null,
              "Failed to empty the database folder:\n" + matchFolder.getPath() + ".",
              "Database Cleanup Failed",
              JOptionPane.WARNING_MESSAGE);
        }
      }
    }
  }
  /**
   * Create the parameters file.
   *
   * @param searchParametersFile the file where to save the search parameters
   * @return the parameters file
   * @throws IOException exception thrown whenever an error occurred while writing the configuration
   *     file
   */
  private File createParametersFile(File searchParametersFile) throws IOException {

    File andromedaTempFolder = new File(andromedaTempFolderPath);

    String fileName;
    try {
      fileName = Util.removeExtension(searchParametersFile.getName()) + ".apar";
    } catch (Exception e) {
      fileName = "SearchGUI.apar";
    }

    File parameterFile = new File(andromedaTempFolder, fileName);
    BufferedWriter bw = new BufferedWriter(new FileWriter(parameterFile));

    try {
      boolean semiSpecific = false;
      DigestionPreferences digestionPreferences = searchParameters.getDigestionPreferences();

      if (digestionPreferences.getCleavagePreference()
          == DigestionPreferences.CleavagePreference.enzyme) {
        Enzyme enzyme = digestionPreferences.getEnzymes().get(0);
        String enzymeName = enzyme.getName();
        bw.write("enzymes=" + enzymeName); // @TODO: support multiple enzymes?
        bw.newLine();
        if (digestionPreferences.getSpecificity(enzyme.getName())
                == DigestionPreferences.Specificity.semiSpecific
            || digestionPreferences.getSpecificity(enzyme.getName())
                == DigestionPreferences.Specificity.specificCTermOnly
            || digestionPreferences.getSpecificity(enzyme.getName())
                == DigestionPreferences.Specificity.specificNTermOnly) {
          semiSpecific = true;
        }
      } else if (digestionPreferences.getCleavagePreference()
          == DigestionPreferences.CleavagePreference.unSpecific) {
        bw.write("enzyme mode=unspecific");
        bw.newLine();
      } else {
        // whole enzyme
        // @TODO: what to put here..?
      }

      if (semiSpecific) {
        bw.write("enzyme mode=semispecific"); // @TODO: support: Semispecific Free N-terminus and
        // Semispecific Free C-terminus
      } else {
        bw.write("enzyme mode=specific");
      }
      bw.newLine();
      PtmSettings modificationProfile = searchParameters.getPtmSettings();
      StringBuilder list = new StringBuilder();
      for (String ptmName : modificationProfile.getVariableModifications()) {
        if (list.length() > 0) {
          list.append(",");
        }
        list.append(ptmName);
      }
      bw.write("variable modifications=" + list);
      bw.newLine();
      list = new StringBuilder();
      for (String ptmName : modificationProfile.getFixedModifications()) {
        if (list.length() > 0) {
          list.append(",");
        }
        list.append(ptmName);
      }
      bw.write("fixed modifications=" + list);
      bw.newLine();
      bw.write("label modifications="); // @TODO: support labels
      bw.newLine();
      if (!modificationProfile.getRefinementVariableModifications().isEmpty()) {
        bw.write("has additional variable modifications=True");
        bw.newLine();
        list = new StringBuilder();
        for (String ptmName : modificationProfile.getRefinementVariableModifications()) {
          if (list.length() > 0) {
            list.append(",");
          }
          list.append(ptmName);
        }
        bw.write("additional variable modifications=" + list);
        bw.newLine();
        bw.write("additional variable modification proteins=");
        bw.newLine();
      } else {
        bw.write("has additional variable modifications=False");
        bw.newLine();
        bw.write("additional variable modifications=");
        bw.newLine();
        bw.write("additional variable modification proteins=");
        bw.newLine();
      }
      bw.write("peptide mass tolerance=" + searchParameters.getPrecursorAccuracy());
      bw.newLine();
      bw.write("max peptide mass=" + andromedaParameters.getMaxPeptideMass());
      bw.newLine();
      bw.write("max combinations=" + andromedaParameters.getMaxCombinations());
      bw.newLine();
      if (searchParameters.isPrecursorAccuracyTypePpm()) {
        bw.write("peptide mass tolerance Unit=ppm");
      } else {
        bw.write("peptide mass tolerance Unit=Da");
      }
      bw.newLine();
      bw.write("fragment mass tolerance=" + searchParameters.getFragmentIonAccuracy());
      bw.newLine();
      if (searchParameters.getFragmentAccuracyType() == SearchParameters.MassAccuracyType.PPM) {
        bw.write("fragment mass tolerance Unit=ppm");
      } else {
        bw.write("fragment mass tolerance Unit=Da");
      }
      bw.newLine();
      bw.write("top peaks=" + andromedaParameters.getTopPeaks());
      bw.newLine();
      bw.write("top peaks window=" + andromedaParameters.getTopPeaksWindow());
      bw.newLine();

      if (digestionPreferences.getCleavagePreference()
          == DigestionPreferences.CleavagePreference.enzyme) {
        Integer missedCleavages = null;
        for (Enzyme enzyme : digestionPreferences.getEnzymes()) {
          int enzymeMissedCleavages = digestionPreferences.getnMissedCleavages(enzyme.getName());
          if (missedCleavages == null || enzymeMissedCleavages > missedCleavages) {
            missedCleavages = enzymeMissedCleavages;
          }
        }
        bw.write("max missed cleavages=" + missedCleavages);
        bw.newLine();
      }

      bw.write("fasta file=\"" + searchParameters.getFastaFile().getAbsolutePath() + "\"");
      bw.newLine();
      bw.write("decoy mode=" + andromedaParameters.getDecoyMode());
      bw.newLine();
      bw.write("include contaminants=False");
      bw.newLine();
      if (andromedaParameters.isIncludeWater()) {
        bw.write("include water=True");
      } else {
        bw.write("include water=False");
      }
      bw.newLine();
      if (andromedaParameters.isIncludeAmmonia()) {
        bw.write("include ammonia=True");
      } else {
        bw.write("include ammonia=False");
      }
      bw.newLine();
      if (andromedaParameters.isDependentLosses()) {
        bw.write("dependent losses=True");
      } else {
        bw.write("dependent losses=False");
      }
      bw.newLine();
      bw.write("special aas=");
      bw.newLine();
      if (andromedaParameters.isFragmentAll()) {
        bw.write("fragment all=True");
      } else {
        bw.write("fragment all=False");
      }
      bw.newLine();
      if (andromedaParameters.isEmpiricalCorrection()) {
        bw.write("empirical correction=True");
      } else {
        bw.write("empirical correction=False");
      }
      bw.newLine();
      if (andromedaParameters.isHigherCharge()) {
        bw.write("higher charges=True");
      } else {
        bw.write("higher charges=False");
      }
      bw.newLine();
      bw.write("fragmentation type=" + andromedaParameters.getFragmentationMethod().name);
      bw.newLine();
      bw.write("max number of modifications=" + andromedaParameters.getMaxNumberOfModifications());
      bw.newLine();
      bw.write("min peptide length no enzyme=" + andromedaParameters.getMinPeptideLengthNoEnzyme());
      bw.newLine();
      bw.write("max peptide length no enzyme=" + andromedaParameters.getMaxPeptideLengthNoEnzyme());
      bw.newLine();
      if (andromedaParameters.isEqualIL()) {
        bw.write("equal il=True");
      } else {
        bw.write("equal il=False");
      }
      bw.newLine();
      bw.write("number of candidates=" + andromedaParameters.getNumberOfCandidates());
      bw.newLine();

    } finally {
      bw.close();
    }
    return parameterFile;
  }
  /**
   * Creates new form ProteinInferenceDialog.
   *
   * @param peptideShakerGUI
   * @param inspectedMatch
   * @param identification
   */
  public ProteinInferenceDialog(
      PeptideShakerGUI peptideShakerGUI, String inspectedMatch, Identification identification) {
    super(peptideShakerGUI, true);
    this.identification = identification;
    this.peptideShakerGUI = peptideShakerGUI;

    try {
      this.inspectedMatch = identification.getProteinMatch(inspectedMatch);
      previousMainMatch = this.inspectedMatch.getMainMatch();
    } catch (Exception e) {
      peptideShakerGUI.catchException(e);
      this.dispose();
    }

    accessions = new ArrayList(Arrays.asList(ProteinMatch.getAccessions(inspectedMatch)));

    for (String proteinAccession : accessions) {
      if (identification.getProteinIdentification().contains(proteinAccession)) {
        uniqueMatches.add(proteinAccession);
      }
    }

    for (String proteinKey : identification.getProteinIdentification()) {
      if (ProteinMatch.getNProteins(proteinKey) > 1
          && !associatedMatches.contains(proteinKey)
          && !proteinKey.equals(inspectedMatch)) {
        for (String proteinAccession : accessions) {
          if (proteinKey.contains(proteinAccession)) {
            associatedMatches.add(proteinKey);
            break;
          }
        }
      }
    }

    initComponents();

    // make sure that the scroll panes are see-through
    proteinMatchJScrollPane.getViewport().setOpaque(false);
    uniqueHitsJScrollPane.getViewport().setOpaque(false);
    relatedHitsJScrollPane.getViewport().setOpaque(false);

    groupClassJComboBox.setRenderer(new AlignedListCellRenderer(SwingConstants.CENTER));

    PSParameter psParameter = new PSParameter();
    try {
      psParameter =
          (PSParameter) identification.getProteinMatchParameter(inspectedMatch, psParameter);
    } catch (Exception e) {
      peptideShakerGUI.catchException(e);
    }
    matchInfoLbl.setText(
        "[Score: "
            + Util.roundDouble(psParameter.getProteinScore(), 2)
            + ", Confidence: "
            + Util.roundDouble(psParameter.getProteinConfidence(), 2)
            + "]");

    // set up the table column properties
    setColumnProperies();

    // The index should be set in the design according to the PSParameter class static fields!
    groupClassJComboBox.setSelectedIndex(psParameter.getGroupClass());

    setLocationRelativeTo(peptideShakerGUI);
    setVisible(true);
  }
 /**
  * Returns the default reference for an identification.
  *
  * @param experimentReference the experiment reference
  * @param sampleReference the sample reference
  * @param replicateNumber the replicate number
  * @return the default reference
  */
 public static String getDefaultReference(
     String experimentReference, String sampleReference, int replicateNumber) {
   return Util.removeForbiddenCharacters(
       experimentReference + "_" + sampleReference + "_" + replicateNumber + "_reporterQuant");
 }
  public void testDB()
      throws SQLException, IOException, ClassNotFoundException, SQLException,
          ClassNotFoundException, InterruptedException {

    String path = this.getClass().getResource("IdentificationDBTest.class").getPath();
    path = path.substring(1, path.indexOf("/target/"));
    path += "/src/test/resources/experiment/testDB";
    try {
      ObjectsCache cache = new ObjectsCache();
      cache.setAutomatedMemoryManagement(false);
      cache.setCacheSize(0);
      IdentificationDB idDB = new IdentificationDB(path, "testId", true, cache);
      try {

        String spectrumKey = "spectrum_file_cus_spectrum_title";
        String peptideKey = "PEPTIDE";
        String proteinKey = "test_protein";
        SpectrumMatch testSpectrumMatch = new SpectrumMatch(spectrumKey);
        ArrayList<String> testProteins = new ArrayList<String>();
        testProteins.add("test protein1");
        testProteins.add("test protein2");
        Peptide peptide = new Peptide(peptideKey, new ArrayList<ModificationMatch>());
        peptide.setParentProteins(testProteins);
        testSpectrumMatch.addHit(
            Advocate.mascot.getIndex(),
            new PeptideAssumption(
                peptide, 1, Advocate.mascot.getIndex(), new Charge(Charge.PLUS, 2), 0.1, "no file"),
            false);
        idDB.addSpectrumMatch(testSpectrumMatch);

        peptide = new Peptide(peptideKey, new ArrayList<ModificationMatch>());
        peptide.setParentProteins(testProteins);
        PeptideMatch testPeptideMatch = new PeptideMatch(peptide, peptide.getKey());
        idDB.addPeptideMatch(testPeptideMatch);

        ProteinMatch testProteinMatch = new ProteinMatch(proteinKey);
        idDB.addProteinMatch(testProteinMatch);

        testSpectrumMatch = idDB.getSpectrumMatch(spectrumKey, true);
        Assert.assertTrue(testSpectrumMatch.getKey().equals(spectrumKey));

        HashMap<Integer, HashMap<Double, ArrayList<SpectrumIdentificationAssumption>>>
            assumptionsMap = testSpectrumMatch.getAssumptionsMap();
        HashMap<Double, ArrayList<SpectrumIdentificationAssumption>> mascotAssumptions =
            assumptionsMap.get(Advocate.mascot.getIndex());
        Assert.assertTrue(mascotAssumptions.size() == 1);
        ArrayList<Double> mascotScores = new ArrayList<Double>(mascotAssumptions.keySet());
        Assert.assertTrue(mascotScores.size() == 1);
        double bestScore = mascotScores.get(0);
        Assert.assertTrue(bestScore == 0.1);
        ArrayList<SpectrumIdentificationAssumption> bestAssumptions =
            mascotAssumptions.get(bestScore);
        PeptideAssumption bestAssumption = (PeptideAssumption) bestAssumptions.get(0);
        Peptide bestPeptide = bestAssumption.getPeptide();
        Assert.assertTrue(bestPeptide.getParentProteinsNoRemapping().size() == 2);
        Assert.assertTrue(
            bestPeptide.getParentProteinsNoRemapping().get(0).equals(testProteins.get(0)));
        Assert.assertTrue(
            bestPeptide.getParentProteinsNoRemapping().get(1).equals(testProteins.get(1)));
        ArrayList<String> proteins = new ArrayList<String>();
        proteins.add(proteinKey);
        bestPeptide.setParentProteins(proteins);
        idDB.updateMatch(testSpectrumMatch);

        testSpectrumMatch = idDB.getSpectrumMatch(spectrumKey, true);
        assumptionsMap = testSpectrumMatch.getAssumptionsMap();
        mascotAssumptions = assumptionsMap.get(Advocate.mascot.getIndex());
        Assert.assertTrue(mascotAssumptions.size() == 1);
        mascotScores = new ArrayList<Double>(mascotAssumptions.keySet());
        Assert.assertTrue(mascotScores.size() == 1);
        bestScore = mascotScores.get(0);
        Assert.assertTrue(bestScore == 0.1);
        bestAssumptions = mascotAssumptions.get(bestScore);
        bestAssumption = (PeptideAssumption) bestAssumptions.get(0);
        bestPeptide = bestAssumption.getPeptide();
        Assert.assertTrue(bestPeptide.getParentProteinsNoRemapping().size() == 1);
        Assert.assertTrue(bestPeptide.getParentProteinsNoRemapping().get(0).equals(proteinKey));

        testPeptideMatch = idDB.getPeptideMatch(peptideKey, true);
        Assert.assertTrue(testPeptideMatch.getKey().equals(peptideKey));

        testProteinMatch = idDB.getProteinMatch(proteinKey, true);
        Assert.assertTrue(testProteinMatch.getKey().equals(proteinKey));

        double testScore = 12.3;
        PepnovoAssumptionDetails testParameter = new PepnovoAssumptionDetails();
        testParameter.setRankScore(testScore);
        idDB.addSpectrumMatchParameter(spectrumKey, testParameter);
        testParameter =
            (PepnovoAssumptionDetails)
                idDB.getSpectrumMatchParameter(spectrumKey, testParameter, true);
        Assert.assertTrue(testParameter.getRankScore() == testScore);

      } finally {
        idDB.close();
      }
    } finally {
      File dbFolder = new File(path);
      DerbyUtil.closeConnection();
      Util.deleteDir(dbFolder);
    }
  }