diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/AminoAcidProperties.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/AminoAcidProperties.java index 896e0cb37a..fb52a2d410 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/AminoAcidProperties.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/AminoAcidProperties.java @@ -43,7 +43,7 @@ public class AminoAcidProperties { * @param aa The one-letter amino acid code * @return true if amino acid is charged */ - public static final boolean isCharged(char aa) { + public static boolean isCharged(char aa) { if (negChargedAAs.contains(String.valueOf(aa))) { return true; } @@ -60,7 +60,7 @@ else if (posChargedAAs.contains(String.valueOf(aa))) { * @param aa The one-letter amino acid code * @return the charge of amino acid (1 if positively charged, -1 if negatively charged, 0 if not charged) */ - public static final int getChargeOfAminoAcid(char aa) { + public static int getChargeOfAminoAcid(char aa) { if (negChargedAAs.contains(String.valueOf(aa))) { return -1; } @@ -76,7 +76,7 @@ else if (posChargedAAs.contains(String.valueOf(aa))) { * @param aa The one-letter amino acid code * @return true if amino acid is polar */ - public static final boolean isPolar(char aa) { + public static boolean isPolar(char aa) { if (polarAAs.contains(String.valueOf(aa))) { return true; } @@ -89,7 +89,7 @@ public static final boolean isPolar(char aa) { * @param aa The one-letter amino acid code * @return the polarity of amino acid (1 if polar, 0 if not polar) */ - public static final int getPolarityOfAminoAcid(char aa) { + public static int getPolarityOfAminoAcid(char aa) { if (polarAAs.contains(String.valueOf(aa))) { return 1; } diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/CommandPrompt.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/CommandPrompt.java index db9d1d7b69..53206e13c3 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/CommandPrompt.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/CommandPrompt.java @@ -31,7 +31,6 @@ import java.io.File; import java.io.FileInputStream; -import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -95,8 +94,8 @@ public static void run(String[] args) throws Exception{ /* * Parse input arguments */ - List propertyList = new ArrayList(); - List specificList = new ArrayList(); + List propertyList = new ArrayList<>(); + List specificList = new ArrayList<>(); String inputLocation = null; String outputLocation = null; String aminoAcidCompositionLocation = null; @@ -179,15 +178,15 @@ private static LinkedHashMap readInputFile(String input } LinkedHashMap ret; if ( inputLocation.toLowerCase().contains(".gb")) { - GenbankReader genbankReader = new GenbankReader( - inStream, new GenericGenbankHeaderParser(), + GenbankReader genbankReader = new GenbankReader<>( + inStream, new GenericGenbankHeaderParser<>(), new ProteinSequenceCreator(set)); ret = genbankReader.process(); } else { - FastaReader fastaReader = new FastaReader( - inStream, new GenericFastaHeaderParser(), + FastaReader fastaReader = new FastaReader<>( + inStream, new GenericFastaHeaderParser<>(), new ProteinSequenceCreator(set)); ret = fastaReader.process(); @@ -198,9 +197,9 @@ private static LinkedHashMap readInputFile(String input public enum PropertyName{MolecularWeight, Absorbance_True, Absorbance_False, ExtinctionCoefficient_True, ExtinctionCoefficient_False, InstabilityIndex, ApliphaticIndex, AverageHydropathyValue, IsoelectricPoint, NetCharge_pH_7, A, R, N, D, C, E, Q, G, H, I, L, - K, M, F, P, S, T, W, Y, V}; + K, M, F, P, S, T, W, Y, V} - private static void printHeader(PrintStream output, List propertyList, List specificList, String delimiter) throws IOException{ + private static void printHeader(PrintStream output, List propertyList, List specificList, String delimiter) { int specificCount = 0; /* * 1 Molecular weight @@ -214,7 +213,7 @@ private static void printHeader(PrintStream output, List propertyList * 9 Composition of the 20 standard amino acid * 0 Composition of the specific amino acid */ - List sList = new ArrayList(); + List sList = new ArrayList<>(); sList.add("SequenceName"); for(Character c:propertyList){ switch(c){ @@ -238,7 +237,7 @@ private static void printHeader(PrintStream output, List propertyList sList.add(PropertyName.T.toString()); sList.add(PropertyName.W.toString()); sList.add(PropertyName.Y.toString()); sList.add(PropertyName.V.toString()); break; - case '0': sList.add("" + specificList.get(specificCount++)); break; + case '0': sList.add(String.valueOf(specificList.get(specificCount++))); break; } } for(int i = 0; i < sList.size(); i++){ @@ -272,19 +271,16 @@ private static void compute(PrintStream output, String header, String sequence, }else{ sequence = Utils.checkSequence(sequence); pSequence = new ProteinSequence(sequence); - aaSet = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + aaSet = AminoAcidCompoundSet.aminoAcidCompoundSet; } IPeptideProperties pp = new PeptidePropertiesImpl(); int specificCount = 0; - List dList = new ArrayList(); + List dList = new ArrayList<>(); for(Character c:propertyList){ switch(c){ case '1': - if(aaTable == null) - dList.add(pp.getMolecularWeight(pSequence)); - else - dList.add(pp.getMolecularWeight(pSequence)); + dList.add(pp.getMolecularWeight(pSequence)); break; case '2': dList.add(pp.getAbsorbance(pSequence, true)); @@ -323,7 +319,7 @@ private static void compute(PrintStream output, String header, String sequence, dList.add(aaCompound2Double.get(Constraints.Y)); dList.add(aaCompound2Double.get(Constraints.V)); break; - case '0': dList.add(pp.getEnrichment(pSequence, aaSet.getCompoundForString("" + specificList.get(specificCount++)))); break; + case '0': dList.add(pp.getEnrichment(pSequence, aaSet.getCompoundForString(String.valueOf(specificList.get(specificCount++))))); break; } } output.print(header.replace(delimiter, "_")); diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Constraints.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Constraints.java index f223eaca23..e300da2e7f 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Constraints.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Constraints.java @@ -41,37 +41,37 @@ * @see IPeptideProperties */ public class Constraints { - private static AminoAcidCompoundSet aaSet = new AminoAcidCompoundSet(); + private static final AminoAcidCompoundSet aaSet = new AminoAcidCompoundSet(); //A, R, N, D, C, E, Q, G, H, I, L, K, M, F, P, S, T, W, Y, V - public static AminoAcidCompound A = aaSet.getCompoundForString("A"); - public static AminoAcidCompound R = aaSet.getCompoundForString("R"); - public static AminoAcidCompound N = aaSet.getCompoundForString("N"); - public static AminoAcidCompound D = aaSet.getCompoundForString("D"); - public static AminoAcidCompound C = aaSet.getCompoundForString("C"); - public static AminoAcidCompound E = aaSet.getCompoundForString("E"); - public static AminoAcidCompound Q = aaSet.getCompoundForString("Q"); - public static AminoAcidCompound G = aaSet.getCompoundForString("G"); - public static AminoAcidCompound H = aaSet.getCompoundForString("H"); - public static AminoAcidCompound I = aaSet.getCompoundForString("I"); - public static AminoAcidCompound L = aaSet.getCompoundForString("L"); - public static AminoAcidCompound K = aaSet.getCompoundForString("K"); - public static AminoAcidCompound M = aaSet.getCompoundForString("M"); - public static AminoAcidCompound F = aaSet.getCompoundForString("F"); - public static AminoAcidCompound P = aaSet.getCompoundForString("P"); - public static AminoAcidCompound S = aaSet.getCompoundForString("S"); - public static AminoAcidCompound T = aaSet.getCompoundForString("T"); - public static AminoAcidCompound W = aaSet.getCompoundForString("W"); - public static AminoAcidCompound Y = aaSet.getCompoundForString("Y"); - public static AminoAcidCompound V = aaSet.getCompoundForString("V"); + public static final AminoAcidCompound A = aaSet.getCompoundForString("A"); + public static final AminoAcidCompound R = aaSet.getCompoundForString("R"); + public static final AminoAcidCompound N = aaSet.getCompoundForString("N"); + public static final AminoAcidCompound D = aaSet.getCompoundForString("D"); + public static final AminoAcidCompound C = aaSet.getCompoundForString("C"); + public static final AminoAcidCompound E = aaSet.getCompoundForString("E"); + public static final AminoAcidCompound Q = aaSet.getCompoundForString("Q"); + public static final AminoAcidCompound G = aaSet.getCompoundForString("G"); + public static final AminoAcidCompound H = aaSet.getCompoundForString("H"); + public static final AminoAcidCompound I = aaSet.getCompoundForString("I"); + public static final AminoAcidCompound L = aaSet.getCompoundForString("L"); + public static final AminoAcidCompound K = aaSet.getCompoundForString("K"); + public static final AminoAcidCompound M = aaSet.getCompoundForString("M"); + public static final AminoAcidCompound F = aaSet.getCompoundForString("F"); + public static final AminoAcidCompound P = aaSet.getCompoundForString("P"); + public static final AminoAcidCompound S = aaSet.getCompoundForString("S"); + public static final AminoAcidCompound T = aaSet.getCompoundForString("T"); + public static final AminoAcidCompound W = aaSet.getCompoundForString("W"); + public static final AminoAcidCompound Y = aaSet.getCompoundForString("Y"); + public static final AminoAcidCompound V = aaSet.getCompoundForString("V"); - public static Map aa2ExtinctionCoefficient = new HashMap(); - public static Map aa2MolecularWeight = new HashMap(); - public static Map aa2Hydrophathicity = new HashMap(); - public static Map aa2PKa = new HashMap(); - public static Map diAA2Instability = new HashMap(); + public static final Map aa2ExtinctionCoefficient = new HashMap<>(); + public static final Map aa2MolecularWeight = new HashMap<>(); + public static final Map aa2Hydrophathicity = new HashMap<>(); + public static final Map aa2PKa = new HashMap<>(); + public static final Map diAA2Instability = new HashMap<>(); - public static Map aa2NTerminalPka = new HashMap(); - public static Map aa2CTerminalPka = new HashMap(); + public static final Map aa2NTerminalPka = new HashMap<>(); + public static final Map aa2CTerminalPka = new HashMap<>(); static{ initMolecularWeight(); @@ -287,7 +287,7 @@ private static void initInstability(){ SingleLetterAACode[] aa = SingleLetterAACode.values(); for(int i = 0; i < aa.length; i++){ for(int j = 0; j < aa.length; j++){ - diAA2Instability.put("" + aa[i] + aa[j], instability[i][j]); + diAA2Instability.put(String.valueOf(aa[i]) + aa[j], instability[i][j]); } } } diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/IPeptideProperties.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/IPeptideProperties.java index babe1e54d8..f8eacb7269 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/IPeptideProperties.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/IPeptideProperties.java @@ -61,7 +61,7 @@ public interface IPeptideProperties{ * @return the total molecular weight of sequence + weight of water molecule * @see ProteinSequence */ - public double getMolecularWeight(ProteinSequence sequence); + double getMolecularWeight(ProteinSequence sequence); /** * Returns the molecular weight of sequence. The sequence argument must be a protein sequence consisting of only non-ambiguous characters. @@ -80,7 +80,7 @@ public interface IPeptideProperties{ * @throws FileNotFoundException * thrown if either elementMassFile or aminoAcidCompositionFile are not found */ - public double getMolecularWeight(ProteinSequence sequence, File aminoAcidCompositionFile) throws JAXBException, FileNotFoundException; + double getMolecularWeight(ProteinSequence sequence, File aminoAcidCompositionFile) throws JAXBException, FileNotFoundException; /** * Returns the molecular weight of sequence. The sequence argument must be a protein sequence consisting of only non-ambiguous characters. @@ -99,7 +99,7 @@ public interface IPeptideProperties{ * @throws FileNotFoundException * thrown if either elementMassFile or aminoAcidCompositionFile are not found */ - public double getMolecularWeight(ProteinSequence sequence, File elementMassFile, File aminoAcidCompositionFile) + double getMolecularWeight(ProteinSequence sequence, File elementMassFile, File aminoAcidCompositionFile) throws JAXBException, FileNotFoundException; /** @@ -114,7 +114,7 @@ public double getMolecularWeight(ProteinSequence sequence, File elementMassFile, * a amino acid composition table obtained by calling IPeptideProperties.obtainAminoAcidCompositionTable * @return the total molecular weight of sequence + weight of water molecule */ - public double getMolecularWeightBasedOnXML(ProteinSequence sequence, AminoAcidCompositionTable aminoAcidCompositionTable); + double getMolecularWeightBasedOnXML(ProteinSequence sequence, AminoAcidCompositionTable aminoAcidCompositionTable); /** * This method would initialize amino acid composition table based on the input xml files and stores the table for usage in future calls to @@ -129,7 +129,7 @@ public double getMolecularWeight(ProteinSequence sequence, File elementMassFile, * @throws FileNotFoundException * thrown if either elementMassFile or aminoAcidCompositionFile are not found */ - public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File aminoAcidCompositionFile) + AminoAcidCompositionTable obtainAminoAcidCompositionTable(File aminoAcidCompositionFile) throws JAXBException, FileNotFoundException; /** @@ -146,7 +146,7 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File aminoAcidC * @throws FileNotFoundException * thrown if either elementMassFile or aminoAcidCompositionFile are not found */ - public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMassFile, File aminoAcidCompositionFile) + AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMassFile, File aminoAcidCompositionFile) throws JAXBException, FileNotFoundException; /** @@ -166,7 +166,7 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @return the extinction coefficient of sequence * @see ProteinSequence */ - public double getExtinctionCoefficient(ProteinSequence sequence, boolean assumeCysReduced); + double getExtinctionCoefficient(ProteinSequence sequence, boolean assumeCysReduced); /** * Returns the absorbance (optical density) of sequence. The sequence argument @@ -182,7 +182,7 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @return the absorbance (optical density) of sequence * @see ProteinSequence */ - public double getAbsorbance(ProteinSequence sequence, boolean assumeCysReduced); + double getAbsorbance(ProteinSequence sequence, boolean assumeCysReduced); /** * Returns the instability index of sequence. The sequence argument must be @@ -196,7 +196,7 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @return the instability index of sequence * @see ProteinSequence */ - public double getInstabilityIndex(ProteinSequence sequence); + double getInstabilityIndex(ProteinSequence sequence); /** * Returns the apliphatic index of sequence. The sequence argument must be a @@ -213,7 +213,7 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @return the aliphatic index of sequence * @see ProteinSequence */ - public double getApliphaticIndex(ProteinSequence sequence); + double getApliphaticIndex(ProteinSequence sequence); /** * Returns the average hydropathy value of sequence. The sequence argument @@ -229,7 +229,7 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @return the average hydropathy value of sequence * @see ProteinSequence */ - public double getAvgHydropathy(ProteinSequence sequence); + double getAvgHydropathy(ProteinSequence sequence); /** * Returns the isoelectric point of sequence. The sequence argument must be @@ -250,9 +250,9 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @return the isoelectric point of sequence * @see ProteinSequence */ - public double getIsoelectricPoint(ProteinSequence sequence, boolean useExpasyValues); + double getIsoelectricPoint(ProteinSequence sequence, boolean useExpasyValues); - public double getIsoelectricPoint(ProteinSequence seuqence); + double getIsoelectricPoint(ProteinSequence seuqence); /** * Returns the net charge of sequence at pH 7. The sequence argument must be @@ -274,11 +274,11 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @return the net charge of sequence at given pHPoint * @see ProteinSequence */ - public double getNetCharge(ProteinSequence sequence, boolean useExpasyValues, double pHPoint); + double getNetCharge(ProteinSequence sequence, boolean useExpasyValues, double pHPoint); - public double getNetCharge(ProteinSequence sequence, boolean useExpasyValues); + double getNetCharge(ProteinSequence sequence, boolean useExpasyValues); - public double getNetCharge(ProteinSequence sequence); + double getNetCharge(ProteinSequence sequence); /** * Returns the composition of specified amino acid in the sequence. The @@ -296,7 +296,7 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @see ProteinSequence * @see AminoAcidCompound */ - public double getEnrichment(ProteinSequence sequence, AminoAcidCompound aminoAcidCode); + double getEnrichment(ProteinSequence sequence, AminoAcidCompound aminoAcidCode); /** * Returns the composition of the 20 standard amino acid in the sequence. @@ -311,5 +311,5 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @see ProteinSequence * @see AminoAcidCompound */ - public Map getAAComposition(ProteinSequence sequence); + Map getAAComposition(ProteinSequence sequence); } diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/PeptideProperties.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/PeptideProperties.java index b0918bf559..473022a0a7 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/PeptideProperties.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/PeptideProperties.java @@ -58,13 +58,13 @@ public enum SingleLetterAACode { W, C, M, H, Y, F, Q, N, I, R, D, P, T, K, E, V, /** * Contains the 20 standard AA code in a set */ - public static Set standardAASet; + public static final Set standardAASet; /** * To initialize the standardAASet */ static{ - standardAASet = new HashSet(); + standardAASet = new HashSet<>(); for(SingleLetterAACode c:SingleLetterAACode.values()) standardAASet.add(c.toString().charAt(0)); } @@ -78,7 +78,7 @@ public enum SingleLetterAACode { W, C, M, H, Y, F, Q, N, I, R, D, P, T, K, E, V, * a protein sequence consisting of non-ambiguous characters only * @return the total molecular weight of sequence + weight of water molecule */ - public static final double getMolecularWeight(String sequence){ + public static double getMolecularWeight(String sequence){ sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -109,7 +109,7 @@ public static final double getMolecularWeight(String sequence){ * @throws JAXBException * thrown if unable to properly parse either elementMassFile or aminoAcidCompositionFile */ - public static final double getMolecularWeight(String sequence, File elementMassFile, File aminoAcidCompositionFile) + public static double getMolecularWeight(String sequence, File elementMassFile, File aminoAcidCompositionFile) throws FileNotFoundException, JAXBException{ sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; @@ -140,7 +140,7 @@ public static final double getMolecularWeight(String sequence, File elementMassF * @throws FileNotFoundException * thrown if either elementMassFile or aminoAcidCompositionFile are not found */ - public static final double getMolecularWeight(String sequence, File aminoAcidCompositionFile) throws FileNotFoundException, JAXBException{ + public static double getMolecularWeight(String sequence, File aminoAcidCompositionFile) throws FileNotFoundException, JAXBException{ sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -166,7 +166,7 @@ public static final double getMolecularWeight(String sequence, File aminoAcidCom * @throws FileNotFoundException * thrown if either elementMassFile or aminoAcidCompositionFile are not found */ - public static final AminoAcidCompositionTable obtainAminoAcidCompositionTable(File aminoAcidCompositionFile) + public static AminoAcidCompositionTable obtainAminoAcidCompositionTable(File aminoAcidCompositionFile) throws JAXBException, FileNotFoundException{ IPeptideProperties pp = new PeptidePropertiesImpl(); return pp.obtainAminoAcidCompositionTable(aminoAcidCompositionFile); @@ -186,7 +186,7 @@ public static final AminoAcidCompositionTable obtainAminoAcidCompositionTable(Fi * @throws FileNotFoundException * thrown if either elementMassFile or aminoAcidCompositionFile are not found */ - public static final AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMassFile, File aminoAcidCompositionFile) + public static AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMassFile, File aminoAcidCompositionFile) throws JAXBException, FileNotFoundException{ IPeptideProperties pp = new PeptidePropertiesImpl(); return pp.obtainAminoAcidCompositionTable(elementMassFile, aminoAcidCompositionFile); @@ -230,7 +230,7 @@ public static double getMolecularWeightBasedOnXML(String sequence, AminoAcidComp * true if Cys are assumed to be reduced and false if Cys are assumed to form cystines * @return the absorbance (optical density) of sequence */ - public static final double getAbsorbance(String sequence, boolean assumeCysReduced){ + public static double getAbsorbance(String sequence, boolean assumeCysReduced){ sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -259,7 +259,7 @@ public static final double getAbsorbance(String sequence, boolean assumeCysReduc * assumed to form cystines * @return the extinction coefficient of sequence */ - public static final double getExtinctionCoefficient(String sequence, boolean assumeCysReduced) { + public static double getExtinctionCoefficient(String sequence, boolean assumeCysReduced) { sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -283,7 +283,7 @@ public static final double getExtinctionCoefficient(String sequence, boolean ass * a protein sequence consisting of non-ambiguous characters only * @return the instability index of sequence */ - public static final double getInstabilityIndex(String sequence) { + public static double getInstabilityIndex(String sequence) { sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -310,7 +310,7 @@ public static final double getInstabilityIndex(String sequence) { * a protein sequence consisting of non-ambiguous characters only * @return the aliphatic index of sequence */ - public static final double getApliphaticIndex(String sequence) { + public static double getApliphaticIndex(String sequence) { sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -337,7 +337,7 @@ public static final double getApliphaticIndex(String sequence) { * a protein sequence consisting of non-ambiguous characters only * @return the average hydropathy value of sequence */ - public static final double getAvgHydropathy(String sequence) { + public static double getAvgHydropathy(String sequence) { sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -369,7 +369,7 @@ public static final double getAvgHydropathy(String sequence) { * whether to use Expasy values (Default) or Innovagen values * @return the isoelectric point of sequence */ - public static final double getIsoelectricPoint(String sequence, boolean useExpasyValues) { + public static double getIsoelectricPoint(String sequence, boolean useExpasyValues) { sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -382,7 +382,7 @@ public static final double getIsoelectricPoint(String sequence, boolean useExpas return pp.getIsoelectricPoint(pSequence, useExpasyValues); } - public static final double getIsoelectricPoint(String sequence){ + public static double getIsoelectricPoint(String sequence){ return getIsoelectricPoint(sequence, true); } @@ -405,7 +405,7 @@ public static final double getIsoelectricPoint(String sequence){ * the pH value to use for computation of the net charge. Default at 7. * @return the net charge of sequence at given pHPoint */ - public static final double getNetCharge(String sequence, boolean useExpasyValues, double pHPoint){ + public static double getNetCharge(String sequence, boolean useExpasyValues, double pHPoint){ sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -418,11 +418,11 @@ public static final double getNetCharge(String sequence, boolean useExpasyValues return pp.getNetCharge(pSequence, useExpasyValues, pHPoint); } - public static final double getNetCharge(String sequence, boolean useExpasyValues) { + public static double getNetCharge(String sequence, boolean useExpasyValues) { return getNetCharge(sequence, useExpasyValues, 7.0); } - public static final double getNetCharge(String sequence){ + public static double getNetCharge(String sequence){ return getNetCharge(sequence, true); } @@ -441,7 +441,7 @@ public static final double getNetCharge(String sequence){ * @return the composition of specified amino acid in the sequence * @see SingleLetterAACode */ - public static final double getEnrichment(String sequence, SingleLetterAACode aminoAcidCode) { + public static double getEnrichment(String sequence, SingleLetterAACode aminoAcidCode) { return getEnrichment(sequence, aminoAcidCode.toString()); } @@ -459,7 +459,7 @@ public static final double getEnrichment(String sequence, SingleLetterAACode ami * the code of the amino acid to compute * @return the composition of specified amino acid in the sequence */ - public static final double getEnrichment(String sequence, char aminoAcidCode){ + public static double getEnrichment(String sequence, char aminoAcidCode){ return getEnrichment(sequence, aminoAcidCode); } @@ -477,7 +477,7 @@ public static final double getEnrichment(String sequence, char aminoAcidCode){ * the code of the amino acid to compute * @return the composition of specified amino acid in the sequence */ - public static final double getEnrichment(String sequence, String aminoAcidCode){ + public static double getEnrichment(String sequence, String aminoAcidCode){ sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -503,7 +503,7 @@ public static final double getEnrichment(String sequence, String aminoAcidCode){ * @return the composition of the 20 standard amino acid in the sequence * @see AminoAcidCompound */ - public static final Map getAAComposition(String sequence) { + public static Map getAAComposition(String sequence) { sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -527,11 +527,11 @@ public static final Map getAAComposition(String seque * a protein sequence consisting of non-ambiguous characters only * @return the composition of the 20 standard amino acid in the sequence */ - public static final Map getAACompositionString(String sequence){ + public static Map getAACompositionString(String sequence){ Map aa2Composition = getAAComposition(sequence); - Map aaString2Composition = new HashMap(); - for(AminoAcidCompound aaCompound:aa2Composition.keySet()){ - aaString2Composition.put(aaCompound.getShortName(), aa2Composition.get(aaCompound)); + Map aaString2Composition = new HashMap<>(); + for(Map.Entry entry : aa2Composition.entrySet()){ + aaString2Composition.put(entry.getKey().getShortName(), entry.getValue()); } return aaString2Composition; } @@ -547,11 +547,11 @@ public static final Map getAACompositionString(String sequence){ * a protein sequence consisting of non-ambiguous characters only * @return the composition of the 20 standard amino acid in the sequence */ - public static final Map getAACompositionChar(String sequence){ + public static Map getAACompositionChar(String sequence){ Map aa2Composition = getAAComposition(sequence); - Map aaChar2Composition = new HashMap(); - for(AminoAcidCompound aaCompound:aa2Composition.keySet()){ - aaChar2Composition.put(aaCompound.getShortName().charAt(0), aa2Composition.get(aaCompound)); + Map aaChar2Composition = new HashMap<>(); + for(Map.Entry entry : aa2Composition.entrySet()){ + aaChar2Composition.put(entry.getKey().getShortName().charAt(0), entry.getValue()); } return aaChar2Composition; } @@ -564,7 +564,7 @@ public static final Map getAACompositionChar(String sequence) * a protein sequence consisting of non-ambiguous characters only * @return the array of charges of amino acids in the protein (1 if amino acid is positively charged, -1 if negatively charged, 0 if not charged) */ - public static final int[] getChargesOfAminoAcids(String sequence) { + public static int[] getChargesOfAminoAcids(String sequence) { int[] charges = new int[sequence.length()]; for ( int i=0; i < sequence.length(); i++ ) { char aa = sequence.toCharArray()[i]; @@ -580,7 +580,7 @@ public static final int[] getChargesOfAminoAcids(String sequence) { * a protein sequence consisting of non-ambiguous characters only * @return the array of polarity of amino acids in the protein (1 if amino acid is polar, 0 if not) */ - public static final int[] getPolarityOfAminoAcids(String sequence) { + public static int[] getPolarityOfAminoAcids(String sequence) { int[] polarity = new int[sequence.length()]; for ( int i=0; i < sequence.length(); i++ ) { char aa = sequence.toCharArray()[i]; diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/PeptidePropertiesImpl.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/PeptidePropertiesImpl.java index 98e14c6a83..fd45f81767 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/PeptidePropertiesImpl.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/PeptidePropertiesImpl.java @@ -210,7 +210,7 @@ private Map getExtinctAACount(ProteinSequence sequen } } AminoAcidCompoundSet aaSet = new AminoAcidCompoundSet(); - Map extinctAA2Count = new HashMap(); + Map extinctAA2Count = new HashMap<>(); //Ignore Case is always true extinctAA2Count.put(aaSet.getCompoundForString("W"), numW + smallW); extinctAA2Count.put(aaSet.getCompoundForString("C"), (int) (numC + smallC)); @@ -352,16 +352,16 @@ private double getIsoelectricPointInnovagen(ProteinSequence sequence){ {3.55, 7.50, 10.00},// Y {3.55, 7.50, 0.0}}; // Z - private final double PH_MIN = 0.0; /* minimum pH value */ - private final double PH_MAX = 14.0; /* maximum pH value */ - private final double MAXLOOP = 2000.0; /* maximum number of iterations */ - private final double EPSI = 0.0001; /* desired precision */ + private static final double PH_MIN = 0.0; /* minimum pH value */ + private static final double PH_MAX = 14.0; /* maximum pH value */ + private static final double MAXLOOP = 2000.0; /* maximum number of iterations */ + private static final double EPSI = 0.0001; /* desired precision */ private double exp10(double pka){ return Math.pow(10, pka); } - private double getIsoelectricPointExpasy(String sequence){ + private double getIsoelectricPointExpasy(CharSequence sequence){ // // Compute the amino-acid composition. // @@ -390,7 +390,7 @@ private double getIsoelectricPointExpasy(String sequence){ double phMax = PH_MAX; double phMid = 0.0; - double charge = 1.0; + double charge; for (int i = 0; i < MAXLOOP && (phMax - phMin) > EPSI; i++){ phMid = phMin + (phMax - phMin) / 2.0; @@ -532,7 +532,7 @@ private Map getChargedAACount(ProteinSequence sequen } } AminoAcidCompoundSet aaSet = new AminoAcidCompoundSet(); - Map chargedAA2Count = new HashMap(); + Map chargedAA2Count = new HashMap<>(); chargedAA2Count.put(aaSet.getCompoundForString("K"), numK); chargedAA2Count.put(aaSet.getCompoundForString("R"), numR); chargedAA2Count.put(aaSet.getCompoundForString("H"), numH); @@ -558,7 +558,7 @@ public double getEnrichment(ProteinSequence sequence, AminoAcidCompound aminoAci @Override public Map getAAComposition(ProteinSequence sequence) { int validLength = 0; - Map aa2Composition = new HashMap(); + Map aa2Composition = new HashMap<>(); AminoAcidCompoundSet aaSet = new AminoAcidCompoundSet(); for(AminoAcidCompound aa:aaSet.getAllCompounds()){ aa2Composition.put(aa, 0.0); diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Utils.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Utils.java index e69b083be7..bea1ab69db 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Utils.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Utils.java @@ -48,7 +48,7 @@ public class Utils { * @return * a value with the given number of decimal places. */ - public final static double roundToDecimals(double d, int c) { + public static double roundToDecimals(double d, int c) { if(c < 0) return d; double p = Math.pow(10,c); d = d * p; @@ -67,7 +67,7 @@ public final static double roundToDecimals(double d, int c) { * @return * true if invalid characters are found, else return false. */ - public final static boolean doesSequenceContainInvalidChar(String sequence, Set cSet){ + public static boolean doesSequenceContainInvalidChar(String sequence, Set cSet){ for(char c:sequence.toCharArray()){ if(!cSet.contains(c)) return true; } @@ -86,7 +86,7 @@ public final static boolean doesSequenceContainInvalidChar(String sequence, Set< * @return * the number of invalid characters in sequence. */ - public final static int getNumberOfInvalidChar(String sequence, Set cSet, boolean ignoreCase){ + public static int getNumberOfInvalidChar(String sequence, Set cSet, boolean ignoreCase){ int total = 0; char[] cArray; if(ignoreCase) cArray = sequence.toUpperCase().toCharArray(); @@ -109,8 +109,8 @@ public final static int getNumberOfInvalidChar(String sequence, Set c * @return * a new sequence with all invalid characters being replaced by '-'. */ - public final static String cleanSequence(String sequence, Set cSet){ - Set invalidCharSet = new HashSet(); + public static String cleanSequence(String sequence, Set cSet){ + Set invalidCharSet = new HashSet<>(); StringBuilder cleanSeq = new StringBuilder(); if(cSet == null) cSet = PeptideProperties.standardAASet; for(char c:sequence.toCharArray()){ @@ -125,7 +125,7 @@ public final static String cleanSequence(String sequence, Set cSet){ // TODO: Should be StringJoiner once JDK8 used StringBuilder stringBuilder = new StringBuilder(); for(char c: invalidCharSet){ - stringBuilder.append("\'" + c + "\'"); + stringBuilder.append("\'").append(c).append("\'"); } stringBuilder.deleteCharAt(stringBuilder.length()-1); stringBuilder.append(" are being replaced with '-'"); @@ -145,7 +145,7 @@ public final static String cleanSequence(String sequence, Set cSet){ * @return * a sequence with no invalid characters. */ - public static final String checkSequence(String sequence){ + public static String checkSequence(String sequence){ return checkSequence(sequence, null); } @@ -162,8 +162,8 @@ public static final String checkSequence(String sequence){ * @return * a sequence with no invalid characters. */ - public static final String checkSequence(String sequence, Set cSet){ - boolean containInvalid = false; + public static String checkSequence(String sequence, Set cSet){ + boolean containInvalid; if(cSet != null){ containInvalid = sequence != null && doesSequenceContainInvalidChar(sequence, cSet); }else{ diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/IProfeatProperties.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/IProfeatProperties.java index 0fab96f94a..e0d3b3d4cb 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/IProfeatProperties.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/IProfeatProperties.java @@ -45,19 +45,22 @@ public interface IProfeatProperties { /** * Enumeration of the seven different attributes */ - public enum ATTRIBUTE {HYDROPHOBICITY, VOLUME, POLARITY, POLARIZABILITY, CHARGE, SECONDARYSTRUCTURE, SOLVENTACCESSIBILITY}; + enum ATTRIBUTE {HYDROPHOBICITY, VOLUME, POLARITY, POLARIZABILITY, CHARGE, SECONDARYSTRUCTURE, SOLVENTACCESSIBILITY} + /** * Enumeration of the three different groupings for each attributes */ - public enum GROUPING {GROUP1, GROUP2, GROUP3}; + enum GROUPING {GROUP1, GROUP2, GROUP3} + /** * Enumeration of the transition between groupA and groupB */ - public enum TRANSITION {BETWEEN_11, BETWEEN_22, BETWEEN_33, BETWEEN_12, BETWEEN_13, BETWEEN_23}; + enum TRANSITION {BETWEEN_11, BETWEEN_22, BETWEEN_33, BETWEEN_12, BETWEEN_13, BETWEEN_23} + /** * Enumeration of the distribution for the first, first 25%, first 50%, first 75% and 100% of the grouping */ - public enum DISTRIBUTION {FIRST, FIRST25, FIRST50, FIRST75, ALL}; + enum DISTRIBUTION {FIRST, FIRST25, FIRST50, FIRST75, ALL} /** * Returns the composition of the specific grouping for the given attribute. @@ -73,11 +76,11 @@ public enum DISTRIBUTION {FIRST, FIRST25, FIRST50, FIRST75, ALL}; * @throws Exception * throws Exception if attribute or group are unknown */ - public double getComposition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group) throws Exception; + double getComposition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group) throws Exception; - public Map getComposition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception; + Map getComposition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception; - public Map> getComposition(ProteinSequence sequence) throws Exception; + Map> getComposition(ProteinSequence sequence) throws Exception; /** * Returns the number of transition between the specified groups for the given attribute with respect to the length of sequence. @@ -93,11 +96,11 @@ public enum DISTRIBUTION {FIRST, FIRST25, FIRST50, FIRST75, ALL}; * @throws Exception * throws Exception if attribute or group are unknown */ - public double getTransition(ProteinSequence sequence, ATTRIBUTE attribute, TRANSITION transition) throws Exception; + double getTransition(ProteinSequence sequence, ATTRIBUTE attribute, TRANSITION transition) throws Exception; - public Map getTransition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception; + Map getTransition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception; - public Map> getTransition(ProteinSequence sequence) throws Exception; + Map> getTransition(ProteinSequence sequence) throws Exception; /** * Computes and return the position with respect to the sequence where the given distribution of the grouping can be found.
@@ -120,11 +123,11 @@ public enum DISTRIBUTION {FIRST, FIRST25, FIRST50, FIRST75, ALL}; * @throws Exception * throws Exception if attribute or group are unknown */ - public double getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group, DISTRIBUTION distribution) throws Exception; + double getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group, DISTRIBUTION distribution) throws Exception; - public Map getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group) throws Exception; + Map getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group) throws Exception; - public Map> getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception; + Map> getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception; - public Map>> getDistributionPosition(ProteinSequence sequence) throws Exception; + Map>> getDistributionPosition(ProteinSequence sequence) throws Exception; } diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/ProfeatPropertiesImpl.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/ProfeatPropertiesImpl.java index 5408c127c5..cad2700a22 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/ProfeatPropertiesImpl.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/ProfeatPropertiesImpl.java @@ -23,7 +23,7 @@ import org.biojava.nbio.aaproperties.profeat.convertor.*; import org.biojava.nbio.core.sequence.ProteinSequence; -import java.util.HashMap; +import java.util.EnumMap; import java.util.Map; public class ProfeatPropertiesImpl implements IProfeatProperties{ @@ -127,35 +127,35 @@ private Convertor getConvertor(ATTRIBUTE attribute) throws Exception{ @Override public Map getComposition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception { - Map grouping2Composition = new HashMap(); + Map grouping2Composition = new EnumMap<>(GROUPING.class); for(GROUPING group:GROUPING.values()) grouping2Composition.put(group, getComposition(sequence, attribute, group)); return grouping2Composition; } @Override public Map> getComposition(ProteinSequence sequence) throws Exception { - Map> attribute2Grouping2Composition = new HashMap>(); + Map> attribute2Grouping2Composition = new EnumMap<>(ATTRIBUTE.class); for(ATTRIBUTE attribute:ATTRIBUTE.values()) attribute2Grouping2Composition.put(attribute, getComposition(sequence, attribute)); return attribute2Grouping2Composition; } @Override public Map getTransition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception { - Map transition2Double = new HashMap(); + Map transition2Double = new EnumMap<>(TRANSITION.class); for(TRANSITION transition:TRANSITION.values()) transition2Double.put(transition, getTransition(sequence, attribute, transition)); return transition2Double; } @Override public Map> getTransition(ProteinSequence sequence) throws Exception { - Map> attribute2Transition2Double = new HashMap>(); + Map> attribute2Transition2Double = new EnumMap<>(ATTRIBUTE.class); for(ATTRIBUTE attribute:ATTRIBUTE.values()) attribute2Transition2Double.put(attribute, getTransition(sequence, attribute)); return attribute2Transition2Double; } @Override public Map getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group) throws Exception { - Map distribution2Double = new HashMap(); + Map distribution2Double = new EnumMap<>(DISTRIBUTION.class); for(DISTRIBUTION distribution:DISTRIBUTION.values()) distribution2Double.put(distribution, getDistributionPosition(sequence, attribute, group, distribution)); return distribution2Double; @@ -163,7 +163,7 @@ public Map getDistributionPosition(ProteinSequence sequenc @Override public Map> getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception { - Map> grouping2Distribution2Double = new HashMap>(); + Map> grouping2Distribution2Double = new EnumMap<>(GROUPING.class); for(GROUPING group:GROUPING.values()) grouping2Distribution2Double.put(group, getDistributionPosition(sequence, attribute, group)); return grouping2Distribution2Double; @@ -172,7 +172,7 @@ public Map> getDistributionPosition(ProteinS @Override public Map>> getDistributionPosition(ProteinSequence sequence) throws Exception { Map>> attribute2Grouping2Distribution2Double = - new HashMap>>(); + new EnumMap<>(ATTRIBUTE.class); for(ATTRIBUTE attribute:ATTRIBUTE.values()) attribute2Grouping2Distribution2Double.put(attribute, getDistributionPosition(sequence, attribute)); return attribute2Grouping2Distribution2Double; diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Charge.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Charge.java index 5bf4bc76f4..b2beeed2bb 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Charge.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Charge.java @@ -39,7 +39,7 @@ public char convert(char c){ } } - private static String[] subCategory = {"Positive", "Neutral", "Negative"}; + private static final String[] subCategory = {"Positive", "Neutral", "Negative"}; @Override public String[] getGrouping(){return Convert2Charge.subCategory;} @Override diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Hydrophobicity.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Hydrophobicity.java index 105fdec86f..c2810e45dd 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Hydrophobicity.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Hydrophobicity.java @@ -38,7 +38,7 @@ public char convert(char c){ return unknownGroup;//Non-standard AA } } - private static String[] subCategory = {"Polar", "Neutral", "Hydrophobicity"}; + private static final String[] subCategory = {"Polar", "Neutral", "Hydrophobicity"}; @Override public String[] getGrouping(){return subCategory;} @Override diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2NormalizedVanDerWaalsVolume.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2NormalizedVanDerWaalsVolume.java index 4facf925b7..970a93534b 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2NormalizedVanDerWaalsVolume.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2NormalizedVanDerWaalsVolume.java @@ -38,7 +38,7 @@ public char convert(char c){ return unknownGroup;//Non-standard AA } } - private static String[] subCategory = {"Range_0-2.78", "Range_2.95-4.0", "Range_4.03-8.08"}; + private static final String[] subCategory = {"Range_0-2.78", "Range_2.95-4.0", "Range_4.03-8.08"}; @Override public String[] getGrouping(){return subCategory;} @Override diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Polarity.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Polarity.java index 2b1f1bec61..80ecc69183 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Polarity.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Polarity.java @@ -38,7 +38,7 @@ public char convert(char c){ return unknownGroup;//Non-standard AA } } - private static String[] subCategory = {"Value_4.9-6.2", "Value_8.0-9.2", "Value_10.4-13.0"}; + private static final String[] subCategory = {"Value_4.9-6.2", "Value_8.0-9.2", "Value_10.4-13.0"}; @Override public String[] getGrouping(){return subCategory;} @Override diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Polarizability.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Polarizability.java index 1af72b5cc9..7888cf66a5 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Polarizability.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Polarizability.java @@ -39,7 +39,7 @@ public char convert(char c){ } } - private static String[] subCategory = {"Value_0-0.08", "Value_0.128-0.186", "Value_0.219-0.409"}; + private static final String[] subCategory = {"Value_0-0.08", "Value_0.128-0.186", "Value_0.219-0.409"}; @Override public String[] getGrouping(){return subCategory;} @Override diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2SecondaryStructure.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2SecondaryStructure.java index 70a51daf41..b3321f659f 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2SecondaryStructure.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2SecondaryStructure.java @@ -37,7 +37,7 @@ public char convert(char c){ return unknownGroup;//Non-standard AA } } - private static String[] subCategory = {"Helix", "Strand", "Coil"}; + private static final String[] subCategory = {"Helix", "Strand", "Coil"}; @Override public String[] getGrouping(){return subCategory;} @Override diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2SolventAccessibility.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2SolventAccessibility.java index 27c7676198..c3497e220f 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2SolventAccessibility.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2SolventAccessibility.java @@ -38,7 +38,7 @@ public char convert(char c){ } } - private static String[] subCategory = {"Buried", "Exposed", "Intermediate"}; + private static final String[] subCategory = {"Buried", "Exposed", "Intermediate"}; @Override public String[] getGrouping(){return subCategory;} @Override diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/AminoAcidCompositionTable.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/AminoAcidCompositionTable.java index 4731e90453..5be7ee1c4f 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/AminoAcidCompositionTable.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/AminoAcidCompositionTable.java @@ -83,7 +83,7 @@ private void generatesAminoAcidCompoundSet(){ * Stores the mass of elements and isotopes */ public void computeMolecularWeight(ElementTable eTable){ - this.aaSymbol2MolecularWeight = new HashMap(); + this.aaSymbol2MolecularWeight = new HashMap<>(); for(AminoAcidComposition a:aminoacid){ //Check to ensure that the symbol is of single character if(a.getSymbol().length() != 1){ @@ -91,7 +91,7 @@ public void computeMolecularWeight(ElementTable eTable){ } //Check to ensure that the symbols are not repeated char c = a.getSymbol().charAt(0); - if(this.aaSymbol2MolecularWeight.keySet().contains(c)){ + if(this.aaSymbol2MolecularWeight.containsKey(c)){ throw new Error("Symbol " + c + " is repeated.\r\n" + "Please check AminoAcidComposition XML file to ensure there are no repeated symbols. Note that this is case-insensitive.\r\n" + "This means that having 'A' and 'a' would be repeating."); diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/CaseFreeAminoAcidCompoundSet.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/CaseFreeAminoAcidCompoundSet.java index 9b211ab305..e830453233 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/CaseFreeAminoAcidCompoundSet.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/CaseFreeAminoAcidCompoundSet.java @@ -39,9 +39,9 @@ */ public class CaseFreeAminoAcidCompoundSet implements CompoundSet { - private final Map aminoAcidCompoundCache = new HashMap(); + private final Map aminoAcidCompoundCache = new HashMap<>(); private final Map> equivalentsCache = - new HashMap>(); + new HashMap<>(); public CaseFreeAminoAcidCompoundSet() { aminoAcidCompoundCache.put("A", new AminoAcidCompound(null, "A", "Ala", "Alanine", 71.0788f)); @@ -64,14 +64,14 @@ public CaseFreeAminoAcidCompoundSet() { aminoAcidCompoundCache.put("W", new AminoAcidCompound(null, "W", "Trp", "Tryptophan", 186.2132f)); aminoAcidCompoundCache.put("Y", new AminoAcidCompound(null, "Y", "Tyr", "Tyrosine", 163.1760f)); aminoAcidCompoundCache.put("V", new AminoAcidCompound(null, "V", "Val", "Valine", 99.1326f)); - aminoAcidCompoundCache.put("B", new AminoAcidCompound(null, "B", "Asx", "Asparagine or Aspartic acid", null)); - aminoAcidCompoundCache.put("Z", new AminoAcidCompound(null, "Z", "Glx", "Glutamine or Glutamic acid", null)); - aminoAcidCompoundCache.put("J", new AminoAcidCompound(null, "J", "Xle", "Leucine or Isoleucine", null)); - aminoAcidCompoundCache.put("X", new AminoAcidCompound(null, "X", "Xaa", "Unspecified", null)); - aminoAcidCompoundCache.put("-", new AminoAcidCompound(null, "-", "---", "Unspecified", null)); - aminoAcidCompoundCache.put(".", new AminoAcidCompound(null, ".", "...", "Unspecified", null)); - aminoAcidCompoundCache.put("_", new AminoAcidCompound(null, "_", "___", "Unspecified", null)); - aminoAcidCompoundCache.put("*", new AminoAcidCompound(null, "*", "***", "Stop", null)); + aminoAcidCompoundCache.put("B", new AminoAcidCompound(null, "B", "Asx", "Asparagine or Aspartic acid", Float.NaN)); + aminoAcidCompoundCache.put("Z", new AminoAcidCompound(null, "Z", "Glx", "Glutamine or Glutamic acid", Float.NaN)); + aminoAcidCompoundCache.put("J", new AminoAcidCompound(null, "J", "Xle", "Leucine or Isoleucine", Float.NaN)); + aminoAcidCompoundCache.put("X", new AminoAcidCompound(null, "X", "Xaa", "Unspecified", Float.NaN)); + aminoAcidCompoundCache.put("-", new AminoAcidCompound(null, "-", "---", "Unspecified", Float.NaN)); + aminoAcidCompoundCache.put(".", new AminoAcidCompound(null, ".", "...", "Unspecified", Float.NaN)); + aminoAcidCompoundCache.put("_", new AminoAcidCompound(null, "_", "___", "Unspecified", Float.NaN)); + aminoAcidCompoundCache.put("*", new AminoAcidCompound(null, "*", "***", "Stop", Float.NaN)); //Selenocysteine - this is encoded by UGA with the presence //of a SECIS element (SElenoCysteine Insertion Sequence) in the mRNA @@ -83,9 +83,9 @@ public CaseFreeAminoAcidCompoundSet() { //which then does the actual conversion to Pyl. aminoAcidCompoundCache.put("O", new AminoAcidCompound(null, "O", "Pyl", "Pyrrolysine", 255.3172f)); - Map lowerCaseSet = new HashMap(); - for(String s:this.aminoAcidCompoundCache.keySet()){ - lowerCaseSet.put(s.toLowerCase(), this.aminoAcidCompoundCache.get(s)); + Map lowerCaseSet = new HashMap<>(); + for(Map.Entry entry : this.aminoAcidCompoundCache.entrySet()){ + lowerCaseSet.put(entry.getKey().toLowerCase(), entry.getValue()); } this.aminoAcidCompoundCache.putAll(lowerCaseSet); } @@ -144,7 +144,7 @@ public Set getEquivalentCompounds(AminoAcidCompound compound) addAmbiguousEquivalents("I", "L", "J"); // ambiguous gaps AminoAcidCompound gap1, gap2, gap3; - Set gaps = new HashSet(); + Set gaps = new HashSet<>(); gaps.add(gap1 = aminoAcidCompoundCache.get("-")); gaps.add(gap2 = aminoAcidCompoundCache.get(".")); gaps.add(gap3 = aminoAcidCompoundCache.get("_")); @@ -152,7 +152,7 @@ public Set getEquivalentCompounds(AminoAcidCompound compound) equivalentsCache.put(gap2, gaps); equivalentsCache.put(gap3, gaps); // X is never equivalent, even to itself - equivalentsCache.put(aminoAcidCompoundCache.get("X"), new HashSet()); + equivalentsCache.put(aminoAcidCompoundCache.get("X"), new HashSet<>()); } return equivalentsCache.get(compound); } @@ -162,18 +162,18 @@ private void addAmbiguousEquivalents(String one, String two, String either) { Set equivalents; AminoAcidCompound cOne, cTwo, cEither; - equivalents = new HashSet(); + equivalents = new HashSet<>(); equivalents.add(cOne = aminoAcidCompoundCache.get(one)); equivalents.add(cTwo = aminoAcidCompoundCache.get(two)); equivalents.add(cEither = aminoAcidCompoundCache.get(either)); equivalentsCache.put(cEither, equivalents); - equivalents = new HashSet(); + equivalents = new HashSet<>(); equivalents.add(cOne); equivalents.add(cEither); equivalentsCache.put(cOne, equivalents); - equivalents = new HashSet(); + equivalents = new HashSet<>(); equivalents.add(cTwo); equivalents.add(cEither); equivalentsCache.put(cTwo, equivalents); @@ -185,8 +185,8 @@ public boolean hasCompound(AminoAcidCompound compound) { } @Override - public List getAllCompounds() { - return new ArrayList(aminoAcidCompoundCache.values()); + public Collection getAllCompounds() { + return new ArrayList<>(aminoAcidCompoundCache.values()); } diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/Element.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/Element.java index b03d15d1ac..1a9f15bb28 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/Element.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/Element.java @@ -120,7 +120,7 @@ public List getIsotopes() { public void setIsotopes(List isotopes) { this.isotope = isotopes; - this.name2Isotope = new HashMap(); + this.name2Isotope = new HashMap<>(); if(isotopes != null){ for(Isotope i:isotopes){ name2Isotope.put(i.getName(), i); diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/ElementTable.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/ElementTable.java index efac678f23..05b54c7014 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/ElementTable.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/ElementTable.java @@ -58,8 +58,8 @@ public void setElement(List eList){ * Populate the Maps for quick retrieval */ public void populateMaps(){ - this.elementName2Element = new HashMap(); - this.isotopeName2Isotope = new HashMap(); + this.elementName2Element = new HashMap<>(); + this.isotopeName2Isotope = new HashMap<>(); if(this.element != null){ for(Element e:this.element){ this.elementName2Element.put(e.getName(), e); diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/ModifiedAminoAcidCompoundSet.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/ModifiedAminoAcidCompoundSet.java index d9c11c7e66..82061e14e6 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/ModifiedAminoAcidCompoundSet.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/ModifiedAminoAcidCompoundSet.java @@ -28,7 +28,7 @@ public class ModifiedAminoAcidCompoundSet implements CompoundSet { - private final Map aminoAcidCompoundCache = new HashMap(); + private final Map aminoAcidCompoundCache = new HashMap<>(); public ModifiedAminoAcidCompoundSet(List aaList, Map aaSymbol2MolecularWeight) { this.aminoAcidCompoundCache.put("-", new AminoAcidCompound(null, "-", "", "", 0.0f)); @@ -83,8 +83,8 @@ public boolean hasCompound(AminoAcidCompound compound) { } @Override - public List getAllCompounds() { - return new ArrayList(aminoAcidCompoundCache.values()); + public Collection getAllCompounds() { + return new ArrayList<>(aminoAcidCompoundCache.values()); } @Override diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/SchemaGenerator.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/SchemaGenerator.java index 8005bf3bac..b5cfea39c2 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/SchemaGenerator.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/SchemaGenerator.java @@ -27,7 +27,7 @@ import java.io.IOException; public class SchemaGenerator extends SchemaOutputResolver{ - private String fileName; + private final String fileName; public SchemaGenerator(String filename){ this.fileName = filename; diff --git a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/CommandPromptTest.java b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/CommandPromptTest.java index 58ed18dc16..bf37136610 100644 --- a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/CommandPromptTest.java +++ b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/CommandPromptTest.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.aaproperties; -import org.biojava.nbio.aaproperties.CommandPrompt; import org.junit.Test; import java.io.File; diff --git a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/CookBookTest.java b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/CookBookTest.java index 25ebf3abed..aa51ac3876 100644 --- a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/CookBookTest.java +++ b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/CookBookTest.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.aaproperties; -import org.biojava.nbio.aaproperties.PeptideProperties; import org.biojava.nbio.aaproperties.xml.AminoAcidCompositionTable; import org.junit.Test; import org.slf4j.Logger; @@ -74,8 +73,8 @@ public void shortExample4(){ //Enrichment of a list of amino acid types Map composition = PeptideProperties.getAACompositionString(sequence); - for(String aa:composition.keySet()){ - logger.debug("Composition of {}: {}", aa, composition.get(aa)); + for(Map.Entry entry : composition.entrySet()){ + logger.debug("Composition of {}: {}", entry.getKey(), entry.getValue()); } } diff --git a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/GenbankCommandPromptTest.java b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/GenbankCommandPromptTest.java index d76acd34c0..15261ae05c 100644 --- a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/GenbankCommandPromptTest.java +++ b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/GenbankCommandPromptTest.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.aaproperties; -import org.biojava.nbio.aaproperties.CommandPrompt; import org.junit.Test; import java.io.File; @@ -33,8 +32,8 @@ public void testAdvancedXMLExample() throws Exception{ //-i BondFeature.gb -a String[] args = new String[11]; args[0] = "-i"; - args[1] = "./src/test/resources/BondFeature.gb";; - args[2] = "-x"; + args[1] = "./src/test/resources/BondFeature.gb"; + args[2] = "-x"; args[3] = "./src/main/resources/AdvancedAminoAcidComposition.xml"; args[4] = "-0"; args[5] = "0"; @@ -53,8 +52,8 @@ public void testExample1() throws Exception{ //-i BondFeature.gb -a String[] args = new String[7]; args[0] = "-i"; - args[1] = "./src/test/resources/BondFeature.gb";; - args[2] = "-a"; + args[1] = "./src/test/resources/BondFeature.gb"; + args[2] = "-a"; args[3] = "-o"; args[4] = output.toString(); args[5] = "-f"; @@ -69,8 +68,8 @@ public void testExample1WithCSV() throws Exception{ //-i BondFeature.gb -a String[] args = new String[7]; args[0] = "-i"; - args[1] = "./src/test/resources/BondFeature.gb";; - args[2] = "-a"; + args[1] = "./src/test/resources/BondFeature.gb"; + args[2] = "-a"; args[3] = "-o"; args[4] = output.toString(); args[5] = "-f"; diff --git a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/PeptidePropertiesImplTest.java b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/PeptidePropertiesImplTest.java index 6220ea0b28..ae82803012 100644 --- a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/PeptidePropertiesImplTest.java +++ b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/PeptidePropertiesImplTest.java @@ -20,8 +20,6 @@ */ package org.biojava.nbio.aaproperties; -import org.biojava.nbio.aaproperties.PeptideProperties; -import org.biojava.nbio.aaproperties.Utils; import org.biojava.nbio.aaproperties.xml.AminoAcidCompositionTable; import org.junit.Test; import org.slf4j.Logger; @@ -345,7 +343,7 @@ public void testNetCharge(){ logger.debug(p); logger.debug("pH\tInnovagen\tExpasy\tdiff"); for ( int i = 1; i < 15; i++) { - double phPoint = (new Double(i)).doubleValue(); + double phPoint = i; double chrgInnovagen = PeptideProperties.getNetCharge(p,false,phPoint); double chrgExpasy = PeptideProperties.getNetCharge(p,true,phPoint); logger.debug(String.format("%2.1f\t%2.2f\t%2.2f\t%2.2f", phPoint, chrgInnovagen, diff --git a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/profeat/CookBookTest.java b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/profeat/CookBookTest.java index b68370cfc9..51f9735488 100644 --- a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/profeat/CookBookTest.java +++ b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/profeat/CookBookTest.java @@ -24,13 +24,13 @@ import org.biojava.nbio.aaproperties.profeat.IProfeatProperties.DISTRIBUTION; import org.biojava.nbio.aaproperties.profeat.IProfeatProperties.GROUPING; import org.biojava.nbio.aaproperties.profeat.IProfeatProperties.TRANSITION; -import org.biojava.nbio.aaproperties.profeat.ProfeatProperties; -//import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; +//import org.junit.Test; + public class CookBookTest { private final static Logger logger = LoggerFactory.getLogger(CookBookTest.class); @@ -43,11 +43,11 @@ public void shortExample1() throws Exception{ */ String sequence = "QIKDLLVSSSTDLDTTLVLVNAIYFKGMWKTAFNAEDTREMPFHVTKQESKPVQMMCMNNSFNVATLPAE"; Map> attribute2Grouping2Double = ProfeatProperties.getComposition(sequence); - for(ATTRIBUTE a:attribute2Grouping2Double.keySet()){ - logger.info("======={}=======", a); - logger.info("GROUP1 = {}", attribute2Grouping2Double.get(a).get(GROUPING.GROUP1)); - logger.info("GROUP2 = {}", attribute2Grouping2Double.get(a).get(GROUPING.GROUP2)); - logger.info("GROUP3 = {}", attribute2Grouping2Double.get(a).get(GROUPING.GROUP3)); + for(Map.Entry> entry : attribute2Grouping2Double.entrySet()){ + logger.info("======={}=======", entry.getKey()); + logger.info("GROUP1 = {}", entry.getValue().get(GROUPING.GROUP1)); + logger.info("GROUP2 = {}", entry.getValue().get(GROUPING.GROUP2)); + logger.info("GROUP3 = {}", entry.getValue().get(GROUPING.GROUP3)); } } @@ -58,14 +58,14 @@ public void shortExample2() throws Exception{ */ String sequence = "QIKDLLVSSSTDLDTTLVLVNAIYFKGMWKTAFNAEDTREMPFHVTKQESKPVQMMCMNNSFNVATLPAE"; Map> attribute2Transition2Double = ProfeatProperties.getTransition(sequence); - for(ATTRIBUTE a:attribute2Transition2Double.keySet()){ - logger.info("======={}=======", a); - logger.info("1<=>1 = {}", attribute2Transition2Double.get(a).get(TRANSITION.BETWEEN_11)); - logger.info("2<=>2 = {}", attribute2Transition2Double.get(a).get(TRANSITION.BETWEEN_22)); - logger.info("3<=>3 = {}", attribute2Transition2Double.get(a).get(TRANSITION.BETWEEN_33)); - logger.info("1<=>2 = {}", attribute2Transition2Double.get(a).get(TRANSITION.BETWEEN_12)); - logger.info("1<=>3 = {}", attribute2Transition2Double.get(a).get(TRANSITION.BETWEEN_13)); - logger.info("2<=>3 = {}", attribute2Transition2Double.get(a).get(TRANSITION.BETWEEN_23)); + for(Map.Entry> entry : attribute2Transition2Double.entrySet()){ + logger.info("======={}=======", entry.getKey()); + logger.info("1<=>1 = {}", entry.getValue().get(TRANSITION.BETWEEN_11)); + logger.info("2<=>2 = {}", entry.getValue().get(TRANSITION.BETWEEN_22)); + logger.info("3<=>3 = {}", entry.getValue().get(TRANSITION.BETWEEN_33)); + logger.info("1<=>2 = {}", entry.getValue().get(TRANSITION.BETWEEN_12)); + logger.info("1<=>3 = {}", entry.getValue().get(TRANSITION.BETWEEN_13)); + logger.info("2<=>3 = {}", entry.getValue().get(TRANSITION.BETWEEN_23)); } } @@ -76,11 +76,11 @@ public void shortExample3() throws Exception{ */ String sequence = "QIKDLLVSSSTDLDTTLVLVNAIYFKGMWKTAFNAEDTREMPFHVTKQESKPVQMMCMNNSFNVATLPAE"; Map>> attribute2Grouping2Distribution2Double = ProfeatProperties.getDistributionPosition(sequence); - for(ATTRIBUTE a:attribute2Grouping2Distribution2Double.keySet()){ - logger.info("======={}=======", a); - logger.info("GROUP1 = {}", attribute2Grouping2Distribution2Double.get(a).get(GROUPING.GROUP1)); - logger.info("GROUP2 = {}", attribute2Grouping2Distribution2Double.get(a).get(GROUPING.GROUP2)); - logger.info("GROUP3 = {}", attribute2Grouping2Distribution2Double.get(a).get(GROUPING.GROUP3)); + for(Map.Entry>> entry : attribute2Grouping2Distribution2Double.entrySet()){ + logger.info("======={}=======", entry.getKey()); + logger.info("GROUP1 = {}", entry.getValue().get(GROUPING.GROUP1)); + logger.info("GROUP2 = {}", entry.getValue().get(GROUPING.GROUP2)); + logger.info("GROUP3 = {}", entry.getValue().get(GROUPING.GROUP3)); } } } diff --git a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/AminoAcidTest.java b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/AminoAcidTest.java index 528192dcb4..e2fa5e3bea 100644 --- a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/AminoAcidTest.java +++ b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/AminoAcidTest.java @@ -133,35 +133,35 @@ public void readXml() throws JAXBException, IOException{ @Test public void generateXml() throws JAXBException, IOException{ - List elementList = new ArrayList(); + List elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 3)); elementList.add(new Name2Count("Hydrogen", 5)); elementList.add(new Name2Count("Nitrogen", 1)); elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition alanine = new AminoAcidComposition("A", "Ala", "Alanine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 6)); elementList.add(new Name2Count("Hydrogen", 12)); elementList.add(new Name2Count("Nitrogen", 4)); elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition arginine = new AminoAcidComposition("R", "Arg", "Arginine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 4)); elementList.add(new Name2Count("Hydrogen", 6)); elementList.add(new Name2Count("Nitrogen", 2)); elementList.add(new Name2Count("Oxygen", 2)); AminoAcidComposition asparagine = new AminoAcidComposition("N", "Asn", "Asparagine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 4)); elementList.add(new Name2Count("Hydrogen", 5)); elementList.add(new Name2Count("Nitrogen", 1)); elementList.add(new Name2Count("Oxygen", 3)); AminoAcidComposition asparticAcid = new AminoAcidComposition("D", "Asp", "Aspartic Acid", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 3)); elementList.add(new Name2Count("Hydrogen", 5)); @@ -170,7 +170,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Sulfur", 1)); AminoAcidComposition cysteine = new AminoAcidComposition("C", "Cys", "Cysteine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 5)); elementList.add(new Name2Count("Hydrogen", 7)); @@ -178,7 +178,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 3)); AminoAcidComposition glutamicAcid = new AminoAcidComposition("E", "Glu", "Glutamic Acid", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 5)); elementList.add(new Name2Count("Hydrogen", 8)); @@ -186,7 +186,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 2)); AminoAcidComposition glutamine = new AminoAcidComposition("Q", "Gln", "Glutamine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 2)); elementList.add(new Name2Count("Hydrogen", 3)); @@ -194,7 +194,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition glycine = new AminoAcidComposition("G", "Gly", "Glycine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 6)); elementList.add(new Name2Count("Hydrogen", 7)); @@ -202,7 +202,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition histidine = new AminoAcidComposition("H", "His", "Histidine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 6)); elementList.add(new Name2Count("Hydrogen", 11)); @@ -210,7 +210,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition isoleucine = new AminoAcidComposition("I", "Ile", "Isoleucine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 6)); elementList.add(new Name2Count("Hydrogen", 11)); @@ -218,7 +218,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition leucine = new AminoAcidComposition("L", "Leu", "Leucine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 6)); elementList.add(new Name2Count("Hydrogen", 12)); @@ -226,7 +226,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition lysine = new AminoAcidComposition("K", "Lys", "Lysine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 5)); elementList.add(new Name2Count("Hydrogen", 9)); @@ -235,7 +235,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Sulfur", 1)); AminoAcidComposition methionine = new AminoAcidComposition("M", "Met", "Methionine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 9)); elementList.add(new Name2Count("Hydrogen", 9)); @@ -243,7 +243,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition phenylalanine = new AminoAcidComposition("F", "Phe", "Phenylalanine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 5)); elementList.add(new Name2Count("Hydrogen", 7)); @@ -251,7 +251,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition proline = new AminoAcidComposition("P", "Pro", "Proline", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 3)); elementList.add(new Name2Count("Hydrogen", 5)); @@ -259,7 +259,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 2)); AminoAcidComposition serine = new AminoAcidComposition("S", "Ser", "Serine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 4)); elementList.add(new Name2Count("Hydrogen", 7)); @@ -267,7 +267,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 2)); AminoAcidComposition threonine = new AminoAcidComposition("T", "Thr", "Threonine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 11)); elementList.add(new Name2Count("Hydrogen", 10)); @@ -275,7 +275,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition tryptophan = new AminoAcidComposition("W", "Trp", "Tryptophan", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 9)); elementList.add(new Name2Count("Hydrogen", 9)); @@ -283,7 +283,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 2)); AminoAcidComposition tyrosine = new AminoAcidComposition("Y", "Tyr", "Tyrosine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 5)); elementList.add(new Name2Count("Hydrogen", 9)); @@ -291,7 +291,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition valine = new AminoAcidComposition("V", "Val", "Valine", elementList, null); - List aList = new ArrayList(); + List aList = new ArrayList<>(); aList.add(alanine); aList.add(arginine); aList.add(asparagine); diff --git a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/ElementTest.java b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/ElementTest.java index 37376b6bd0..801f4f28d7 100644 --- a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/ElementTest.java +++ b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/ElementTest.java @@ -20,10 +20,6 @@ */ package org.biojava.nbio.aaproperties.xml; -import org.biojava.nbio.aaproperties.xml.Element; -import org.biojava.nbio.aaproperties.xml.ElementTable; -import org.biojava.nbio.aaproperties.xml.Isotope; -import org.biojava.nbio.aaproperties.xml.SchemaGenerator; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -62,98 +58,98 @@ public void readXml() throws JAXBException, IOException{ @Test public void generateXml() throws JAXBException, IOException { - List iList = new ArrayList(); + List iList = new ArrayList<>(); Element hydrogen = new Element("Hydrogen", "H", 1, null, 1.00794); iList.add(new Isotope("Hydrogen", 1, 1.00782503207)); iList.add(new Isotope("Deuterium", 2, 2.0141017778)); iList.add(new Isotope("Tritium", 3, 3.0160492777)); hydrogen.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element helium = new Element("Helium", "He", 2, null, 4.002602); iList.add(new Isotope("Helium-3", 3, 3.0160293191)); iList.add(new Isotope("Helium-4", 4, 4.00260325415)); helium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element lithium = new Element("Lithium", "Li", 3, null, 6.941); iList.add(new Isotope("Lithium-6", 6, 6.015122795)); iList.add(new Isotope("Lithium-7", 7, 7.01600455)); lithium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element beryllium = new Element("Beryllium", "Be", 4, null, 9.012182); iList.add(new Isotope("Beryllium-9", 9, 9.0121822)); beryllium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element boron = new Element("Boron", "B", 5, null, 10.811); iList.add(new Isotope("Boron-10", 10, 10.012937)); iList.add(new Isotope("Boron-11", 11, 11.0093054)); boron.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element carbon = new Element("Carbon", "C", 6, null, 12.0107); iList.add(new Isotope("Carbon-12", 12, 12.0)); iList.add(new Isotope("Carbon-13", 13, 13.0033548378)); iList.add(new Isotope("Carbon-14", 14, 14.003241989)); carbon.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element nitrogen = new Element("Nitrogen", "N", 7, null, 14.0067); iList.add(new Isotope("Nitrogen-14", 14, 14.0030740048)); iList.add(new Isotope("Nitrogen-15", 15, 15.0001088982)); nitrogen.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element oxygen = new Element("Oxygen", "O", 8, null, 15.9994); iList.add(new Isotope("Oxygen-16", 16, 15.99491461956)); iList.add(new Isotope("Oxygen-17", 17, 16.9991317)); iList.add(new Isotope("Oxygen-18", 18, 17.999161)); oxygen.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element fluorine = new Element("Fluorine", "F", 9, null, 18.9984032); iList.add(new Isotope("Fluorine-19", 19, 18.99840322)); fluorine.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element neon = new Element("Neon", "Ne", 10, null, 20.1797); iList.add(new Isotope("Neon-20", 20, 19.9924401754)); iList.add(new Isotope("Neon-21", 21, 20.99384668)); iList.add(new Isotope("Neon-22", 22, 21.991385114)); neon.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element sodium = new Element("Sodium", "Na", 11, null, 22.98976928); iList.add(new Isotope("Sodium-23", 23, 22.9897692809)); sodium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element magnesium = new Element("Magnesium", "Mg", 12, null, 24.305); iList.add(new Isotope("Magnesium-24", 24, 23.9850417)); iList.add(new Isotope("Magnesium-25", 25, 24.98583692)); iList.add(new Isotope("Magnesium-26", 26, 25.982592929)); magnesium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element aluminium = new Element("Aluminium", "Al", 13, null, 26.9815386); iList.add(new Isotope("Aluminium-27", 27, 26.98153863)); aluminium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element silicon = new Element("Silicon", "Si", 14, null, 28.0855); iList.add(new Isotope("Silicon-28", 28, 27.9769265325)); iList.add(new Isotope("Silicon-29", 29, 28.9764947)); iList.add(new Isotope("Silicon-30", 30, 29.97377017)); silicon.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element phosphorus = new Element("Phosphorus", "P", 15, null, 30.973762); iList.add(new Isotope("Phosphorus-31", 31, 30.97376163)); phosphorus.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element sulfur = new Element("Sulfur", "S", 16, null, 32.065); iList.add(new Isotope("Sulfur-32", 32, 31.972071)); iList.add(new Isotope("Sulfur-33", 33, 32.97145876)); @@ -161,27 +157,27 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Sulfur-36", 36, 35.96708076)); sulfur.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element chlorine = new Element("Chlorine", "Cl", 17, null, 35.453); iList.add(new Isotope("Chlorine-35", 35, 34.96885268)); iList.add(new Isotope("Chlorine-37", 37, 36.96590259)); chlorine.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element argon = new Element("Argon", "Ar", 18, null, 39.948); iList.add(new Isotope("Argon-36", 36, 35.967545106)); iList.add(new Isotope("Argon-38", 38, 37.9627324)); iList.add(new Isotope("Argon-40", 40, 39.9623831225)); argon.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element potassium = new Element("Potassium", "K", 19, null, 39.0983); iList.add(new Isotope("Potassium-39", 39, 38.96370668)); iList.add(new Isotope("Potassium-40", 40, 39.96399848)); iList.add(new Isotope("Potassium-41", 41, 40.96182576)); potassium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element calcium = new Element("Calcium", "Ca", 20, null, 40.078); iList.add(new Isotope("Calcium-40", 40, 39.96259098)); iList.add(new Isotope("Calcium-42", 42, 41.95861801)); @@ -191,12 +187,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Calcium-48", 48, 47.952534)); calcium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element scandium = new Element("Scandium", "Sc", 21, null, 44.955912); iList.add(new Isotope("Scandium-45", 45, 44.9559119)); scandium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element titanium = new Element("Titanium", "Ti", 22, null, 47.867); iList.add(new Isotope("Titanium-46", 46, 45.9526316)); iList.add(new Isotope("Titanium-47", 47, 46.9517631)); @@ -205,13 +201,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Titanium-50", 50, 49.9447912)); titanium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element vanadium = new Element("Vanadium", "V", 23, null, 50.9415); iList.add(new Isotope("Vanadium-50", 50, 49.9471585)); iList.add(new Isotope("Vanadium-51", 51, 50.9439595)); vanadium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element chromium = new Element("Chromium", "Cr", 24, null, 51.9961); iList.add(new Isotope("Chromium-50", 50, 49.9460442)); iList.add(new Isotope("Chromium-52", 52, 51.9405075)); @@ -219,12 +215,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Chromium-54", 54, 53.9388804)); chromium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element manganese = new Element("Manganese", "Mn", 25, null, 54.938045); iList.add(new Isotope("Manganese-55", 55, 54.9380451)); manganese.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element iron = new Element("Iron", "Fe", 26, null, 55.845); iList.add(new Isotope("Iron-54", 54, 53.9396105)); iList.add(new Isotope("Iron-56", 56, 55.9349375)); @@ -232,12 +228,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Iron-58", 58, 57.9332756)); iron.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element cobalt = new Element("Cobalt", "Co", 27, null, 58.933195); iList.add(new Isotope("Cobalt-59", 59, 58.933195)); cobalt.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element nickel = new Element("Nickel", "Ni", 28, null, 58.6934); iList.add(new Isotope("Nickel-58", 58, 57.9353429)); iList.add(new Isotope("Nickel-60", 60, 59.9307864)); @@ -246,13 +242,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Nickel-64", 64, 63.927966)); nickel.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element copper = new Element("Copper", "Cu", 29, null, 63.546); iList.add(new Isotope("Copper-63", 63, 62.9295975)); iList.add(new Isotope("Copper-65", 65, 64.9277895)); copper.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element zinc = new Element("Zinc", "Zn", 30, null, 65.38); iList.add(new Isotope("Zinc-64", 64, 63.9291422)); iList.add(new Isotope("Zinc-66", 66, 65.9260334)); @@ -261,13 +257,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Zinc-70", 70, 69.9253193)); zinc.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element gallium = new Element("Gallium", "Ga", 31, null, 69.723); iList.add(new Isotope("Gallium-69", 69, 68.9255736)); iList.add(new Isotope("Gallium-71", 71, 70.9247013)); gallium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element germanium = new Element("Germanium", "Ge", 32, null, 72.64); iList.add(new Isotope("Germanium-70", 70, 69.9242474)); iList.add(new Isotope("Germanium-72", 72, 71.9220758)); @@ -276,12 +272,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Germanium-76", 76, 75.9214026)); germanium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element arsenic = new Element("Arsenic", "As", 33, null, 74.9216); iList.add(new Isotope("Arsenic-75", 75, 74.9215965)); arsenic.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element selenium = new Element("Selenium", "Se", 34, null, 78.96); iList.add(new Isotope("Selenium-74", 74, 73.9224764)); iList.add(new Isotope("Selenium-76", 76, 75.9192136)); @@ -291,13 +287,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Selenium-82", 82, 81.9166994)); selenium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element bromine = new Element("Bromine", "Br", 35, null, 79.904); iList.add(new Isotope("Bromine-79", 79, 78.9183371)); iList.add(new Isotope("Bromine-81", 81, 80.9162906)); bromine.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element krypton = new Element("Krypton", "Kr", 36, null, 83.798); iList.add(new Isotope("Krypton-78", 78, 77.9203648)); iList.add(new Isotope("Krypton-80", 80, 79.916379)); @@ -307,13 +303,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Krypton-86", 86, 85.91061073)); krypton.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element rubidium = new Element("Rubidium", "Rb", 37, null, 85.4678); iList.add(new Isotope("Rubidium-85", 85, 84.911789738)); iList.add(new Isotope("Rubidium-87", 87, 86.909180527)); rubidium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element strontium = new Element("Strontium", "Sr", 38, null, 87.62); iList.add(new Isotope("Strontium-84", 84, 83.913425)); iList.add(new Isotope("Strontium-86", 86, 85.9092602)); @@ -321,12 +317,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Strontium-88", 88, 87.9056121)); strontium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element yttrium = new Element("Yttrium", "Y", 39, null, 88.90585); iList.add(new Isotope("Yttrium-89", 89, 88.9058483)); yttrium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element zirconium = new Element("Zirconium", "Zr", 40, null, 91.224); iList.add(new Isotope("Zirconium-90", 90, 89.9047044)); iList.add(new Isotope("Zirconium-91", 91, 90.9056458)); @@ -335,12 +331,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Zirconium-96", 96, 95.9082734)); zirconium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element niobium = new Element("Niobium", "Nb", 41, null, 92.90638); iList.add(new Isotope("Niobium-93", 93, 92.9063781)); niobium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element molybdenum = new Element("Molybdenum", "Mo", 42, null, 95.96); iList.add(new Isotope("Molybdenum-92", 92, 91.906811)); iList.add(new Isotope("Molybdenum-94", 94, 93.9050883)); @@ -351,14 +347,14 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Molybdenum-100", 100, 99.907477)); molybdenum.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element technetium = new Element("Technetium", "Tc", 43, null, 98.0); iList.add(new Isotope("Technetium-97", 97, 96.906365)); iList.add(new Isotope("Technetium-98", 98, 97.907216)); iList.add(new Isotope("Technetium-99", 99, 98.9062547)); technetium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element ruthenium = new Element("Ruthenium", "Ru", 44, null, 101.07); iList.add(new Isotope("Ruthenium-96", 96, 95.907598)); iList.add(new Isotope("Ruthenium-98", 98, 97.905287)); @@ -369,12 +365,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Ruthenium-104", 104, 103.905433)); ruthenium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element rhodium = new Element("Rhodium", "Rh", 45, null, 102.9055); iList.add(new Isotope("Rhodium-103", 103, 102.905504)); rhodium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element palladium = new Element("Palladium", "Pd", 46, null, 106.42); iList.add(new Isotope("Palladium-102", 102, 101.905609)); iList.add(new Isotope("Palladium-104", 104, 103.904036)); @@ -384,13 +380,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Palladium-110", 110, 109.905153)); palladium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element silver = new Element("Silver", "Ag", 47, null, 107.8682); iList.add(new Isotope("Silver-107", 107, 106.905097)); iList.add(new Isotope("Silver-109", 109, 108.904752)); silver.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element cadmium = new Element("Cadmium", "Cd", 48, null, 112.411); iList.add(new Isotope("Cadmium-106", 106, 105.906459)); iList.add(new Isotope("Cadmium-108", 108, 107.904184)); @@ -402,13 +398,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Cadmium-116", 116, 115.904756)); cadmium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element indium = new Element("Indium", "In", 49, null, 114.818); iList.add(new Isotope("Indium-113", 113, 112.904058)); iList.add(new Isotope("Indium-115", 115, 114.903878)); indium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element tin = new Element("Tin", "Sn", 50, null, 118.71); iList.add(new Isotope("Tin-112", 112, 111.904818)); iList.add(new Isotope("Tin-114", 114, 113.902779)); @@ -422,13 +418,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Tin-124", 124, 123.9052739)); tin.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element antimony = new Element("Antimony", "Sb", 51, null, 121.76); iList.add(new Isotope("Antimony-121", 121, 120.9038157)); iList.add(new Isotope("Antimony-123", 123, 122.904214)); antimony.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element tellurium = new Element("Tellurium", "Te", 52, null, 127.6); iList.add(new Isotope("Tellurium-120", 120, 119.90402)); iList.add(new Isotope("Tellurium-122", 122, 121.9030439)); @@ -440,12 +436,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Tellurium-130", 130, 129.9062244)); tellurium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element iodine = new Element("Iodine", "I", 53, null, 126.90447); iList.add(new Isotope("Iodine-127", 127, 126.904473)); iodine.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element xenon = new Element("Xenon", "Xe", 54, null, 131.293); iList.add(new Isotope("Xenon-124", 124, 123.905893)); iList.add(new Isotope("Xenon-126", 126, 125.904274)); @@ -458,12 +454,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Xenon-136", 136, 135.907219)); xenon.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element caesium = new Element("Caesium", "Cs", 55, null, 132.9054519); iList.add(new Isotope("Caesium-133", 133, 132.905451933)); caesium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element barium = new Element("Barium", "Ba", 56, null, 137.327); iList.add(new Isotope("Barium-130", 130, 129.9063208)); iList.add(new Isotope("Barium-132", 132, 131.9050613)); @@ -474,13 +470,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Barium-138", 138, 137.9052472)); barium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element lanthanum = new Element("Lanthanum", "La", 57, null, 138.90547); iList.add(new Isotope("Lanthanum-138", 138, 137.907112)); iList.add(new Isotope("Lanthanum-139", 139, 138.9063533)); lanthanum.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element cerium = new Element("Cerium", "Ce", 58, null, 140.116); iList.add(new Isotope("Cerium-136", 136, 135.907172)); iList.add(new Isotope("Cerium-138", 138, 137.905991)); @@ -488,12 +484,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Cerium-142", 142, 141.909244)); cerium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element praseodymium = new Element("Praseodymium", "Pr", 59, null, 140.90765); iList.add(new Isotope("Praseodymium-141", 141, 140.9076528)); praseodymium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element neodymium = new Element("Neodymium", "Nd", 60, null, 144.242); iList.add(new Isotope("Neodymium-142", 142, 141.9077233)); iList.add(new Isotope("Neodymium-143", 143, 142.9098143)); @@ -504,13 +500,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Neodymium-150", 150, 149.920891)); neodymium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element promethium = new Element("Promethium", "Pm", 61, null, 145.0); iList.add(new Isotope("Promethium-145", 145, 144.912749)); iList.add(new Isotope("Promethium-147", 147, 146.9151385)); promethium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element samarium = new Element("Samarium", "Sm", 62, null, 150.36); iList.add(new Isotope("Samarium-144", 144, 143.911999)); iList.add(new Isotope("Samarium-147", 147, 146.9148979)); @@ -521,13 +517,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Samarium-154", 154, 153.9222093)); samarium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element europium = new Element("Europium", "Eu", 63, null, 151.964); iList.add(new Isotope("Europium-151", 151, 150.9198502)); iList.add(new Isotope("Europium-153", 153, 152.9212303)); europium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element gadolinium = new Element("Gadolinium", "Gd", 64, null, 157.25); iList.add(new Isotope("Gadolinium-152", 152, 151.919791)); iList.add(new Isotope("Gadolinium-154", 154, 153.9208656)); @@ -538,12 +534,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Gadolinium-160", 160, 159.9270541)); gadolinium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element terbium = new Element("Terbium", "Tb", 65, null, 158.92535); iList.add(new Isotope("Terbium-159", 159, 158.9253468)); terbium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element dysprosium = new Element("Dysprosium", "Dy", 66, null, 162.5); iList.add(new Isotope("Dysprosium-156", 156, 155.924283)); iList.add(new Isotope("Dysprosium-158", 158, 157.924409)); @@ -554,12 +550,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Dysprosium-164", 164, 163.9291748)); dysprosium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element holmium = new Element("Holmium", "Ho", 67, null, 164.93032); iList.add(new Isotope("Holmium-165", 165, 164.9303221)); holmium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element erbium = new Element("Erbium", "Er", 68, null, 167.259); iList.add(new Isotope("Erbium-162", 162, 161.928778)); iList.add(new Isotope("Erbium-164", 164, 163.9292)); @@ -569,12 +565,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Erbium-170", 170, 169.9354643)); erbium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element thulium = new Element("Thulium", "Tm", 69, null, 168.93421); iList.add(new Isotope("Thulium-169", 169, 168.9342133)); thulium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element ytterbium = new Element("Ytterbium", "Yb", 70, null, 173.054); iList.add(new Isotope("Ytterbium-168", 168, 167.933897)); iList.add(new Isotope("Ytterbium-170", 170, 169.9347618)); @@ -585,13 +581,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Ytterbium-176", 176, 175.9425717)); ytterbium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element lutetium = new Element("Lutetium", "Lu", 71, null, 174.9668); iList.add(new Isotope("Lutetium-175", 175, 174.9407718)); iList.add(new Isotope("Lutetium-176", 176, 175.9426863)); lutetium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element hafnium = new Element("Hafnium", "Hf", 72, null, 178.49); iList.add(new Isotope("Hafnium-174", 174, 173.940046)); iList.add(new Isotope("Hafnium-176", 176, 175.9414086)); @@ -601,13 +597,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Hafnium-180", 180, 179.94655)); hafnium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element tantalum = new Element("Tantalum", "Ta", 73, null, 180.94788); iList.add(new Isotope("Tantalum-180", 180, 179.9474648)); iList.add(new Isotope("Tantalum-181", 181, 180.9479958)); tantalum.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element tungsten = new Element("Tungsten", "W", 74, null, 183.84); iList.add(new Isotope("Tungsten-180", 180, 179.946704)); iList.add(new Isotope("Tungsten-182", 182, 181.9482042)); @@ -616,13 +612,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Tungsten-186", 186, 185.9543641)); tungsten.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element rhenium = new Element("Rhenium", "Re", 75, null, 186.207); iList.add(new Isotope("Rhenium-185", 185, 184.952955)); iList.add(new Isotope("Rhenium-187", 187, 186.9557531)); rhenium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element osmium = new Element("Osmium", "Os", 76, null, 190.23); iList.add(new Isotope("Osmium-184", 184, 183.9524891)); iList.add(new Isotope("Osmium-186", 186, 185.9538382)); @@ -633,13 +629,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Osmium-192", 192, 191.9614807)); osmium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element iridium = new Element("Iridium", "Ir", 77, null, 192.217); iList.add(new Isotope("Iridium-191", 191, 190.960594)); iList.add(new Isotope("Iridium-193", 193, 192.9629264)); iridium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element platinum = new Element("Platinum", "Pt", 78, null, 195.084); iList.add(new Isotope("Platinum-190", 190, 189.959932)); iList.add(new Isotope("Platinum-192", 192, 191.961038)); @@ -649,12 +645,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Platinum-198", 198, 197.967893)); platinum.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element gold = new Element("Gold", "Au", 79, null, 196.966569); iList.add(new Isotope("Gold-197", 197, 196.9665687)); gold.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element mercury = new Element("Mercury", "Hg", 80, null, 200.59); iList.add(new Isotope("Mercury-196", 196, 195.965833)); iList.add(new Isotope("Mercury-198", 198, 197.966769)); @@ -665,13 +661,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Mercury-204", 204, 203.9734939)); mercury.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element thallium = new Element("Thallium", "Tl", 81, null, 204.3833); iList.add(new Isotope("Thallium-203", 203, 202.9723442)); iList.add(new Isotope("Thallium-205", 205, 204.9744275)); thallium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element lead = new Element("Lead", "Pb", 82, null, 207.2); iList.add(new Isotope("Lead-204", 204, 203.9730436)); iList.add(new Isotope("Lead-206", 206, 205.9744653)); @@ -679,7 +675,7 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Lead-208", 208, 207.9766521)); lead.setIsotopes(iList); - List eList = new ArrayList(); + List eList = new ArrayList<>(); eList.add(hydrogen); eList.add(helium); eList.add(lithium); diff --git a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/GenerateJavaCodesFromTextTest.java b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/GenerateJavaCodesFromTextTest.java index 45515d9b11..ab2df5fec7 100644 --- a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/GenerateJavaCodesFromTextTest.java +++ b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/GenerateJavaCodesFromTextTest.java @@ -43,7 +43,7 @@ public class GenerateJavaCodesFromTextTest { //@Test public void generateCodes() throws IOException{ BufferedReader input = new BufferedReader(new FileReader("./src/test/resources/Symbol2Name.txt")); - Map symbol2Name = new HashMap(); + Map symbol2Name = new HashMap<>(); String line = input.readLine();//Header line is not required while((line = input.readLine()) != null){ String[] sA = line.split("\t"); @@ -52,10 +52,10 @@ public void generateCodes() throws IOException{ input.close(); input = new BufferedReader(new FileReader("./src/test/resources/Symbol2Weight.txt")); - List elementNameList = new ArrayList(); + List elementNameList = new ArrayList<>(); String elementName = null; String elementNameLower = null; - Double elementMass = null; + double elementMass; while((line = input.readLine()) != null){ String[] sA = line.split("\t"); if(sA[0].length() > 0){ @@ -90,7 +90,7 @@ public void generateCodes() throws IOException{ } private double cleanNumber(String s){ - int index = s.indexOf("("); + int index = s.indexOf('('); if(index != -1) s = s.substring(0, index); return Double.parseDouble(s.replace(" ", "").replace("[", "").replace("]", "")); } diff --git a/biojava-alignment/src/main/java/demo/CookbookMSA.java b/biojava-alignment/src/main/java/demo/CookbookMSA.java index d2952bbeac..c617745539 100644 --- a/biojava-alignment/src/main/java/demo/CookbookMSA.java +++ b/biojava-alignment/src/main/java/demo/CookbookMSA.java @@ -43,7 +43,7 @@ public static void main(String[] args) throws Exception { } private static void multipleSequenceAlignment(String[] ids) throws Exception { - List lst = new ArrayList(); + List lst = new ArrayList<>(); for (String id : ids) { lst.add(getSequenceForId(id)); } diff --git a/biojava-alignment/src/main/java/demo/DemoAlignProteins.java b/biojava-alignment/src/main/java/demo/DemoAlignProteins.java index 079dab8409..9aef5ed5fa 100644 --- a/biojava-alignment/src/main/java/demo/DemoAlignProteins.java +++ b/biojava-alignment/src/main/java/demo/DemoAlignProteins.java @@ -23,9 +23,9 @@ import org.biojava.nbio.alignment.Alignments; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; import org.biojava.nbio.alignment.SimpleGapPenalty; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.alignment.template.PairwiseSequenceAligner; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.ProteinSequence; diff --git a/biojava-alignment/src/main/java/demo/DemoDistanceTree.java b/biojava-alignment/src/main/java/demo/DemoDistanceTree.java index c9f82d39f7..cddbe85b01 100644 --- a/biojava-alignment/src/main/java/demo/DemoDistanceTree.java +++ b/biojava-alignment/src/main/java/demo/DemoDistanceTree.java @@ -20,9 +20,6 @@ */ package demo; -import java.io.InputStream; -import java.util.LinkedHashMap; - import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.MultipleSequenceAlignment; @@ -32,15 +29,14 @@ import org.biojava.nbio.core.sequence.io.FastaReader; import org.biojava.nbio.core.sequence.io.GenericFastaHeaderParser; import org.biojava.nbio.core.sequence.io.ProteinSequenceCreator; -import org.biojava.nbio.phylo.DistanceMatrixCalculator; -import org.biojava.nbio.phylo.DistanceTreeEvaluator; -import org.biojava.nbio.phylo.ForesterWrapper; -import org.biojava.nbio.phylo.TreeConstructor; -import org.biojava.nbio.phylo.TreeConstructorType; +import org.biojava.nbio.phylo.*; import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix; import org.forester.evoinference.matrix.distance.DistanceMatrix; import org.forester.phylogeny.Phylogeny; +import java.io.InputStream; +import java.util.LinkedHashMap; + /** * This demo contains the CookBook example to create a phylogenetic tree from a * multiple sequence alignment (MSA). @@ -57,12 +53,11 @@ public static void main(String[] args) throws Exception { InputStream inStream = TreeConstructor.class .getResourceAsStream("/PF00104_small.fasta"); - FastaReader fastaReader = - new FastaReader( - inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet - .getAminoAcidCompoundSet())); + FastaReader fastaReader = + new FastaReader<>( + inStream, + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap proteinSequences = fastaReader.process(); @@ -70,7 +65,7 @@ public static void main(String[] args) throws Exception { inStream.close(); MultipleSequenceAlignment msa = - new MultipleSequenceAlignment(); + new MultipleSequenceAlignment<>(); for (ProteinSequence proteinSequence : proteinSequences.values()) { msa.addAlignedSequence(proteinSequence); diff --git a/biojava-alignment/src/main/java/demo/TestDNANeedlemanWunsch.java b/biojava-alignment/src/main/java/demo/TestDNANeedlemanWunsch.java index c94e22d934..07ad2cda69 100644 --- a/biojava-alignment/src/main/java/demo/TestDNANeedlemanWunsch.java +++ b/biojava-alignment/src/main/java/demo/TestDNANeedlemanWunsch.java @@ -23,9 +23,9 @@ import org.biojava.nbio.alignment.Alignments; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; import org.biojava.nbio.alignment.SimpleGapPenalty; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.alignment.template.PairwiseSequenceAligner; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.sequence.DNASequence; import org.biojava.nbio.core.sequence.compound.AmbiguityDNACompoundSet; diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/Alignments.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/Alignments.java index 4ed72d0979..33967f0221 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/Alignments.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/Alignments.java @@ -23,12 +23,12 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.template.ProfilePair; -import org.biojava.nbio.core.alignment.template.SequencePair; +import org.biojava.nbio.alignment.template.*; import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.Profile; +import org.biojava.nbio.core.alignment.template.ProfilePair; +import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; -import org.biojava.nbio.alignment.template.*; import org.biojava.nbio.core.sequence.compound.AmbiguityDNACompoundSet; import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; import org.biojava.nbio.core.sequence.compound.DNACompoundSet; @@ -58,7 +58,7 @@ public class Alignments { /** * List of implemented sequence pair in a profile scoring routines. */ - public static enum PairInProfileScorerType { + public enum PairInProfileScorerType { IDENTITIES, // similar to MUSCLE SIMILARITIES } @@ -66,7 +66,7 @@ public static enum PairInProfileScorerType { /** * List of implemented pairwise sequence alignment routines. */ - public static enum PairwiseSequenceAlignerType { + public enum PairwiseSequenceAlignerType { GLOBAL, // Needleman-Wunsch/Gotoh GLOBAL_LINEAR_SPACE, // Guan-Uberbacher LOCAL, // Smith-Waterman/Gotoh @@ -76,7 +76,7 @@ public static enum PairwiseSequenceAlignerType { /** * List of implemented pairwise sequence scoring routines. */ - public static enum PairwiseSequenceScorerType { + public enum PairwiseSequenceScorerType { GLOBAL, GLOBAL_IDENTITIES, // similar to CLUSTALW and CLUSTALW2 GLOBAL_SIMILARITIES, @@ -90,7 +90,7 @@ public static enum PairwiseSequenceScorerType { /** * List of implemented profile-profile alignment routines. */ - public static enum ProfileProfileAlignerType { + public enum ProfileProfileAlignerType { GLOBAL, // similar to MUSCLE and KALIGN GLOBAL_LINEAR_SPACE, // similar to CLUSTALW and CLUSTALW2 GLOBAL_CONSENSUS, // similar to CLUSTAL @@ -102,7 +102,7 @@ public static enum ProfileProfileAlignerType { /** * List of implemented profile refinement routines. */ - public static enum RefinerType { + public enum RefinerType { PARTITION_SINGLE, // similar to CLUSTALW2 PARTITION_SINGLE_ALL, // similar to CLUSTALW2 PARTITION_TREE, // similar to MUSCLE @@ -150,7 +150,7 @@ public static , C extends Compound> Profile getMulti PairwiseSequenceScorerType ps = PairwiseSequenceScorerType.GLOBAL_IDENTITIES; GapPenalty gapPenalty = new SimpleGapPenalty(); SubstitutionMatrix subMatrix = null; - if (cs == AminoAcidCompoundSet.getAminoAcidCompoundSet()) { + if (cs == AminoAcidCompoundSet.aminoAcidCompoundSet) { @SuppressWarnings("unchecked") // compound types must be equal since compound sets are equal SubstitutionMatrix temp = (SubstitutionMatrix) SubstitutionMatrixHelper.getBlosum62(); subMatrix = temp; @@ -189,7 +189,7 @@ public static , C extends Compound> Profile getMulti runPairwiseScorers(scorers); // stage 2: hierarchical clustering into a guide tree - GuideTree tree = new GuideTree(sequences, scorers); + GuideTree tree = new GuideTree<>(sequences, scorers); scorers = null; // stage 3: progressive alignment @@ -233,7 +233,7 @@ public static , C extends Compound> SequencePair get static , C extends Compound> List> getAllPairsAligners( List sequences, PairwiseSequenceAlignerType type, GapPenalty gapPenalty, SubstitutionMatrix subMatrix) { - List> allPairs = new ArrayList>(); + List> allPairs = new ArrayList<>(); for (int i = 0; i < sequences.size(); i++) { for (int j = i+1; j < sequences.size(); j++) { allPairs.add(getPairwiseAligner(sequences.get(i), sequences.get(j), type, gapPenalty, subMatrix)); @@ -256,7 +256,7 @@ static , C extends Compound> List, C extends Compound> List> getAllPairsScorers( List sequences, PairwiseSequenceScorerType type, GapPenalty gapPenalty, SubstitutionMatrix subMatrix) { - List> allPairs = new ArrayList>(); + List> allPairs = new ArrayList<>(); for (int i = 0; i < sequences.size(); i++) { for (int j = i+1; j < sequences.size(); j++) { allPairs.add(getPairwiseScorer(sequences.get(i), sequences.get(j), type, gapPenalty, subMatrix)); @@ -291,7 +291,7 @@ public static , C extends Compound> double[] getAllPairsSc * @return calculated elements */ static List getListFromFutures(List> futures) { - List list = new ArrayList(); + List list = new ArrayList<>(); for (Future f : futures) { // TODO when added to ConcurrencyTools, log completions and exceptions instead of printing stack traces try { @@ -326,9 +326,9 @@ public static , C extends Compound> PairwiseSequenceAligne switch (type) { default: case GLOBAL: - return new NeedlemanWunsch(query, target, gapPenalty, subMatrix); + return new NeedlemanWunsch<>(query, target, gapPenalty, subMatrix); case LOCAL: - return new SmithWaterman(query, target, gapPenalty, subMatrix); + return new SmithWaterman<>(query, target, gapPenalty, subMatrix); case GLOBAL_LINEAR_SPACE: case LOCAL_LINEAR_SPACE: // TODO other alignment options (Myers-Miller, Thompson) @@ -374,18 +374,18 @@ static , C extends Compound> PairwiseSequenceScorer case GLOBAL: return getPairwiseAligner(query, target, PairwiseSequenceAlignerType.GLOBAL, gapPenalty, subMatrix); case GLOBAL_IDENTITIES: - return new FractionalIdentityScorer(getPairwiseAligner(query, target, + return new FractionalIdentityScorer<>(getPairwiseAligner(query, target, PairwiseSequenceAlignerType.GLOBAL, gapPenalty, subMatrix)); case GLOBAL_SIMILARITIES: - return new FractionalSimilarityScorer(getPairwiseAligner(query, target, + return new FractionalSimilarityScorer<>(getPairwiseAligner(query, target, PairwiseSequenceAlignerType.GLOBAL, gapPenalty, subMatrix)); case LOCAL: return getPairwiseAligner(query, target, PairwiseSequenceAlignerType.LOCAL, gapPenalty, subMatrix); case LOCAL_IDENTITIES: - return new FractionalIdentityScorer(getPairwiseAligner(query, target, + return new FractionalIdentityScorer<>(getPairwiseAligner(query, target, PairwiseSequenceAlignerType.LOCAL, gapPenalty, subMatrix)); case LOCAL_SIMILARITIES: - return new FractionalSimilarityScorer(getPairwiseAligner(query, target, + return new FractionalSimilarityScorer<>(getPairwiseAligner(query, target, PairwiseSequenceAlignerType.LOCAL, gapPenalty, subMatrix)); case KMERS: case WU_MANBER: @@ -413,7 +413,7 @@ static , C extends Compound> ProfileProfileAligner g switch (type) { default: case GLOBAL: - return new SimpleProfileProfileAligner(profile1, profile2, gapPenalty, subMatrix); + return new SimpleProfileProfileAligner<>(profile1, profile2, gapPenalty, subMatrix); case GLOBAL_LINEAR_SPACE: case GLOBAL_CONSENSUS: case LOCAL: @@ -443,7 +443,7 @@ static , C extends Compound> ProfileProfileAligner g switch (type) { default: case GLOBAL: - return new SimpleProfileProfileAligner(profile1, profile2, gapPenalty, subMatrix); + return new SimpleProfileProfileAligner<>(profile1, profile2, gapPenalty, subMatrix); case GLOBAL_LINEAR_SPACE: case GLOBAL_CONSENSUS: case LOCAL: @@ -473,7 +473,7 @@ static , C extends Compound> ProfileProfileAligner g switch (type) { default: case GLOBAL: - return new SimpleProfileProfileAligner(profile1, profile2, gapPenalty, subMatrix); + return new SimpleProfileProfileAligner<>(profile1, profile2, gapPenalty, subMatrix); case GLOBAL_LINEAR_SPACE: case GLOBAL_CONSENSUS: case LOCAL: @@ -503,7 +503,7 @@ static , C extends Compound> ProfileProfileAligner g switch (type) { default: case GLOBAL: - return new SimpleProfileProfileAligner(profile1, profile2, gapPenalty, subMatrix); + return new SimpleProfileProfileAligner<>(profile1, profile2, gapPenalty, subMatrix); case GLOBAL_LINEAR_SPACE: case GLOBAL_CONSENSUS: case LOCAL: @@ -550,7 +550,7 @@ public static , C extends Compound> Profile getProgr ProfileProfileAlignerType type, GapPenalty gapPenalty, SubstitutionMatrix subMatrix) { // find inner nodes in post-order traversal of tree (each leaf node has a single sequence profile) - List> innerNodes = new ArrayList>(); + List> innerNodes = new ArrayList<>(); for (GuideTreeNode n : tree) { if (n.getProfile() == null) { innerNodes.add(n); @@ -567,7 +567,7 @@ public static , C extends Compound> Profile getProgr getProfileProfileAligner(p1, pf2, type, gapPenalty, subMatrix)) : ((p2 != null) ? getProfileProfileAligner(pf1, p2, type, gapPenalty, subMatrix) : getProfileProfileAligner(pf1, pf2, type, gapPenalty, subMatrix)); - n.setProfileFuture(ConcurrencyTools.submit(new CallableProfileProfileAligner(aligner), String.format( + n.setProfileFuture(ConcurrencyTools.submit(new CallableProfileProfileAligner<>(aligner), String.format( "Aligning pair %d of %d", i++, all))); } @@ -599,9 +599,9 @@ public static , C extends Compound> Profile getProgr static , C extends Compound> List> runPairwiseAligners(List> aligners) { int n = 1, all = aligners.size(); - List>> futures = new ArrayList>>(); + List>> futures = new ArrayList<>(); for (PairwiseSequenceAligner aligner : aligners) { - futures.add(ConcurrencyTools.submit(new CallablePairwiseSequenceAligner(aligner), + futures.add(ConcurrencyTools.submit(new CallablePairwiseSequenceAligner<>(aligner), String.format("Aligning pair %d of %d", n++, all))); } return getListFromFutures(futures); @@ -619,9 +619,9 @@ public static , C extends Compound> Profile getProgr public static , C extends Compound> double[] runPairwiseScorers( List> scorers) { int n = 1, all = scorers.size(); - List> futures = new ArrayList>(); + List> futures = new ArrayList<>(); for (PairwiseSequenceScorer scorer : scorers) { - futures.add(ConcurrencyTools.submit(new CallablePairwiseSequenceScorer(scorer), + futures.add(ConcurrencyTools.submit(new CallablePairwiseSequenceScorer<>(scorer), String.format("Scoring pair %d of %d", n++, all))); } List results = getListFromFutures(futures); @@ -644,9 +644,9 @@ public static , C extends Compound> double[] runPairwiseSc static , C extends Compound> List> runProfileAligners(List> aligners) { int n = 1, all = aligners.size(); - List>> futures = new ArrayList>>(); + List>> futures = new ArrayList<>(); for (ProfileProfileAligner aligner : aligners) { - futures.add(ConcurrencyTools.submit(new CallableProfileProfileAligner(aligner), + futures.add(ConcurrencyTools.submit(new CallableProfileProfileAligner<>(aligner), String.format("Aligning pair %d of %d", n++, all))); } return getListFromFutures(futures); diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalIdentityInProfileScorer.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalIdentityInProfileScorer.java index c84ea753d9..5d0006ba0d 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalIdentityInProfileScorer.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalIdentityInProfileScorer.java @@ -23,9 +23,9 @@ package org.biojava.nbio.alignment; +import org.biojava.nbio.alignment.template.PairInProfileScorer; import org.biojava.nbio.core.alignment.SimpleSequencePair; import org.biojava.nbio.core.alignment.template.AlignedSequence; -import org.biojava.nbio.alignment.template.PairInProfileScorer; import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; @@ -41,7 +41,7 @@ public class FractionalIdentityInProfileScorer, C extends Compound> extends FractionalIdentityScorer implements PairInProfileScorer { - private Profile profile; + private final Profile profile; /** * Creates a fractional identity scorer for an aligned pair of sequences in the given alignment profile. @@ -51,7 +51,7 @@ public class FractionalIdentityInProfileScorer, C extends * @param target index in the profile of the second sequence of the pair */ public FractionalIdentityInProfileScorer(Profile profile, int query, int target) { - super(new SimpleSequencePair(profile.getAlignedSequence(query), profile.getAlignedSequence(target))); + super(new SimpleSequencePair<>(profile.getAlignedSequence(query), profile.getAlignedSequence(target))); this.profile = profile; } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalIdentityScorer.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalIdentityScorer.java index 4b494db779..538f7a97ec 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalIdentityScorer.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalIdentityScorer.java @@ -23,8 +23,10 @@ package org.biojava.nbio.alignment; +import org.biojava.nbio.alignment.template.AbstractScorer; +import org.biojava.nbio.alignment.template.PairwiseSequenceAligner; +import org.biojava.nbio.alignment.template.PairwiseSequenceScorer; import org.biojava.nbio.core.alignment.template.SequencePair; -import org.biojava.nbio.alignment.template.*; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; @@ -40,7 +42,8 @@ public class FractionalIdentityScorer, C extends Compound> implements PairwiseSequenceScorer { // always stored - private S query, target; + private final S query; + private final S target; private int max, score; // optional cached input field diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalSimilarityInProfileScorer.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalSimilarityInProfileScorer.java index ecd975d459..de826a6d4c 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalSimilarityInProfileScorer.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalSimilarityInProfileScorer.java @@ -23,9 +23,9 @@ package org.biojava.nbio.alignment; +import org.biojava.nbio.alignment.template.PairInProfileScorer; import org.biojava.nbio.core.alignment.SimpleSequencePair; import org.biojava.nbio.core.alignment.template.AlignedSequence; -import org.biojava.nbio.alignment.template.PairInProfileScorer; import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; @@ -41,7 +41,7 @@ public class FractionalSimilarityInProfileScorer, C extends Compound> extends FractionalSimilarityScorer implements PairInProfileScorer { - private Profile profile; + private final Profile profile; /** * Creates a fractional similarity scorer for an aligned pair of sequences in the given alignment profile. @@ -51,7 +51,7 @@ public class FractionalSimilarityInProfileScorer, C extend * @param target index in the profile of the second sequence of the pair */ public FractionalSimilarityInProfileScorer(Profile profile, int query, int target) { - super(new SimpleSequencePair(profile.getAlignedSequence(query), profile.getAlignedSequence(target))); + super(new SimpleSequencePair<>(profile.getAlignedSequence(query), profile.getAlignedSequence(target))); this.profile = profile; } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalSimilarityScorer.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalSimilarityScorer.java index 05911367f8..df59360b1b 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalSimilarityScorer.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalSimilarityScorer.java @@ -23,8 +23,10 @@ package org.biojava.nbio.alignment; +import org.biojava.nbio.alignment.template.AbstractScorer; +import org.biojava.nbio.alignment.template.PairwiseSequenceAligner; +import org.biojava.nbio.alignment.template.PairwiseSequenceScorer; import org.biojava.nbio.core.alignment.template.SequencePair; -import org.biojava.nbio.alignment.template.*; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; @@ -40,7 +42,8 @@ public class FractionalSimilarityScorer, C extends Compoun implements PairwiseSequenceScorer { // always stored - private S query, target; + private final S query; + private final S target; private int max, score; // optional cached input field diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/GuideTree.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/GuideTree.java index ecbcf66e79..a1fdddc364 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/GuideTree.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/GuideTree.java @@ -23,9 +23,9 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.SimpleProfile; import org.biojava.nbio.alignment.template.GuideTreeNode; import org.biojava.nbio.alignment.template.PairwiseSequenceScorer; +import org.biojava.nbio.core.alignment.SimpleProfile; import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.alignment.template.ProfilePair; import org.biojava.nbio.core.sequence.AccessionID; @@ -39,7 +39,6 @@ import org.forester.phylogeny.PhylogenyNode; import javax.swing.tree.TreeNode; - import java.util.*; import java.util.concurrent.Future; @@ -54,11 +53,11 @@ */ public class GuideTree, C extends Compound> implements Iterable> { - private List sequences; - private List> scorers; - private BasicSymmetricalDistanceMatrix distances; - private String newick; - private Node root; + private final List sequences; + private final List> scorers; + private final BasicSymmetricalDistanceMatrix distances; + private final String newick; + private final Node root; /** * Creates a guide tree for use during progressive multiple sequence alignment. @@ -170,10 +169,13 @@ public String toString() { */ public class Node implements GuideTreeNode { - private GuideTreeNode parent, child1, child2; - private double distance; - private String name; - private boolean isLeaf, isVisited; + private final GuideTreeNode parent; + private GuideTreeNode child1; + private GuideTreeNode child2; + private final double distance; + private final String name; + private final boolean isLeaf; + private boolean isVisited; private Profile profile; private Future> profileFuture; @@ -182,7 +184,7 @@ private Node(PhylogenyNode node, Node parent) { distance = node.getDistanceToParent(); name = node.getName(); if(isLeaf = node.isExternal()) { - profile = new SimpleProfile(sequences.get(distances.getIndex(name))); + profile = new SimpleProfile<>(sequences.get(distances.getIndex(name))); } else { child1 = new Node(node.getChildNode1(), this); child2 = new Node(node.getChildNode2(), this); @@ -237,7 +239,7 @@ public void setProfileFuture(Future> profileFuture) { @Override public Enumeration> children() { - Vector> children = new Vector>(); + Vector> children = new Vector<>(); children.add(getChild1()); children.add(getChild2()); return children.elements(); @@ -301,11 +303,11 @@ private void visit() { // helper class that defines the default post-order (leaves to root) traversal private class PostOrderIterator implements Iterator> { - private Stack nodes; + private final Stack nodes; private PostOrderIterator() { getRoot().clearVisited(); - nodes = new Stack(); + nodes = new Stack<>(); nodes.push(getRoot()); } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/NeedlemanWunsch.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/NeedlemanWunsch.java index 81fc49d803..1f9aeefa21 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/NeedlemanWunsch.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/NeedlemanWunsch.java @@ -24,8 +24,8 @@ package org.biojava.nbio.alignment; import org.biojava.nbio.alignment.routines.AnchoredPairwiseSequenceAligner; -import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.alignment.template.GapPenalty; +import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SimpleGapPenalty.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SimpleGapPenalty.java index d45c2a1bc8..54e0e0f967 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SimpleGapPenalty.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SimpleGapPenalty.java @@ -23,10 +23,10 @@ package org.biojava.nbio.alignment; -import java.io.Serializable; - import org.biojava.nbio.alignment.template.GapPenalty; +import java.io.Serializable; + /** * Implements a data structure for the gap penalties used during a sequence alignment routine. * diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SimpleProfileProfileAligner.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SimpleProfileProfileAligner.java index 73579ab8f4..fb4c3011e0 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SimpleProfileProfileAligner.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SimpleProfileProfileAligner.java @@ -23,12 +23,14 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.template.ProfilePair; -import org.biojava.nbio.core.alignment.template.Profile; -import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; +import org.biojava.nbio.alignment.template.AbstractProfileProfileAligner; +import org.biojava.nbio.alignment.template.Aligner; +import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.core.alignment.SimpleProfilePair; -import org.biojava.nbio.alignment.template.*; import org.biojava.nbio.core.alignment.template.AlignedSequence.Step; +import org.biojava.nbio.core.alignment.template.Profile; +import org.biojava.nbio.core.alignment.template.ProfilePair; +import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; @@ -110,7 +112,7 @@ public SimpleProfileProfileAligner(Future> query, Profile sx, List sy) { - profile = pair = new SimpleProfilePair(getQuery(), getTarget(), sx, sy); + profile = pair = new SimpleProfilePair<>(getQuery(), getTarget(), sx, sy); } } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SmithWaterman.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SmithWaterman.java index 7d7e017694..6317a6341a 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SmithWaterman.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SmithWaterman.java @@ -23,11 +23,11 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.SimpleSequencePair; import org.biojava.nbio.alignment.template.AbstractPairwiseSequenceAligner; +import org.biojava.nbio.alignment.template.GapPenalty; +import org.biojava.nbio.core.alignment.SimpleSequencePair; import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.core.alignment.template.AlignedSequence.Step; -import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; @@ -69,7 +69,7 @@ public SmithWaterman(S query, S target, GapPenalty gapPenalty, SubstitutionMatri @Override protected void setProfile(List sx, List sy) { - profile = pair = new SimpleSequencePair(getQuery(), getTarget(), sx, xyStart[0], + profile = pair = new SimpleSequencePair<>(getQuery(), getTarget(), sx, xyStart[0], getQuery().getLength() - xyMax[0], sy, xyStart[1], getTarget().getLength() - xyMax[1]); } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/StandardRescoreRefiner.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/StandardRescoreRefiner.java index 40c8dc1e76..e0e7d553fb 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/StandardRescoreRefiner.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/StandardRescoreRefiner.java @@ -26,16 +26,16 @@ import org.biojava.nbio.alignment.Alignments.PairInProfileScorerType; import org.biojava.nbio.alignment.Alignments.ProfileProfileAlignerType; import org.biojava.nbio.alignment.template.AbstractScorer; -import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.alignment.template.RescoreRefiner; +import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; public class StandardRescoreRefiner, C extends Compound> extends AbstractScorer implements RescoreRefiner { - private PairInProfileScorerType pips; - private ProfileProfileAlignerType ppa; + private final PairInProfileScorerType pips; + private final ProfileProfileAlignerType ppa; public StandardRescoreRefiner(PairInProfileScorerType pips, ProfileProfileAlignerType ppa) { this.pips = pips; diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SubstitutionMatrixScorer.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SubstitutionMatrixScorer.java index a903ebd1ce..a2a531c8ad 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SubstitutionMatrixScorer.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SubstitutionMatrixScorer.java @@ -40,8 +40,8 @@ public class SubstitutionMatrixScorer, C extends Compound> private final SubstitutionMatrix matrix; - private S query; - private S target; + private final S query; + private final S target; private double score; public SubstitutionMatrixScorer(SequencePair pair, SubstitutionMatrix matrix) { diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmFileAnnotation.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmFileAnnotation.java index ddeb03b451..7e5cbfa325 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmFileAnnotation.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmFileAnnotation.java @@ -125,7 +125,7 @@ public void setRefLocation(String refLocation) { private Set dbReferences; private StringBuffer refComment; /**TODO When implementing toString(), the function should loop on the vector */ - private Vector references = new Vector(); + private Vector references = new Vector<>(); private StringBuffer keywords; private CharSequence comment; private StringBuffer pfamAccession; @@ -137,7 +137,7 @@ public void setRefLocation(String refLocation) { private float falseDiscoveryRate; public StockholmFileAnnotation() { - embTrees = new HashMap>(); + embTrees = new HashMap<>(); } public StringBuffer getDbComment() { @@ -164,7 +164,7 @@ public void setDbReferences(Set dbReferences) { */ public void addDBReference(String dbReferenceRepresentingString) { if (this.dbReferences == null) { - this.dbReferences = new HashSet(); + this.dbReferences = new HashSet<>(); } dbReferences.add(new DatabaseReference(dbReferenceRepresentingString)); } @@ -492,7 +492,7 @@ public void setGFMembership(String membership) { public void addGFNewHampshire(String newHampshire) { List hampshireTree = embTrees.get(TREE_DEFAULT_ID); if (hampshireTree == null) { - hampshireTree = new ArrayList(); + hampshireTree = new ArrayList<>(); } hampshireTree.add(newHampshire); embTrees.put(TREE_DEFAULT_ID, hampshireTree); diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmFileParser.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmFileParser.java index eb92301be9..5180bf1dbb 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmFileParser.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmFileParser.java @@ -356,7 +356,7 @@ public List parse(InputStream inStream, int max) throws IOEx if (internalScanner == null) { internalScanner = new Scanner(inStream); } - ArrayList structures = new ArrayList(); + ArrayList structures = new ArrayList<>(); while (max != INFINITY && max-- > 0) { StockholmStructure structure = parse(internalScanner); if (structure != null) { @@ -399,7 +399,7 @@ StockholmStructure parse(Scanner scanner) throws ParserException, IOException { throw new IllegalArgumentException("No Scanner defined"); } } - String line = null; + String line; int linesCount = 0; try { while (scanner.hasNextLine()) { @@ -507,9 +507,8 @@ StockholmStructure parse(Scanner scanner) throws ParserException, IOException { if (structure != null) { int length = -1; Map sequences = structure.getSequences(); - for (String sequencename : sequences.keySet()) { - StringBuffer sequence = sequences.get(sequencename); - if (length == -1) { + for (StringBuffer sequence : sequences.values()) { + if (length == -1) { length = sequence.length(); } else if (length != sequence.length()) { throw new RuntimeException("Sequences have different lengths"); @@ -544,79 +543,114 @@ private void handleSequenceLine(String line) throws ParserException { * the line to be parsed */ private void handleFileAnnotation(String featureName, String value) { - if (featureName.equals(GF_ACCESSION_NUMBER)) { - stockholmStructure.getFileAnnotation().setGFAccessionNumber(value); - } else if (featureName.equals(GF_IDENTIFICATION)) { - stockholmStructure.getFileAnnotation().setGFIdentification(value); - } else if (featureName.equals(GF_DB_REFERENCE)) { - stockholmStructure.getFileAnnotation().addDBReference(value); - } else if (featureName.equals(GF_DEFINITION)) { - stockholmStructure.getFileAnnotation().setGFDefinition(value); - } else if (featureName.equals(GF_AUTHOR)) { - stockholmStructure.getFileAnnotation().setGFAuthors(value); - } else if (featureName.equals(GF_ALIGNMENT_METHOD)) { - stockholmStructure.getFileAnnotation().setAlignmentMethod(value); - } else if (featureName.equals(GF_BUILD_METHOD)) { - stockholmStructure.getFileAnnotation().addGFBuildMethod(value); - } else if (featureName.equals(GF_SEARCH_METHOD)) { - stockholmStructure.getFileAnnotation().setGFSearchMethod(value); - } else if (featureName.equals(GF_SOURCE_SEED)) { - stockholmStructure.getFileAnnotation().setGFSourceSeed(value); - } else if (featureName.equals(GF_SOURCE_STRUCTURE)) { - stockholmStructure.getFileAnnotation().setGFSourceStructure(value); - } else if (featureName.equals(GF_GATHERING_THRESHOLD)) { - stockholmStructure.getFileAnnotation().setGFGatheringThreshs(value); - } else if (featureName.equals(GF_TRUSTED_CUTOFF)) { - stockholmStructure.getFileAnnotation().setGFTrustedCutoffs(value); - } else if (featureName.equals(GF_NOISE_CUTOFF)) { - stockholmStructure.getFileAnnotation().setGFNoiseCutoffs(value); - } else if (featureName.equals(GF_TYPE_FIELD)) { - stockholmStructure.getFileAnnotation().setGFTypeField(value); - } else if (featureName.equals(GF_PREVIOUS_IDS)) { - stockholmStructure.getFileAnnotation().setGFPreviousIDs(value); - } else if (featureName.equals(GF_SEQUENCE)) { - // status = STATUS_IN_SEQUENCE; - stockholmStructure.getFileAnnotation().setGFNumSequences(value); - } else if (featureName.equals(GF_DB_COMMENT)) { - stockholmStructure.getFileAnnotation().setGFDBComment(value); - // } else if (featureName.equals(GF_DB_REFERENCE)) { - // stockholmStructure.getFileAnnotation().addDBReference(value); - } else if (featureName.equals(GF_REFERENCE_COMMENT)) { - stockholmStructure.getFileAnnotation().setGFRefComment(value); - } else if (featureName.equals(GF_REFERENCE_NUMBER)) { - StockholmFileAnnotationReference reference = new StockholmFileAnnotationReference(); - stockholmStructure.getFileAnnotation().getReferences().add(reference); - } else if (featureName.equals(GF_REFERENCE_MEDLINE)) { - stockholmStructure.getFileAnnotation().getReferences().lastElement().setRefMedline(value); - } else if (featureName.equals(GF_REFERENCE_TITLE)) { - stockholmStructure.getFileAnnotation().getReferences().lastElement().addToRefTitle(value); - } else if (featureName.equals(GF_REFERENCE_AUTHOR)) { - stockholmStructure.getFileAnnotation().getReferences().lastElement().addToRefAuthor(value); - } else if (featureName.equals(GF_REFERENCE_LOCALTION)) { - stockholmStructure.getFileAnnotation().getReferences().lastElement().setRefLocation(value); - } else if (featureName.equals(GF_KEYWORDS)) { - stockholmStructure.getFileAnnotation().setGFKeywords(value); - } else if (featureName.equals(GF_COMMENT)) { - stockholmStructure.getFileAnnotation().addToGFComment(value); - } else if (featureName.equals(GF_PFAM_ACCESSION)) { - stockholmStructure.getFileAnnotation().setGFPfamAccession(value); - } else if (featureName.equals(GF_LOCATION)) { - stockholmStructure.getFileAnnotation().setGFLocation(value); - } else if (featureName.equals(GF_WIKIPEDIA_LINK)) { - stockholmStructure.getFileAnnotation().setGFWikipediaLink(value); - } else if (featureName.equals(GF_CLAN)) { - stockholmStructure.getFileAnnotation().setGFClan(value); - } else if (featureName.equals(GF_MEMBERSHIP)) { - stockholmStructure.getFileAnnotation().setGFMembership(value); - } else if (featureName.equals(GF_NEW_HAMPSHIRE)) { - stockholmStructure.getFileAnnotation().addGFNewHampshire(value); - } else if (featureName.equals(GF_TREE_ID)) { - stockholmStructure.getFileAnnotation().addGFTreeID(value); - } else if (featureName.equals(GF_FALSE_DISCOVERY_RATE)) { - stockholmStructure.getFileAnnotation().addGFFalseDiscoveryRate(value); - } else { - // unknown feature - logger.warn("Unknown File Feature [{}].\nPlease contact the Biojava team.", featureName); + switch (featureName) { + case GF_ACCESSION_NUMBER: + stockholmStructure.getFileAnnotation().setGFAccessionNumber(value); + break; + case GF_IDENTIFICATION: + stockholmStructure.getFileAnnotation().setGFIdentification(value); + break; + case GF_DB_REFERENCE: + stockholmStructure.getFileAnnotation().addDBReference(value); + break; + case GF_DEFINITION: + stockholmStructure.getFileAnnotation().setGFDefinition(value); + break; + case GF_AUTHOR: + stockholmStructure.getFileAnnotation().setGFAuthors(value); + break; + case GF_ALIGNMENT_METHOD: + stockholmStructure.getFileAnnotation().setAlignmentMethod(value); + break; + case GF_BUILD_METHOD: + stockholmStructure.getFileAnnotation().addGFBuildMethod(value); + break; + case GF_SEARCH_METHOD: + stockholmStructure.getFileAnnotation().setGFSearchMethod(value); + break; + case GF_SOURCE_SEED: + stockholmStructure.getFileAnnotation().setGFSourceSeed(value); + break; + case GF_SOURCE_STRUCTURE: + stockholmStructure.getFileAnnotation().setGFSourceStructure(value); + break; + case GF_GATHERING_THRESHOLD: + stockholmStructure.getFileAnnotation().setGFGatheringThreshs(value); + break; + case GF_TRUSTED_CUTOFF: + stockholmStructure.getFileAnnotation().setGFTrustedCutoffs(value); + break; + case GF_NOISE_CUTOFF: + stockholmStructure.getFileAnnotation().setGFNoiseCutoffs(value); + break; + case GF_TYPE_FIELD: + stockholmStructure.getFileAnnotation().setGFTypeField(value); + break; + case GF_PREVIOUS_IDS: + stockholmStructure.getFileAnnotation().setGFPreviousIDs(value); + break; + case GF_SEQUENCE: + // status = STATUS_IN_SEQUENCE; + stockholmStructure.getFileAnnotation().setGFNumSequences(value); + break; + case GF_DB_COMMENT: + stockholmStructure.getFileAnnotation().setGFDBComment(value); + // } else if (featureName.equals(GF_DB_REFERENCE)) { + // stockholmStructure.getFileAnnotation().addDBReference(value); + break; + case GF_REFERENCE_COMMENT: + stockholmStructure.getFileAnnotation().setGFRefComment(value); + break; + case GF_REFERENCE_NUMBER: + StockholmFileAnnotationReference reference = new StockholmFileAnnotationReference(); + stockholmStructure.getFileAnnotation().getReferences().add(reference); + break; + case GF_REFERENCE_MEDLINE: + stockholmStructure.getFileAnnotation().getReferences().lastElement().setRefMedline(value); + break; + case GF_REFERENCE_TITLE: + stockholmStructure.getFileAnnotation().getReferences().lastElement().addToRefTitle(value); + break; + case GF_REFERENCE_AUTHOR: + stockholmStructure.getFileAnnotation().getReferences().lastElement().addToRefAuthor(value); + break; + case GF_REFERENCE_LOCALTION: + stockholmStructure.getFileAnnotation().getReferences().lastElement().setRefLocation(value); + break; + case GF_KEYWORDS: + stockholmStructure.getFileAnnotation().setGFKeywords(value); + break; + case GF_COMMENT: + stockholmStructure.getFileAnnotation().addToGFComment(value); + break; + case GF_PFAM_ACCESSION: + stockholmStructure.getFileAnnotation().setGFPfamAccession(value); + break; + case GF_LOCATION: + stockholmStructure.getFileAnnotation().setGFLocation(value); + break; + case GF_WIKIPEDIA_LINK: + stockholmStructure.getFileAnnotation().setGFWikipediaLink(value); + break; + case GF_CLAN: + stockholmStructure.getFileAnnotation().setGFClan(value); + break; + case GF_MEMBERSHIP: + stockholmStructure.getFileAnnotation().setGFMembership(value); + break; + case GF_NEW_HAMPSHIRE: + stockholmStructure.getFileAnnotation().addGFNewHampshire(value); + break; + case GF_TREE_ID: + stockholmStructure.getFileAnnotation().addGFTreeID(value); + break; + case GF_FALSE_DISCOVERY_RATE: + stockholmStructure.getFileAnnotation().addGFFalseDiscoveryRate(value); + break; + default: + // unknown feature + logger.warn("Unknown File Feature [{}].\nPlease contact the Biojava team.", featureName); + break; } } @@ -630,33 +664,47 @@ private void handleFileAnnotation(String featureName, String value) { * the line to be parsed. */ private void handleConsensusAnnotation(String featureName, String value) { - if (featureName.equals(GC_SECONDARY_STRUCTURE)) { - stockholmStructure.getConsAnnotation().setSecondaryStructure(value); - } else if (featureName.equals(GC_SEQUENSE_CONSENSUS)) { - stockholmStructure.getConsAnnotation().setSequenceConsensus(value); - } else if (featureName.equals(GC_SURFACE_ACCESSIBILITY)) { - stockholmStructure.getConsAnnotation().setSurfaceAccessibility(value); - } else if (featureName.equals(GC_TRANS_MEMBRANE)) { - stockholmStructure.getConsAnnotation().setTransMembrane(value); - } else if (featureName.equals(GC_POSTERIOR_PROBABILITY)) { - stockholmStructure.getConsAnnotation().setPosteriorProbability(value); - } else if (featureName.equals(GC_LIGAND_BINDING)) { - stockholmStructure.getConsAnnotation().setLigandBinding(value); - } else if (featureName.equals(GC_ACTIVE_SITE)) { - stockholmStructure.getConsAnnotation().setActiveSite(value); - } else if (featureName.equals(GC_AS_PFAM_PREDICTED)) { - stockholmStructure.getConsAnnotation().setAsPFamPredicted(value); - } else if (featureName.equals(GC_AS_SWISSPROT)) { - stockholmStructure.getConsAnnotation().setAsSwissProt(value); - } else if (featureName.equals(GC_INTRON)) { - stockholmStructure.getConsAnnotation().setIntron(value); - } else if (featureName.equals(GC_REFERENCE_ANNOTATION)) { - stockholmStructure.getConsAnnotation().setReferenceAnnotation(value); - } else if (featureName.equals(GC_MODEL_MASK)) { - stockholmStructure.getConsAnnotation().setModelMask(value); - } else { - // unknown feature - logger.warn("Unknown Consensus Feature [{}].\nPlease contact the Biojava team.", featureName); + switch (featureName) { + case GC_SECONDARY_STRUCTURE: + stockholmStructure.getConsAnnotation().setSecondaryStructure(value); + break; + case GC_SEQUENSE_CONSENSUS: + stockholmStructure.getConsAnnotation().setSequenceConsensus(value); + break; + case GC_SURFACE_ACCESSIBILITY: + stockholmStructure.getConsAnnotation().setSurfaceAccessibility(value); + break; + case GC_TRANS_MEMBRANE: + stockholmStructure.getConsAnnotation().setTransMembrane(value); + break; + case GC_POSTERIOR_PROBABILITY: + stockholmStructure.getConsAnnotation().setPosteriorProbability(value); + break; + case GC_LIGAND_BINDING: + stockholmStructure.getConsAnnotation().setLigandBinding(value); + break; + case GC_ACTIVE_SITE: + stockholmStructure.getConsAnnotation().setActiveSite(value); + break; + case GC_AS_PFAM_PREDICTED: + stockholmStructure.getConsAnnotation().setAsPFamPredicted(value); + break; + case GC_AS_SWISSPROT: + stockholmStructure.getConsAnnotation().setAsSwissProt(value); + break; + case GC_INTRON: + stockholmStructure.getConsAnnotation().setIntron(value); + break; + case GC_REFERENCE_ANNOTATION: + stockholmStructure.getConsAnnotation().setReferenceAnnotation(value); + break; + case GC_MODEL_MASK: + stockholmStructure.getConsAnnotation().setModelMask(value); + break; + default: + // unknown feature + logger.warn("Unknown Consensus Feature [{}].\nPlease contact the Biojava team.", featureName); + break; } } @@ -667,21 +715,29 @@ private void handleConsensusAnnotation(String featureName, String value) { * the line to be parsed */ private void handleSequenceAnnotation(String seqName, String featureName, String value) { - if (featureName.equals(GS_ACCESSION_NUMBER)) { - stockholmStructure.addGSAccessionNumber(seqName, value); - } else if (featureName.equals(GS_DESCRIPTION)) { - stockholmStructure.addGSDescription(seqName, value); - } else if (featureName.equals(GS_DATABASE_REFERENCE)) { - stockholmStructure.addGSdbReference(seqName, value); - } else if (featureName.equals(GS_ORGANISM_SPECIES)) { - stockholmStructure.addGSOrganismSpecies(seqName, value); - } else if (featureName.equals(GS_ORGANISM_CLASSIFICATION)) { - stockholmStructure.addGSOrganismClassification(seqName, value); - } else if (featureName.equals(GS_LOOK)) { - stockholmStructure.addGSLook(seqName, value); - } else { - // unknown feature - logger.warn("Unknown Sequence Feature [{}].\nPlease contact the Biojava team.", featureName); + switch (featureName) { + case GS_ACCESSION_NUMBER: + stockholmStructure.addGSAccessionNumber(seqName, value); + break; + case GS_DESCRIPTION: + stockholmStructure.addGSDescription(seqName, value); + break; + case GS_DATABASE_REFERENCE: + stockholmStructure.addGSdbReference(seqName, value); + break; + case GS_ORGANISM_SPECIES: + stockholmStructure.addGSOrganismSpecies(seqName, value); + break; + case GS_ORGANISM_CLASSIFICATION: + stockholmStructure.addGSOrganismClassification(seqName, value); + break; + case GS_LOOK: + stockholmStructure.addGSLook(seqName, value); + break; + default: + // unknown feature + logger.warn("Unknown Sequence Feature [{}].\nPlease contact the Biojava team.", featureName); + break; } } @@ -693,27 +749,38 @@ private void handleSequenceAnnotation(String seqName, String featureName, String */ private void handleResidueAnnotation(String seqName, String featureName, String value) { - if (featureName.equals(GR_SURFACE_ACCESSIBILITY)) { - stockholmStructure.addSurfaceAccessibility(seqName, value); - } else if (featureName.equals(GR_TRANS_MEMBRANE)) { - stockholmStructure.addTransMembrane(seqName, value); - } else if (featureName.equals(GR_POSTERIOR_PROBABILITY)) { - stockholmStructure.addPosteriorProbability(seqName, value); - } else if (featureName.equals(GR_LIGAND_BINDING)) { - stockholmStructure.addLigandBinding(seqName, value); - } else if (featureName.equals(GR_ACTIVE_SITE)) { - stockholmStructure.addActiveSite(seqName, value); - } else if (featureName.equals(GR_AS_PFAM_PREDICTED)) { - stockholmStructure.addASPFamPredicted(seqName, value); - } else if (featureName.equals(GR_AS_SWISSPROT)) { - stockholmStructure.addASSwissProt(seqName, value); - } else if (featureName.equals(GR_INTRON)) { - stockholmStructure.addIntron(seqName, value); - } else if (featureName.equals(GR_SECONDARY_STRUCTURE)) { - stockholmStructure.addSecondaryStructure(seqName, value); - } else { - // unknown feature - logger.warn("Unknown Residue Feature [{}].\nPlease contact the Biojava team.", featureName); + switch (featureName) { + case GR_SURFACE_ACCESSIBILITY: + stockholmStructure.addSurfaceAccessibility(seqName, value); + break; + case GR_TRANS_MEMBRANE: + stockholmStructure.addTransMembrane(seqName, value); + break; + case GR_POSTERIOR_PROBABILITY: + stockholmStructure.addPosteriorProbability(seqName, value); + break; + case GR_LIGAND_BINDING: + stockholmStructure.addLigandBinding(seqName, value); + break; + case GR_ACTIVE_SITE: + stockholmStructure.addActiveSite(seqName, value); + break; + case GR_AS_PFAM_PREDICTED: + stockholmStructure.addASPFamPredicted(seqName, value); + break; + case GR_AS_SWISSPROT: + stockholmStructure.addASSwissProt(seqName, value); + break; + case GR_INTRON: + stockholmStructure.addIntron(seqName, value); + break; + case GR_SECONDARY_STRUCTURE: + stockholmStructure.addSecondaryStructure(seqName, value); + break; + default: + // unknown feature + logger.warn("Unknown Residue Feature [{}].\nPlease contact the Biojava team.", featureName); + break; } } } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmSequenceAnnotation.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmSequenceAnnotation.java index 9044c3a34c..0bf25c1a4a 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmSequenceAnnotation.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmSequenceAnnotation.java @@ -74,7 +74,7 @@ public void setDbReferences(Set dbReferences) { */ public void addDBReference(String dbReferenceRepresentingString) { if (this.dbReferences == null) { - this.dbReferences = new HashSet(); + this.dbReferences = new HashSet<>(); } dbReferences.add(new DatabaseReference(dbReferenceRepresentingString)); } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmStructure.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmStructure.java index 494d8290a2..692f26d8bc 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmStructure.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmStructure.java @@ -94,9 +94,9 @@ public class StockholmStructure { public StockholmStructure() { fileAnnotation = new StockholmFileAnnotation(); consAnnotation = new StockholmConsensusAnnotation(); - sequences = new HashMap(); - seqsAnnotation = new HashMap(); - resAnnotation = new HashMap(); + sequences = new HashMap<>(); + seqsAnnotation = new HashMap<>(); + resAnnotation = new HashMap<>(); } public StockholmFileAnnotation getFileAnnotation() { @@ -235,10 +235,11 @@ public List> getBioSequences(boolea if (forcedSequenceType != null && !(forcedSequenceType.equals(PFAM) || forcedSequenceType.equals(RFAM))) { throw new IllegalArgumentException("Illegal Argument " + forcedSequenceType); } - List> seqs = new ArrayList>(); - for (String sequencename : sequences.keySet()) { - AbstractSequence seq = null; - String sequence = sequences.get(sequencename).toString(); + List> seqs = new ArrayList<>(); + for (Map.Entry entry : sequences.entrySet()) { + String sequencename = entry.getKey(); + AbstractSequence seq; + String sequence = entry.getValue().toString(); if (ignoreCase) { sequence = sequence.toUpperCase(); } @@ -256,9 +257,8 @@ else if (forcedSequenceType.equals(PFAM)) } String[] seqDetails = splitSeqName(sequencename); seq.setDescription(seqDetails[0]); - seq.setBioBegin((seqDetails[1] == null || seqDetails[1].trim().equals("") ? null : new Integer( - seqDetails[1]))); - seq.setBioEnd((seqDetails[2] == null || seqDetails[2].trim().equals("") ? null : new Integer(seqDetails[2]))); + seq.setBioBegin((seqDetails[1] == null || seqDetails[1].trim().isEmpty() ? null : Integer.valueOf(seqDetails[1]))); + seq.setBioEnd((seqDetails[2] == null || seqDetails[2].trim().isEmpty() ? null : Integer.valueOf(seqDetails[2]))); seqs.add(seq); } @@ -308,22 +308,22 @@ private String[] splitSeqName(String sequenceName) { @Override public String toString() { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); List> bioSeqs = getBioSequences(false); int sequenceLength = -1; for (AbstractSequence sequence : bioSeqs) { String sequenceAsString = sequence.getSequenceAsString(); sequenceLength = sequenceAsString.length(); if (sequenceLength > 50) { - result.append(sequenceAsString.substring(0, 40)); + result.append(sequenceAsString, 0, 40); result.append("..."); - result.append(sequenceAsString.substring(sequenceLength - 3, sequenceLength)); + result.append(sequenceAsString, sequenceLength - 3, sequenceLength); } else { result.append(sequenceAsString); } - result.append(" " + sequence.getDescription() + "\n"); + result.append(" ").append(sequence.getDescription()).append("\n"); } - result.append("Alignment with " + bioSeqs.size() + " rows and " + sequenceLength + " columns"); + result.append("Alignment with ").append(bioSeqs.size()).append(" rows and ").append(sequenceLength).append(" columns"); return result.toString(); } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/AlignerHelper.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/AlignerHelper.java index edba157916..bb7aeaa16f 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/AlignerHelper.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/AlignerHelper.java @@ -62,8 +62,11 @@ public enum Last { */ public static class Cut { - private int queryIndex; - private int[][] targetIndices, tiLast, ti1, ti2; + private final int queryIndex; + private int[][] targetIndices; + private int[][] tiLast; + private final int[][] ti1; + private final int[][] ti2; public Cut(int queryIndex, int[] dim) { this.queryIndex = queryIndex; @@ -171,7 +174,7 @@ public static int addAnchors(Cut[] cuts, int[] scores, boolean addScore, int[] a for (Cut c : cuts) { anchors[c.getQueryIndex()] = c.getTargetIndex(zMax); } - return addScore ? (int) subscore : 0; + return addScore ? subscore : 0; } public static Cut[] getCuts(int k, Subproblem subproblem, int[] dim, boolean anchor0) { @@ -244,11 +247,11 @@ public int getQueryStartIndex() { public boolean isStartAnchored() { return isAnchored; } - private int queryStartIndex; // [0] - private int targetStartIndex; // [1] - private int queryEndIndex; // [2] - private int targetEndIndex; // [3] - private boolean isAnchored; + private final int queryStartIndex; // [0] + private final int targetStartIndex; // [1] + private final int queryEndIndex; // [2] + private final int targetEndIndex; // [3] + private final boolean isAnchored; public Subproblem(int queryStartIndex, int targetStartIndex, int queryEndIndex, int targetEndIndex) { this(queryStartIndex, targetStartIndex, queryEndIndex, targetEndIndex, false); } @@ -267,8 +270,8 @@ public Subproblem(int queryStartIndex, int targetStartIndex, int queryEndIndex, * @return list alignment subproblems */ public static List getSubproblems(List anchors, int querySequenceLength, int targetSequenceLength) { - Collections.sort(anchors, new Anchor.QueryIndexComparator()); - List list = new ArrayList(); + anchors.sort(new Anchor.QueryIndexComparator()); + List list = new ArrayList<>(); Anchor last = new Anchor(-1, -1); // sentinal anchor boolean isAnchored = false; for (int i = 0; i < anchors.size(); i++) { diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/AnchoredPairwiseSequenceAligner.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/AnchoredPairwiseSequenceAligner.java index 41b9502782..64b32ff317 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/AnchoredPairwiseSequenceAligner.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/AnchoredPairwiseSequenceAligner.java @@ -23,17 +23,18 @@ package org.biojava.nbio.alignment.routines; -import org.biojava.nbio.core.alignment.SimpleSequencePair; import org.biojava.nbio.alignment.routines.AlignerHelper.Anchor; import org.biojava.nbio.alignment.template.AbstractPairwiseSequenceAligner; +import org.biojava.nbio.alignment.template.GapPenalty; +import org.biojava.nbio.core.alignment.SimpleSequencePair; import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.core.alignment.template.AlignedSequence.Step; -import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /** @@ -96,9 +97,7 @@ public AnchoredPairwiseSequenceAligner(S query, S target, GapPenalty gapPenalty, */ public int[] getAnchors() { int[] anchor = new int[getScoreMatrixDimensions()[0] - 1]; - for (int i = 0; i < anchor.length; i++) { - anchor[i] = -1; - } + Arrays.fill(anchor, -1); for (int i = 0; i < anchors.size(); i++) { anchor[anchors.get(i).getQueryIndex()] = anchors.get(i).getTargetIndex(); } @@ -111,7 +110,7 @@ public int[] getAnchors() { * @param anchors list of points that are tied to the given indices in the target */ public void setAnchors(int[] anchors) { - super.anchors = new ArrayList(); + super.anchors = new ArrayList<>(); if (anchors != null) { for (int i = 0; i < anchors.length; i++) { if (anchors[i] >= 0) { @@ -133,7 +132,7 @@ public void addAnchor(int queryIndex, int targetIndex) { @Override protected void setProfile(List sx, List sy) { - profile = pair = new SimpleSequencePair(getQuery(), getTarget(), sx, sy); + profile = pair = new SimpleSequencePair<>(getQuery(), getTarget(), sx, sy); } } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/GuanUberbacher.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/GuanUberbacher.java index 3ff44d8a8c..e1471ffab4 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/GuanUberbacher.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/GuanUberbacher.java @@ -23,8 +23,8 @@ package org.biojava.nbio.alignment.routines; -import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.alignment.template.GapPenalty; +import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; @@ -42,7 +42,7 @@ */ public class GuanUberbacher, C extends Compound> extends AnchoredPairwiseSequenceAligner { - private static int defaultCutsPerSection = 10; + private static final int defaultCutsPerSection = 10; /** * Sets the default number of cuts added to each section during each pass. diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractMatrixAligner.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractMatrixAligner.java index b5e6f6188c..c1831c24c1 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractMatrixAligner.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractMatrixAligner.java @@ -23,12 +23,12 @@ package org.biojava.nbio.alignment.template; -import org.biojava.nbio.core.alignment.template.Profile; -import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.alignment.routines.AlignerHelper.Anchor; import org.biojava.nbio.alignment.routines.AlignerHelper.Last; import org.biojava.nbio.alignment.routines.AlignerHelper.Subproblem; import org.biojava.nbio.core.alignment.template.AlignedSequence.Step; +import org.biojava.nbio.core.alignment.template.Profile; +import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.CompoundSet; import org.biojava.nbio.core.sequence.template.Sequence; @@ -55,7 +55,7 @@ public abstract class AbstractMatrixAligner, C extends Com protected GapPenalty gapPenalty; private SubstitutionMatrix subMatrix; private boolean local, storingScoreMatrix; - protected List anchors = new ArrayList(); + protected List anchors = new ArrayList<>(); protected int cutsPerSection; // output fields @@ -218,8 +218,8 @@ private String scoreMatrixToString(int[][][] scores) { CompoundSet compoundSet = getCompoundSet(); int lengthCompound = compoundSet.getMaxSingleCompoundStringLength(), lengthRest = Math.max(Math.max(Integer.toString(min).length(), Integer.toString(max).length()), lengthCompound) + 1; - String padCompound = "%" + Integer.toString(lengthCompound) + "s", - padRest = "%" + Integer.toString(lengthRest); + String padCompound = "%" + lengthCompound + "s", + padRest = "%" + lengthRest; List query = getCompoundsOfQuery(), target = getCompoundsOfTarget(); for (int type = 0; type < scores[0][0].length; type++) { if (type > 0) { @@ -312,7 +312,7 @@ protected void align() { } boolean linear = (gapPenalty.getType() == GapPenalty.Type.LINEAR); Last[][][] traceback = new Last[dim[0]][][]; - List sx = new ArrayList(), sy = new ArrayList(); + List sx = new ArrayList<>(), sy = new ArrayList<>(); if (!local) { xyMax = new int[] { dim[0] - 1, dim[1] - 1 }; diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractPairwiseSequenceAligner.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractPairwiseSequenceAligner.java index 8c86470608..abd765b089 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractPairwiseSequenceAligner.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractPairwiseSequenceAligner.java @@ -137,12 +137,12 @@ protected CompoundSet getCompoundSet() { @Override protected List getCompoundsOfQuery() { - return (query == null) ? new ArrayList() : query.getAsList(); + return (query == null) ? new ArrayList<>() : query.getAsList(); } @Override protected List getCompoundsOfTarget() { - return (target == null) ? new ArrayList() : target.getAsList(); + return (target == null) ? new ArrayList<>() : target.getAsList(); } @Override @@ -176,7 +176,7 @@ protected void reset() { maxt += getSubstitutionMatrix().getValue(c, c); } max = Math.max(maxq, maxt); - score = min = isLocal() ? 0 : (int) (2 * getGapPenalty().getOpenPenalty() + (query.getLength() + + score = min = isLocal() ? 0 : (2 * getGapPenalty().getOpenPenalty() + (query.getLength() + target.getLength()) * getGapPenalty().getExtensionPenalty()); } } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractProfileProfileAligner.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractProfileProfileAligner.java index 01cba48463..95af0ea5ff 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractProfileProfileAligner.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractProfileProfileAligner.java @@ -23,10 +23,10 @@ package org.biojava.nbio.alignment.template; -import org.biojava.nbio.core.alignment.template.ProfilePair; +import org.biojava.nbio.alignment.template.GapPenalty.Type; import org.biojava.nbio.core.alignment.template.Profile; +import org.biojava.nbio.core.alignment.template.ProfilePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; -import org.biojava.nbio.alignment.template.GapPenalty.Type; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.CompoundSet; import org.biojava.nbio.core.sequence.template.Sequence; @@ -189,13 +189,13 @@ protected CompoundSet getCompoundSet() { @Override protected List getCompoundsOfQuery() { // TODO replace with consensus sequence - return (query == null) ? new ArrayList() : query.getAlignedSequence(1).getAsList(); + return (query == null) ? new ArrayList<>() : query.getAlignedSequence(1).getAsList(); } @Override protected List getCompoundsOfTarget() { // TODO replace with consensus sequence - return (target == null) ? new ArrayList() : target.getAlignedSequence(1).getAsList(); + return (target == null) ? new ArrayList<>() : target.getAlignedSequence(1).getAsList(); } @Override @@ -236,7 +236,7 @@ protected void reset() { if (query != null && target != null && getGapPenalty() != null && getSubstitutionMatrix() != null && query.getCompoundSet().equals(target.getCompoundSet())) { int maxq = 0, maxt = 0; - cslist = query.getCompoundSet().getAllCompounds(); + cslist = new ArrayList(query.getCompoundSet().getAllCompounds()); qfrac = new float[query.getLength()][]; for (int i = 0; i < qfrac.length; i++) { qfrac[i] = query.getCompoundWeightsAt(i + 1, cslist); @@ -248,24 +248,27 @@ protected void reset() { maxt += getSubstitutionScore(tfrac[i], tfrac[i]); } max = Math.max(maxq, maxt); - score = min = isLocal() ? 0 : (int) (2 * getGapPenalty().getOpenPenalty() + (query.getLength() + + score = min = isLocal() ? 0 : (2 * getGapPenalty().getOpenPenalty() + (query.getLength() + target.getLength()) * getGapPenalty().getExtensionPenalty()); } } // helper method that scores alignment of two column vectors private int getSubstitutionScore(float[] qv, float[] tv) { - float score = 0.0f; + double score = 0.0; + SubstitutionMatrix s = getSubstitutionMatrix(); for (int q = 0; q < qv.length; q++) { - if (qv[q] > 0.0f) { + float qvq = qv[q]; + if (qvq > 0.0) { + C cq = cslist.get(q); for (int t = 0; t < tv.length; t++) { - if (tv[t] > 0.0f) { - score += qv[q]*tv[t]*getSubstitutionMatrix().getValue(cslist.get(q), cslist.get(t)); - } + float tvt = tv[t]; + if (tvt > 0.0) + score += qvq * tvt * s.getValue(cq, cslist.get(t)); } } } - return Math.round(score); + return (int) Math.round(score); //TODO return double? } } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallablePairwiseSequenceAligner.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallablePairwiseSequenceAligner.java index e1c4616620..6725a47f5f 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallablePairwiseSequenceAligner.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallablePairwiseSequenceAligner.java @@ -39,7 +39,7 @@ public class CallablePairwiseSequenceAligner, C extends Compound> implements Callable> { - private PairwiseSequenceAligner psa; + private final PairwiseSequenceAligner psa; /** * Creates a pairwise sequence alignment task for simplified parallel execution. diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallablePairwiseSequenceScorer.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallablePairwiseSequenceScorer.java index d5d3d4b243..4d8d833bcd 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallablePairwiseSequenceScorer.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallablePairwiseSequenceScorer.java @@ -37,7 +37,7 @@ */ public class CallablePairwiseSequenceScorer, C extends Compound> implements Callable { - private PairwiseSequenceScorer pss; + private final PairwiseSequenceScorer pss; /** * Creates a pairwise sequence scoring task for simplified parallel execution. diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallableProfileProfileAligner.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallableProfileProfileAligner.java index 063426a91a..27a0c812d3 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallableProfileProfileAligner.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallableProfileProfileAligner.java @@ -39,7 +39,7 @@ public class CallableProfileProfileAligner, C extends Compound> implements Callable> { - private ProfileProfileAligner ppa; + private final ProfileProfileAligner ppa; /** * Creates a profile-profile alignment task for simplified parallel execution. diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/GapPenalty.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/GapPenalty.java index 1c3aab1978..ef8fe96133 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/GapPenalty.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/GapPenalty.java @@ -39,9 +39,9 @@ public interface GapPenalty { *
  • DYNAMIC, if penalty values change during alignment * */ - enum Type {CONSTANT, LINEAR, AFFINE, DYNAMIC}; + enum Type {CONSTANT, LINEAR, AFFINE, DYNAMIC} - /** + /** * Returns penalty given when an already open gap elongates by a single element * * @return gap extension penalty diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/GuideTreeNode.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/GuideTreeNode.java index 76b16261e6..a212fac464 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/GuideTreeNode.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/GuideTreeNode.java @@ -23,8 +23,8 @@ package org.biojava.nbio.alignment.template; -import org.biojava.nbio.core.alignment.template.ProfilePair; import org.biojava.nbio.core.alignment.template.Profile; +import org.biojava.nbio.core.alignment.template.ProfilePair; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/Comparison.java b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/Comparison.java index dc8ead79a7..f5081a04f6 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/Comparison.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/Comparison.java @@ -44,12 +44,12 @@ public class Comparison { * SequenceI * @return float */ - public final static float PID(String seq1, String seq2) { + public static float PID(String seq1, String seq2) { return PID(seq1, seq2, 0, seq1.length()); } // Another pid with region specification - public final static float PID(String seq1, String seq2, int start, int end) { + public static float PID(String seq1, String seq2, int start, int end) { int s1len = seq1.length(); int s2len = seq2.length(); @@ -100,8 +100,8 @@ public final static float PID(String seq1, String seq2, int start, int end) { * * @return true if it is a gap, false otherwise */ - public static final boolean isGap(char c) { - return (c == '-' || c == '.' || c == ' ') ? true : false; + public static boolean isGap(char c) { + return c == '-' || c == '.' || c == ' '; } } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/DistanceMatrixCalculator.java b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/DistanceMatrixCalculator.java index d0464bae8b..f8fd3bb1fc 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/DistanceMatrixCalculator.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/DistanceMatrixCalculator.java @@ -20,8 +20,6 @@ */ package org.biojava.nbio.phylo; -import java.io.IOException; -import java.util.List; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.MultipleSequenceAlignment; import org.biojava.nbio.core.sequence.template.Compound; @@ -33,6 +31,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.List; + /** * The DistanceMatrixCalculator methods generate a {@link DistanceMatrix} from a * {@link MultipleSequenceAlignment} or other indirect distance infomation (RMSD). diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/DistanceTreeEvaluator.java b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/DistanceTreeEvaluator.java index ec9e274ab6..8a7d649949 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/DistanceTreeEvaluator.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/DistanceTreeEvaluator.java @@ -66,8 +66,8 @@ private DistanceTreeEvaluator() { public static double evaluate(Phylogeny tree, DistanceMatrix matrix) { int numSequences = matrix.getSize(); List externalNodes = tree.getExternalNodes(); - HashMap externalNodesHashMap = new HashMap(); - Set path = new HashSet(); + HashMap externalNodesHashMap = new HashMap<>(); + Set path = new HashSet<>(); for (PhylogenyNode node : externalNodes) { externalNodesHashMap.put(node.getName(), node); diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/ForesterWrapper.java b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/ForesterWrapper.java index 74cdf2e2f4..34acacc00b 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/ForesterWrapper.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/ForesterWrapper.java @@ -20,12 +20,8 @@ */ package org.biojava.nbio.phylo; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; import org.biojava.nbio.core.sequence.MultipleSequenceAlignment; import org.biojava.nbio.core.sequence.io.FastaWriter; -import org.biojava.nbio.core.sequence.io.template.FastaHeaderFormatInterface; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix; @@ -34,6 +30,10 @@ import org.forester.msa.Msa; import org.forester.phylogeny.Phylogeny; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; + /** * This class contains wrapper methods for communication between BioJava and * forester (e.g, Data Structure conversion). @@ -64,14 +64,9 @@ public static , D extends Compound> Msa convert( // Convert the biojava MSA to a FASTA String OutputStream os = new ByteArrayOutputStream(); - FastaWriter fastaW = new FastaWriter(os, + FastaWriter fastaW = new FastaWriter<>(os, msa.getAlignedSequences(), - new FastaHeaderFormatInterface() { - @Override - public String getHeader(C sequence) { - return sequence.getAccession().toString(); - }; - }); + sequence -> sequence.getAccession().toString()); fastaW.process(); String fastaMSA = os.toString(); diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/TreeConstructorType.java b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/TreeConstructorType.java index d3f632046b..ba12f8251c 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/TreeConstructorType.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/TreeConstructorType.java @@ -38,5 +38,5 @@ public enum TreeConstructorType { UPGMA, /** What does this stand for? (Aleix: Nov 2015) */ - AV; + AV } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/TreeType.java b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/TreeType.java index 1f2896e923..d380219465 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/TreeType.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/TreeType.java @@ -41,7 +41,7 @@ public enum TreeType { /** Description name of the Tree Type */ protected final String name; - private TreeType(String name){ + TreeType(String name){ this.name = name; } } diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignAllGlobal.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignAllGlobal.java index 9deee78c08..8d5d3f2543 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignAllGlobal.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignAllGlobal.java @@ -20,8 +20,8 @@ */ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; +import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.ProteinSequence; @@ -45,7 +45,7 @@ public static void main(String[] args) { } private static void alignAllGlobal(String[] ids) throws Exception { - List lst = new ArrayList(); + List lst = new ArrayList<>(); for (String id : ids) { lst.add(getSequenceForId(id)); } diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignAllLocal.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignAllLocal.java index a56463159e..888a1e6cc5 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignAllLocal.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignAllLocal.java @@ -20,8 +20,8 @@ */ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; +import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.ProteinSequence; @@ -45,7 +45,7 @@ public static void main(String[] args) { } private static void alignAllLocal(String[] ids) throws Exception { - List lst = new ArrayList(); + List lst = new ArrayList<>(); for (String id : ids) { lst.add(getSequenceForId(id)); } diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignPairGlobal.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignPairGlobal.java index e93dc28b07..a56961a395 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignPairGlobal.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignPairGlobal.java @@ -20,8 +20,8 @@ */ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; +import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.ProteinSequence; diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignPairLocal.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignPairLocal.java index 40ff627d29..c5a8a0ff1c 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignPairLocal.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignPairLocal.java @@ -20,8 +20,8 @@ */ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; +import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.ProteinSequence; diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookMSA.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookMSA.java index cfe3fcc05e..24085e698d 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookMSA.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookMSA.java @@ -42,7 +42,7 @@ public static void main(String[] args) { } private static void multipleSequenceAlignment(String[] ids) throws Exception { - List lst = new ArrayList(); + List lst = new ArrayList<>(); for (String id : ids) { lst.add(getSequenceForId(id)); } diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookMSAProfiler.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookMSAProfiler.java index 55a4c7d0ec..a290ff09b1 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookMSAProfiler.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookMSAProfiler.java @@ -20,11 +20,11 @@ */ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceScorerType; import org.biojava.nbio.alignment.Alignments.ProfileProfileAlignerType; import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.alignment.template.PairwiseSequenceScorer; +import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.ProteinSequence; @@ -81,8 +81,7 @@ public static void main(String[] args) throws Exception { Profiler profiler = new Profiler(); System.out.printf("Loading sequences from %s... ", args[0]); - List list = new ArrayList(); - list.addAll(FastaReaderHelper.readFastaProteinSequence(new File(args[0])).values()); + List list = new ArrayList<>(FastaReaderHelper.readFastaProteinSequence(new File(args[0])).values()); if (args.length > 1 && Integer.parseInt(args[1]) < list.size()) { System.out.printf("%s/%d", args[1], list.size()); list = list.subList(0, Integer.parseInt(args[1])); @@ -106,7 +105,7 @@ public static void main(String[] args) throws Exception { profiler.setCheckpoint(); System.out.print("Stage 2: hierarchical clustering into a guide tree... "); - GuideTree tree = new GuideTree(list, + GuideTree tree = new GuideTree<>(list, scorers); scorers = null; System.out.printf("%d ms using %d kB%n%n%s%n%n", profiler.getTimeSinceCheckpoint()/1000000, diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/FractionalIdentityScorerTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/FractionalIdentityScorerTest.java index 08bf9c73f8..5528155d8e 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/FractionalIdentityScorerTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/FractionalIdentityScorerTest.java @@ -23,9 +23,9 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.alignment.template.PairwiseSequenceScorer; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.ProteinSequence; @@ -52,20 +52,20 @@ public void setup() throws CompoundNotFoundException { target = new ProteinSequence("RDG"); gaps = new SimpleGapPenalty((short) 10, (short) 1); blosum62 = SubstitutionMatrixHelper.getBlosum62(); - alignment = new NeedlemanWunsch(query, target, gaps, blosum62); - self = new NeedlemanWunsch(query, query, gaps, blosum62); - scorer1 = new FractionalIdentityScorer(alignment); - scorer2 = new FractionalIdentityScorer(self); + alignment = new NeedlemanWunsch<>(query, target, gaps, blosum62); + self = new NeedlemanWunsch<>(query, query, gaps, blosum62); + scorer1 = new FractionalIdentityScorer<>(alignment); + scorer2 = new FractionalIdentityScorer<>(self); } @Test public void testFractionalIdentityScorerPairwiseSequenceAlignerOfSC() { - assertNotNull(new FractionalIdentityScorer(alignment)); + assertNotNull(new FractionalIdentityScorer<>(alignment)); } @Test public void testFractionalIdentityScorerSequencePairOfSC() { - assertNotNull(new FractionalIdentityScorer(alignment.getPair())); + assertNotNull(new FractionalIdentityScorer<>(alignment.getPair())); } @Test diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/FractionalSimilarityScorerTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/FractionalSimilarityScorerTest.java index 26d7615d44..5f03604f26 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/FractionalSimilarityScorerTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/FractionalSimilarityScorerTest.java @@ -24,9 +24,9 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.alignment.template.PairwiseSequenceScorer; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.ProteinSequence; @@ -53,20 +53,20 @@ public void setup() throws CompoundNotFoundException { target = new ProteinSequence("RADG"); gaps = new SimpleGapPenalty((short) 2, (short) 1); blosum62 = SubstitutionMatrixHelper.getBlosum62(); - alignment = new NeedlemanWunsch(query, target, gaps, blosum62); - self = new NeedlemanWunsch(query, query, gaps, blosum62); - scorer1 = new FractionalSimilarityScorer(alignment); - scorer2 = new FractionalSimilarityScorer(self); + alignment = new NeedlemanWunsch<>(query, target, gaps, blosum62); + self = new NeedlemanWunsch<>(query, query, gaps, blosum62); + scorer1 = new FractionalSimilarityScorer<>(alignment); + scorer2 = new FractionalSimilarityScorer<>(self); } @Test public void testFractionalSimilarityScorerPairwiseSequenceAlignerOfSC() { - assertNotNull(new FractionalSimilarityScorer(alignment)); + assertNotNull(new FractionalSimilarityScorer<>(alignment)); } @Test public void testFractionalSimilarityScorerSequencePairOfSC() { - assertNotNull(new FractionalSimilarityScorer(alignment.getPair())); + assertNotNull(new FractionalSimilarityScorer<>(alignment.getPair())); } @Test diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/GuideTreeTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/GuideTreeTest.java index 08adf113ec..a9ba7f6c78 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/GuideTreeTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/GuideTreeTest.java @@ -23,11 +23,11 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceScorerType; import org.biojava.nbio.alignment.Alignments.ProfileProfileAlignerType; import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.alignment.template.GuideTreeNode; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.ProteinSequence; @@ -49,11 +49,11 @@ public class GuideTreeTest { @Before public void setup() throws CompoundNotFoundException { - proteins = Arrays.asList(new ProteinSequence[] {new ProteinSequence("ARND"), new ProteinSequence("ARND"), - new ProteinSequence("HILK"), new ProteinSequence("ANDR")}); + proteins = Arrays.asList(new ProteinSequence("ARND"), new ProteinSequence("ARND"), + new ProteinSequence("HILK"), new ProteinSequence("ANDR")); gaps = new SimpleGapPenalty((short) 2, (short) 1); blosum62 = SubstitutionMatrixHelper.getBlosum62(); - tree = new GuideTree(proteins, Alignments.getAllPairsScorers(proteins, + tree = new GuideTree<>(proteins, Alignments.getAllPairsScorers(proteins, PairwiseSequenceScorerType.GLOBAL_IDENTITIES, gaps, blosum62)); } @@ -112,12 +112,13 @@ public void testIterator() { switch (i++) { case 0: assertEquals(n.getName(), "1"); break; case 1: assertEquals(n.getName(), "2"); break; - case 2: assertEquals(n.getName(), ""); break; + case 2: + case 6: + case 4: + assertEquals(n.getName(), ""); break; case 3: assertEquals(n.getName(), "3"); break; - case 4: assertEquals(n.getName(), ""); break; - case 5: assertEquals(n.getName(), "4"); break; - case 6: assertEquals(n.getName(), ""); break; - } + case 5: assertEquals(n.getName(), "4"); break; + } } } diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/LocalAlignmentTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/LocalAlignmentTest.java index c4d88ebddb..c99d59b945 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/LocalAlignmentTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/LocalAlignmentTest.java @@ -22,9 +22,9 @@ */ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; import org.biojava.nbio.alignment.template.PairwiseSequenceAligner; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.DNASequence; diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/NeedlemanWunschTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/NeedlemanWunschTest.java index 5b44fc25f4..2cc98c4315 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/NeedlemanWunschTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/NeedlemanWunschTest.java @@ -23,10 +23,10 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.alignment.template.PairwiseSequenceAligner; +import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.DNASequence; @@ -38,9 +38,7 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; public class NeedlemanWunschTest { @@ -57,15 +55,15 @@ public void setup() throws CompoundNotFoundException { target = new ProteinSequence("RDG"); gaps = new SimpleGapPenalty(10, 1); blosum62 = SubstitutionMatrixHelper.getBlosum62(); - alignment = new NeedlemanWunsch(query, target, gaps, blosum62); - self = new NeedlemanWunsch(query, query, gaps, blosum62); + alignment = new NeedlemanWunsch<>(query, target, gaps, blosum62); + self = new NeedlemanWunsch<>(query, query, gaps, blosum62); } @Test public void testComplex() throws Exception { short match = 2, gop = -5, gep = -3; // 2, 5, and 3 are coprime; -2 is the mismatch score - SimpleSubstitutionMatrix mx = new SimpleSubstitutionMatrix(new DNACompoundSet(), match, (short)-match); + SimpleSubstitutionMatrix mx = new SimpleSubstitutionMatrix<>(new DNACompoundSet(), match, (short) -match); DNASequence a = new DNASequence("CGTAT ATATCGCGCGCGCGATATATATATCT TCTCTAAAAAAA".replaceAll(" ", "")); DNASequence b = new DNASequence("GGTATATATATCGCGCGCACGAT TATATATCTCTCTCTAAAAAAA".replaceAll(" ", "")); @@ -88,7 +86,7 @@ public void testComplex() throws Exception { @Test public void testNeedlemanWunsch() { NeedlemanWunsch nw = - new NeedlemanWunsch(); + new NeedlemanWunsch<>(); nw.setQuery(query); nw.setTarget(target); nw.setGapPenalty(gaps); @@ -229,7 +227,7 @@ public void testGetPair() { public void should_align_all_anchored() throws CompoundNotFoundException { DNASequence query = new DNASequence("ACG", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("CGT", AmbiguityDNACompoundSet.getDNACompoundSet()); - NeedlemanWunsch aligner = new NeedlemanWunsch(query, target, new SimpleGapPenalty((short)0, (short)10), SubstitutionMatrixHelper.getNuc4_4()); + NeedlemanWunsch aligner = new NeedlemanWunsch<>(query, target, new SimpleGapPenalty((short) 0, (short) 10), SubstitutionMatrixHelper.getNuc4_4()); aligner.setAnchors(new int[] { 0, 1, 2} ); assertEquals(String.format("ACG%nCGT%n"), aligner.getPair().toString()); } @@ -241,7 +239,7 @@ public void should_align_all_anchored() throws CompoundNotFoundException { public void should_align_starting_anchor() throws CompoundNotFoundException { DNASequence query = new DNASequence("AAT", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("AATT", AmbiguityDNACompoundSet.getDNACompoundSet()); - NeedlemanWunsch aligner = new NeedlemanWunsch(query, target, new SimpleGapPenalty((short)0, (short)10), SubstitutionMatrixHelper.getNuc4_4()); + NeedlemanWunsch aligner = new NeedlemanWunsch<>(query, target, new SimpleGapPenalty((short) 0, (short) 10), SubstitutionMatrixHelper.getNuc4_4()); aligner.setAnchors(new int[] { 1, -1, -1} ); assertEquals(String.format("-AAT%nAATT%n"), aligner.getPair().toString()); } @@ -253,7 +251,7 @@ public void should_align_starting_anchor() throws CompoundNotFoundException { public void should_align_ending_anchor() throws CompoundNotFoundException { DNASequence query = new DNASequence("AAG", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("AATT", AmbiguityDNACompoundSet.getDNACompoundSet()); - NeedlemanWunsch aligner = new NeedlemanWunsch(query, target, new SimpleGapPenalty((short)0, (short)10), SubstitutionMatrixHelper.getNuc4_4()); + NeedlemanWunsch aligner = new NeedlemanWunsch<>(query, target, new SimpleGapPenalty((short) 0, (short) 10), SubstitutionMatrixHelper.getNuc4_4()); aligner.addAnchor(2, 3); assertEquals(String.format("AA-G%nAATT%n"), aligner.getPair().toString()); } @@ -265,7 +263,7 @@ public void should_align_ending_anchor() throws CompoundNotFoundException { public void should_align_middle_anchor() throws CompoundNotFoundException { DNASequence query = new DNASequence("ACTTT", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("ACGTTT", AmbiguityDNACompoundSet.getDNACompoundSet()); - NeedlemanWunsch aligner = new NeedlemanWunsch(query, target, new SimpleGapPenalty((short)0, (short)10), SubstitutionMatrixHelper.getNuc4_4()); + NeedlemanWunsch aligner = new NeedlemanWunsch<>(query, target, new SimpleGapPenalty((short) 0, (short) 10), SubstitutionMatrixHelper.getNuc4_4()); aligner.setAnchors(new int[] { -1, 2, -1} ); assertEquals(String.format("A-CTTT%nACGTTT%n"), aligner.getPair().toString()); } @@ -277,7 +275,7 @@ public void should_align_middle_anchor() throws CompoundNotFoundException { public void should_align_multiple_anchors() throws CompoundNotFoundException { DNASequence query = new DNASequence("ACGT", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("ATACGT", AmbiguityDNACompoundSet.getDNACompoundSet()); - NeedlemanWunsch aligner = new NeedlemanWunsch(query, target, new SimpleGapPenalty((short)0, (short)10), SubstitutionMatrixHelper.getNuc4_4()); + NeedlemanWunsch aligner = new NeedlemanWunsch<>(query, target, new SimpleGapPenalty((short) 0, (short) 10), SubstitutionMatrixHelper.getNuc4_4()); aligner.addAnchor(0, 0); aligner.addAnchor(1, 1); aligner.addAnchor(2, 2); @@ -292,8 +290,8 @@ public void should_align_multiple_anchors() throws CompoundNotFoundException { public void anchors_should_not_change_score() throws CompoundNotFoundException { DNASequence query = new DNASequence("ACGT", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("ACGT", AmbiguityDNACompoundSet.getDNACompoundSet()); - NeedlemanWunsch aligner = new NeedlemanWunsch(query, target, new SimpleGapPenalty((short)5, (short)10), SubstitutionMatrixHelper.getNuc4_4()); - NeedlemanWunsch anchored = new NeedlemanWunsch(query, target, new SimpleGapPenalty((short)5, (short)10), SubstitutionMatrixHelper.getNuc4_4()); + NeedlemanWunsch aligner = new NeedlemanWunsch<>(query, target, new SimpleGapPenalty((short) 5, (short) 10), SubstitutionMatrixHelper.getNuc4_4()); + NeedlemanWunsch anchored = new NeedlemanWunsch<>(query, target, new SimpleGapPenalty((short) 5, (short) 10), SubstitutionMatrixHelper.getNuc4_4()); anchored.addAnchor(0, 0); anchored.addAnchor(1, 1); anchored.addAnchor(2, 2); @@ -308,7 +306,7 @@ public void anchors_should_not_change_score() throws CompoundNotFoundException { public void testAnchoredDNAAlignment() throws CompoundNotFoundException { DNASequence query = new DNASequence( "ACGTACCGGTTTT", DNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("TACGTCCGGTTACGTACGTT", DNACompoundSet.getDNACompoundSet()); - NeedlemanWunsch aligner = new NeedlemanWunsch(query, target, new SimpleGapPenalty((short)5, (short)2), SubstitutionMatrixHelper.getNuc4_4()); + NeedlemanWunsch aligner = new NeedlemanWunsch<>(query, target, new SimpleGapPenalty((short) 5, (short) 2), SubstitutionMatrixHelper.getNuc4_4()); assertEquals(String.format("-ACGTACCGGTT-------TT%nTACGT-CCGGTTACGTACGTT%n"), aligner.getPair().toString()); } @@ -335,7 +333,7 @@ public void testIntOverflowBug() throws CompoundNotFoundException { AmbiguityDNACompoundSet.getDNACompoundSet()); NeedlemanWunsch aligner = - new NeedlemanWunsch(query, target, gap, matrix); + new NeedlemanWunsch<>(query, target, gap, matrix); //System.out.println("getScore: " + aligner.getScore()); diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleProfilePairTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleProfilePairTest.java index 5d4e9acd53..3e3c887ede 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleProfilePairTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleProfilePairTest.java @@ -23,9 +23,10 @@ package org.biojava.nbio.alignment; +import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.core.alignment.SimpleProfilePair; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.AlignedSequence.Step; -import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.alignment.template.ProfilePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; @@ -36,9 +37,6 @@ import org.junit.Test; import java.util.Arrays; -import org.biojava.nbio.alignment.NeedlemanWunsch; -import org.biojava.nbio.alignment.SimpleGapPenalty; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import static org.junit.Assert.assertEquals; @@ -57,34 +55,31 @@ public void setup() throws CompoundNotFoundException { protein4 = new ProteinSequence("ANDR"); gaps = new SimpleGapPenalty((short) 2, (short) 1); blosum62 = SubstitutionMatrixHelper.getBlosum62(); - pair1 = new NeedlemanWunsch(protein1, protein2, gaps, blosum62).getPair(); - pair2 = new NeedlemanWunsch(protein3, protein4, gaps, blosum62).getPair(); + pair1 = new NeedlemanWunsch<>(protein1, protein2, gaps, blosum62).getPair(); + pair2 = new NeedlemanWunsch<>(protein3, protein4, gaps, blosum62).getPair(); } @Test public void testSimpleProfilePair() { ProfilePair all = - new SimpleProfilePair(pair1, pair2, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.GAP}), Arrays.asList( - new Step[] {Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND})); + new SimpleProfilePair<>(pair1, pair2, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.GAP), Arrays.asList( + Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND)); assertEquals(all.toString(), String.format("ARND--%nARND--%n--HILK%nA-ND-R%n")); } @Test public void testGetQuery() { ProfilePair all = - new SimpleProfilePair(pair1, pair2, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.GAP}), Arrays.asList( - new Step[] {Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND})); + new SimpleProfilePair<>(pair1, pair2, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.GAP), Arrays.asList( + Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND)); assertEquals(all.getQuery(), pair1); } @Test public void testGetTarget() { ProfilePair all = - new SimpleProfilePair(pair1, pair2, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.GAP}), Arrays.asList( - new Step[] {Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND})); + new SimpleProfilePair<>(pair1, pair2, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.GAP), Arrays.asList( + Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND)); assertEquals(all.getTarget(), pair2); } diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleProfileProfileAlignerTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleProfileProfileAlignerTest.java index 625e954730..de3f91694e 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleProfileProfileAlignerTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleProfileProfileAlignerTest.java @@ -56,22 +56,22 @@ public void setup() throws CompoundNotFoundException { protein4 = new ProteinSequence("ANDR"); gaps = new SimpleGapPenalty(2, 1); blosum62 = SubstitutionMatrixHelper.getBlosum62(); - prof1 = new SimpleProfile(protein1); - prof2 = new SimpleProfile(protein2); - prof3 = new SimpleProfile(protein3); - prof4 = new SimpleProfile(protein4); - sppa1 = new SimpleProfileProfileAligner(prof1, prof2, gaps, blosum62); + prof1 = new SimpleProfile<>(protein1); + prof2 = new SimpleProfile<>(protein2); + prof3 = new SimpleProfile<>(protein3); + prof4 = new SimpleProfile<>(protein4); + sppa1 = new SimpleProfileProfileAligner<>(prof1, prof2, gaps, blosum62); pp1 = sppa1.getPair(); - sppa2 = new SimpleProfileProfileAligner(prof3, prof4, gaps, blosum62); + sppa2 = new SimpleProfileProfileAligner<>(prof3, prof4, gaps, blosum62); pp2 = sppa2.getPair(); - sppa3 = new SimpleProfileProfileAligner(pp1, pp2, gaps, blosum62); + sppa3 = new SimpleProfileProfileAligner<>(pp1, pp2, gaps, blosum62); all = sppa3.getPair(); } @Test public void testSimpleProfileProfileAligner() { SimpleProfileProfileAligner alig = - new SimpleProfileProfileAligner(); + new SimpleProfileProfileAligner<>(); alig.setQuery(prof1); alig.setTarget(prof2); alig.setGapPenalty(gaps); diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleSubstitutionMatrixTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleSubstitutionMatrixTest.java index 72ed4137d7..30150e5483 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleSubstitutionMatrixTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleSubstitutionMatrixTest.java @@ -42,7 +42,7 @@ public class SimpleSubstitutionMatrixTest { @Test(expected=FileNotFoundException.class) public void testSimpleSubstitutionMatrixNotFound() throws FileNotFoundException { - new SimpleSubstitutionMatrix(AminoAcidCompoundSet.getAminoAcidCompoundSet(), + new SimpleSubstitutionMatrix<>(AminoAcidCompoundSet.aminoAcidCompoundSet, new File("blosum63.txt")); } @@ -51,7 +51,7 @@ public void test() throws CompoundNotFoundException { NucleotideCompound A = new DNASequence("A").getCompoundAt(1); NucleotideCompound a = new DNASequence("a").getCompoundAt(1); NucleotideCompound c = new DNASequence("c").getCompoundAt(1); - SubstitutionMatrix matrix = new SimpleSubstitutionMatrix(DNACompoundSet.getDNACompoundSet(), (short)1, (short)0); + SubstitutionMatrix matrix = new SimpleSubstitutionMatrix<>(DNACompoundSet.getDNACompoundSet(), (short) 1, (short) 0); assertEquals(1, (matrix.getValue(A, A))); assertEquals(1, (matrix.getValue(a, a))); assertEquals(1, (matrix.getValue(A, a))); @@ -61,7 +61,7 @@ public void test() throws CompoundNotFoundException { @Test() public void testSimpleSubstitutionMatrix() { SubstitutionMatrix matrix = SimpleSubstitutionMatrix.getBlosum62(); - assertEquals(matrix.getCompoundSet(), AminoAcidCompoundSet.getAminoAcidCompoundSet()); + assertEquals(matrix.getCompoundSet(), AminoAcidCompoundSet.aminoAcidCompoundSet); assertEquals(matrix.getName(), "blosum62"); assertEquals(matrix.getMaxValue(), 11); assertEquals(matrix.getMinValue(), -4); @@ -70,7 +70,7 @@ public void testSimpleSubstitutionMatrix() { @Test public void testSimpleSubstitutionMatrixCompoundSetOfCStringString() { DNACompoundSet dnacs = DNACompoundSet.getDNACompoundSet(); - SubstitutionMatrix dnaTest = new SimpleSubstitutionMatrix(dnacs, + SubstitutionMatrix dnaTest = new SimpleSubstitutionMatrix<>(dnacs, "# Test\nA C G T\nA 5 0 0 0\nC 0 5 0 0\nG 0 0 5 0\nT 0 0 0 1\n", "DNA Test"); short[][] matrix = dnaTest.getMatrix(); assertEquals(matrix[1][1], 5); @@ -83,8 +83,8 @@ public void testSimpleSubstitutionMatrixCompoundSetOfCStringString() { @Test public void testSimpleSubstitutionMatrixCompoundSetOfCShortShort() { - SubstitutionMatrix matrix = new SimpleSubstitutionMatrix( - AminoAcidCompoundSet.getAminoAcidCompoundSet(), (short) 5, (short) 1); + SubstitutionMatrix matrix = new SimpleSubstitutionMatrix<>( + AminoAcidCompoundSet.aminoAcidCompoundSet, (short) 5, (short) 1); assertEquals(matrix.getName(), "IDENTITY_5_1"); } @@ -106,7 +106,7 @@ public void testSetName() { @Test public void testToString() { - SubstitutionMatrix matrix = new SimpleSubstitutionMatrix( + SubstitutionMatrix matrix = new SimpleSubstitutionMatrix<>( DNACompoundSet.getDNACompoundSet(), "# Test\nA C G T\nA 5 0 0 0\nC 0 5 0 0 \nG 0 0 5 0\n T 0 0 0 1\n", "DNAtest"); assertEquals(matrix.toString().substring(0,6), "# Test"); @@ -119,7 +119,7 @@ public void testToString() { @Test public void testCaseEquivalence() { DNACompoundSet dnacs = DNACompoundSet.getDNACompoundSet(); - SubstitutionMatrix dnaTest = new SimpleSubstitutionMatrix(dnacs, + SubstitutionMatrix dnaTest = new SimpleSubstitutionMatrix<>(dnacs, "# Test\nA C G T\nA 5 0 0 0\nC 0 5 0 0\nG 0 0 5 0\nT 0 0 0 1\n", "DNA Test"); @SuppressWarnings("unused") short[][] matrix = dnaTest.getMatrix(); diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SmithWatermanTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SmithWatermanTest.java index a3335b500e..cb3e94a349 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SmithWatermanTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SmithWatermanTest.java @@ -23,8 +23,8 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.template.GapPenalty; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.ProteinSequence; @@ -49,14 +49,14 @@ public void setup() throws CompoundNotFoundException { target = new ProteinSequence("ERDNKGFPS"); gaps = new SimpleGapPenalty((short) 2, (short) 1); blosum62 = SubstitutionMatrixHelper.getBlosum62(); - alignment = new SmithWaterman(query, target, gaps, blosum62); - self = new SmithWaterman(query, query, gaps, blosum62); + alignment = new SmithWaterman<>(query, target, gaps, blosum62); + self = new SmithWaterman<>(query, query, gaps, blosum62); } @Test public void testSmithWaterman() { SmithWaterman alig = - new SmithWaterman(); + new SmithWaterman<>(); alig.setQuery(query); alig.setTarget(target); alig.setGapPenalty(gaps); diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/TestDNAAlignment.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/TestDNAAlignment.java index a50d8c4cde..6d7312dd33 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/TestDNAAlignment.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/TestDNAAlignment.java @@ -23,9 +23,9 @@ */ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; import org.biojava.nbio.alignment.template.PairwiseSequenceAligner; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; @@ -57,7 +57,7 @@ public void testDNAAlignment() { Profile profile = Alignments.getMultipleSequenceAlignment(lst); - Assert.assertTrue(profile.getSize() == 10); + Assert.assertEquals(10, profile.getSize()); Assert.assertTrue(profile.getAlignedSequence(1).getSequenceAsString().length() > 50); @@ -74,15 +74,10 @@ public void testDNAAlignment() { private static List getDNAFASTAFile() throws Exception { - InputStream inStream = TestDNAAlignment.class.getResourceAsStream(String.format("/dna-fasta.txt")); + InputStream inStream = TestDNAAlignment.class.getResourceAsStream("/dna-fasta.txt"); LinkedHashMap fastas = FastaReaderHelper.readFastaDNASequence(inStream); - List sequences = new ArrayList(); - - for (String key : fastas.keySet()) { - DNASequence seq = fastas.get(key); - sequences.add(seq); - } + List sequences = new ArrayList<>(fastas.values()); return sequences; } @@ -96,7 +91,7 @@ public void testDNAMultipleAlignmentWithMixedCompoundSets() throws CompoundNotFo DNASequence target = new DNASequence("ACTGACGTGTAGCTGACTGA", DNACompoundSet.getDNACompoundSet()); DNASequence query = new DNASequence("ACTGACGTGTAGCTGACTGTA", AmbiguityDNACompoundSet.getDNACompoundSet()); - List lst = new ArrayList(); + List lst = new ArrayList<>(); lst.add(target); lst.add(query); @@ -163,6 +158,6 @@ public void testLinearAlignment() throws CompoundNotFoundException { SubstitutionMatrix matrix = SubstitutionMatrixHelper.getNuc4_4(); SimpleGapPenalty gapP = new SimpleGapPenalty((short)0, (short)3); PairwiseSequenceAligner aligner = Alignments.getPairwiseAligner(query, target, PairwiseSequenceAlignerType.GLOBAL, gapP, matrix); - Assert.assertEquals(String.format("GTAAAA-G----------%nG-AAAACGTTTTTTTTTT%n"), aligner.getPair().toString());; + Assert.assertEquals(String.format("GTAAAA-G----------%nG-AAAACGTTTTTTTTTT%n"), aligner.getPair().toString()); } } diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/TestSubOptimalMSA.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/TestSubOptimalMSA.java index 13a14120a5..11c68570dc 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/TestSubOptimalMSA.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/TestSubOptimalMSA.java @@ -20,8 +20,6 @@ */ package org.biojava.nbio.alignment; -import static org.junit.Assert.*; - import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.DNASequence; @@ -34,9 +32,11 @@ import java.util.ArrayList; import java.util.List; +import static org.junit.Assert.assertEquals; + public class TestSubOptimalMSA { - private List sequences = new ArrayList(); + private final List sequences = new ArrayList<>(); @Before public void setUp() { diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/aaindex/TestAAINDEXLoading.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/aaindex/TestAAINDEXLoading.java index 1dbcc8cfcf..91c16b1aa3 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/aaindex/TestAAINDEXLoading.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/aaindex/TestAAINDEXLoading.java @@ -63,7 +63,7 @@ public void testSDMmatrix(){ SubstitutionMatrix sdm = SubstitutionMatrixHelper.getMatrixFromAAINDEX(matrixName); - int scale = 1; + int scale; if ( sdm instanceof ScaledSubstitutionMatrix) { ScaledSubstitutionMatrix scaledSDM = (ScaledSubstitutionMatrix)sdm; scale = scaledSDM.getScale(); @@ -71,7 +71,7 @@ public void testSDMmatrix(){ } - AminoAcidCompoundSet aas = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet aas = AminoAcidCompoundSet.aminoAcidCompoundSet; AminoAcidCompound v = aas.getCompoundForString("V"); AminoAcidCompound w = aas.getCompoundForString("W"); @@ -149,7 +149,7 @@ public void testOVEJ920104(){ Assert.assertEquals(1000, scale); } - AminoAcidCompoundSet aas = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet aas = AminoAcidCompoundSet.aminoAcidCompoundSet; AminoAcidCompound minus = aas.getCompoundForString("-"); diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/io/TestStockholmParser.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/io/TestStockholmParser.java index 2e888705bf..67ac48522a 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/io/TestStockholmParser.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/io/TestStockholmParser.java @@ -78,10 +78,10 @@ public void testPiwi(){ StockholmStructure data = fileParser.parse(inStream); - Assert.assertTrue("Did not get enough sequences!", data.getBioSequences(false).size() == 20); + Assert.assertEquals("Did not get enough sequences!", 20, data.getBioSequences(false).size()); AbstractSequence seq = data.getBioSequences(false).get(0); - Assert.assertTrue(seq != null); + Assert.assertNotNull(seq); Assert.assertTrue(seq.getSequenceAsString().length() > 20); diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/routines/AlignerHelperTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/routines/AlignerHelperTest.java index 9d12abb897..ae3308ac6c 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/routines/AlignerHelperTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/routines/AlignerHelperTest.java @@ -28,8 +28,7 @@ import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.*; /** * @@ -62,7 +61,7 @@ public void getCuts_should_return_spaced_cuts_when_query_interval_larger_than_cu } @Test public void getSubproblems_should_return_score_indicies_of_alignment_subproblems() { - List anchors = new ArrayList(); + List anchors = new ArrayList<>(); anchors.add(new Anchor(1, 2)); anchors.add(new Anchor(5, 5)); List problems = AlignerHelper.Subproblem.getSubproblems(anchors, 10, 15); @@ -82,18 +81,18 @@ public void getSubproblems_should_return_score_indicies_of_alignment_subproblems } @Test public void getSubproblems_should_allow_zero_anchors() { - List anchors = new ArrayList(); + List anchors = new ArrayList<>(); List problems = AlignerHelper.Subproblem.getSubproblems(anchors, 10, 15); assertEquals(1, problems.size()); assertEquals(0, problems.get(0).getQueryStartIndex()); assertEquals(0, problems.get(0).getTargetStartIndex()); assertEquals(10, problems.get(0).getQueryEndIndex()); assertEquals(15, problems.get(0).getTargetEndIndex()); - assertEquals(false, problems.get(0).isStartAnchored()); + assertFalse(problems.get(0).isStartAnchored()); } @Test public void getSubproblems_should_allow_start_and_end_anchors() { - List anchors = new ArrayList(); + List anchors = new ArrayList<>(); anchors.add(new Anchor(0, 0)); anchors.add(new Anchor(9, 14)); List problems = AlignerHelper.Subproblem.getSubproblems(anchors, 10, 15); @@ -102,21 +101,21 @@ public void getSubproblems_should_allow_start_and_end_anchors() { assertEquals(0, problems.get(0).getTargetStartIndex()); assertEquals(0, problems.get(0).getQueryEndIndex()); assertEquals(0, problems.get(0).getTargetEndIndex()); - assertEquals(false, problems.get(0).isStartAnchored()); + assertFalse(problems.get(0).isStartAnchored()); assertEquals(1, problems.get(1).getQueryStartIndex()); assertEquals(1, problems.get(1).getTargetStartIndex()); assertEquals(9, problems.get(1).getQueryEndIndex()); assertEquals(14, problems.get(1).getTargetEndIndex()); - assertEquals(true, problems.get(1).isStartAnchored()); + assertTrue(problems.get(1).isStartAnchored()); assertEquals(10, problems.get(2).getQueryStartIndex()); assertEquals(15, problems.get(2).getTargetStartIndex()); assertEquals(10, problems.get(2).getQueryEndIndex()); assertEquals(15, problems.get(2).getTargetEndIndex()); - assertEquals(true, problems.get(2).isStartAnchored()); + assertTrue(problems.get(2).isStartAnchored()); } @Test public void getSubproblems_should_allow_adjacent_anchors() { - List anchors = new ArrayList(); + List anchors = new ArrayList<>(); anchors.add(new Anchor(1, 1)); anchors.add(new Anchor(2, 3)); List problems = AlignerHelper.Subproblem.getSubproblems(anchors, 10, 15); @@ -132,14 +131,14 @@ public void getSubproblems_should_allow_adjacent_anchors() { } @Test(expected=IllegalArgumentException.class) public void getSubproblems_should_not_allow_repeated_anchors() { - List anchors = new ArrayList(); + List anchors = new ArrayList<>(); anchors.add(new Anchor(1, 1)); anchors.add(new Anchor(1, 2)); AlignerHelper.Subproblem.getSubproblems(anchors, 10, 15); } @Test(expected=IllegalArgumentException.class) public void getSubproblems_should_not_allow_unalignable_anchors() { - List anchors = new ArrayList(); + List anchors = new ArrayList<>(); anchors.add(new Anchor(1, 2)); anchors.add(new Anchor(2, 1)); AlignerHelper.Subproblem.getSubproblems(anchors, 10, 15); diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/routines/GuanUberbacherTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/routines/GuanUberbacherTest.java index 5ecb525231..03447629be 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/routines/GuanUberbacherTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/routines/GuanUberbacherTest.java @@ -24,8 +24,8 @@ package org.biojava.nbio.alignment.routines; import org.biojava.nbio.alignment.SimpleGapPenalty; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.template.GapPenalty; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.DNASequence; @@ -54,14 +54,14 @@ public void setup() throws CompoundNotFoundException { target = new ProteinSequence("RDG"); gaps = new SimpleGapPenalty(10, 1); blosum62 = SubstitutionMatrixHelper.getBlosum62(); - alignment = new GuanUberbacher(query, target, gaps, blosum62); - self = new GuanUberbacher(query, query, gaps, blosum62); + alignment = new GuanUberbacher<>(query, target, gaps, blosum62); + self = new GuanUberbacher<>(query, query, gaps, blosum62); } @Test public void testGuanUberbacher() { GuanUberbacher gu = - new GuanUberbacher(); + new GuanUberbacher<>(); gu.setQuery(query); gu.setTarget(target); gu.setGapPenalty(gaps); @@ -111,7 +111,7 @@ public void testGetPair() { public void should_align_shorter_query() throws CompoundNotFoundException { DNASequence query = new DNASequence("A", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("AT", AmbiguityDNACompoundSet.getDNACompoundSet()); - GuanUberbacher aligner = new GuanUberbacher(query, target, new SimpleGapPenalty((short)5, (short)2), SubstitutionMatrixHelper.getNuc4_4()); + GuanUberbacher aligner = new GuanUberbacher<>(query, target, new SimpleGapPenalty((short) 5, (short) 2), SubstitutionMatrixHelper.getNuc4_4()); assertEquals(String.format("A-%nAT%n"), aligner.getPair().toString()); } /** @@ -121,7 +121,7 @@ public void should_align_shorter_query() throws CompoundNotFoundException { public void should_align_shorter_target() throws CompoundNotFoundException { DNASequence query = new DNASequence("AT", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("A", AmbiguityDNACompoundSet.getDNACompoundSet()); - GuanUberbacher aligner = new GuanUberbacher(query, target, new SimpleGapPenalty((short)5, (short)2), SubstitutionMatrixHelper.getNuc4_4()); + GuanUberbacher aligner = new GuanUberbacher<>(query, target, new SimpleGapPenalty((short) 5, (short) 2), SubstitutionMatrixHelper.getNuc4_4()); assertEquals(String.format("AT%nA-%n"), aligner.getPair().toString()); } /** @@ -131,7 +131,7 @@ public void should_align_shorter_target() throws CompoundNotFoundException { public void should_align_multiple_cuts() throws CompoundNotFoundException { DNASequence query = new DNASequence("AAT", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("AATG", AmbiguityDNACompoundSet.getDNACompoundSet()); - GuanUberbacher aligner = new GuanUberbacher(query, target, new SimpleGapPenalty((short)0, (short)2), SubstitutionMatrixHelper.getNuc4_4()); + GuanUberbacher aligner = new GuanUberbacher<>(query, target, new SimpleGapPenalty((short) 0, (short) 2), SubstitutionMatrixHelper.getNuc4_4()); aligner.setCutsPerSection(2); // 3 bases with 2 cuts assertEquals(String.format("AAT-%nAATG%n"), aligner.getPair().toString()); } diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/phylo/TestDistanceTreeEvaluator.java b/biojava-alignment/src/test/java/org/biojava/nbio/phylo/TestDistanceTreeEvaluator.java index 3c129e0c22..ddb841d7d5 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/phylo/TestDistanceTreeEvaluator.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/phylo/TestDistanceTreeEvaluator.java @@ -24,7 +24,7 @@ import org.forester.phylogeny.Phylogeny; import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; /** * Test for the evaluation of distance trees. @@ -35,7 +35,7 @@ public class TestDistanceTreeEvaluator { @Test - public void testErrorFree() throws Exception { + public void testErrorFree() { // Create a perfect additive distance matrix BasicSymmetricalDistanceMatrix DM = new BasicSymmetricalDistanceMatrix( @@ -44,7 +44,7 @@ public void testErrorFree() throws Exception { // dAB = 0.8, dBC = 0.4, dAC = 0.8 for (int i = 0; i < 3; i++) { char id = (char) ('A' + i); - DM.setIdentifier(i, id + ""); + DM.setIdentifier(i, String.valueOf(id)); for (int j = i; j < 3; j++) { if (i == j) { DM.setValue(i, j, 0.0); @@ -66,7 +66,7 @@ public void testErrorFree() throws Exception { } @Test - public void testErrorEstimation() throws Exception { + public void testErrorEstimation() { // Matrix taken from forester test BasicSymmetricalDistanceMatrix m = new BasicSymmetricalDistanceMatrix(4); diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/phylo/TestForesterWrapper.java b/biojava-alignment/src/test/java/org/biojava/nbio/phylo/TestForesterWrapper.java index c4fe468852..3fa5e7c20d 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/phylo/TestForesterWrapper.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/phylo/TestForesterWrapper.java @@ -20,11 +20,6 @@ */ package org.biojava.nbio.phylo; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.LinkedHashMap; - import org.biojava.nbio.core.sequence.MultipleSequenceAlignment; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; @@ -33,11 +28,15 @@ import org.biojava.nbio.core.sequence.io.FastaWriter; import org.biojava.nbio.core.sequence.io.GenericFastaHeaderParser; import org.biojava.nbio.core.sequence.io.ProteinSequenceCreator; -import org.biojava.nbio.core.sequence.io.template.FastaHeaderFormatInterface; import org.forester.msa.Msa; import org.junit.Test; -import static org.junit.Assert.*; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.LinkedHashMap; + +import static org.junit.Assert.assertEquals; /** * Test the BioJava-forester wrapper methods. @@ -54,12 +53,11 @@ public void testMSAconversion() throws Exception { InputStream inStream = TestForesterWrapper.class .getResourceAsStream("/1u6d_symm.fasta"); - FastaReader fastaReader = - new FastaReader( - inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet - .getAminoAcidCompoundSet())); + FastaReader fastaReader = + new FastaReader<>( + inStream, + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap proteinSequences = fastaReader .process(); @@ -67,7 +65,7 @@ public void testMSAconversion() throws Exception { inStream.close(); MultipleSequenceAlignment msa = - new MultipleSequenceAlignment(); + new MultipleSequenceAlignment<>(); String expected = ""; for (ProteinSequence proteinSequence : proteinSequences.values()) { @@ -79,14 +77,9 @@ public void testMSAconversion() throws Exception { // Convert the biojava MSA to a FASTA String OutputStream os = new ByteArrayOutputStream(); FastaWriter fastaW = - new FastaWriter(os, - msa.getAlignedSequences(), - new FastaHeaderFormatInterface() { - @Override - public String getHeader(ProteinSequence sequence) { - return sequence.getAccession().toString(); - }; - }); + new FastaWriter<>(os, + msa.getAlignedSequences(), + sequence -> sequence.getAccession().toString()); fastaW.process(); String biojava = os.toString(); @@ -95,8 +88,8 @@ public String getHeader(ProteinSequence sequence) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < fMsa.getNumberOfSequences(); i++) { - sb.append(">" + fMsa.getIdentifier(i) + System.lineSeparator()); - sb.append(fMsa.getSequenceAsString(i) + System.lineSeparator()); + sb.append(">").append(fMsa.getIdentifier(i)).append(System.lineSeparator()); + sb.append(fMsa.getSequenceAsString(i)).append(System.lineSeparator()); } String forester = sb.toString(); diff --git a/biojava-core/pom.xml b/biojava-core/pom.xml index b465a40a36..a7aa8be1e4 100644 --- a/biojava-core/pom.xml +++ b/biojava-core/pom.xml @@ -62,6 +62,15 @@ org.apache.logging.log4j log4j-core + + + + + com.squareup.okhttp3 + okhttp + 3.14.7 + + diff --git a/biojava-core/src/main/java/demo/DemoSixFrameTranslation.java b/biojava-core/src/main/java/demo/DemoSixFrameTranslation.java index 354e0bea26..ae98073d1a 100644 --- a/biojava-core/src/main/java/demo/DemoSixFrameTranslation.java +++ b/biojava-core/src/main/java/demo/DemoSixFrameTranslation.java @@ -106,9 +106,9 @@ public static void main(String[] args){ CompoundSet nucleotideCompoundSet = AmbiguityRNACompoundSet.getRNACompoundSet(); FastaReader proxy = - new FastaReader( + new FastaReader<>( stream, - new GenericFastaHeaderParser(), + new GenericFastaHeaderParser<>(), new DNASequenceCreator(ambiguityDNACompoundSet)); // has only one entry in this example, but could be easily extended to parse a FASTA file with multiple sequences diff --git a/biojava-core/src/main/java/demo/ParseFastaFileDemo.java b/biojava-core/src/main/java/demo/ParseFastaFileDemo.java index 5951ed3ad6..ec1ad49772 100644 --- a/biojava-core/src/main/java/demo/ParseFastaFileDemo.java +++ b/biojava-core/src/main/java/demo/ParseFastaFileDemo.java @@ -21,9 +21,6 @@ package demo; -import java.io.File; -import java.io.InputStream; -import java.util.LinkedHashMap; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; @@ -32,6 +29,11 @@ import org.biojava.nbio.core.sequence.io.ProteinSequenceCreator; import org.biojava.nbio.core.util.InputStreamProvider; +import java.io.File; +import java.io.InputStream; +import java.util.LinkedHashMap; +import java.util.Map; + /** * Created by andreas on 6/17/15. @@ -94,19 +96,19 @@ public static void main(String[] args) throws Exception { InputStream inStream = isp.getInputStream(f); - FastaReader fastaReader = new FastaReader( + FastaReader fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap b; int nrSeq = 0; while ((b = fastaReader.process(100)) != null) { - for (String key : b.keySet()) { + for (Map.Entry entry : b.entrySet()) { nrSeq++; - System.out.println(nrSeq + " : " + key + " " + b.get(key)); + System.out.println(nrSeq + " : " + entry.getKey() + " " + entry.getValue()); if ( nrSeq % 100000 == 0) System.out.println(nrSeq ); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleAlignedSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleAlignedSequence.java index 8980fdad7b..27bf026225 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleAlignedSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleAlignedSequence.java @@ -54,8 +54,10 @@ public class SimpleAlignedSequence, C extends Compound> im // always stored private AlignedSequence prev; - private S original; - private int length, numBefore, numAfter; + private final S original; + private final int length; + private int numBefore; + private int numAfter; private Location location; // cached (lazily initialized) @@ -266,8 +268,9 @@ public boolean isGap(int alignmentIndex) { // methods for Sequence + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { int count = 0; List search = Arrays.asList(compounds); for (C compound : getAsList()) { @@ -285,7 +288,7 @@ public AccessionID getAccession() { @Override public List getAsList() { - List compounds = new ArrayList(); + List compounds = new ArrayList<>(); for (int i = 1; i <= length; i++) { compounds.add(getCompoundAt(i)); } @@ -294,7 +297,7 @@ public List getAsList() { @Override public boolean equals(Object o){ - + if (this == o) return true; if(! Equals.classEqual(this, o)) { return false; } @@ -382,7 +385,7 @@ public String toString() { // helper method to initialize the location private void setLocation(List steps) { - List sublocations = new ArrayList(); + List sublocations = new ArrayList<>(); int start = 0, step = 0, oStep = numBefore+numAfter, oMax = this.original.getLength(), pStep = 0, pMax = (prev == null) ? 0 : prev.getLength(); boolean inGap = true; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleProfile.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleProfile.java index 7cd7ef1bf5..d7438af53d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleProfile.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleProfile.java @@ -57,7 +57,7 @@ public class SimpleProfile, C extends Compound> implements private List> list; private List originals; - private int length; + private final int length; /** * Creates a pair profile for the given already aligned sequences. @@ -70,11 +70,11 @@ protected SimpleProfile(AlignedSequence query, AlignedSequence targe if (query.getLength() != target.getLength()) { throw new IllegalArgumentException("Aligned sequences differ in size"); } - list = new ArrayList>(); + list = new ArrayList<>(); list.add(query); list.add(target); list = Collections.unmodifiableList(list); - originals = new ArrayList(); + originals = new ArrayList<>(); originals.add(query.getOriginalSequence()); originals.add(target.getOriginalSequence()); originals = Collections.unmodifiableList(originals); @@ -87,14 +87,14 @@ protected SimpleProfile(AlignedSequence query, AlignedSequence targe * @param sequence sequence to seed profile */ public SimpleProfile(S sequence) { - List s = new ArrayList(); + List s = new ArrayList<>(); for (int i = 0; i < sequence.getLength(); i++) { s.add(Step.COMPOUND); } - list = new ArrayList>(); - list.add(new SimpleAlignedSequence(sequence, s)); + list = new ArrayList<>(); + list.add(new SimpleAlignedSequence<>(sequence, s)); list = Collections.unmodifiableList(list); - originals = new ArrayList(); + originals = new ArrayList<>(); originals.add(sequence); originals = Collections.unmodifiableList(originals); length = sequence.getLength(); @@ -117,11 +117,11 @@ protected SimpleProfile(S query, S target, List sx, int xb, int xa, List>(); - list.add(new SimpleAlignedSequence(query, sx, xb, xa)); - list.add(new SimpleAlignedSequence(target, sy, yb, ya)); + list = new ArrayList<>(); + list.add(new SimpleAlignedSequence<>(query, sx, xb, xa)); + list.add(new SimpleAlignedSequence<>(target, sy, yb, ya)); list = Collections.unmodifiableList(list); - originals = new ArrayList(); + originals = new ArrayList<>(); originals.add(query); originals.add(target); originals = Collections.unmodifiableList(originals); @@ -141,15 +141,15 @@ protected SimpleProfile(Profile query, Profile target, List sx if (sx.size() != sy.size()) { throw new IllegalArgumentException("Alignments differ in size"); } - list = new ArrayList>(); + list = new ArrayList<>(); for (AlignedSequence s : query) { - list.add(new SimpleAlignedSequence(s, sx)); + list.add(new SimpleAlignedSequence<>(s, sx)); } for (AlignedSequence s : target) { - list.add(new SimpleAlignedSequence(s, sy)); + list.add(new SimpleAlignedSequence<>(s, sy)); } list = Collections.unmodifiableList(list); - originals = new ArrayList(); + originals = new ArrayList<>(); originals.addAll(query.getOriginalSequences()); originals.addAll(target.getOriginalSequences()); originals = Collections.unmodifiableList(originals); @@ -163,8 +163,8 @@ protected SimpleProfile(Profile query, Profile target, List sx * collection is empty. */ public SimpleProfile(Collection> alignedSequences) { - list = new ArrayList>(); - originals = new ArrayList(); + list = new ArrayList<>(); + originals = new ArrayList<>(); Iterator> itr = alignedSequences.iterator(); if(!itr.hasNext()) { @@ -213,16 +213,17 @@ public List> getAlignedSequences() { @Override public List> getAlignedSequences(int... listIndices) { - List> tempList = new ArrayList>(); + List> tempList = new ArrayList<>(); for (int i : listIndices) { tempList.add(getAlignedSequence(i)); } return Collections.unmodifiableList(tempList); } + @SafeVarargs @Override - public List> getAlignedSequences(S... sequences) { - List> tempList = new ArrayList>(); + public final List> getAlignedSequences(S... sequences) { + List> tempList = new ArrayList<>(); for (S s : sequences) { tempList.add(getAlignedSequence(s)); } @@ -242,17 +243,18 @@ public C getCompoundAt(S sequence, int alignmentIndex) { @Override public int[] getCompoundCountsAt(int alignmentIndex) { - return getCompoundCountsAt(alignmentIndex, getCompoundSet().getAllCompounds()); + return getCompoundCountsAt(alignmentIndex, new ArrayList(getCompoundSet().getAllCompounds())); } @Override public int[] getCompoundCountsAt(int alignmentIndex, List compounds) { int[] counts = new int[compounds.size()]; - C gap = getCompoundSet().getCompoundForString("-"); + CompoundSet s = getCompoundSet(); + C gap = s.getCompoundForString("-"); int igap = compounds.indexOf(gap); for (C compound : getCompoundsAt(alignmentIndex)) { int i = compounds.indexOf(compound); - if (i >= 0 && i != igap && !getCompoundSet().compoundsEquivalent(compound, gap)) { + if (i >= 0 && i != igap && !s.compoundsEquivalent(compound, gap)) { counts[i]++; } } @@ -262,7 +264,7 @@ public int[] getCompoundCountsAt(int alignmentIndex, List compounds) { @Override public List getCompoundsAt(int alignmentIndex) { // TODO handle circular alignments - List column = new ArrayList(); + List column = new ArrayList<>(); for (AlignedSequence s : list) { column.add(s.getCompoundAt(alignmentIndex)); } @@ -276,19 +278,20 @@ public CompoundSet getCompoundSet() { @Override public float[] getCompoundWeightsAt(int alignmentIndex) { - return getCompoundWeightsAt(alignmentIndex, getCompoundSet().getAllCompounds()); + return getCompoundWeightsAt(alignmentIndex, new ArrayList(getCompoundSet().getAllCompounds())); } @Override public float[] getCompoundWeightsAt(int alignmentIndex, List compounds) { - float[] weights = new float[compounds.size()]; + int N = compounds.size(); + float[] weights = new float[N]; int[] counts = getCompoundCountsAt(alignmentIndex, compounds); float total = 0.0f; - for (int i : counts) { + for (int i : counts) total += i; - } + if (total > 0.0f) { - for (int i = 0; i < weights.length; i++) { + for (int i = 0; i < N; i++) { weights[i] = counts[i]/total; } } @@ -351,9 +354,10 @@ public ProfileView getSubProfile(Location location) { @Override public boolean hasGap(int alignmentIndex) { - C gap = getCompoundSet().getCompoundForString("-"); + CompoundSet s = getCompoundSet(); + C gap = s.getCompoundForString("-"); for (C compound : getCompoundsAt(alignmentIndex)) { - if (getCompoundSet().compoundsEquivalent(compound, gap)) { + if (s.compoundsEquivalent(compound, gap)) { return true; } } @@ -565,7 +569,7 @@ private void printConservation(StringBuilder s, String idFormat, int seqIndexPad protected static final SubstitutionMatrix matrix = SubstitutionMatrixHelper.getBlosum65(); private boolean isSimilar(char c1, char c2) { - AminoAcidCompoundSet set = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet set = AminoAcidCompoundSet.aminoAcidCompoundSet; AminoAcidCompound aa1 = set.getCompoundForString(String.valueOf(c1)); AminoAcidCompound aa2 = set.getCompoundForString(String.valueOf(c2)); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleProfilePair.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleProfilePair.java index 8d1479bacf..5c5296228c 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleProfilePair.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleProfilePair.java @@ -46,7 +46,8 @@ public class SimpleProfilePair, C extends Compound> extend private static final long serialVersionUID = 1L; - private Profile query, target; + private final Profile query; + private final Profile target; /** * Creates a pair profile for the given profiles. diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/AAIndexFileParser.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/AAIndexFileParser.java index 6e2e5bff56..7b60bb3bc2 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/AAIndexFileParser.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/AAIndexFileParser.java @@ -38,7 +38,7 @@ public class AAIndexFileParser { int scale = -1; - Map> matrices; + final Map> matrices; ScaledSubstitutionMatrix currentMatrix; String currentRows; @@ -53,7 +53,7 @@ public class AAIndexFileParser { public AAIndexFileParser(){ - matrices = new HashMap>(); + matrices = new HashMap<>(); } /** parse an inputStream that points to an AAINDEX database file @@ -71,7 +71,7 @@ public void parse(InputStream inputStream) throws IOException { inMatrix = false; BufferedReader buf = new BufferedReader (new InputStreamReader (inputStream)); - String line = null; + String line; line = buf.readLine(); while ( line != null ) { @@ -125,10 +125,10 @@ private void processScores(String line) { } - Float score = Float.parseFloat(values[i]); + float score = Float.parseFloat(values[i]); score = scale * score; - Short s = (short) Math.round(score); + short s = (short) Math.round(score); matrix[currentRowPos][i] = s; @@ -150,7 +150,7 @@ private void processScores(String line) { } } - private int determineScale(String value) { + private static int determineScale(String value) { String[] spl = value.split("\\."); @@ -177,12 +177,12 @@ private void initMatrix(String line) { matrix = new short[nrRows][nrCols]; - rows = new ArrayList(); - cols = new ArrayList(); + rows = new ArrayList<>(); + cols = new ArrayList<>(); //System.out.println(">" + currentRows+"<"); - AminoAcidCompoundSet compoundSet = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet compoundSet = AminoAcidCompoundSet.aminoAcidCompoundSet; for ( int i = 0 ; i < currentRows.length() ; i ++){ char c = currentRows.charAt(i); AminoAcidCompound aa = compoundSet.getCompoundForString(String.valueOf(c)); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/AAIndexProvider.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/AAIndexProvider.java index 32b5994c60..9eecd9580d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/AAIndexProvider.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/AAIndexProvider.java @@ -26,5 +26,5 @@ public interface AAIndexProvider { - public SubstitutionMatrix getMatrix(String matrixName); + SubstitutionMatrix getMatrix(String matrixName); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/DefaultAAIndexProvider.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/DefaultAAIndexProvider.java index d9119ed7e8..f105cc4ba1 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/DefaultAAIndexProvider.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/DefaultAAIndexProvider.java @@ -38,7 +38,7 @@ public class DefaultAAIndexProvider implements AAIndexProvider { private final static Logger logger = LoggerFactory.getLogger(DefaultAAIndexProvider.class); - Map> matrices; + final Map> matrices; public DefaultAAIndexProvider(){ @@ -65,7 +65,7 @@ public SubstitutionMatrix getMatrix(String matrixName) { } public InputStream getInputStreamToAAindexFile(){ - return SubstitutionMatrixHelper.class.getResourceAsStream(String.format("/matrices/AAINDEX.txt")); + return SubstitutionMatrixHelper.class.getResourceAsStream("/matrices/AAINDEX.txt"); } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/ScaledSubstitutionMatrix.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/ScaledSubstitutionMatrix.java index ee26384bfa..c1cf9e51f8 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/ScaledSubstitutionMatrix.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/ScaledSubstitutionMatrix.java @@ -52,14 +52,14 @@ public class ScaledSubstitutionMatrix implements private String description, name; private short[][] matrix; private short max, min; - private AminoAcidCompoundSet compoundSet; + private final AminoAcidCompoundSet compoundSet; private List rows, cols; private int scale; public ScaledSubstitutionMatrix(){ - compoundSet = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + compoundSet = AminoAcidCompoundSet.aminoAcidCompoundSet; } @@ -164,8 +164,8 @@ public String getMatrixAsString() { int lengthCompound = compoundSet.getMaxSingleCompoundStringLength(), lengthRest = Math.max(Math.max(Short.toString(min).length(), Short.toString(max).length()), lengthCompound) + 1; - String padCompound = "%" + Integer.toString(lengthCompound) + "s", - padRest = "%" + Integer.toString(lengthRest); + String padCompound = "%" + lengthCompound + "s", + padRest = "%" + lengthRest; for (int i = 0; i < lengthCompound; i++) { s.append(" "); @@ -216,7 +216,7 @@ public SubstitutionMatrix normalizeMatrix(short scale) { @Override public Map getRow(AminoAcidCompound row) { int rowIndex = rows.indexOf(row); - Map map = new HashMap(); + Map map = new HashMap<>(); for (int colIndex = 0; colIndex < matrix[rowIndex].length; colIndex++) { map.put(cols.get(colIndex), matrix[rowIndex][colIndex]); } @@ -226,7 +226,7 @@ public Map getRow(AminoAcidCompound row) { @Override public Map getColumn(AminoAcidCompound column) { int colIndex = cols.indexOf(column); - Map map = new HashMap(); + Map map = new HashMap<>(); for (int i = 0; i < matrix.length; i++) { map.put(rows.get(i), matrix[i][colIndex]); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/SimpleSubstitutionMatrix.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/SimpleSubstitutionMatrix.java index 8eb897219e..cb8f23d8dd 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/SimpleSubstitutionMatrix.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/SimpleSubstitutionMatrix.java @@ -50,14 +50,15 @@ public class SimpleSubstitutionMatrix implements Substitutio private static final String comment = "#"; - private CompoundSet compoundSet; + private final CompoundSet compoundSet; private String description, name; - private short[][] matrix; + private final short[][] matrix; private short max, min; - private List rows, cols; + private final List rows; + private final List cols; public static SubstitutionMatrix getBlosum62() { - return new SimpleSubstitutionMatrix(AminoAcidCompoundSet.getAminoAcidCompoundSet(), new InputStreamReader( + return new SimpleSubstitutionMatrix<>(AminoAcidCompoundSet.aminoAcidCompoundSet, new InputStreamReader( SimpleSubstitutionMatrix.class.getResourceAsStream("/matrices/blosum62.txt")), "blosum62"); } @@ -107,10 +108,11 @@ public SimpleSubstitutionMatrix(CompoundSet compoundSet, short match, short r name = "IDENTITY_" + match + "_" + replace; max = (match > replace) ? match : replace; min = (match < replace) ? match : replace; - rows = cols = compoundSet.getAllCompounds(); - matrix = new short[rows.size()][cols.size()]; - for (int r = 0; r < rows.size(); r++) { - for (int c = 0; c < cols.size(); c++) { + rows = cols = new ArrayList<>(compoundSet.getAllCompounds()); + int N = rows.size(); + matrix = new short[N][N]; + for (int r = 0; r < N; r++) { + for (int c = 0; c < N; c++) { try { matrix[r][c] = (compoundSet.compoundsEquivalent(rows.get(r), cols.get(c))) ? match : replace; } catch (UnsupportedOperationException e) { @@ -126,10 +128,10 @@ private SimpleSubstitutionMatrix(CompoundSet compoundSet, Scanner input, Stri this.name = name; max = Short.MIN_VALUE; min = Short.MAX_VALUE; - rows = new ArrayList(); - cols = new ArrayList(); + rows = new ArrayList<>(); + cols = new ArrayList<>(); StringBuilder descriptionIn = new StringBuilder(); - List matrixIn = new ArrayList(); + List matrixIn = new ArrayList<>(); while(input.hasNextLine()) { String line = input.nextLine(); if (line.startsWith(comment)) { @@ -184,8 +186,8 @@ public String getMatrixAsString() { StringBuilder s = new StringBuilder(); int lengthCompound = compoundSet.getMaxSingleCompoundStringLength(), lengthRest = Math.max(Math.max(Short.toString(min).length(), Short.toString(max).length()), lengthCompound) + 1; - String padCompound = "%" + Integer.toString(lengthCompound) + "s", - padRest = "%" + Integer.toString(lengthRest); + String padCompound = "%" + lengthCompound + "s", + padRest = "%" + lengthRest; for (int i = 0; i < lengthCompound; i++) { s.append(" "); } @@ -229,7 +231,8 @@ public String getName() { private static int getIndexOfCompound(List list, C compound) { int index = list.indexOf(compound); if (index == -1) { - for (int i = 0; i < list.size(); i++) { + int N = list.size(); + for (int i = 0; i < N; i++) { if (compound.equalsIgnoreCase(list.get(i))) { index = i; break; @@ -288,8 +291,9 @@ public String toString() { @Override public Map getRow(C row) { int rowIndex = rows.indexOf(row); - Map map = new HashMap(); - for (int colIndex = 0; colIndex < matrix[rowIndex].length; colIndex++) { + Map map = new HashMap<>(); + int N = matrix[rowIndex].length; + for (int colIndex = 0; colIndex < N; colIndex++) { map.put(cols.get(colIndex), matrix[rowIndex][colIndex]); } return map; @@ -298,7 +302,7 @@ public Map getRow(C row) { @Override public Map getColumn(C column) { int colIndex = cols.indexOf(column); - Map map = new HashMap(); + Map map = new HashMap<>(); for (int i = 0; i < matrix.length; i++) { map.put(rows.get(i), matrix[i][colIndex]); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/SubstitutionMatrixHelper.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/SubstitutionMatrixHelper.java index 7b629e7352..ad37e92e37 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/SubstitutionMatrixHelper.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/SubstitutionMatrixHelper.java @@ -48,10 +48,10 @@ public class SubstitutionMatrixHelper implements Serializable { */ private static final long serialVersionUID = 148491724604653225L; - private static Map> aminoAcidMatrices = - new HashMap>(); - private static Map> nucleotideMatrices = - new HashMap>(); + private static final Map> aminoAcidMatrices = + new HashMap<>(); + private static final Map> nucleotideMatrices = + new HashMap<>(); // prevents instantiation private SubstitutionMatrixHelper() { } @@ -251,8 +251,8 @@ public static SubstitutionMatrix getAminoAcidSubstitutionMatr // reads in an amino acid substitution matrix, if necessary private static SubstitutionMatrix getAminoAcidMatrix(String file) { if (!aminoAcidMatrices.containsKey(file)) { - aminoAcidMatrices.put(file, new SimpleSubstitutionMatrix( - AminoAcidCompoundSet.getAminoAcidCompoundSet(), getReader(file), file)); + aminoAcidMatrices.put(file, new SimpleSubstitutionMatrix<>( + AminoAcidCompoundSet.aminoAcidCompoundSet, getReader(file), file)); } return aminoAcidMatrices.get(file); } @@ -260,7 +260,7 @@ private static SubstitutionMatrix getAminoAcidMatrix(String f // reads in a nucleotide substitution matrix, if necessary private static SubstitutionMatrix getNucleotideMatrix(String file) { if (!nucleotideMatrices.containsKey(file)) { - nucleotideMatrices.put(file, new SimpleSubstitutionMatrix( + nucleotideMatrices.put(file, new SimpleSubstitutionMatrix<>( AmbiguityDNACompoundSet.getDNACompoundSet(), getReader(file), file)); } return nucleotideMatrices.get(file); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableAlignedSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableAlignedSequence.java index cfe85f7d33..1291eda8ad 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableAlignedSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableAlignedSequence.java @@ -23,7 +23,6 @@ package org.biojava.nbio.core.alignment.template; -import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.core.sequence.location.template.Location; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableProfile.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableProfile.java index eed30626de..522896c774 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableProfile.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableProfile.java @@ -23,8 +23,6 @@ package org.biojava.nbio.core.alignment.template; -import org.biojava.nbio.core.alignment.template.Profile; -import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableProfilePair.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableProfilePair.java index 70bd1d6410..3d63b0fd39 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableProfilePair.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableProfilePair.java @@ -23,8 +23,6 @@ package org.biojava.nbio.core.alignment.template; -import org.biojava.nbio.core.alignment.template.ProfilePair; -import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableSequencePair.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableSequencePair.java index 86304b7448..78480912c4 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableSequencePair.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableSequencePair.java @@ -23,8 +23,6 @@ package org.biojava.nbio.core.alignment.template; -import org.biojava.nbio.core.alignment.template.SequencePair; -import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Hit.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Hit.java index bf5ee54c69..0a3ba9cae4 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Hit.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Hit.java @@ -20,11 +20,12 @@ */ package org.biojava.nbio.core.search.io; +import org.biojava.nbio.core.sequence.template.Sequence; + import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; - -import org.biojava.nbio.core.sequence.template.Sequence; +import java.util.Objects; /** * This class models a search Hit. @@ -47,7 +48,7 @@ public abstract class Hit implements Iterable{ */ private final int hitLen; private final List hsps; - private Sequence hitSequence; + private final Sequence hitSequence; @@ -85,7 +86,7 @@ public boolean equals(Object obj) { if (this.hitLen != other.hitLen) { return false; } - if (this.hsps != other.hsps && (this.hsps == null || !this.hsps.equals(other.hsps))) { + if (!Objects.equals(this.hsps, other.hsps)) { return false; } return true; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Hsp.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Hsp.java index 8245c635c3..a94f8c29fc 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Hsp.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Hsp.java @@ -20,8 +20,6 @@ */ package org.biojava.nbio.core.search.io; -import java.util.ArrayList; -import java.util.List; import org.biojava.nbio.core.alignment.SimpleAlignedSequence; import org.biojava.nbio.core.alignment.SimpleSequencePair; import org.biojava.nbio.core.alignment.template.AlignedSequence.Step; @@ -37,6 +35,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + /** * This class models a search Hsp. * You will retrieve a list of this using iterator of a Hit @@ -51,25 +53,25 @@ public abstract class Hsp , C extends Compound> { private static final Logger logger = LoggerFactory.getLogger(Hsp.class); - private Integer hspNum; - private Double hspBitScore; - private Integer hspScore; - private Double hspEvalue; - private Integer hspQueryFrom; - private Integer hspQueryTo; - private Integer hspHitFrom; - private Integer hspHitTo; - private Integer hspQueryFrame; - private Integer hspHitFrame; + private final Integer hspNum; + private final Double hspBitScore; + private final Integer hspScore; + private final Double hspEvalue; + private final Integer hspQueryFrom; + private final Integer hspQueryTo; + private final Integer hspHitFrom; + private final Integer hspHitTo; + private final Integer hspQueryFrame; + private final Integer hspHitFrame; private Integer hspIdentity; - private Integer hspPositive; - private Integer hspGaps; + private final Integer hspPositive; + private final Integer hspGaps; private Integer hspAlignLen; - private String hspQseq; - private String hspHseq; - private String hspIdentityString; - private Double percentageIdentity = null; - private Integer mismatchCount = null; + private final String hspQseq; + private final String hspHseq; + private final String hspIdentityString; + private final Double percentageIdentity; + private final Integer mismatchCount; private SimpleSequencePair returnAln; @Override @@ -98,13 +100,13 @@ public boolean equals(Object obj) { return false; } final Hsp other = (Hsp) obj; - if ((this.hspQseq == null) ? (other.hspQseq != null) : !this.hspQseq.equals(other.hspQseq)) { + if (!Objects.equals(this.hspQseq, other.hspQseq)) { return false; } - if ((this.hspHseq == null) ? (other.hspHseq != null) : !this.hspHseq.equals(other.hspHseq)) { + if (!Objects.equals(this.hspHseq, other.hspHseq)) { return false; } - if ((this.hspIdentityString == null) ? (other.hspIdentityString != null) : !this.hspIdentityString.equals(other.hspIdentityString)) { + if (!Objects.equals(this.hspIdentityString, other.hspIdentityString)) { return false; } return true; @@ -115,17 +117,15 @@ public SequencePair getAlignment(){ SimpleAlignedSequence alignedQuery, alignedHit; // queryFrom e hitTo? - int numBefore, numAfter; +// int numBefore, numAfter; alignedQuery = new SimpleAlignedSequence(getSequence(hspQseq), getAlignmentsSteps(hspQseq)); alignedHit = new SimpleAlignedSequence(getSequence(hspHseq), getAlignmentsSteps(hspHseq)); - returnAln = new SimpleSequencePair(alignedQuery, alignedHit); - - return returnAln; + return returnAln = new SimpleSequencePair<>(alignedQuery, alignedHit); } - private Sequence getSequence(String gappedSequenceString){ + private static Sequence getSequence(String gappedSequenceString){ if (gappedSequenceString == null) return null; Sequence returnSeq = null; @@ -137,7 +137,7 @@ private Sequence getSequence(String gappedSequenceString){ else if (sequenceString.matches("^[ACUG]+$")) returnSeq = new RNASequence(sequenceString, DNACompoundSet.getDNACompoundSet()); else - returnSeq = new ProteinSequence(sequenceString, AminoAcidCompoundSet.getAminoAcidCompoundSet()); + returnSeq = new ProteinSequence(sequenceString, AminoAcidCompoundSet.aminoAcidCompoundSet); } catch (CompoundNotFoundException ex) { logger.error("Unexpected error, could not find compound when creating Sequence object from Hsp", ex); } @@ -145,7 +145,7 @@ else if (sequenceString.matches("^[ACUG]+$")) } private List getAlignmentsSteps(String gappedSequenceString){ - List returnList = new ArrayList(); + List returnList = new ArrayList<>(); for (char c: gappedSequenceString.toCharArray()){ if (c=='-') returnList.add(Step.GAP); else returnList.add(Step.COMPOUND); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Result.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Result.java index aa1b432b57..aeab300342 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Result.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Result.java @@ -20,14 +20,10 @@ */ package org.biojava.nbio.core.search.io; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.NoSuchElementException; - import org.biojava.nbio.core.sequence.template.Sequence; +import java.util.*; + /** * This class models a search result. * You will find one of this for every query sequence specified in the run. @@ -41,20 +37,20 @@ */ public abstract class Result implements Iterable{ - private String program; - private String version; - private String reference; - private String dbFile; + private final String program; + private final String version; + private final String reference; + private final String dbFile; - private HashMap programSpecificParameters; + private final HashMap programSpecificParameters; - private int iterationNumber; - private String queryID; - private String queryDef; - private int queryLength; - private Sequence querySequence; - private List hits; - private int hitCounter = -1; + private final int iterationNumber; + private final String queryID; + private final String queryDef; + private final int queryLength; + private final Sequence querySequence; + private final List hits; + private final int hitCounter = -1; public Result(String program, String version, String reference, String dbFile, HashMap programSpecificParameters, int iterationNumber, String queryID, String queryDef, int queryLength, List hits, Sequence querySequence) { this.program = program; @@ -87,6 +83,7 @@ public int hashCode() { */ @Override public boolean equals(Object obj) { + if (this == obj) return true; if (obj == null) { return false; } @@ -94,16 +91,9 @@ public boolean equals(Object obj) { return false; } final Result other = (Result) obj; - if ((this.queryID == null) ? (other.queryID != null) : !this.queryID.equals(other.queryID)) { - return false; - } - if ((this.queryDef == null) ? (other.queryDef != null) : !this.queryDef.equals(other.queryDef)) { - return false; - } - if (this.hits != other.hits && (this.hits == null || !this.hits.equals(other.hits))) { - return false; - } - return true; + return Objects.equals(this.queryID, other.queryID) && + Objects.equals(this.queryDef, other.queryDef) && + Objects.equals(this.hits, other.hits); } public int getIterationNumber() { diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/ResultFactory.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/ResultFactory.java index 479df1ac4d..5e2693b997 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/ResultFactory.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/ResultFactory.java @@ -20,11 +20,12 @@ */ package org.biojava.nbio.core.search.io; +import org.biojava.nbio.core.sequence.template.Sequence; + import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.List; -import org.biojava.nbio.core.sequence.template.Sequence; /** * Designed by Paolo Pavan. @@ -59,7 +60,7 @@ public interface ResultFactory { * @param results * @throws Exception */ - void storeObjects(List results) throws IOException, ParseException; + void storeObjects(List results); /** * Specify the collection of sequences objects used as queries in the Search run. diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/SearchIO.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/SearchIO.java index 52654720d9..ce41e1c248 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/SearchIO.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/SearchIO.java @@ -23,11 +23,7 @@ import java.io.File; import java.io.IOException; import java.text.ParseException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.ServiceLoader; -import java.util.NoSuchElementException; +import java.util.*; /** * Designed by Paolo Pavan. @@ -55,7 +51,7 @@ public class SearchIO implements Iterable{ */ private List results; - private final String NOT_SUPPORTED_FILE_EXCEPTION = + private static final String NOT_SUPPORTED_FILE_EXCEPTION = "This extension is not associated with any parser. You can try to specify a ResultFactory object."; /** @@ -140,7 +136,7 @@ public void writeResults() throws IOException, ParseException { */ private ResultFactory guessFactory(File f){ if (extensionFactoryAssociation == null){ - extensionFactoryAssociation = new HashMap(); + extensionFactoryAssociation = new HashMap<>(); ServiceLoader impl = ServiceLoader.load(ResultFactory.class); for (ResultFactory loadedImpl : impl) { List fileExtensions = loadedImpl.getFileExtensions(); @@ -149,7 +145,7 @@ private ResultFactory guessFactory(File f){ } String filename = f.getAbsolutePath(); - int extensionPos = filename.lastIndexOf("."); + int extensionPos = filename.lastIndexOf('.'); String extension = filename.substring(extensionPos + 1); if (extensionFactoryAssociation.get(extension) == null) throw new UnsupportedOperationException(NOT_SUPPORTED_FILE_EXCEPTION diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastHitBuilder.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastHitBuilder.java index f227e9a68b..ba2e8b5232 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastHitBuilder.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastHitBuilder.java @@ -22,9 +22,10 @@ import org.biojava.nbio.core.search.io.Hsp; -import java.util.List; import org.biojava.nbio.core.sequence.template.Sequence; +import java.util.List; + /** * Designed by Paolo Pavan. * You may want to find my contacts on Github and LinkedIn for code info diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastResult.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastResult.java index bcacdde20d..00a2340455 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastResult.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastResult.java @@ -22,9 +22,10 @@ import org.biojava.nbio.core.search.io.Hit; import org.biojava.nbio.core.search.io.Result; +import org.biojava.nbio.core.sequence.template.Sequence; + import java.util.HashMap; import java.util.List; -import org.biojava.nbio.core.sequence.template.Sequence; /** * This class models a Blast/Blast plus result. diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastResultBuilder.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastResultBuilder.java index 8d7e06a89e..95a5891cb7 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastResultBuilder.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastResultBuilder.java @@ -21,9 +21,10 @@ package org.biojava.nbio.core.search.io.blast; import org.biojava.nbio.core.search.io.Hit; +import org.biojava.nbio.core.sequence.template.Sequence; + import java.util.HashMap; import java.util.List; -import org.biojava.nbio.core.sequence.template.Sequence; /** * Designed by Paolo Pavan. diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastTabularParser.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastTabularParser.java index 410fad0fce..0f408c0ef0 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastTabularParser.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastTabularParser.java @@ -20,16 +20,6 @@ */ package org.biojava.nbio.core.search.io.blast; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.LineNumberReader; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Scanner; import org.biojava.nbio.core.search.io.Hit; import org.biojava.nbio.core.search.io.Hsp; import org.biojava.nbio.core.search.io.Result; @@ -38,6 +28,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.*; +import java.text.ParseException; +import java.util.*; + /** * Designed by Paolo Pavan. * You may want to find my contacts on Github and LinkedIn for code info @@ -48,7 +42,7 @@ */ public class BlastTabularParser implements ResultFactory { - private final String blastReference = + private static final String blastReference = "Zheng Zhang, Scott Schwartz, Lukas Wagner, and Webb Miller (2000), A greedy algorithm for aligning DNA sequences", J Comput Biol 2000; 7(1-2):203-14."; /** * Tries to define a different level of consistency during parsing. @@ -71,7 +65,7 @@ private enum PARSING_CONSISTENCY { // data imported private: int queryIdNumber = 0; - HashMap queryIdMapping = new HashMap(); + final Map queryIdMapping = new HashMap<>(); String programName=null, queryName = null, databaseFile = null; private String queryId ; private String subjectId ; @@ -89,7 +83,7 @@ private enum PARSING_CONSISTENCY { @Override public List getFileExtensions() { - List l = new ArrayList(); + List l = new ArrayList<>(); l.add("blasttabular"); l.add("blasttxt"); return l; @@ -102,7 +96,7 @@ public void setFile(File f) { @Override public List createObjects(double maxEScore) throws IOException, ParseException { - List results = new ArrayList(); + List results = new ArrayList<>(); log.info("Query for hits"); LineNumberReader lnr = new LineNumberReader(new FileReader(targetFile)); @@ -126,33 +120,33 @@ public List createObjects(double maxEScore) throws IOException, ParseExc .setQueryDef(queryName) .setReference(blastReference); - List hits = new ArrayList(); + List hits = new ArrayList<>(); String currentQueryId = queryId; while (currentQueryId.equals(queryId) && lineNumber < fileLinesCount){ BlastHitBuilder hitBuilder = new BlastHitBuilder(); - List hsps = new ArrayList(); + List hsps = new ArrayList<>(); String currentSubjectId=subjectId; while (currentSubjectId.equals(subjectId) && lineNumber < fileLinesCount){ - if (new Double(evalue) > maxEScore) { + if (Double.parseDouble(evalue) > maxEScore) { line = fetchData(scanner); lineNumber++; continue; } BlastHspBuilder hspBuilder = new BlastHspBuilder(); hspBuilder - .setHspAlignLen(new Integer(alnLength)) - .setHspGaps(new Integer(gapOpenCount)) - .setHspQueryFrom(new Integer(queryStart)) - .setHspQueryTo(new Integer(queryEnd)) - .setHspHitFrom(new Integer(subjectStart)) - .setHspHitTo(new Integer(subjectEnd)) - .setHspEvalue(new Double(evalue)) - .setHspBitScore(new Double(bitScore)) - .setPercentageIdentity(new Double(percIdentity)/100) - .setMismatchCount(new Integer(mismatchCount)); + .setHspAlignLen(Integer.parseInt(alnLength)) + .setHspGaps(Integer.parseInt(gapOpenCount)) + .setHspQueryFrom(Integer.parseInt(queryStart)) + .setHspQueryTo(Integer.parseInt(queryEnd)) + .setHspHitFrom(Integer.parseInt(subjectStart)) + .setHspHitTo(Integer.parseInt(subjectEnd)) + .setHspEvalue(Double.parseDouble(evalue)) + .setHspBitScore(Double.parseDouble(bitScore)) + .setPercentageIdentity(Double.parseDouble(percIdentity)/100) + .setMismatchCount(Integer.parseInt(mismatchCount)); hsps.add(hspBuilder.createBlastHsp()); if (scanner.hasNext()) line = fetchData(scanner); lineNumber++; @@ -172,7 +166,7 @@ private String fetchData(Scanner scanner){ String[] split; line = scanner.nextLine(); - while (line.startsWith("#")){ + while (line.charAt(0) == '#'){ // blast tabular with header options contains some more informations if (line.matches("#\\s.?BLAST.+")) programName = line.replace("#\\s",""); if (line.startsWith("# Query:")) queryName = line.replace("# Query: ",""); @@ -203,13 +197,10 @@ private String fetchData(Scanner scanner){ // blast tabular reports only the first word of the query name. // If it was specified in the header it is better to use that definition if (parsingConsistency == PARSING_CONSISTENCY.IMPROVED && headerFound) { - if (queryIdMapping.get(queryId)==null) { - queryIdNumber ++; - queryIdMapping.put(queryId,"Query_" + queryIdNumber); - } + // If a complete definition of the query name was readed, than we can use // a queryID schema that is consistent with blast xml report - queryId = queryIdMapping.get(queryId); + queryId = queryIdMapping.computeIfAbsent(queryId, x -> "Query_" + (++queryIdNumber)); } if (!headerFound) queryName = queryId; @@ -217,7 +208,7 @@ private String fetchData(Scanner scanner){ } @Override - public void storeObjects(List results) throws IOException, ParseException { + public void storeObjects(List results) { throw new UnsupportedOperationException("Not supported yet."); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastXMLParser.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastXMLParser.java index 1b30639b80..25efda84cd 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastXMLParser.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastXMLParser.java @@ -25,6 +25,15 @@ import org.biojava.nbio.core.search.io.Hsp; import org.biojava.nbio.core.search.io.Result; import org.biojava.nbio.core.search.io.ResultFactory; +import org.biojava.nbio.core.sequence.template.Sequence; +import org.biojava.nbio.core.util.XMLHelper; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.xpath.XPathException; import java.io.File; import java.io.IOException; import java.text.ParseException; @@ -32,14 +41,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPathException; -import org.biojava.nbio.core.sequence.template.Sequence; -import org.biojava.nbio.core.util.XMLHelper; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.SAXException; /** * Re-designed by Paolo Pavan on the footprint of: @@ -102,10 +103,10 @@ public List createObjects(double maxEScore) throws IOException, ParseExc String dbFile = XMLHelper.selectSingleElement(blastDoc.getDocumentElement(),"BlastOutput_db").getTextContent(); logger.info("Query for hits in "+ targetFile); - ArrayList IterationsList = XMLHelper.selectElements(blastDoc.getDocumentElement(), "BlastOutput_iterations/Iteration[Iteration_hits]"); + List IterationsList = XMLHelper.selectElements(blastDoc.getDocumentElement(), "BlastOutput_iterations/Iteration[Iteration_hits]"); logger.info(IterationsList.size() + " results"); - resultsCollection = new ArrayList(); + resultsCollection = new ArrayList<>(); for (Element element : IterationsList) { BlastResultBuilder resultBuilder = new BlastResultBuilder(); // will add BlastOutput* key sections in the result object @@ -117,10 +118,10 @@ public List createObjects(double maxEScore) throws IOException, ParseExc // Iteration* section keys: resultBuilder - .setIterationNumber(new Integer(XMLHelper.selectSingleElement(element,"Iteration_iter-num").getTextContent())) + .setIterationNumber(Integer.parseInt(XMLHelper.selectSingleElement(element, "Iteration_iter-num").getTextContent())) .setQueryID(XMLHelper.selectSingleElement(element,"Iteration_query-ID").getTextContent()) .setQueryDef(XMLHelper.selectSingleElement(element, "Iteration_query-def").getTextContent()) - .setQueryLength(new Integer(XMLHelper.selectSingleElement(element,"Iteration_query-len").getTextContent())); + .setQueryLength(Integer.parseInt(XMLHelper.selectSingleElement(element, "Iteration_query-len").getTextContent())); if (queryReferences != null) resultBuilder.setQuerySequence(queryReferencesMap.get( XMLHelper.selectSingleElement(element,"Iteration_query-ID").getTextContent() @@ -128,48 +129,49 @@ public List createObjects(double maxEScore) throws IOException, ParseExc + hitsCollection = new ArrayList<>(); + Element iterationHitsElement = XMLHelper.selectSingleElement(element, "Iteration_hits"); - ArrayList hitList = XMLHelper.selectElements(iterationHitsElement, "Hit"); + List hitList = XMLHelper.selectElements(iterationHitsElement, "Hit"); - hitsCollection = new ArrayList(); for (Element hitElement : hitList) { BlastHitBuilder blastHitBuilder = new BlastHitBuilder(); blastHitBuilder - .setHitNum(new Integer(XMLHelper.selectSingleElement(hitElement, "Hit_num").getTextContent())) + .setHitNum(Integer.parseInt(XMLHelper.selectSingleElement(hitElement, "Hit_num").getTextContent())) .setHitId(XMLHelper.selectSingleElement(hitElement, "Hit_id").getTextContent()) .setHitDef(XMLHelper.selectSingleElement(hitElement, "Hit_def").getTextContent()) .setHitAccession(XMLHelper.selectSingleElement(hitElement, "Hit_accession").getTextContent()) - .setHitLen(new Integer(XMLHelper.selectSingleElement(hitElement, "Hit_len").getTextContent())); + .setHitLen(Integer.parseInt(XMLHelper.selectSingleElement(hitElement, "Hit_len").getTextContent())); if (databaseReferences != null) blastHitBuilder.setHitSequence(databaseReferencesMap.get( XMLHelper.selectSingleElement(hitElement, "Hit_id").getTextContent() )); Element hithspsElement = XMLHelper.selectSingleElement(hitElement, "Hit_hsps"); - ArrayList hspList = XMLHelper.selectElements(hithspsElement, "Hsp"); + List hspList = XMLHelper.selectElements(hithspsElement, "Hsp"); - hspsCollection = new ArrayList(); + hspsCollection = new ArrayList<>(); for (Element hspElement : hspList) { - Double evalue = new Double(XMLHelper.selectSingleElement(hspElement, "Hsp_evalue").getTextContent()); + double evalue = new Double(XMLHelper.selectSingleElement(hspElement, "Hsp_evalue").getTextContent()); // add the new hsp only if it pass the specified threshold. It can save lot of memory and some parsing time if (evalue <= maxEScore) { BlastHspBuilder blastHspBuilder = new BlastHspBuilder(); blastHspBuilder - .setHspNum(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_num").getTextContent())) + .setHspNum(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_num").getTextContent())) .setHspBitScore(new Double(XMLHelper.selectSingleElement(hspElement, "Hsp_bit-score").getTextContent())) - .setHspScore(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_score").getTextContent())) + .setHspScore(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_score").getTextContent())) .setHspEvalue(evalue) - .setHspQueryFrom(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_query-from").getTextContent())) - .setHspQueryTo(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_query-to").getTextContent())) - .setHspHitFrom(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_hit-from").getTextContent())) - .setHspHitTo(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_hit-to").getTextContent())) - .setHspQueryFrame(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_query-frame").getTextContent())) - .setHspHitFrame(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_hit-frame").getTextContent())) - .setHspIdentity(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_identity").getTextContent())) - .setHspPositive(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_positive").getTextContent())) - .setHspGaps(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_gaps").getTextContent())) - .setHspAlignLen(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_align-len").getTextContent())) + .setHspQueryFrom(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_query-from").getTextContent())) + .setHspQueryTo(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_query-to").getTextContent())) + .setHspHitFrom(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_hit-from").getTextContent())) + .setHspHitTo(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_hit-to").getTextContent())) + .setHspQueryFrame(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_query-frame").getTextContent())) + .setHspHitFrame(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_hit-frame").getTextContent())) + .setHspIdentity(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_identity").getTextContent())) + .setHspPositive(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_positive").getTextContent())) + .setHspGaps(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_gaps").getTextContent())) + .setHspAlignLen(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_align-len").getTextContent())) .setHspQseq(XMLHelper.selectSingleElement(hspElement, "Hsp_qseq").getTextContent()) .setHspHseq(XMLHelper.selectSingleElement(hspElement, "Hsp_hseq").getTextContent()) .setHspIdentityString(XMLHelper.selectSingleElement(hspElement, "Hsp_midline").getTextContent()); @@ -195,7 +197,7 @@ public List createObjects(double maxEScore) throws IOException, ParseExc @Override public List getFileExtensions(){ - ArrayList extensions = new ArrayList(1); + ArrayList extensions = new ArrayList<>(1); extensions.add("blastxml"); return extensions; } @@ -215,25 +217,23 @@ public void setDatabaseReferences(List sequences) { */ private void mapIds() { if (queryReferences != null) { - queryReferencesMap = new HashMap(queryReferences.size()); + queryReferencesMap = new HashMap<>(queryReferences.size()); for (int counter=0; counter < queryReferences.size() ; counter ++){ - String id = "Query_"+(counter+1); - queryReferencesMap.put(id, queryReferences.get(counter)); + queryReferencesMap.put("Query_"+(counter+1), queryReferences.get(counter)); } } if (databaseReferences != null) { - databaseReferencesMap = new HashMap(databaseReferences.size()); + databaseReferencesMap = new HashMap<>(databaseReferences.size()); for (int counter=0; counter < databaseReferences.size() ; counter ++){ // this is strange: while Query_id are 1 based, Hit (database) id are 0 based - String id = "gnl|BL_ORD_ID|"+(counter); - databaseReferencesMap.put(id, databaseReferences.get(counter)); + databaseReferencesMap.put("gnl|BL_ORD_ID|"+(counter), databaseReferences.get(counter)); } } } @Override - public void storeObjects(List results) throws IOException, ParseException { + public void storeObjects(List results) { throw new UnsupportedOperationException("This parser does not support writing yet."); } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/AccessionID.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/AccessionID.java index c54c6930a8..c929fc6015 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/AccessionID.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/AccessionID.java @@ -25,6 +25,8 @@ import org.biojava.nbio.core.util.Equals; import org.biojava.nbio.core.util.Hashcoder; +import java.util.Objects; + /** * Used in Sequences as the unique indentifier. If possible, set the {@link DataSource} to know the * source of the id. This allows a SequenceProxy to gather features or related sequences @@ -36,7 +38,7 @@ */ public class AccessionID { - private String id = null; + private final String id; private DataSource source = DataSource.LOCAL; private Integer version; private String identifier = null; @@ -93,13 +95,14 @@ public DataSource getDataSource() { @Override public boolean equals(Object o) { + if (this == o) return true; boolean equals = false; if (Equals.classEqual(this, o)) { AccessionID l = (AccessionID) o; - equals = (Equals.equal(getID(), l.getID()) - && Equals.equal(getDataSource(), l.getDataSource()) - && Equals.equal(getIdentifier(), l.getIdentifier()) - && Equals.equal(getVersion(), l.getVersion())); + equals = (Objects.equals(getID(), l.getID()) + && Objects.equals(getDataSource(), l.getDataSource()) + && Objects.equals(getIdentifier(), l.getIdentifier()) + && Objects.equals(getVersion(), l.getVersion())); } return equals; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/CDSSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/CDSSequence.java index 5973dd386e..e240327ffa 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/CDSSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/CDSSequence.java @@ -37,8 +37,8 @@ public class CDSSequence extends DNASequence { //private static final Logger log = Logger.getLogger(CDSSequence.class.getName()); - Integer phase = 0; // 0, 1, 2 - TranscriptSequence parentTranscriptSequence; + final Integer phase; // 0, 1, 2 + final TranscriptSequence parentTranscriptSequence; /** * diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/ChromosomeSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/ChromosomeSequence.java index f53c539137..eeae4281a4 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/ChromosomeSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/ChromosomeSequence.java @@ -37,7 +37,7 @@ public class ChromosomeSequence extends DNASequence { private int chromosomeNumber; - private LinkedHashMap geneSequenceHashMap = new LinkedHashMap(); + private final LinkedHashMap geneSequenceHashMap = new LinkedHashMap<>(); /** * Empty constructor used by tools that need a proper Bean that allows the actual diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/DNASequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/DNASequence.java index a8d072b4a1..9f77194fce 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/DNASequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/DNASequence.java @@ -136,14 +136,14 @@ public int getGCCount() { * Returns a Sequence which runs in the current reverse order */ public SequenceView getReverse() { - return new ReversedSequenceView(this); + return new ReversedSequenceView<>(this); } /** * Returns a Sequence which will complement every base */ public SequenceView getComplement() { - return new ComplementSequenceView(this); + return new ComplementSequenceView<>(this); } /** @@ -172,7 +172,7 @@ public static void main(String[] args) throws Exception { logger.info("DNA Sequence: {}", dnaSequence.toString()); StringProxySequenceReader sequenceStringProxyLoader = - new StringProxySequenceReader("GCTA", DNACompoundSet.getDNACompoundSet()); + new StringProxySequenceReader<>("GCTA", DNACompoundSet.getDNACompoundSet()); DNASequence dnaSequenceFromProxy = new DNASequence(sequenceStringProxyLoader); logger.info("DNA Sequence from Proxy: {}", dnaSequenceFromProxy.toString()); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/GeneSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/GeneSequence.java index db1f4fd26f..05a040344a 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/GeneSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/GeneSequence.java @@ -30,7 +30,6 @@ import org.slf4j.LoggerFactory; import java.util.ArrayList; -import java.util.Collections; import java.util.LinkedHashMap; /** @@ -41,14 +40,14 @@ public class GeneSequence extends DNASequence { private final static Logger logger = LoggerFactory.getLogger(GeneSequence.class); - private final LinkedHashMap transcriptSequenceHashMap = new LinkedHashMap(); - private final LinkedHashMap intronSequenceHashMap = new LinkedHashMap(); - private final LinkedHashMap exonSequenceHashMap = new LinkedHashMap(); - private final ArrayList intronSequenceList = new ArrayList(); - private final ArrayList exonSequenceList = new ArrayList(); + private final LinkedHashMap transcriptSequenceHashMap = new LinkedHashMap<>(); + private final LinkedHashMap intronSequenceHashMap = new LinkedHashMap<>(); + private final LinkedHashMap exonSequenceHashMap = new LinkedHashMap<>(); + private final ArrayList intronSequenceList = new ArrayList<>(); + private final ArrayList exonSequenceList = new ArrayList<>(); boolean intronAdded = false; // need to deal with the problem that typically introns are not added when validating the list and adding in introns as the regions not included in exons private Strand strand = Strand.UNDEFINED; - private ChromosomeSequence chromosomeSequence; + private final ChromosomeSequence chromosomeSequence; /** * A class that keeps track of the details of a GeneSequence which is difficult to properly model. Two important concepts that is difficult @@ -102,7 +101,7 @@ public void addIntronsUsingExons() throws Exception { } ExonComparator exonComparator = new ExonComparator(); //sort based on start position and sense; - Collections.sort(exonSequenceList, exonComparator); + exonSequenceList.sort(exonComparator); int shift = -1; if (getStrand() == Strand.NEGATIVE) { shift = 1; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/MultipleSequenceAlignment.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/MultipleSequenceAlignment.java index 1ab060d23e..bc30122aea 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/MultipleSequenceAlignment.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/MultipleSequenceAlignment.java @@ -42,7 +42,7 @@ */ public class MultipleSequenceAlignment, C extends Compound> implements LightweightProfile { - private List sequences = new ArrayList(); + private final List sequences = new ArrayList<>(); private Integer length = null; /** @@ -98,7 +98,7 @@ public List getAlignedSequences() { */ @Override public List getCompoundsAt(int alignmentIndex) { - List column = new ArrayList(); + List column = new ArrayList<>(); for (S s : sequences) { column.add(s.getCompoundAt(alignmentIndex)); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/ProteinSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/ProteinSequence.java index e3abbea6bd..a2d5f06029 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/ProteinSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/ProteinSequence.java @@ -25,6 +25,7 @@ import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.compound.*; import org.biojava.nbio.core.sequence.features.FeatureInterface; +import org.biojava.nbio.core.sequence.features.Qualifier; import org.biojava.nbio.core.sequence.io.DNASequenceCreator; import org.biojava.nbio.core.sequence.io.FastaReader; import org.biojava.nbio.core.sequence.io.PlainFastaHeaderParser; @@ -34,6 +35,7 @@ import org.biojava.nbio.core.sequence.template.AbstractSequence; import org.biojava.nbio.core.sequence.template.CompoundSet; import org.biojava.nbio.core.sequence.template.ProxySequenceReader; +import org.biojava.nbio.core.util.FileDownloadUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,7 +44,6 @@ import java.net.URL; import java.util.LinkedHashMap; import java.util.List; -import org.biojava.nbio.core.sequence.features.Qualifier; /** * The representation of a ProteinSequence @@ -67,7 +68,7 @@ public class ProteinSequence extends AbstractSequence { * @throws CompoundNotFoundException */ public ProteinSequence(String seqString) throws CompoundNotFoundException { - this(seqString, AminoAcidCompoundSet.getAminoAcidCompoundSet()); + this(seqString, AminoAcidCompoundSet.aminoAcidCompoundSet); } /** @@ -89,7 +90,7 @@ public ProteinSequence(String seqString, CompoundSet compound * @param proxyLoader */ public ProteinSequence(ProxySequenceReader proxyLoader) { - this(proxyLoader, AminoAcidCompoundSet.getAminoAcidCompoundSet()); + this(proxyLoader, AminoAcidCompoundSet.aminoAcidCompoundSet); } /** @@ -158,12 +159,12 @@ private DNASequence getRawParentSequence(String accessId) throws IOException { logger.trace("Getting parent DNA sequence from URL: {}", url.toString()); - InputStream is = url.openConnection().getInputStream(); + InputStream is = FileDownloadUtils.downloadStream(url, 60000); //url.openConnection().getInputStream(); FastaReader parentReader - = new FastaReader(is, - new PlainFastaHeaderParser(), - new DNASequenceCreator(AmbiguityDNACompoundSet.getDNACompoundSet())); + = new FastaReader<>(is, + new PlainFastaHeaderParser<>(), + new DNASequenceCreator(AmbiguityDNACompoundSet.getDNACompoundSet())); LinkedHashMap seq = parentReader.process(); DNASequence parentSeq = null; @@ -203,7 +204,7 @@ public static void main(String[] args) throws Exception { ProteinSequence proteinSequence = new ProteinSequence("ARNDCEQGHILKMFPSTWYVBZJX"); logger.info("Protein Sequence: {}", proteinSequence.toString()); - StringProxySequenceReader sequenceStringProxyLoader = new StringProxySequenceReader("XRNDCEQGHILKMFPSTWYVBZJA", AminoAcidCompoundSet.getAminoAcidCompoundSet()); + StringProxySequenceReader sequenceStringProxyLoader = new StringProxySequenceReader<>("XRNDCEQGHILKMFPSTWYVBZJA", AminoAcidCompoundSet.aminoAcidCompoundSet); ProteinSequence proteinSequenceFromProxy = new ProteinSequence(sequenceStringProxyLoader); logger.info("Protein Sequence from Proxy: {}", proteinSequenceFromProxy.toString()); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/RNASequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/RNASequence.java index e44e884552..fb6f602d5e 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/RNASequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/RNASequence.java @@ -86,7 +86,7 @@ public RNASequence(ProxySequenceReader proxyLoader, * @return */ public SequenceView getReverseComplement() { - return new ComplementSequenceView(getInverse()); + return new ComplementSequenceView<>(getInverse()); } /** @@ -97,7 +97,7 @@ public SequenceView getReverseComplement() { */ @Override public SequenceView getInverse() { - return new ReversedSequenceView(this); + return new ReversedSequenceView<>(this); } /** @@ -105,7 +105,7 @@ public SequenceView getInverse() { * @return */ public SequenceView getComplement() { - return new ComplementSequenceView(this); + return new ComplementSequenceView<>(this); } /** diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/SequenceOptimizationHints.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/SequenceOptimizationHints.java index 0fab276028..6e7c131902 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/SequenceOptimizationHints.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/SequenceOptimizationHints.java @@ -68,13 +68,13 @@ public static void setSequenceCollection(SequenceCollection aSequenceColection) public enum SequenceUsage { - FULL_SEQUENCE_DATA, SUB_SEQUENCE_DATA, MINIMAL_SEQUENCE_DATA; - } + FULL_SEQUENCE_DATA, SUB_SEQUENCE_DATA, MINIMAL_SEQUENCE_DATA + } public enum SequenceCollection { - ALL_SEQUENCES, VARIABLE_SEQUENCES, MINIMINAL_SEQUENCES; - } + ALL_SEQUENCES, VARIABLE_SEQUENCES, MINIMINAL_SEQUENCES + } static private SequenceUsage sequenceUsage = SequenceUsage.FULL_SEQUENCE_DATA; static private SequenceCollection sequenceCollection = SequenceCollection.ALL_SEQUENCES; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/StartCodonSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/StartCodonSequence.java index eb3d37674a..f900ea3d2d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/StartCodonSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/StartCodonSequence.java @@ -29,7 +29,7 @@ * @author Scooter Willis */ public class StartCodonSequence extends DNASequence { -public DNASequence parentGeneSequence = null; +public final DNASequence parentGeneSequence; public StartCodonSequence(TranscriptSequence parentGeneSequence, int begin, int end){ diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/StopCodonSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/StopCodonSequence.java index 636d8548e0..990a1d09ab 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/StopCodonSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/StopCodonSequence.java @@ -30,7 +30,7 @@ */ public class StopCodonSequence extends DNASequence { -public DNASequence parentGeneSequence = null; +public final DNASequence parentGeneSequence; public StopCodonSequence(TranscriptSequence parentGeneSequence, int begin, int end){ diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/Strand.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/Strand.java index f4816adf7a..032983893d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/Strand.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/Strand.java @@ -33,7 +33,7 @@ public enum Strand { private final String stringRepresentation; private final int numericRepresentation; - private Strand(String stringRepresentation, int numericRepresentation) { + Strand(String stringRepresentation, int numericRepresentation) { this.stringRepresentation = stringRepresentation; this.numericRepresentation = numericRepresentation; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TaxonomyID.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TaxonomyID.java index 64784727bd..b83755bc98 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TaxonomyID.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TaxonomyID.java @@ -30,8 +30,8 @@ public class TaxonomyID { - private String id = null; - DataSource dataSource = DataSource.UNKNOWN; + private final String id; + final DataSource dataSource; public TaxonomyID(String id, DataSource dataSource) { this.id = id; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TranscriptSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TranscriptSequence.java index 29e6e60140..cf26496582 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TranscriptSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TranscriptSequence.java @@ -29,7 +29,6 @@ import org.slf4j.LoggerFactory; import java.util.ArrayList; -import java.util.Collections; import java.util.LinkedHashMap; /** @@ -41,11 +40,11 @@ public class TranscriptSequence extends DNASequence { private final static Logger logger = LoggerFactory.getLogger(TranscriptSequence.class); - private final ArrayList cdsSequenceList = new ArrayList(); - private final LinkedHashMap cdsSequenceHashMap = new LinkedHashMap(); + private final ArrayList cdsSequenceList = new ArrayList<>(); + private final LinkedHashMap cdsSequenceHashMap = new LinkedHashMap<>(); private StartCodonSequence startCodonSequence = null; private StopCodonSequence stopCodonSequence = null; - private GeneSequence parentGeneSequence = null; + private final GeneSequence parentGeneSequence; /** * @@ -113,7 +112,7 @@ public CDSSequence addCDS(AccessionID accession, int begin, int end, int phase) CDSSequence cdsSequence = new CDSSequence(this, begin, end, phase); //sense should be the same as parent cdsSequence.setAccession(accession); cdsSequenceList.add(cdsSequence); - Collections.sort(cdsSequenceList, new CDSComparator()); + cdsSequenceList.sort(new CDSComparator()); cdsSequenceHashMap.put(accession.getID(), cdsSequence); return cdsSequence; } @@ -137,16 +136,16 @@ public CDSSequence addCDS(AccessionID accession, int begin, int end, int phase) * @return */ public ArrayList getProteinCDSSequences() { - ArrayList proteinSequenceList = new ArrayList(); + ArrayList proteinSequenceList = new ArrayList<>(); for (int i = 0; i < cdsSequenceList.size(); i++) { CDSSequence cdsSequence = cdsSequenceList.get(i); String codingSequence = cdsSequence.getCodingSequence(); // logger.debug("CDS {} {} = {}", getStrand(), cdsSequence.getPhase(), codingSequence); if (this.getStrand() == Strand.NEGATIVE) { if (cdsSequence.phase == 1) { - codingSequence = codingSequence.substring(1, codingSequence.length()); + codingSequence = codingSequence.substring(1); } else if (cdsSequence.phase == 2) { - codingSequence = codingSequence.substring(2, codingSequence.length()); + codingSequence = codingSequence.substring(2); } if (i < cdsSequenceList.size() - 1) { CDSSequence nextCDSSequence = cdsSequenceList.get(i + 1); @@ -160,9 +159,9 @@ public ArrayList getProteinCDSSequences() { } } else { if (cdsSequence.phase == 1) { - codingSequence = codingSequence.substring(1, codingSequence.length()); + codingSequence = codingSequence.substring(1); } else if (cdsSequence.phase == 2) { - codingSequence = codingSequence.substring(2, codingSequence.length()); + codingSequence = codingSequence.substring(2); } if (i < cdsSequenceList.size() - 1) { CDSSequence nextCDSSequence = cdsSequenceList.get(i + 1); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AminoAcidCompound.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AminoAcidCompound.java index b1906b81a3..6be60ed5aa 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AminoAcidCompound.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AminoAcidCompound.java @@ -23,75 +23,76 @@ package org.biojava.nbio.core.sequence.compound; -import java.io.Serializable; - import org.biojava.nbio.core.sequence.template.AbstractCompound; -import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.CompoundSet; +import java.io.Serializable; + /** * Used to describe an Amino Acid. + * * @author Richard Holland * @author Scooter Willis * @author Andy Yates */ public class AminoAcidCompound extends AbstractCompound implements Serializable { - /** - * - */ -private static final long serialVersionUID = -1955116496725902319L; -private final AminoAcidCompoundSet compoundSet; + /** + * + */ + private static final long serialVersionUID = -1955116496725902319L; + private final AminoAcidCompoundSet compoundSet; - public AminoAcidCompound(AminoAcidCompoundSet compoundSet, String shortName, - String longName, String description, Float molecularWeight) { - super(shortName); - setShortName(shortName); - setLongName(longName); - setDescription(description); - setMolecularWeight(molecularWeight); - this.compoundSet = compoundSet; - } + public AminoAcidCompound(AminoAcidCompoundSet compoundSet, String shortName, + String longName, String description, float molecularWeight) { + super(shortName); + setShortName(shortName); + setLongName(longName); + setDescription(description); + this.molecularWeight = molecularWeight; + this.compoundSet = compoundSet; + } - // TODO need to allow for modified name; that's not equality though is it? - @Override -public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof AminoAcidCompound)) { - return false; - } - AminoAcidCompound them = (AminoAcidCompound) obj; - if (toString().equals(them.toString())) { - return true; - } - return getLongName().equals(them.getLongName()); +// // TODO need to allow for modified name; that's not equality though is it? +// @Override +// public boolean equals(Object obj) { +// if (obj == null) { +// return false; +// } +// if (!(obj instanceof AminoAcidCompound)) { +// return false; +// } +// AminoAcidCompound them = (AminoAcidCompound) obj; +// if (toString().equals(them.toString())) { +// return true; +// } +// return getLongName().equals(them.getLongName()); +// +// } - } - @Override -public int hashCode() { - return toString().hashCode(); - } +// @Override +// public int hashCode() { +// return toString().hashCode(); +// } - @Override -public boolean equalsIgnoreCase(Compound compound) { - if (compound == null) { - return false; - } - if (!(compound instanceof AminoAcidCompound)) { - return false; - } - AminoAcidCompound them = (AminoAcidCompound) compound; - if (toString().equalsIgnoreCase(them.toString())) { - return true; - } - return getLongName().equalsIgnoreCase(them.getLongName()); - } +// @Override +// public boolean equalsIgnoreCase(Compound compound) { +// if (compound == null) { +// return false; +// } +// if (!(compound instanceof AminoAcidCompound)) { +// return false; +// } +// AminoAcidCompound them = (AminoAcidCompound) compound; +// if (toString().equalsIgnoreCase(them.toString())) { +// return true; +// } +// return getLongName().equalsIgnoreCase(them.getLongName()); +// } - public CompoundSet getCompoundSet() { - return compoundSet; - } + public CompoundSet getCompoundSet() { + return compoundSet; + } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AminoAcidCompoundSet.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AminoAcidCompoundSet.java index 8252f27198..a59a9557b2 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AminoAcidCompoundSet.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AminoAcidCompoundSet.java @@ -44,11 +44,11 @@ public class AminoAcidCompoundSet implements CompoundSet, Ser * */ private static final long serialVersionUID = 4000344194364133456L; - private final Map aminoAcidCompoundCache = new HashMap(); - private final Map aminoAcidCompoundCache3Letter = new HashMap(); + private final Map aminoAcidCompoundCache = new HashMap<>(); + private final Map aminoAcidCompoundCache3Letter = new HashMap<>(); private final Map> equivalentsCache = - new HashMap>(); + new HashMap<>(); public AminoAcidCompoundSet() { aminoAcidCompoundCache.put("A", new AminoAcidCompound(this, "A", "Ala", "Alanine", 71.0788f)); @@ -71,14 +71,14 @@ public AminoAcidCompoundSet() { aminoAcidCompoundCache.put("W", new AminoAcidCompound(this, "W", "Trp", "Tryptophan", 186.2132f)); aminoAcidCompoundCache.put("Y", new AminoAcidCompound(this, "Y", "Tyr", "Tyrosine", 163.1760f)); aminoAcidCompoundCache.put("V", new AminoAcidCompound(this, "V", "Val", "Valine", 99.1326f)); - aminoAcidCompoundCache.put("B", new AminoAcidCompound(this, "B", "Asx", "Asparagine or Aspartic acid", null)); - aminoAcidCompoundCache.put("Z", new AminoAcidCompound(this, "Z", "Glx", "Glutamine or Glutamic acid", null)); - aminoAcidCompoundCache.put("J", new AminoAcidCompound(this, "J", "Xle", "Leucine or Isoleucine", null)); - aminoAcidCompoundCache.put("X", new AminoAcidCompound(this, "X", "Xaa", "Unspecified", null)); - aminoAcidCompoundCache.put("-", new AminoAcidCompound(this, "-", "---", "Unspecified", null)); - aminoAcidCompoundCache.put(".", new AminoAcidCompound(this, ".", "...", "Unspecified", null)); - aminoAcidCompoundCache.put("_", new AminoAcidCompound(this, "_", "___", "Unspecified", null)); - aminoAcidCompoundCache.put("*", new AminoAcidCompound(this, "*", "***", "Stop", null)); + aminoAcidCompoundCache.put("B", new AminoAcidCompound(this, "B", "Asx", "Asparagine or Aspartic acid", Float.NaN)); + aminoAcidCompoundCache.put("Z", new AminoAcidCompound(this, "Z", "Glx", "Glutamine or Glutamic acid", Float.NaN)); + aminoAcidCompoundCache.put("J", new AminoAcidCompound(this, "J", "Xle", "Leucine or Isoleucine", Float.NaN)); + aminoAcidCompoundCache.put("X", new AminoAcidCompound(this, "X", "Xaa", "Unspecified", Float.NaN)); + aminoAcidCompoundCache.put("-", new AminoAcidCompound(this, "-", "---", "Unspecified", Float.NaN)); + aminoAcidCompoundCache.put(".", new AminoAcidCompound(this, ".", "...", "Unspecified", Float.NaN)); + aminoAcidCompoundCache.put("_", new AminoAcidCompound(this, "_", "___", "Unspecified", Float.NaN)); + aminoAcidCompoundCache.put("*", new AminoAcidCompound(this, "*", "***", "Stop", Float.NaN)); //Selenocysteine - this is encoded by UGA with the presence //of a SECIS element (SElenoCysteine Insertion Sequence) in the mRNA @@ -90,11 +90,8 @@ public AminoAcidCompoundSet() { //which then does the actual conversion to Pyl. aminoAcidCompoundCache.put("O", new AminoAcidCompound(this, "O", "Pyl", "Pyrrolysine", 255.3172f)); - for(String oneLtr : aminoAcidCompoundCache.keySet()) { - AminoAcidCompound aa = aminoAcidCompoundCache.get(oneLtr); - String threeLtr = aa.getLongName().toUpperCase(); - aminoAcidCompoundCache3Letter.put(threeLtr, aa); - } + for(AminoAcidCompound aa : aminoAcidCompoundCache.values()) + aminoAcidCompoundCache3Letter.put(aa.getLongName().toUpperCase(), aa); } @Override @@ -104,15 +101,13 @@ public String getStringForCompound(AminoAcidCompound compound) { @Override public AminoAcidCompound getCompoundForString(String string) { - if (string.length() == 0) { + int sl = string.length(); + if (sl == 0) return null; - } - if (string.length() == 3) { + if (sl == 3) return this.aminoAcidCompoundCache3Letter.get(string.toUpperCase()); - } - if (string.length() > this.getMaxSingleCompoundStringLength()) { + if (sl > this.getMaxSingleCompoundStringLength()) throw new IllegalArgumentException("String supplied ("+string+") is too long. Max is "+getMaxSingleCompoundStringLength()); - } return this.aminoAcidCompoundCache.get(string.toUpperCase()); } @@ -127,11 +122,7 @@ public boolean isCompoundStringLengthEqual() { return true; } - private final static AminoAcidCompoundSet aminoAcidCompoundSet = new AminoAcidCompoundSet(); - - public static AminoAcidCompoundSet getAminoAcidCompoundSet() { - return aminoAcidCompoundSet; - } + public final static AminoAcidCompoundSet aminoAcidCompoundSet = new AminoAcidCompoundSet(); @Override public boolean compoundsEquivalent(AminoAcidCompound compoundOne, AminoAcidCompound compoundTwo) { @@ -154,7 +145,7 @@ public Set getEquivalentCompounds(AminoAcidCompound compound) addAmbiguousEquivalents("I", "L", "J"); // ambiguous gaps AminoAcidCompound gap1, gap2, gap3; - Set gaps = new HashSet(); + Set gaps = new HashSet<>(3); gaps.add(gap1 = aminoAcidCompoundCache.get("-")); gaps.add(gap2 = aminoAcidCompoundCache.get(".")); gaps.add(gap3 = aminoAcidCompoundCache.get("_")); @@ -162,7 +153,7 @@ public Set getEquivalentCompounds(AminoAcidCompound compound) equivalentsCache.put(gap2, gaps); equivalentsCache.put(gap3, gaps); // X is never equivalent, even to itself - equivalentsCache.put(aminoAcidCompoundCache.get("X"), new HashSet()); + equivalentsCache.put(aminoAcidCompoundCache.get("X"), Collections.EMPTY_SET); } return equivalentsCache.get(compound); } @@ -172,18 +163,18 @@ private void addAmbiguousEquivalents(String one, String two, String either) { Set equivalents; AminoAcidCompound cOne, cTwo, cEither; - equivalents = new HashSet(); + equivalents = new HashSet<>(3); equivalents.add(cOne = aminoAcidCompoundCache.get(one)); equivalents.add(cTwo = aminoAcidCompoundCache.get(two)); equivalents.add(cEither = aminoAcidCompoundCache.get(either)); equivalentsCache.put(cEither, equivalents); - equivalents = new HashSet(); + equivalents = new HashSet<>(2); equivalents.add(cOne); equivalents.add(cEither); equivalentsCache.put(cOne, equivalents); - equivalents = new HashSet(); + equivalents = new HashSet<>(2); equivalents.add(cTwo); equivalents.add(cEither); equivalentsCache.put(cTwo, equivalents); @@ -197,16 +188,19 @@ public boolean hasCompound(AminoAcidCompound compound) { @Override public boolean isValidSequence(Sequence sequence) { for (AminoAcidCompound compound: sequence) { - if (!hasCompound(compound)) { + if (!hasCompound(compound)) return false; - } } return true; } @Override - public List getAllCompounds() { - return new ArrayList(aminoAcidCompoundCache.values()); + public Collection getAllCompounds() { + return + //new ArrayList<>( + Collections.unmodifiableCollection( + aminoAcidCompoundCache.values() + ); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/CodonCompound.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/CodonCompound.java index d78b307b42..35180fa4ef 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/CodonCompound.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/CodonCompound.java @@ -1,139 +1,138 @@ -/* - * BioJava development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public Licence. This should - * be distributed with the code. If you do not have a copy, - * see: - * - * http://www.gnu.org/copyleft/lesser.html - * - * Copyright for this code is held jointly by the individual - * authors. These should be listed in @author doc comments. - * - * For more information on the BioJava project and its aims, - * or to join the biojava-l mailing list, visit the home page - * at: - * - * http://www.biojava.org/ - * - * Created on 01-21-2010 - */ -package org.biojava.nbio.core.sequence.compound; - -import org.biojava.nbio.core.sequence.template.AbstractCompound; -import org.biojava.nbio.core.sequence.template.Compound; -/** - * Define a codon - * @author Andy Yates - */ -public class CodonCompound extends AbstractCompound { - - private final NucleotideCompound one; - private final NucleotideCompound two; - private final NucleotideCompound three; - private final boolean start; - - public CodonCompound(NucleotideCompound one, NucleotideCompound two, - NucleotideCompound three, boolean start) { - super(one.toString()+two.toString()+three.toString()); - this.one = one; - this.two = two; - this.three = three; - this.start = start; - } - - @Override -public boolean equalsIgnoreCase(Compound compound) { - if (compound == null) { - return false; - } - if (!(compound instanceof CodonCompound)) { - return false; - } - CodonCompound them = (CodonCompound) compound; - return toString().equalsIgnoreCase(them.toString()); - } - - @Override -public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof CodonCompound)) { - return false; - } - CodonCompound them = (CodonCompound)obj; - return toString().equals(them.toString()); - } - - @Override -public int hashCode() { - return toString().hashCode(); - } - - public NucleotideCompound getOne() { - return one; - } - - public NucleotideCompound getTwo() { - return two; - } - - public NucleotideCompound getThree() { - return three; - } - - public boolean isStart() { - return start; - } - - @Override -public String getDescription() { - // TODO Auto-generated method stub - return null; - } - - @Override -public String getLongName() { - // TODO Auto-generated method stub - return null; - } - - @Override -public Float getMolecularWeight() { - // TODO Auto-generated method stub - return null; - } - - @Override -public String getShortName() { - // TODO Auto-generated method stub - return null; - } - - @Override -public void setDescription(String description) { - // TODO Auto-generated method stub - - } - - @Override -public void setLongName(String longName) { - // TODO Auto-generated method stub - - } - - @Override -public void setMolecularWeight(Float molecularWeight) { - // TODO Auto-generated method stub - - } - - @Override -public void setShortName(String shortName) { - // TODO Auto-generated method stub - - } - -} +///* +// * BioJava development code +// * +// * This code may be freely distributed and modified under the +// * terms of the GNU Lesser General Public Licence. This should +// * be distributed with the code. If you do not have a copy, +// * see: +// * +// * http://www.gnu.org/copyleft/lesser.html +// * +// * Copyright for this code is held jointly by the individual +// * authors. These should be listed in @author doc comments. +// * +// * For more information on the BioJava project and its aims, +// * or to join the biojava-l mailing list, visit the home page +// * at: +// * +// * http://www.biojava.org/ +// * +// * Created on 01-21-2010 +// */ +//package org.biojava.nbio.core.sequence.compound; +// +//import org.biojava.nbio.core.sequence.template.AbstractCompound; +//import org.biojava.nbio.core.sequence.template.Compound; +///** +// * Define a codon +// * @author Andy Yates +// */ +//public class CodonCompound extends AbstractCompound { +// +// private final NucleotideCompound one; +// private final NucleotideCompound two; +// private final NucleotideCompound three; +// private final boolean start; +// +// public CodonCompound(NucleotideCompound one, NucleotideCompound two, +// NucleotideCompound three, boolean start) { +// super(one.toString()+two.toString()+three.toString()); +// this.one = one; +// this.two = two; +// this.three = three; +// this.start = start; +// } +// +// @Override +//public boolean equalsIgnoreCase(Compound compound) { +// if (compound == null) { +// return false; +// } +// if (!(compound instanceof CodonCompound)) { +// return false; +// } +// CodonCompound them = (CodonCompound) compound; +// return toString().equalsIgnoreCase(them.toString()); +// } +// +// @Override +//public boolean equals(Object obj) { +// if (obj == null) { +// return false; +// } +// if (!(obj instanceof CodonCompound)) { +// return false; +// } +// CodonCompound them = (CodonCompound)obj; +// return toString().equals(them.toString()); +// } +// +// @Override +//public int hashCode() { +// return toString().hashCode(); +// } +// +// public NucleotideCompound getOne() { +// return one; +// } +// +// public NucleotideCompound getTwo() { +// return two; +// } +// +// public NucleotideCompound getThree() { +// return three; +// } +// +// public boolean isStart() { +// return start; +// } +// +// @Override +//public String getDescription() { +// // TODO Auto-generated method stub +// return null; +// } +// +// @Override +//public String getLongName() { +// // TODO Auto-generated method stub +// return null; +// } +// +// @Override +//public Float getMolecularWeight() { +// // TODO Auto-generated method stub +// return null; +// } +// +// @Override +//public String getShortName() { +// // TODO Auto-generated method stub +// return null; +// } +// +// @Override +//public void setDescription(String description) { +// // TODO Auto-generated method stub +// +// } +// +// @Override +//public void setLongName(String longName) { +// // TODO Auto-generated method stub +// +// } +// +// public void setMolecularWeight(Float molecularWeight) { +// // TODO Auto-generated method stub +// +// } +// +// @Override +//public void setShortName(String shortName) { +// // TODO Auto-generated method stub +// +// } +// +//} diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/NucleotideCompound.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/NucleotideCompound.java index 786c79f812..48d6e31a59 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/NucleotideCompound.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/NucleotideCompound.java @@ -27,9 +27,9 @@ import org.biojava.nbio.core.sequence.template.AbstractCompound; import org.biojava.nbio.core.sequence.template.ComplementCompound; -import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.CompoundSet; +import java.util.Collections; import java.util.HashSet; import java.util.Set; @@ -51,14 +51,14 @@ public NucleotideCompound(String base, CompoundSet compoundS super(base); this.compoundSet = compoundSet; this.complementStr = complementStr; - this.constituents = unmodifiableSet(new HashSet(asList(this))); + this.constituents = unmodifiableSet(new HashSet<>(Collections.singletonList(this))); } public NucleotideCompound(String base, CompoundSet compoundSet, String complementStr, NucleotideCompound[] constituents) { super(base); this.compoundSet = compoundSet; this.complementStr = complementStr; - this.constituents = unmodifiableSet(new HashSet(asList(constituents))); + this.constituents = unmodifiableSet(new HashSet<>(asList(constituents))); } @Override @@ -70,35 +70,35 @@ public String getShortName() { public ComplementCompound getComplement() { return compoundSet.getCompoundForString(complementStr); } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof NucleotideCompound)) { - return false; - } - NucleotideCompound them = (NucleotideCompound) obj; - return toString().equals(them.toString()); - } - - @Override - public int hashCode() { - return toString().hashCode(); - } - - @Override - public boolean equalsIgnoreCase(Compound compound) { - if (compound == null) { - return false; - } - if (!(compound instanceof NucleotideCompound)) { - return false; - } - NucleotideCompound them = (NucleotideCompound) compound; - return toString().equalsIgnoreCase(them.toString()); - } +// +// @Override +// public boolean equals(Object obj) { +// if (obj == null) { +// return false; +// } +// if (!(obj instanceof NucleotideCompound)) { +// return false; +// } +// NucleotideCompound them = (NucleotideCompound) obj; +// return toString().equals(them.toString()); +// } +// +// @Override +// public int hashCode() { +// return toString().hashCode(); +// } +// +// @Override +// public boolean equalsIgnoreCase(Compound compound) { +// if (compound == null) { +// return false; +// } +// if (!(compound instanceof NucleotideCompound)) { +// return false; +// } +// NucleotideCompound them = (NucleotideCompound) compound; +// return toString().equalsIgnoreCase(them.toString()); +// } public Set getConstituents() { return constituents; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/edits/Edit.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/edits/Edit.java index 19923effed..2279df647e 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/edits/Edit.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/edits/Edit.java @@ -58,7 +58,7 @@ public interface Edit { * with a target Sequence. These ends can be of 0 length but conceptionally * they can still exist. */ - public static abstract class AbstractEdit implements Edit { + abstract class AbstractEdit implements Edit { private final static Logger logger = LoggerFactory.getLogger(AbstractEdit.class); @@ -78,15 +78,15 @@ public static abstract class AbstractEdit implements Edit @Override public Sequence edit(Sequence editingSequence) { Sequence targetSequence = getTargetSequence(editingSequence); - List> sequences = new ArrayList>(); + List> sequences = new ArrayList<>(); sequences.add(getFivePrime(editingSequence)); sequences.add(targetSequence); sequences.add(getThreePrime(editingSequence)); - return new JoiningSequenceReader(sequences); + return new JoiningSequenceReader<>(sequences); } - private int start = -1; + private final int start; private int end = -1; private String stringSequence; private Sequence sequence; @@ -119,8 +119,8 @@ protected void setSequence(Sequence sequence) { public Sequence getTargetSequence(Sequence editingSequence) { if (sequence == null && stringSequence != null) { try { - sequence = new BasicSequence( - stringSequence, editingSequence.getCompoundSet()); + sequence = new BasicSequence<>( + stringSequence, editingSequence.getCompoundSet()); } catch (CompoundNotFoundException e) { // TODO is there a better way to handle this exception? logger.error("Problem setting sequence, some unrecognised compounds: {}", e.getMessage()); @@ -136,7 +136,7 @@ public Sequence getTargetSequence(Sequence editingSequence) { protected Sequence getEmptySequence(Sequence editingSequence) { Sequence s = null; try { - s = new BasicSequence("", editingSequence.getCompoundSet()); + s = new BasicSequence<>("", editingSequence.getCompoundSet()); } catch (CompoundNotFoundException e) { // should not happen logger.error("Could not construct empty sequence. {}. This is most likely a bug.", e.getMessage()); @@ -156,7 +156,7 @@ public int getEnd() { /** * Implementation which allows for the deletion of bases from a Sequence */ - public static class Delete extends AbstractEdit { + class Delete extends AbstractEdit { public Delete(int position) { this(position, position); @@ -209,7 +209,7 @@ protected Sequence getThreePrime(Sequence editingSequence) { * The code will raise exceptions if you attempt a single base edit * with an insertion. */ - public static class Insert extends AbstractEdit { + class Insert extends AbstractEdit { private final boolean singlePosition; @@ -285,7 +285,7 @@ protected Sequence getThreePrime(Sequence editingSequence) { * presence of a CompoundSet to parse a String (if given) which means * the eventual length of a Sequence is a lazy operation. */ - public static class Substitute extends AbstractEdit { + class Substitute extends AbstractEdit { public Substitute(String sequence, int position) { super(position); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/AbstractFeature.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/AbstractFeature.java index d601c573b0..41f94eb72f 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/AbstractFeature.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/AbstractFeature.java @@ -26,11 +26,7 @@ import org.biojava.nbio.core.sequence.template.AbstractSequence; import org.biojava.nbio.core.sequence.template.Compound; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; /** * A feature is currently any descriptive item that can be associated with a sequence position(s) @@ -40,15 +36,15 @@ */ public abstract class AbstractFeature, C extends Compound> implements FeatureInterface { - List> childrenFeatures = new ArrayList>(); + List> childrenFeatures = new ArrayList<>(); FeatureInterface parentFeature; AbstractLocation sequenceLocation; - String type = ""; - String source = ""; + String type; + String source; private String description = ""; private String shortDescription = ""; private Object userObject = null; - private Map> Qualifiers = new HashMap>(); + private Map> Qualifiers = new HashMap<>(); /** * A feature has a type and a source @@ -196,28 +192,19 @@ public void setShortDescription(String shortDescription) { * of overlapping features so they are delivered in a proper order. */ - public static final Comparator> LOCATION_LENGTH = new Comparator>() { - - @Override - public int compare(FeatureInterface e1, FeatureInterface e2) { - double v1 = e1.getLocations().getStart().getPosition(); - double v2 = e2.getLocations().getStart().getPosition(); - if (v1 < v2) { - return -1; - } else if (v1 > v2) { - return 1; - } else { - double end1 = e1.getLocations().getEnd().getPosition(); - double end2 = e2.getLocations().getEnd().getPosition(); - if(end1 > end2) - return -1; - else if(end1 < end2) - return 1; - else - return 0; - } - + public static final Comparator> LOCATION_LENGTH = (e1, e2) -> { + double v1 = e1.getLocations().getStart().getPosition(); + double v2 = e2.getLocations().getStart().getPosition(); + if (v1 < v2) { + return -1; + } else if (v1 > v2) { + return 1; + } else { + double end1 = e1.getLocations().getEnd().getPosition(); + double end2 = e2.getLocations().getEnd().getPosition(); + return Double.compare(end2, end1); } + }; /** @@ -225,33 +212,17 @@ else if(end1 < end2) * */ - static public final Comparator> LENGTH = new Comparator>() { - - @Override - public int compare(FeatureInterface e1, FeatureInterface e2) { - double v1 = Math.abs(e1.getLocations().getEnd().getPosition()- e1.getLocations().getStart().getPosition()); - double v2 = Math.abs(e2.getLocations().getEnd().getPosition() - e2.getLocations().getStart().getPosition()); - if (v1 < v2) { - return -1; - } else if (v1 > v2) { - return 1; - } else { - return 0; - } + static public final Comparator> LENGTH = (e1, e2) -> { + double v1 = Math.abs(e1.getLocations().getEnd().getPosition()- e1.getLocations().getStart().getPosition()); + double v2 = Math.abs(e2.getLocations().getEnd().getPosition() - e2.getLocations().getStart().getPosition()); + return Double.compare(v1, v2); - } }; /** * Sort features by type */ - public static final Comparator> TYPE = new Comparator>() { - - @Override - public int compare(FeatureInterface o1, FeatureInterface o2) { - return o1.getType().compareTo(o2.getType()); - } - }; + public static final Comparator> TYPE = Comparator.comparing(FeatureInterface::getType); /** * @return the userObject @@ -292,7 +263,7 @@ public void addQualifier(String key, Qualifier qualifier) { vals.add(qualifier); Qualifiers.put(key, vals); } else { - List vals = new ArrayList(); + List vals = new ArrayList<>(); vals.add(qualifier); Qualifiers.put(key, vals); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/DBReferenceInfo.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/DBReferenceInfo.java index ce8793c561..28b14712ca 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/DBReferenceInfo.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/DBReferenceInfo.java @@ -37,9 +37,9 @@ * @author Paolo Pavan */ public class DBReferenceInfo extends Qualifier { - private LinkedHashMap properties = new LinkedHashMap(); - private String database = ""; - private String id = ""; + private LinkedHashMap properties = new LinkedHashMap<>(); + private String database; + private String id; /** * The source database and id diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/DatabaseReferenceInterface.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/DatabaseReferenceInterface.java index 0cb3ea5d8c..ceb6e34509 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/DatabaseReferenceInterface.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/DatabaseReferenceInterface.java @@ -32,5 +32,5 @@ */ public interface DatabaseReferenceInterface { - public LinkedHashMap> getDatabaseReferences(); + LinkedHashMap> getDatabaseReferences(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureDbReferenceInfo.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureDbReferenceInfo.java index c270cc74e7..3b49341d22 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureDbReferenceInfo.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureDbReferenceInfo.java @@ -46,11 +46,11 @@ public class FeatureDbReferenceInfo, C extends Com private AbstractLocation location; private FeatureInterface parentFeature; - private List> childrenFeatures = new ArrayList>(); + private List> childrenFeatures = new ArrayList<>(); private String description = ""; private String shortDescription = ""; private Object userObject; - private Map> qualifiers = new HashMap>(); + private Map> qualifiers = new HashMap<>(); public FeatureDbReferenceInfo(String database, String id) { @@ -150,7 +150,7 @@ public void setQualifiers(Map> qualifiers) { @Override public void addQualifier(String key, Qualifier qualifier) { if (qualifiers == null) { - qualifiers = new HashMap>(); + qualifiers = new HashMap<>(); } // Check for key. Update list of values if (qualifiers.containsKey(key)){ @@ -158,7 +158,7 @@ public void addQualifier(String key, Qualifier qualifier) { vals.add(qualifier); qualifiers.put(key, vals); } else { - List vals = new ArrayList(); + List vals = new ArrayList<>(); vals.add(qualifier); qualifiers.put(key, vals); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureInterface.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureInterface.java index 47564bcefa..0c1d26e478 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureInterface.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureInterface.java @@ -21,13 +21,13 @@ package org.biojava.nbio.core.sequence.features; -import java.util.List; -import java.util.Map; - import org.biojava.nbio.core.sequence.location.template.AbstractLocation; import org.biojava.nbio.core.sequence.template.AbstractSequence; import org.biojava.nbio.core.sequence.template.Compound; +import java.util.List; +import java.util.Map; + /** * Interface class to handle describing arbitrary features. A feature can be found at multiple locations in a sequence such as * the surface of a protein where different sequence positions make up that feature. Ligand binding pocket is another example. @@ -47,21 +47,21 @@ public interface FeatureInterface, C extends Compo * @return */ - public String getShortDescription(); + String getShortDescription(); /** * Set the short description that can be used to describe the feature * @param shortDescription */ - public void setShortDescription(String shortDescription); + void setShortDescription(String shortDescription); /** * Get the description that can be used to describe the feature * @return */ - public String getDescription(); + String getDescription(); /** @@ -69,7 +69,7 @@ public interface FeatureInterface, C extends Compo * @return */ - public void setDescription(String description); + void setDescription(String description); /** * The location(s) of this feature where the location should contain a reference to parent and sequence etc. @@ -80,7 +80,7 @@ public interface FeatureInterface, C extends Compo * * @return a Location anchoring this feature */ - public AbstractLocation getLocations(); + AbstractLocation getLocations(); /** * The new location for this feature. @@ -93,14 +93,14 @@ public interface FeatureInterface, C extends Compo * @param loc the new Location for this feature * */ - public void setLocation(AbstractLocation loc); + void setLocation(AbstractLocation loc); /** * The type of the feature. * * @return the type of this sequence */ - public String getType(); + String getType(); /** * Change the type of this feature. @@ -108,7 +108,7 @@ public interface FeatureInterface, C extends Compo * @param type new type String * */ - public void setType(String type); + void setType(String type); /** @@ -116,7 +116,7 @@ public interface FeatureInterface, C extends Compo * * @return the source, or generator */ - public String getSource(); + String getSource(); /** * Change the source of the FeatureInterface. @@ -124,46 +124,46 @@ public interface FeatureInterface, C extends Compo * @param source the new source String * */ - public void setSource(String source); + void setSource(String source); /** * Set the parent feature * @param feature */ - public void setParentFeature(FeatureInterface feature); + void setParentFeature(FeatureInterface feature); /** * Get the parent feature * @return */ - public FeatureInterface getParentFeature(); + FeatureInterface getParentFeature(); /** * Get the features contained by this feature * @return */ - public List> getChildrenFeatures(); + List> getChildrenFeatures(); /** * Set the children features * @param features */ - public void setChildrenFeatures(List> features); + void setChildrenFeatures(List> features); /** * @return the userObject */ - public Object getUserObject(); + Object getUserObject(); /** * @param userObject the userObject to set */ - public void setUserObject(Object userObject); + void setUserObject(Object userObject); /** @@ -171,19 +171,19 @@ public interface FeatureInterface, C extends Compo * @return */ - public Map> getQualifiers(); + Map> getQualifiers(); /** * Set the qualifiers * @param qualifiers */ - public void setQualifiers(Map> qualifiers); + void setQualifiers(Map> qualifiers); /** * Add a qualifier * @param qualifier */ - public void addQualifier(String key, Qualifier qualifier); + void addQualifier(String key, Qualifier qualifier); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeaturesKeyWordInterface.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeaturesKeyWordInterface.java index 9674d1abee..e8b62432b1 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeaturesKeyWordInterface.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeaturesKeyWordInterface.java @@ -22,7 +22,7 @@ package org.biojava.nbio.core.sequence.features; -import java.util.ArrayList; +import java.util.List; /** * Models the keywords that are annotated for a protein sequence at Uniprot. If a ProxySequenceReader @@ -36,5 +36,5 @@ public interface FeaturesKeyWordInterface { * * @return */ - public ArrayList getKeyWords() ; + List getKeyWords() ; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/QualityFeature.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/QualityFeature.java index 7eec33a62a..0e7da9a97b 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/QualityFeature.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/QualityFeature.java @@ -37,7 +37,7 @@ */ public class QualityFeature, C extends Compound> extends AbstractFeature { - private List qualities = new ArrayList(); + private List qualities = new ArrayList<>(); /** * @param type diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/QuantityFeature.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/QuantityFeature.java index bce00e2729..524bdfdaa3 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/QuantityFeature.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/QuantityFeature.java @@ -35,7 +35,7 @@ */ public class QuantityFeature, C extends Compound> extends AbstractFeature { - private List quantities = new ArrayList(); + private List quantities = new ArrayList<>(); /** * diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/ABITrace.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/ABITrace.java index d2cebd7cd1..8b7fdc65a8 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/ABITrace.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/ABITrace.java @@ -22,23 +22,15 @@ package org.biojava.nbio.core.sequence.io; -import java.io.IOException; -import java.io.File; -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.DataInputStream; -import java.io.ByteArrayInputStream; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.net.URL; -import java.io.InputStream; - +import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.compound.ABITracerCompoundSet; import org.biojava.nbio.core.sequence.compound.NucleotideCompound; import org.biojava.nbio.core.sequence.template.AbstractSequence; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; + +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.*; +import java.net.URL; /** * Title: ABITrace

    @@ -55,7 +47,12 @@ public class ABITrace { //the next three lines are the important persistent data private String sequence; - private int A[], G[], C[], T[], baseCalls[], qCalls[]; + private int[] A; + private int[] G; + private int[] C; + private int[] T; + private int[] baseCalls; + private int[] qCalls; private int traceLength, seqLength; //This is the actual file data. @@ -110,7 +107,7 @@ public ABITrace( URL ABIFile ) throws IOException * @throws IOException if there is a problem reading from the BufferedInputStream */ private void ABITraceInit(BufferedInputStream bis) throws IOException{ - byte[] bytes = null; + byte[] bytes; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b; while ((b = bis.read()) >= 0) @@ -191,16 +188,17 @@ public AbstractSequence getSequence() throws CompoundNotFoun * @throws CompoundNotFoundException if the base is not valid */ public int[] getTrace (String base) throws CompoundNotFoundException { - if (base.equals("A")) { - return A; - } else if (base.equals("C")) { - return C; - } else if (base.equals("G")) { - return G; - } else if (base.equals("T")) { - return T; - } else { - throw new CompoundNotFoundException("Don't know base: " + base); + switch (base) { + case "A": + return A; + case "C": + return C; + case "G": + return G; + case "T": + return T; + default: + throw new CompoundNotFoundException("Don't know base: " + base); } } @@ -320,9 +318,9 @@ private int transmute(int ya, int height, double scale) { * @return - scaling factor */ private double calculateScale(int height) { - double newScale = 0.0; - double max = (double) getMaximum(); - double ht = (double) height; + double newScale; + double max = getMaximum(); + double ht = height; newScale = ((ht - 50.0)) / max; return newScale; } @@ -366,9 +364,9 @@ private void initData(byte[] fileData) { * traces into their arrays. */ private void setTraces() { - int pointers[] = new int[4]; //alphabetical, 0=A, 1=C, 2=G, 3=T - int datas[] = new int[4]; - char order[] = new char[4]; + int[] pointers = new int[4]; //alphabetical, 0=A, 1=C, 2=G, 3=T + int[] datas = new int[4]; + char[] order = new char[4]; datas[0] = DATA9; datas[1] = DATA10; @@ -413,10 +411,10 @@ private void setTraces() { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(qq)); for (int x = 0; x <= traceLength - 1; x++) { try { - if (i == 0) A[x] = (int) dis.readShort(); - if (i == 1) C[x] = (int) dis.readShort(); - if (i == 2) G[x] = (int) dis.readShort(); - if (i == 3) T[x] = (int) dis.readShort(); + if (i == 0) A[x] = dis.readShort(); + if (i == 1) C[x] = dis.readShort(); + if (i == 2) G[x] = dis.readShort(); + if (i == 3) T[x] = dis.readShort(); } catch (IOException e)//This shouldn't happen. If it does something must be seriously wrong. { throw new IllegalStateException("Unexpected IOException encountered while manipulating internal streams."); @@ -430,7 +428,7 @@ private void setTraces() { * Fetch the sequence from the trace data. */ private void setSeq() { - char tempseq[] = new char[seqLength]; + char[] tempseq = new char[seqLength]; for (int x = 0; x <= seqLength - 1; ++x) { tempseq[x] = (char) traceData[PBAS2 + x]; } @@ -447,7 +445,7 @@ private void setQcalls() { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(qq)); for (int i = 0; i <= seqLength - 1; ++i) { try { - qCalls[i] = (int) dis.readByte(); + qCalls[i] = dis.readByte(); } catch (IOException e)//This shouldn't happen. If it does something must be seriously wrong. { throw new IllegalStateException("Unexpected IOException encountered while manipulating internal streams."); @@ -465,7 +463,7 @@ private void setBasecalls() { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(qq)); for (int i = 0; i <= seqLength - 1; ++i) { try { - baseCalls[i] = (int) dis.readShort(); + baseCalls[i] = dis.readShort(); } catch (IOException e)//This shouldn't happen. If it does something must be seriously wrong. { throw new IllegalStateException("Unexpected IOException encountered while manipulating internal streams."); @@ -540,7 +538,7 @@ private void setIndex() { * @return - int beginning at pointer in trace array */ private int getIntAt(int pointer) { - int out = 0; + int out; byte[] temp = new byte[4]; getSubArray(temp, pointer); try { @@ -560,9 +558,7 @@ private int getIntAt(int pointer) { * @param traceDataOffset - starting point */ private void getSubArray(byte[] b, int traceDataOffset) { - for (int x = 0; x <= b.length - 1; x++) { - b[x] = traceData[traceDataOffset + x]; - } + System.arraycopy(traceData, traceDataOffset + 0, b, 0, b.length - 1 + 1); } /** @@ -573,7 +569,7 @@ private void getSubArray(byte[] b, int traceDataOffset) { * @return - if format of ABI file is correct */ private boolean isABI() { - char ABI[] = new char[4]; + char[] ABI = new char[4]; for (int i = 0; i <= 2; i++) { ABI[i] = (char) traceData[i]; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/BufferedReaderBytesRead.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/BufferedReaderBytesRead.java index e8b56ba29b..fc5a9b0bad 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/BufferedReaderBytesRead.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/BufferedReaderBytesRead.java @@ -76,8 +76,12 @@ public class BufferedReaderBytesRead extends Reader { private boolean skipLF = false; /** The skipLF flag when the mark was set */ private boolean markedSkipLF = false; - private static int defaultCharBufferSize = 8192; - private static int defaultExpectedLineLength = 80; + + private static final int defaultCharBufferSize = + 16 * 1024; + //8192; + + private static final int defaultExpectedLineLength = 80; long bytesRead = 0; /** @@ -146,16 +150,14 @@ private void fill() throws IOException { if (readAheadLimit <= cb.length) { /* Shuffle in the current buffer */ System.arraycopy(cb, markedChar, cb, 0, delta); - markedChar = 0; - dst = delta; } else { /* Reallocate buffer to accommodate read-ahead limit */ char[] ncb = new char[readAheadLimit]; System.arraycopy(cb, markedChar, ncb, 0, delta); cb = ncb; - markedChar = 0; - dst = delta; } + markedChar = 0; + dst = delta; nextChar = nChars = delta; } } @@ -415,7 +417,7 @@ private String readLine(boolean ignoreLF) throws IOException { public String readLine() throws IOException { String line = readLine(false); if (line != null) { - bytesRead = bytesRead + line.length(); + bytesRead += line.length(); } return line; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/CasePreservingProteinSequenceCreator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/CasePreservingProteinSequenceCreator.java index 54865cb132..13a8ce7f1a 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/CasePreservingProteinSequenceCreator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/CasePreservingProteinSequenceCreator.java @@ -92,7 +92,7 @@ public AbstractSequence getSequence(String sequence, public AbstractSequence getSequence( List list) { AbstractSequence seq =super.getSequence(list); - Collection strCase = new ArrayList(seq.getLength()); + Collection strCase = new ArrayList<>(seq.getLength()); for(int i=0;i getSequence( * This list contains only Booleans. */ private static List getStringCase(String str) { - List types = new ArrayList(str.length()); + List types = new ArrayList<>(str.length()); for(int i=0;i getStringCase(String str) { } public static void main(String[] args) throws Exception { - CasePreservingProteinSequenceCreator creator = new CasePreservingProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet()); + CasePreservingProteinSequenceCreator creator = new CasePreservingProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet); AbstractSequence seq = creator.getSequence("aaAA",0); logger.info("Sequence: {}", seq.getSequenceAsString()); //"AAAA" logger.info("User Collection: {}", seq.getUserCollection()); //"[false, false, true, true]" diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/DNASequenceCreator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/DNASequenceCreator.java index 48eab7cb23..78a5dd4832 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/DNASequenceCreator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/DNASequenceCreator.java @@ -83,7 +83,7 @@ public AbstractSequence getSequence( @Override public AbstractSequence getSequence( List list) { - ArrayListProxySequenceReader store = new ArrayListProxySequenceReader(); + ArrayListProxySequenceReader store = new ArrayListProxySequenceReader<>(); store.setCompoundSet(compoundSet); store.setContents(list); return new DNASequence(store); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaGeneWriter.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaGeneWriter.java index 741bc2c26f..c7351a526e 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaGeneWriter.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaGeneWriter.java @@ -42,11 +42,11 @@ public class FastaGeneWriter { private final static Logger logger = LoggerFactory.getLogger(FastaGeneWriter.class); - boolean showExonUppercase = false; - OutputStream os; - Collection sequences; - FastaHeaderFormatInterface headerFormat; - private int lineLength = 60; + final boolean showExonUppercase; + final OutputStream os; + final Collection sequences; + final FastaHeaderFormatInterface headerFormat; + private int lineLength; /** * * @param os @@ -86,7 +86,7 @@ public void process() throws Exception { os.write(lineSep); int compoundCount = 0; - String seq = ""; + String seq; //GeneSequence currently has a strand attribute to indicate direction seq = sequence.getSequence5PrimeTo3Prime().getSequenceAsString(); @@ -95,8 +95,8 @@ public void process() throws Exception { int geneBioBegin = sequence.getBioBegin(); int geneBioEnd = sequence.getBioEnd(); for (ExonSequence exonSequence : sequence.getExonSequences()) { - int featureBioBegin = 0; - int featureBioEnd = 0; + int featureBioBegin; + int featureBioEnd; if (sequence.getStrand() != Strand.NEGATIVE) { featureBioBegin = exonSequence.getBioBegin() - geneBioBegin; featureBioEnd = exonSequence.getBioEnd() - geneBioBegin; @@ -156,7 +156,7 @@ public void setLineLength(int lineLength) { public static void main(String[] args) { try { - ArrayList sequences = new ArrayList(); + ArrayList sequences = new ArrayList<>(); ChromosomeSequence seq1 = new ChromosomeSequence("ATATATATATATATATATATATATATATATATACGCGCGCGCGCGCGCGCGCGCGCGCGCGCGCATATATATATATATATATATATACGCGCGCGCGCGCGCGCATATATATATATATATATATATATATATATATACGCGCGCGCGCGCGCGCGCGCGCGCGCGCGCATATATATATATATATATATATACGCGCGCGCGCGCGCGC"); GeneSequence gene1 = seq1.addGene(new AccessionID("gene1"), 1, 20, Strand.POSITIVE); @@ -170,7 +170,7 @@ public static void main(String[] args) { sequences.add(gene2); - FastaGeneWriter fastaWriter = new FastaGeneWriter(System.out, sequences, new GenericFastaHeaderFormat(), true); + FastaGeneWriter fastaWriter = new FastaGeneWriter(System.out, sequences, new GenericFastaHeaderFormat<>(), true); fastaWriter.process(); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaReader.java index 4ad7dbeb9c..fa1d1bf323 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaReader.java @@ -35,6 +35,7 @@ import java.io.*; import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.Map; /** * Use FastaReaderHelper as an example of how to use this class where FastaReaderHelper should be the @@ -46,7 +47,7 @@ public class FastaReader, C extends Compound> { private final static Logger logger = LoggerFactory.getLogger(FastaReader.class); SequenceCreatorInterface sequenceCreator; - SequenceHeaderParserInterface headerParser; + final SequenceHeaderParserInterface headerParser; BufferedReaderBytesRead br; InputStreamReader isr; FileInputStream fi = null; @@ -148,7 +149,7 @@ public LinkedHashMap process(int max) throws IOException { boolean keepGoing = true; - LinkedHashMap sequences = new LinkedHashMap(); + LinkedHashMap sequences = new LinkedHashMap<>(); do { line = line.trim(); // nice to have but probably not needed @@ -189,11 +190,12 @@ public LinkedHashMap process(int max) throws IOException { if (line == null) { //i.e. EOF - if ( sb.length() == 0 && header.length() != 0 ) { + int sbl = sb.length(); + if ( sbl == 0 && header.length() != 0 ) { logger.warn("Can't parse sequence {}. Got sequence of length 0!", sequenceIndex); logger.warn("header: {}", header); header = null; - } else if ( sb.length() > 0 ) { + } else if ( sbl > 0 ) { //logger.info("Sequence index=" + sequenceIndex + " " + fileIndex ); try { @SuppressWarnings("unchecked") @@ -238,7 +240,7 @@ public static void main(String[] args) { if ( is == null) System.err.println("Could not get input file " + inputFile); - FastaReader fastaReader = new FastaReader(is, new GenericFastaHeaderParser(), new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + FastaReader fastaReader = new FastaReader<>(is, new GenericFastaHeaderParser<>(), new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap proteinSequences = fastaReader.process(); is.close(); @@ -247,20 +249,20 @@ public static void main(String[] args) { File file = new File(inputFile); FastaReader fastaProxyReader = - new FastaReader( + new FastaReader<>( file, - new GenericFastaHeaderParser(), + new GenericFastaHeaderParser<>(), new FileProxyProteinSequenceCreator( file, - AminoAcidCompoundSet.getAminoAcidCompoundSet(), + AminoAcidCompoundSet.aminoAcidCompoundSet, new FastaSequenceParser() ) ); LinkedHashMap proteinProxySequences = fastaProxyReader.process(); - for(String key : proteinProxySequences.keySet()){ - ProteinSequence proteinSequence = proteinProxySequences.get(key); - logger.info("Protein Proxy Sequence Key: {}", key); + for(Map.Entry entry : proteinProxySequences.entrySet()){ + ProteinSequence proteinSequence = entry.getValue(); + logger.info("Protein Proxy Sequence Key: {}", entry.getKey()); // if(key.equals("Q98SJ1_CHICK/15-61")){ // int dummy = 1; // } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaReaderHelper.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaReaderHelper.java index 4338ff5375..ab882378cb 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaReaderHelper.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaReaderHelper.java @@ -24,11 +24,7 @@ import org.biojava.nbio.core.sequence.DNASequence; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.RNASequence; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; -import org.biojava.nbio.core.sequence.compound.DNACompoundSet; -import org.biojava.nbio.core.sequence.compound.NucleotideCompound; -import org.biojava.nbio.core.sequence.compound.RNACompoundSet; +import org.biojava.nbio.core.sequence.compound.*; import java.io.File; import java.io.FileInputStream; @@ -57,15 +53,15 @@ public static LinkedHashMap readFastaDNASequence(File file, } FastaReader fastaProxyReader = - new FastaReader( + new FastaReader<>( file, - new GenericFastaHeaderParser(), + new GenericFastaHeaderParser<>(), new FileProxyDNASequenceCreator( file, DNACompoundSet.getDNACompoundSet(), new FastaSequenceParser() - ) - ); + ) + ); return fastaProxyReader.process(); } @@ -85,15 +81,15 @@ public static LinkedHashMap readFastaRNASequence(File file, } FastaReader fastaProxyReader = - new FastaReader( + new FastaReader<>( file, - new GenericFastaHeaderParser(), + new GenericFastaHeaderParser<>(), new FileProxyRNASequenceCreator( file, RNACompoundSet.getRNACompoundSet(), new FastaSequenceParser() - ) - ); + ) + ); return fastaProxyReader.process(); } @@ -124,10 +120,10 @@ public static LinkedHashMap readFastaProteinSequence( */ public static LinkedHashMap readFastaProteinSequence( InputStream inStream) throws IOException { - FastaReader fastaReader = new FastaReader( + FastaReader fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); return fastaReader.process(); } @@ -139,9 +135,9 @@ public static LinkedHashMap readFastaProteinSequence( */ public static LinkedHashMap readFastaDNASequence( InputStream inStream) throws IOException { - FastaReader fastaReader = new FastaReader( + FastaReader fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), + new GenericFastaHeaderParser<>(), new DNASequenceCreator(DNACompoundSet.getDNACompoundSet())); return fastaReader.process(); } @@ -168,9 +164,9 @@ public static LinkedHashMap readFastaDNASequence( */ public static LinkedHashMap readFastaRNASequence( InputStream inStream) throws IOException { - FastaReader fastaReader = new FastaReader( + FastaReader fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), + new GenericFastaHeaderParser<>(), new RNASequenceCreator(RNACompoundSet.getRNACompoundSet())); return fastaReader.process(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriter.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriter.java index 5bdc0df018..248e21ad52 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriter.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriter.java @@ -30,11 +30,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.BufferedOutputStream; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; +import java.io.*; import java.util.Collection; import java.util.LinkedHashMap; @@ -50,9 +46,9 @@ public class FastaWriter, C extends Compound> { private final static Logger logger = LoggerFactory.getLogger(FastaWriter.class); - OutputStream os; - Collection sequences; - FastaHeaderFormatInterface headerFormat; + final OutputStream os; + final Collection sequences; + final FastaHeaderFormatInterface headerFormat; private int lineLength = 60; byte[] lineSep = System.getProperty("line.separator").getBytes(); /** @@ -103,7 +99,7 @@ public void process() throws IOException { os.write(lineSep); int compoundCount = 0; - String seq = ""; + String seq; seq = sequence.getSequenceAsString(); @@ -133,7 +129,7 @@ public static void main(String[] args) { FileInputStream is = new FileInputStream("/Users/Scooter/scripps/dyadic/c1-454Scaffolds.faa"); - FastaReader fastaReader = new FastaReader(is, new GenericFastaHeaderParser(), new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + FastaReader fastaReader = new FastaReader<>(is, new GenericFastaHeaderParser<>(), new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap proteinSequences = fastaReader.process(); is.close(); @@ -144,7 +140,7 @@ public static void main(String[] args) { BufferedOutputStream bo = new BufferedOutputStream(fileOutputStream); long start = System.currentTimeMillis(); - FastaWriter fastaWriter = new FastaWriter(bo, proteinSequences.values(), new GenericFastaHeaderFormat()); + FastaWriter fastaWriter = new FastaWriter<>(bo, proteinSequences.values(), new GenericFastaHeaderFormat<>()); fastaWriter.process(); bo.close(); long end = System.currentTimeMillis(); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriterHelper.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriterHelper.java index 966d723728..1e3ec619cf 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriterHelper.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriterHelper.java @@ -71,9 +71,9 @@ public static void writeProteinSequence(File file, public static void writeProteinSequence(OutputStream outputStream, Collection proteinSequences) throws Exception { - FastaWriter fastaWriter = new FastaWriter( + FastaWriter fastaWriter = new FastaWriter<>( outputStream, proteinSequences, - new GenericFastaHeaderFormat()); + new GenericFastaHeaderFormat<>()); fastaWriter.process(); } @@ -103,7 +103,7 @@ public static void writeGeneSequence(File file, Collection geneSeq public static void writeGeneSequence(OutputStream outputStream, Collection geneSequences,boolean showExonUppercase) throws Exception { FastaGeneWriter fastaWriter = new FastaGeneWriter( outputStream, geneSequences, - new GenericFastaHeaderFormat(),showExonUppercase); + new GenericFastaHeaderFormat<>(),showExonUppercase); fastaWriter.process(); } @@ -132,9 +132,9 @@ public static void writeNucleotideSequence(File file, Collection dn */ public static void writeNucleotideSequence(OutputStream outputStream, Collection dnaSequences) throws Exception { - FastaWriter fastaWriter = new FastaWriter( + FastaWriter fastaWriter = new FastaWriter<>( outputStream, dnaSequences, - new GenericFastaHeaderFormat()); + new GenericFastaHeaderFormat<>()); fastaWriter.process(); } @@ -170,7 +170,7 @@ public static void writeSequence(OutputStream outputStream, Sequence sequence */ private static Collection> singleSeqToCollection(Sequence sequence) { - Collection> sequences = new ArrayList>(); + Collection> sequences = new ArrayList<>(); sequences.add(sequence); return sequences; } @@ -188,19 +188,11 @@ public static void writeSequences(OutputStream outputStream, Collection> sequences) throws Exception { FastaHeaderFormatInterface, Compound> fhfi = - new FastaHeaderFormatInterface, Compound>() { - - @Override - public String getHeader(Sequence sequence) { - return sequence.getAccession().toString(); - } - - ; - }; + sequence -> sequence.getAccession().toString(); FastaWriter, Compound> fastaWriter = - new FastaWriter, Compound>(outputStream, - sequences, fhfi); + new FastaWriter<>(outputStream, + sequences, fhfi); fastaWriter.process(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyDNASequenceCreator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyDNASequenceCreator.java index fb89f1c4e3..a23ddce00b 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyDNASequenceCreator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyDNASequenceCreator.java @@ -50,9 +50,9 @@ public class FileProxyDNASequenceCreator implements SequenceCreatorInterface { - CompoundSet compoundSet = null; - File file = null; - SequenceParserInterface sequenceParser; + final CompoundSet compoundSet; + final File file; + final SequenceParserInterface sequenceParser; /** * Need File so that we can store full path name in SequenceFileProxyLoader for Random File access as a quick read @@ -78,7 +78,7 @@ public FileProxyDNASequenceCreator(File file, */ @Override public AbstractSequence getSequence(String sequence, long index ) throws CompoundNotFoundException, IOException { - SequenceFileProxyLoader sequenceFileProxyLoader = new SequenceFileProxyLoader( + SequenceFileProxyLoader sequenceFileProxyLoader = new SequenceFileProxyLoader<>( file, sequenceParser, index, diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyProteinSequenceCreator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyProteinSequenceCreator.java index 7db550683f..f9749302b8 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyProteinSequenceCreator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyProteinSequenceCreator.java @@ -49,9 +49,9 @@ */ public class FileProxyProteinSequenceCreator implements SequenceCreatorInterface { - CompoundSet compoundSet; - File file; - SequenceParserInterface sequenceParser; + final CompoundSet compoundSet; + final File file; + final SequenceParserInterface sequenceParser; /** * Need File so that we can store full path name in SequenceFileProxyLoader for Random File access as a quick read @@ -76,13 +76,13 @@ public FileProxyProteinSequenceCreator(File file, CompoundSet @Override public AbstractSequence getSequence(String sequence, long index) throws CompoundNotFoundException, IOException { SequenceFileProxyLoader sequenceFileProxyLoader = - new SequenceFileProxyLoader( + new SequenceFileProxyLoader<>( file, sequenceParser, index, sequence.length(), compoundSet - ); + ); return new ProteinSequence(sequenceFileProxyLoader, compoundSet); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyRNASequenceCreator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyRNASequenceCreator.java index 4be68696fb..bc6c4f7941 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyRNASequenceCreator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyRNASequenceCreator.java @@ -50,9 +50,9 @@ public class FileProxyRNASequenceCreator implements SequenceCreatorInterface { - CompoundSet compoundSet = null; - File file = null; - SequenceParserInterface sequenceParser; + final CompoundSet compoundSet; + final File file; + final SequenceParserInterface sequenceParser; /** * Need File so that we can store full path name in SequenceFileProxyLoader for Random File access as a quick read @@ -78,7 +78,7 @@ public FileProxyRNASequenceCreator(File file, */ @Override public AbstractSequence getSequence(String sequence, long index ) throws CompoundNotFoundException, IOException { - SequenceFileProxyLoader sequenceFileProxyLoader = new SequenceFileProxyLoader( + SequenceFileProxyLoader sequenceFileProxyLoader = new SequenceFileProxyLoader<>( file, sequenceParser, index, diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankReader.java index 951cce40c0..b8c69f9311 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankReader.java @@ -36,13 +36,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; +import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; @@ -55,9 +49,9 @@ */ public class GenbankReader, C extends Compound> { - private SequenceCreatorInterface sequenceCreator; - private GenbankSequenceParser genbankParser; - private BufferedReader bufferedReader; + private final SequenceCreatorInterface sequenceCreator; + private final GenbankSequenceParser genbankParser; + private final BufferedReader bufferedReader; private boolean closed; private final Logger logger = LoggerFactory.getLogger(this.getClass()); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankReaderHelper.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankReaderHelper.java index 51c1f7593b..38d4eb408d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankReaderHelper.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankReaderHelper.java @@ -24,11 +24,7 @@ import org.biojava.nbio.core.sequence.DNASequence; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.RNASequence; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; -import org.biojava.nbio.core.sequence.compound.DNACompoundSet; -import org.biojava.nbio.core.sequence.compound.NucleotideCompound; -import org.biojava.nbio.core.sequence.compound.RNACompoundSet; +import org.biojava.nbio.core.sequence.compound.*; import org.biojava.nbio.core.sequence.template.AbstractSequence; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -61,15 +57,15 @@ public static LinkedHashMap readGenbankDNASequence(File fil } GenbankReader GenbankProxyReader = - new GenbankReader( + new GenbankReader<>( file, - new GenericGenbankHeaderParser(), + new GenericGenbankHeaderParser<>(), new FileProxyDNASequenceCreator( file, DNACompoundSet.getDNACompoundSet(), new GenbankSequenceParser, NucleotideCompound>() - ) - ); + ) + ); return GenbankProxyReader.process(); } @@ -88,16 +84,16 @@ public static LinkedHashMap readGenbankProteinSequence( return readGenbankProteinSequence(file); } - GenbankReader GenbankProxyReader = - new GenbankReader( + GenbankReader GenbankProxyReader = + new GenbankReader<>( file, - new GenericGenbankHeaderParser(), + new GenericGenbankHeaderParser<>(), new FileProxyProteinSequenceCreator( file, - AminoAcidCompoundSet.getAminoAcidCompoundSet(), + AminoAcidCompoundSet.aminoAcidCompoundSet, new GenbankSequenceParser, AminoAcidCompound>() - ) - ); + ) + ); return GenbankProxyReader.process(); } @@ -117,15 +113,15 @@ public static LinkedHashMap readGenbankRNASequence(File fil } GenbankReader GenbankProxyReader = - new GenbankReader( + new GenbankReader<>( file, - new GenericGenbankHeaderParser(), + new GenericGenbankHeaderParser<>(), new FileProxyRNASequenceCreator( file, RNACompoundSet.getRNACompoundSet(), new GenbankSequenceParser, NucleotideCompound>() - ) - ); + ) + ); return GenbankProxyReader.process(); } @@ -156,10 +152,10 @@ public static LinkedHashMap readGenbankProteinSequence( */ public static LinkedHashMap readGenbankProteinSequence( InputStream inStream) throws Exception { - GenbankReader GenbankReader = new GenbankReader( + GenbankReader GenbankReader = new GenbankReader<>( inStream, - new GenericGenbankHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + new GenericGenbankHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); return GenbankReader.process(); } @@ -171,9 +167,9 @@ public static LinkedHashMap readGenbankProteinSequence( */ public static LinkedHashMap readGenbankDNASequence( InputStream inStream) throws Exception { - GenbankReader GenbankReader = new GenbankReader( + GenbankReader GenbankReader = new GenbankReader<>( inStream, - new GenericGenbankHeaderParser(), + new GenericGenbankHeaderParser<>(), new DNASequenceCreator(DNACompoundSet.getDNACompoundSet())); return GenbankReader.process(); } @@ -199,9 +195,9 @@ public static LinkedHashMap readGenbankDNASequence( */ public static LinkedHashMap readGenbankRNASequence( InputStream inStream) throws Exception { - GenbankReader GenbankReader = new GenbankReader( + GenbankReader GenbankReader = new GenbankReader<>( inStream, - new GenericGenbankHeaderParser(), + new GenericGenbankHeaderParser<>(), new RNASequenceCreator(RNACompoundSet.getRNACompoundSet())); return GenbankReader.process(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankSequenceParser.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankSequenceParser.java index 9641a38894..97829fc547 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankSequenceParser.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankSequenceParser.java @@ -75,7 +75,7 @@ public class GenbankSequenceParser, C extends Comp */ private HashMap> featureCollection; - private Logger log = LoggerFactory.getLogger(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); // this is a compoundset parsed from header. private CompoundSet compoundType; @@ -138,7 +138,7 @@ public class GenbankSequenceParser, C extends Comp private String parse(BufferedReader bufferedReader) { - String sectionKey = null; + String sectionKey; List section; // Get an ordered list of key->value pairs in array-tuples do { @@ -146,172 +146,190 @@ private String parse(BufferedReader bufferedReader) { sectionKey = section.get(0)[0]; if (sectionKey == null) { //if we reach the end of the file, section contains empty strings - if(section.get(0)[1]==null || section.get(0)[1]=="" || + if(section.get(0)[1]==null || section.get(0)[1].equals("") || section.get(0)[1].length()==0) { throw new ParserException(Messages.ENDOFFILE); } throw new ParserException(Messages.SECTIONKEYNULL); } // process section-by-section - if (sectionKey.equals(LOCUS_TAG)) { - String loc = section.get(0)[1]; - header = loc; - Matcher m = lp.matcher(loc); - if (m.matches()) { - headerParser.setName(m.group(1)); - headerParser.setAccession(m.group(1)); // default if no accession found - - String lengthUnits = m.group(2); - String type = m.group(5); - - if (lengthUnits.equalsIgnoreCase("aa")) { - compoundType = AminoAcidCompoundSet.getAminoAcidCompoundSet(); - } else if (lengthUnits.equalsIgnoreCase("bp")) { - if (type != null) { - if (type.contains("RNA")) { - compoundType = RNACompoundSet.getRNACompoundSet(); + switch (sectionKey) { + case LOCUS_TAG: { + String loc = section.get(0)[1]; + header = loc; + Matcher m = lp.matcher(loc); + if (m.matches()) { + headerParser.setName(m.group(1)); + headerParser.setAccession(m.group(1)); // default if no accession found + + String lengthUnits = m.group(2); + String type = m.group(5); + + if (lengthUnits.equalsIgnoreCase("aa")) { + compoundType = AminoAcidCompoundSet.aminoAcidCompoundSet; + } else if (lengthUnits.equalsIgnoreCase("bp")) { + if (type != null) { + if (type.contains("RNA")) { + compoundType = RNACompoundSet.getRNACompoundSet(); + } else { + compoundType = DNACompoundSet.getDNACompoundSet(); + } } else { compoundType = DNACompoundSet.getDNACompoundSet(); } - } else { - compoundType = DNACompoundSet.getDNACompoundSet(); } - } - log.debug("compound type: {}", compoundType.getClass().getSimpleName()); + log.debug("compound type: {}", compoundType.getClass().getSimpleName()); - } else { - throw new ParserException("Bad locus line"); - } - } else if (sectionKey.equals(DEFINITION_TAG)) { - headerParser.setDescription(section.get(0)[1]); - } else if (sectionKey.equals(ACCESSION_TAG)) { - // if multiple accessions, store only first as accession, - // and store rest in annotation - String[] accs = section.get(0)[1].split("\\s+"); - accession = accs[0].trim(); - headerParser.setAccession(accession); - } else if (sectionKey.equals(VERSION_TAG)) { - String ver = section.get(0)[1]; - Matcher m = vp.matcher(ver); - if (m.matches()) { - String verAcc = m.group(1); - if (!accession.equals(verAcc)) { - // the version refers to a different accession! - // believe the version line, and store the original - // accession away in the additional accession set - accession = verAcc; - } - if (m.group(3) != null) { - headerParser.setVersion(Integer.parseInt(m.group(3))); - } - if (m.group(5) != null) { - headerParser.setIdentifier(m.group(5)); + } else { + throw new ParserException("Bad locus line"); } - } else { - throw new ParserException("Bad version line"); + break; } - } else if (sectionKey.equals(KEYWORDS_TAG)) { - } else if (sectionKey.equals(SOURCE_TAG)) { - // ignore - can get all this from the first feature - } else if (sectionKey.equals(REFERENCE_TAG)) { - if (!section.isEmpty()) { - GenbankReference genbankReference = new GenbankReference(); - for (String[] ref : section) { - if (ref[0].equals(AUTHORS_TAG)) { - genbankReference.setAuthors(ref[1]); - } else if (ref[0].equals(TITLE_TAG)) { - genbankReference.setTitle(ref[1]); - } else if (ref[0].equals(JOURNAL_TAG)) { - genbankReference.setJournal(ref[1]); + case DEFINITION_TAG: + headerParser.setDescription(section.get(0)[1]); + break; + case ACCESSION_TAG: + // if multiple accessions, store only first as accession, + // and store rest in annotation + String[] accs = section.get(0)[1].split("\\s+"); + accession = accs[0].trim(); + headerParser.setAccession(accession); + break; + case VERSION_TAG: { + String ver = section.get(0)[1]; + Matcher m = vp.matcher(ver); + if (m.matches()) { + String verAcc = m.group(1); + if (!accession.equals(verAcc)) { + // the version refers to a different accession! + // believe the version line, and store the original + // accession away in the additional accession set + accession = verAcc; + } + if (m.group(3) != null) { + headerParser.setVersion(Integer.parseInt(m.group(3))); + } + if (m.group(5) != null) { + headerParser.setIdentifier(m.group(5)); } + } else { + throw new ParserException("Bad version line"); } - headerParser.addReference(genbankReference); + break; } - } else if (sectionKey.equals(COMMENT_TAG)) { - // Set up some comments - headerParser.setComment(section.get(0)[1]); - } else if (sectionKey.equals(FEATURE_TAG)) { - // starting from second line of input, start a new feature whenever we come across - // a key that does not start with / - AbstractFeature gbFeature = null; - for (int i = 1; i < section.size(); i++) { - String key = section.get(i)[0]; - String val = section.get(i)[1]; - if (key.startsWith("/")) { - if (gbFeature == null) { - throw new ParserException("Malformed GenBank file: found a qualifier without feature."); - } - key = key.substring(1); // strip leading slash - val = val.replaceAll("\\s*[\\n\\r]+\\s*", " ").trim(); - if (val.endsWith("\"")) { - val = val.substring(1, val.length() - 1); // strip quotes + case KEYWORDS_TAG: + break; + case SOURCE_TAG: + // ignore - can get all this from the first feature + break; + case REFERENCE_TAG: + if (!section.isEmpty()) { + GenbankReference genbankReference = new GenbankReference(); + for (String[] ref : section) { + switch (ref[0]) { + case AUTHORS_TAG: + genbankReference.setAuthors(ref[1]); + break; + case TITLE_TAG: + genbankReference.setTitle(ref[1]); + break; + case JOURNAL_TAG: + genbankReference.setJournal(ref[1]); + break; + } } - // parameter on old feature - if (key.equals("db_xref")) { - Matcher m = dbxp.matcher(val); - if (m.matches()) { - String dbname = m.group(1); - String raccession = m.group(2); - Qualifier xref = new DBReferenceInfo(dbname, raccession); - gbFeature.addQualifier(key, xref); - - ArrayList listDBEntry = new ArrayList(); - listDBEntry.add((DBReferenceInfo) xref); - mapDB.put(key, listDBEntry); - } else { - throw new ParserException("Bad dbxref"); + headerParser.addReference(genbankReference); + } + break; + case COMMENT_TAG: + // Set up some comments + headerParser.setComment(section.get(0)[1]); + break; + case FEATURE_TAG: + // starting from second line of input, start a new feature whenever we come across + // a key that does not start with / + AbstractFeature gbFeature = null; + for (int i = 1; i < section.size(); i++) { + String key = section.get(i)[0]; + String val = section.get(i)[1]; + if (key.startsWith("/")) { + if (gbFeature == null) { + throw new ParserException("Malformed GenBank file: found a qualifier without feature."); } - } else if (key.equalsIgnoreCase("organism")) { - Qualifier q = new Qualifier(key, val.replace('\n', ' ')); - gbFeature.addQualifier(key, q); - } else { - if (key.equalsIgnoreCase("translation")) { - // strip spaces from sequence - val = val.replaceAll("\\s+", ""); - Qualifier q = new Qualifier(key, val); + key = key.substring(1); // strip leading slash + val = val.replaceAll("\\s*[\\n\\r]+\\s*", " ").trim(); + if (val.endsWith("\"")) { + val = val.substring(1, val.length() - 1); // strip quotes + } + // parameter on old feature + if (key.equals("db_xref")) { + Matcher m = dbxp.matcher(val); + if (m.matches()) { + String dbname = m.group(1); + String raccession = m.group(2); + DBReferenceInfo xref = new DBReferenceInfo(dbname, raccession); + gbFeature.addQualifier(key, xref); + + ArrayList listDBEntry = new ArrayList<>(); + listDBEntry.add(xref); + mapDB.put(key, listDBEntry); + } else { + throw new ParserException("Bad dbxref"); + } + } else if (key.equalsIgnoreCase("organism")) { + Qualifier q = new Qualifier(key, val.replace('\n', ' ')); gbFeature.addQualifier(key, q); } else { - Qualifier q = new Qualifier(key, val); - gbFeature.addQualifier(key, q); + if (key.equalsIgnoreCase("translation")) { + // strip spaces from sequence + val = val.replaceAll("\\s+", ""); + Qualifier q = new Qualifier(key, val); + gbFeature.addQualifier(key, q); + } else { + Qualifier q = new Qualifier(key, val); + gbFeature.addQualifier(key, q); + } } + } else { + // new feature! + gbFeature = new TextFeature(key, val, key, key); + Location l = + locationParser.parse(val); + gbFeature.setLocation((AbstractLocation) l); + + if (!featureCollection.containsKey(key)) { + featureCollection.put(key, new ArrayList()); + } + featureCollection.get(key).add(gbFeature); } - } else { - // new feature! - gbFeature = new TextFeature(key, val, key, key); - Location l = - locationParser.parse(val); - gbFeature.setLocation((AbstractLocation)l); - - if (!featureCollection.containsKey(key)) { - featureCollection.put(key, new ArrayList()); - } - featureCollection.get(key).add(gbFeature); } - } - } else if (sectionKey.equals(BASE_COUNT_TAG)) { - // ignore - can calculate from sequence content later if needed - } else if (sectionKey.equals(START_SEQUENCE_TAG)) { - // our first line is ignorable as it is the ORIGIN tag - // the second line onwards conveniently have the number as - // the [0] tuple, and sequence string as [1] so all we have - // to do is concat the [1] parts and then strip out spaces, - // and replace '.' and '~' with '-' for our parser. - StringBuffer seq = new StringBuffer(); - for (int i = 1; i < section.size(); i++) { - seq.append(section.get(i)[1]); - } - seqData = seq.toString().replaceAll("\\s+", "").replaceAll("[\\.|~]", "-").toUpperCase(); - } else if(sectionKey.equals(DBSOURCE)) { - //TODO - } else if(sectionKey.equals(PRIMARY)) { - //TODO - } else if(sectionKey.equals(DBLINK)) { - //TODO - } else { - if(!sectionKey.equals(END_SEQUENCE_TAG)) { - log.info("found unknown section key: "+sectionKey); - } + break; + case BASE_COUNT_TAG: + // ignore - can calculate from sequence content later if needed + break; + case START_SEQUENCE_TAG: + // our first line is ignorable as it is the ORIGIN tag + // the second line onwards conveniently have the number as + // the [0] tuple, and sequence string as [1] so all we have + // to do is concat the [1] parts and then strip out spaces, + // and replace '.' and '~' with '-' for our parser. + StringBuilder seq = new StringBuilder(); + for (int i = 1; i < section.size(); i++) { + seq.append(section.get(i)[1]); + } + seqData = seq.toString().replaceAll("\\s+", "").replaceAll("[\\.|~]", "-").toUpperCase(); + break; + case DBSOURCE: + case DBLINK: + case PRIMARY: + //TODO + break; + default: + if (!sectionKey.equals(END_SEQUENCE_TAG)) { + log.info("found unknown section key: " + sectionKey); + } + break; } } while (!sectionKey.equals(END_SEQUENCE_TAG)); return seqData; @@ -326,8 +344,8 @@ private String parse(BufferedReader bufferedReader) { // reads an indented section, combining split lines and creating a list of // key->value tuples private List readSection(BufferedReader bufferedReader) { - List section = new ArrayList(); - String line = ""; + List section = new ArrayList<>(); + String line; String currKey = null; StringBuffer currVal = new StringBuffer(); @@ -385,19 +403,17 @@ private List readSection(BufferedReader bufferedReader) { } } } - } catch (IOException e) { - throw new ParserException(e.getMessage()); - } catch (RuntimeException e) { + } catch (IOException | RuntimeException e) { throw new ParserException(e.getMessage()); } return section; } @Override - public String getSequence(BufferedReader bufferedReader, int sequenceLength) throws IOException { - featureCollection = new HashMap>(); - mapDB = new LinkedHashMap>(); - headerParser = new GenericGenbankHeaderParser(); + public String getSequence(BufferedReader bufferedReader, int sequenceLength) { + featureCollection = new HashMap<>(); + mapDB = new LinkedHashMap<>(); + headerParser = new GenericGenbankHeaderParser<>(); try { parse(bufferedReader); } catch (ParserException e) { @@ -421,7 +437,7 @@ public LinkedHashMap> getDatabaseReferences() } public ArrayList getKeyWords() { - return new ArrayList(featureCollection.keySet()); + return new ArrayList<>(featureCollection.keySet()); } public ArrayList getFeatures(String keyword) { @@ -432,8 +448,8 @@ public HashMap> getFeatures() { } public void parseFeatures(AbstractSequence sequence) { - for (String k: featureCollection.keySet()) - for (AbstractFeature f: featureCollection.get(k)) + for (ArrayList abstractFeatures : featureCollection.values()) + for (AbstractFeature f: abstractFeatures) sequence.addFeature(f); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankWriter.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankWriter.java index cab8d23db1..819e785df0 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankWriter.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankWriter.java @@ -38,11 +38,11 @@ * */ public class GenbankWriter, C extends Compound> { - int SEQUENCE_INDENT = 9; + final int SEQUENCE_INDENT = 9; - OutputStream os; - Collection sequences; - GenbankHeaderFormatInterface headerFormat; + final OutputStream os; + final Collection sequences; + final GenbankHeaderFormatInterface headerFormat; private int lineLength = 60; // byte[] lineSep = System.getProperty("line.separator").getBytes(); @@ -85,7 +85,7 @@ public GenbankWriter(OutputStream os, Collection sequences, * @param lineSeparator */ - public void process() throws Exception { + public void process() { // Loosely based on code from Howard Salis // TODO - Force lower case? // boolean closeit = false; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankWriterHelper.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankWriterHelper.java index 19e26bd3a7..dc2a2768ec 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankWriterHelper.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankWriterHelper.java @@ -70,16 +70,15 @@ public static void writeProteinSequence(File file, * * @param outputStream * @param proteinSequences - * @throws Exception - */ + */ public static void writeProteinSequence(OutputStream outputStream, - Collection proteinSequences) throws Exception { + Collection proteinSequences) { - GenbankWriter genbankWriter = new GenbankWriter( + GenbankWriter genbankWriter = new GenbankWriter<>( outputStream, proteinSequences, - new GenericGenbankHeaderFormat()); + new GenericGenbankHeaderFormat<>()); genbankWriter.process(); } @@ -106,11 +105,10 @@ public static void writeNucleotideSequence(File file, * * @param outputStream * @param dnaSequences - * @throws Exception - */ + */ public static void writeNucleotideSequence(OutputStream outputStream, - Collection dnaSequences) throws Exception { + Collection dnaSequences) { writeNucleotideSequence(outputStream, dnaSequences, LINEAR_DNA); } @@ -120,16 +118,14 @@ public static void writeNucleotideSequence(OutputStream outputStream, * @param outputStream * @param dnaSequences * @param seqType - * @throws Exception - */ + */ public static void writeNucleotideSequence(OutputStream outputStream, - Collection dnaSequences, String seqType) - throws Exception { - GenericGenbankHeaderFormat genericGenbankHeaderFormat = new GenericGenbankHeaderFormat( + Collection dnaSequences, String seqType) { + GenericGenbankHeaderFormat genericGenbankHeaderFormat = new GenericGenbankHeaderFormat<>( seqType); // genericGenbankHeaderFormat.setLineSeparator(lineSep); - GenbankWriter genbankWriter = new GenbankWriter( + GenbankWriter genbankWriter = new GenbankWriter<>( outputStream, dnaSequences, genericGenbankHeaderFormat); // genbankWriter.setLineSeparator(lineSep); genbankWriter.process(); @@ -156,10 +152,9 @@ public static void writeSequence(File file, Sequence sequence) * * @param outputStream * @param sequence - * @throws Exception - */ + */ public static void writeSequence(OutputStream outputStream, - Sequence sequence) throws Exception { + Sequence sequence) { writeSequences(outputStream, singleSeqToCollection(sequence)); } @@ -171,7 +166,7 @@ public static void writeSequence(OutputStream outputStream, private static Collection> singleSeqToCollection( Sequence sequence) { - Collection> sequences = new ArrayList>(); + Collection> sequences = new ArrayList<>(); sequences.add(sequence); return sequences; } @@ -185,23 +180,13 @@ private static Collection> singleSeqToCollection( * Stream to write to; can be System.out * @param sequences * The sequences to write out - * @throws Exception - * Thrown normally thanks to IO problems - */ + */ public static void writeSequences(OutputStream outputStream, - Collection> sequences) throws Exception { - - GenbankHeaderFormatInterface, Compound> fhfi = new GenbankHeaderFormatInterface, Compound>() { - - @Override - public String getHeader(Sequence sequence) { - return sequence.getAccession().toString(); - } + Collection> sequences) { - ; - }; + GenbankHeaderFormatInterface, Compound> fhfi = sequence -> sequence.getAccession().toString(); - GenbankWriter, Compound> genbankWriter = new GenbankWriter, Compound>( + GenbankWriter, Compound> genbankWriter = new GenbankWriter<>( outputStream, sequences, fhfi); genbankWriter.process(); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericFastaHeaderParser.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericFastaHeaderParser.java index 1a83dee701..e13f06d7ba 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericFastaHeaderParser.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericFastaHeaderParser.java @@ -71,8 +71,8 @@ public class GenericFastaHeaderParser, C extends C */ private String[] getHeaderValues(String header) { String[] data = new String[0]; - ArrayList values = new ArrayList(); - StringBuffer sb = new StringBuffer(); + ArrayList values = new ArrayList<>(); + StringBuilder sb = new StringBuilder(); //commented out 1/11/2012 to resolve an issue where headers do contain a length= at the end that are not recognized //if(header.indexOf("length=") != -1){ // data = new String[1]; @@ -152,7 +152,7 @@ public void parseHeader(String header, S sequence) { String[] pdbe = data[0].split(" "); String[] pdbaccession = pdbe[0].split(":"); sequence.setAccession(new AccessionID(pdbaccession[1], DataSource.PDBe)); - } else if (data[0].indexOf(":") != -1 && data.length > 1 && data[1].equals("PDBID")) { + } else if (data[0].contains(":") && data.length > 1 && data[1].equals("PDBID")) { sequence.setAccession(new AccessionID(data[0], DataSource.PDB2)); } else if (data[0].equalsIgnoreCase("pat")) { sequence.setAccession(new AccessionID(data[2], DataSource.PATENTS)); @@ -178,7 +178,7 @@ public void parseHeader(String header, S sequence) { public static void main(String[] args) { logger.info("parseHeader"); - String header = ""; + String header; ProteinSequence sequence = null; try { sequence = new ProteinSequence(""); @@ -187,7 +187,7 @@ public static void main(String[] args) { logger.error("Could not create empty protein sequence. Error: {}. This is most likely a bug.",e.getMessage()); } GenericFastaHeaderParser instance = - new GenericFastaHeaderParser(); + new GenericFastaHeaderParser<>(); header = "gi|gi-number|gb|accession|locus"; instance.parseHeader(header, sequence); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericGenbankHeaderFormat.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericGenbankHeaderFormat.java index a19c9f648c..902c50bfa6 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericGenbankHeaderFormat.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericGenbankHeaderFormat.java @@ -36,7 +36,7 @@ public class GenericGenbankHeaderFormat, C extends GenbankHeaderFormatInterface { private static final int HEADER_WIDTH = 12; private static final String lineSep = "%n"; - private String seqType = null; + private final String seqType; public GenericGenbankHeaderFormat() { seqType = null; @@ -169,8 +169,8 @@ private String _write_the_first_line(S sequence) { + " is too long"); } - String units = ""; - String mol_type = ""; + String units; + String mol_type; if (sequence.getCompoundSet() instanceof DNACompoundSet) { units = "bp"; mol_type = "DNA"; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericGenbankHeaderParser.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericGenbankHeaderParser.java index 7c828b54f2..279c0cdbfc 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericGenbankHeaderParser.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericGenbankHeaderParser.java @@ -25,6 +25,7 @@ import org.biojava.nbio.core.exceptions.ParserException; import org.biojava.nbio.core.sequence.AccessionID; +import org.biojava.nbio.core.sequence.DataSource; import org.biojava.nbio.core.sequence.io.template.SequenceHeaderParserInterface; import org.biojava.nbio.core.sequence.reference.AbstractReference; import org.biojava.nbio.core.sequence.template.AbstractSequence; @@ -33,8 +34,6 @@ import java.util.ArrayList; import java.util.List; -import org.biojava.nbio.core.sequence.DataSource; - public class GenericGenbankHeaderParser, C extends Compound> implements SequenceHeaderParserInterface { private String accession = null; @@ -43,8 +42,8 @@ public class GenericGenbankHeaderParser, C extends @SuppressWarnings("unused") private int version; private boolean versionSeen; - private ArrayList comments = new ArrayList<>(); - private List references = new ArrayList<>(); + private final ArrayList comments = new ArrayList<>(); + private final List references = new ArrayList<>(); /** * Parse the header and set the values in the sequence diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericInsdcHeaderFormat.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericInsdcHeaderFormat.java index 97e37f30cd..870e526c43 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericInsdcHeaderFormat.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericInsdcHeaderFormat.java @@ -32,11 +32,7 @@ import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.util.StringManipulationHelper; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Formatter; -import java.util.List; -import java.util.Locale; +import java.util.*; /** * @author mckeee1 @@ -56,7 +52,7 @@ public class GenericInsdcHeaderFormat, C extends C * @param quote */ private String _write_feature_qualifier(String key, String value, boolean quote) { - String line = ""; + String line; if(null == value) { line = QUALIFIER_INDENT_STR + "/" + key + lineSep; return line; @@ -70,7 +66,7 @@ private String _write_feature_qualifier(String key, String value, boolean quote) return line + lineSep; } String goodlines = ""; - while(!"".equals(line.replaceAll("^\\s+", ""))) { + while(!line.replaceAll("^\\s+", "").isEmpty()) { if(line.length() <= MAX_WIDTH) { goodlines += line + lineSep; break; @@ -101,7 +97,7 @@ private String _wrap_location(String location) { if(location.length() <= length) { return location; } - int index = location.substring(length).lastIndexOf(","); + int index = location.substring(length).lastIndexOf(','); if(-1 == index) { //No good place to split (!) return location; @@ -195,7 +191,7 @@ private String _insdc_feature_location_string(FeatureInterface locations = new ArrayList(); + ArrayList locations = new ArrayList<>(); for(FeatureInterface, C> f : feature.getChildrenFeatures()) { locations.add(_insdc_location_string_ignoring_strand_and_subfeatures(f.getLocations(), record_length)); } @@ -208,7 +204,7 @@ private String _insdc_feature_location_string(FeatureInterface locations = new ArrayList(); + ArrayList locations = new ArrayList<>(); for(FeatureInterface, C> f : feature.getChildrenFeatures()) { locations.add(_insdc_location_string_ignoring_strand_and_subfeatures(f.getLocations(), record_length)); } @@ -340,14 +336,14 @@ raise ValueError("Expected a SeqFeature position object.") */ protected ArrayList _split_multi_line(String text, int max_len) { // TODO Auto-generated method stub - ArrayList output = new ArrayList(); + ArrayList output = new ArrayList<>(); text = text.trim(); if(text.length() <= max_len) { output.add(text); return output; } - ArrayList words = new ArrayList(); + ArrayList words = new ArrayList<>(); Collections.addAll(words, text.split("\\s+")); while(!words.isEmpty()) { text = words.remove(0); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/IUPACParser.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/IUPACParser.java index 8f1b449283..51c10918dd 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/IUPACParser.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/IUPACParser.java @@ -86,7 +86,7 @@ public static IUPACParser getInstance() { public static final String IUPAC_LOCATION = "org/biojava/nbio/core/sequence/iupac.txt"; - private InputStream is; + private final InputStream is; private List tables; private Map nameLookup; private Map idLookup; @@ -134,8 +134,8 @@ public IUPACTable getTable(Integer id) { private void populateLookups() { if(nameLookup == null) { - nameLookup = new HashMap(); - idLookup = new HashMap(); + nameLookup = new HashMap<>(); + idLookup = new HashMap<>(); for(IUPACTable t: getTables()) { nameLookup.put(t.getName(), t); idLookup.put(t.getId(), t); @@ -144,7 +144,7 @@ private void populateLookups() { } private List parseTables() { - List localTables = new ArrayList(); + List localTables = new ArrayList<>(); List lines = IOUtils.getList(is); Integer id = null; String name, aa, starts, baseone, basetwo, basethree; @@ -158,24 +158,26 @@ private List parseTables() { } else { String[] keyValue = line.split("\\s*=\\s*"); - if (keyValue[0].equals("AAs")) { - aa = keyValue[1]; - } - else if (keyValue[0].equals("Starts")) { - starts = keyValue[1]; - } - else if (keyValue[0].equals("Base1")) { - baseone = keyValue[1]; - } - else if (keyValue[0].equals("Base2")) { - basetwo = keyValue[1]; - } - else if (keyValue[0].equals("Base3")) { - basethree = keyValue[1]; - } - else { - name = keyValue[0]; - id = Integer.parseInt(keyValue[1]); + switch (keyValue[0]) { + case "AAs": + aa = keyValue[1]; + break; + case "Starts": + starts = keyValue[1]; + break; + case "Base1": + baseone = keyValue[1]; + break; + case "Base2": + basetwo = keyValue[1]; + break; + case "Base3": + basethree = keyValue[1]; + break; + default: + name = keyValue[0]; + id = Integer.parseInt(keyValue[1]); + break; } } } @@ -198,7 +200,7 @@ public static class IUPACTable implements Table { private final String baseTwo; private final String baseThree; - private final List codons = new ArrayList(); + private final List codons = new ArrayList<>(); private CompoundSet compounds = null; public IUPACTable(String name, int id, String aminoAcidString, @@ -328,7 +330,7 @@ public CompoundSet getCodonCompoundSet( } private List> codonStrings() { - List> codons = new ArrayList>(); + List> codons = new ArrayList<>(); for (int i = 0; i < baseOne.length(); i++) { List codon = Arrays.asList(Character .toString(baseOne.charAt(i)), @@ -348,7 +350,7 @@ private List startCodons() { } private List split(String string) { - List split = new ArrayList(); + List split = new ArrayList<>(); for (int i = 0; i < string.length(); i++) { split.add(Character.toString(string.charAt(i))); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/ProteinSequenceCreator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/ProteinSequenceCreator.java index c40e3efa2a..fe9e7cba9d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/ProteinSequenceCreator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/ProteinSequenceCreator.java @@ -42,7 +42,7 @@ public class ProteinSequenceCreator implements SequenceCreatorInterface { - private CompoundSet compoundSet; + private final CompoundSet compoundSet; /** * * @param compoundSet @@ -70,7 +70,7 @@ public AbstractSequence getSequence(String sequence, @Override public AbstractSequence getSequence( List list) { - ArrayListProxySequenceReader store = new ArrayListProxySequenceReader(); + ArrayListProxySequenceReader store = new ArrayListProxySequenceReader<>(); store.setCompoundSet(compoundSet); store.setContents(list); return new ProteinSequence(store); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/RNASequenceCreator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/RNASequenceCreator.java index 96abe9cd35..32d20da1ee 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/RNASequenceCreator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/RNASequenceCreator.java @@ -78,7 +78,7 @@ public AbstractSequence getSequence( @Override public AbstractSequence getSequence(List list) { ArrayListProxySequenceReader store = - new ArrayListProxySequenceReader(); + new ArrayListProxySequenceReader<>(); store.setCompoundSet(compoundSet); store.setContents(list); return new RNASequence(store); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/embl/EmblReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/embl/EmblReader.java index 45e50cd9ea..18f2db965e 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/embl/EmblReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/embl/EmblReader.java @@ -21,7 +21,10 @@ package org.biojava.nbio.core.sequence.io.embl; -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; import java.util.Arrays; import java.util.LinkedList; @@ -46,7 +49,7 @@ public class EmblReader { public static EmblRecord process(File file) throws IOException { EmblRecord emblRecord = new EmblRecord(); - StringBuilder sequence = new StringBuilder(""); + StringBuilder sequence = new StringBuilder(); LinkedList emblReferences = new LinkedList<>(); EmblReference emblReference = new EmblReference(); LinkedList accessionNumber = new LinkedList<>(); @@ -59,13 +62,13 @@ public static EmblRecord process(File file) throws IOException { throw new IllegalArgumentException("the file can't be a directory"); try (FileReader fileReader = new FileReader(file)) { - String line = ""; + String line; String lineIdentifier; String lineInfo; try (BufferedReader bufferedReader = new BufferedReader(fileReader)) { while ((line = bufferedReader.readLine()) != null) { if (line.length() > 1) { - lineInfo = line.substring(2, line.length()).trim(); + lineInfo = line.substring(2).trim(); lineIdentifier = line.substring(0, 2); if (lineIdentifier.equals("ID")) emblRecord.setEmblId(populateID(lineInfo)); @@ -129,22 +132,30 @@ private static void populateSequence(String line, StringBuilder sequence) { private static void populateEmblReferences(String lineIdentifier, String lineInfo, EmblReference emblReference , LinkedList emblReferences) { - if (lineIdentifier.equals("RN")) - emblReference.setReferenceNumber(lineInfo); - else if (lineIdentifier.equals("RP")) - emblReference.setReferencePosition(lineInfo); - else if (lineIdentifier.equals("RX")) - emblReference.setReferenceCrossReference(lineInfo); - else if (lineIdentifier.equals("RG")) - emblReference.setReferenceGroup(lineInfo); - else if (lineIdentifier.equals("RA")) - emblReference.setReferenceAuthor(lineInfo); - else if (lineIdentifier.equals("RT")) - emblReference.setReferenceTitle(lineInfo); - else if (lineIdentifier.equals("RL")) { - emblReference.setReferenceLocation(lineInfo); - emblReferences.add(emblReference.copyEmblReference(emblReference)); - } + switch (lineIdentifier) { + case "RN": + emblReference.setReferenceNumber(lineInfo); + break; + case "RP": + emblReference.setReferencePosition(lineInfo); + break; + case "RX": + emblReference.setReferenceCrossReference(lineInfo); + break; + case "RG": + emblReference.setReferenceGroup(lineInfo); + break; + case "RA": + emblReference.setReferenceAuthor(lineInfo); + break; + case "RT": + emblReference.setReferenceTitle(lineInfo); + break; + case "RL": + emblReference.setReferenceLocation(lineInfo); + emblReferences.add(emblReference.copyEmblReference(emblReference)); + break; + } } private static void populateAccessionNumber(String line, LinkedList accessionNumber) { diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/FastaHeaderFormatInterface.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/FastaHeaderFormatInterface.java index a0bb6af6d3..5b1937a2d5 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/FastaHeaderFormatInterface.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/FastaHeaderFormatInterface.java @@ -35,5 +35,5 @@ public interface FastaHeaderFormatInterface, C extends Com * @param sequence * @return */ - public String getHeader(S sequence); + String getHeader(S sequence); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/GenbankHeaderFormatInterface.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/GenbankHeaderFormatInterface.java index 5e08a424bf..6556845f08 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/GenbankHeaderFormatInterface.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/GenbankHeaderFormatInterface.java @@ -36,8 +36,8 @@ public interface GenbankHeaderFormatInterface, C extends C * @param sequence * @return */ - public static final String UNKNOWN_DNA = "UNK"; + String UNKNOWN_DNA = "UNK"; - public String getHeader(S sequence); + String getHeader(S sequence); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceCreatorInterface.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceCreatorInterface.java index 9ec26dc225..0f9730decd 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceCreatorInterface.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceCreatorInterface.java @@ -43,7 +43,7 @@ public interface SequenceCreatorInterface { * @throws CompoundNotFoundException * @throws IOException */ - public AbstractSequence getSequence(String sequence, long index) throws CompoundNotFoundException, IOException; + AbstractSequence getSequence(String sequence, long index) throws CompoundNotFoundException, IOException; /** * @@ -51,13 +51,13 @@ public interface SequenceCreatorInterface { * @param index * @return */ - public AbstractSequence getSequence(ProxySequenceReader proxyLoader, long index); + AbstractSequence getSequence(ProxySequenceReader proxyLoader, long index); /** * * @param list * @return */ - public AbstractSequence getSequence(List list); + AbstractSequence getSequence(List list); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceHeaderParserInterface.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceHeaderParserInterface.java index dba9d7ca3d..f501543176 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceHeaderParserInterface.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceHeaderParserInterface.java @@ -35,5 +35,5 @@ public interface SequenceHeaderParserInterface, C extends * @param header * @param sequence */ - public void parseHeader(String header, S sequence); + void parseHeader(String header, S sequence); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceParserInterface.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceParserInterface.java index fd536e2802..af982f4846 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceParserInterface.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceParserInterface.java @@ -37,5 +37,5 @@ public interface SequenceParserInterface { * @return * @throws Exception */ - public String getSequence(BufferedReader bufferedReader,int sequenceLength) throws IOException; + String getSequence(BufferedReader bufferedReader, int sequenceLength) throws IOException; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/util/IOUtils.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/util/IOUtils.java index a798fcc6c3..19547a7ba8 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/util/IOUtils.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/util/IOUtils.java @@ -70,7 +70,7 @@ public static void close(Closeable c) { public static void copy(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[BUFFER]; - int n = 0; + int n; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } @@ -110,13 +110,8 @@ public static void processReader(BufferedReader br, ReaderProcessor processor) t * @throws ParserException Can throw this if we cannot parse the given reader */ public static List getList(BufferedReader br) throws ParserException { - final List list = new ArrayList(); - processReader(br, new ReaderProcessor() { - @Override - public void process(String line) { - list.add(line); - } - }); + final List list = new ArrayList<>(); + processReader(br, list::add); return list; } @@ -183,8 +178,8 @@ public static InputStream openFile(File file) throws IOException { * * @author ayates */ - public static interface ReaderProcessor { - void process(String line) throws IOException; + public interface ReaderProcessor { + void process(String line); } /** @@ -330,15 +325,10 @@ public static String getPDBLegend() { * @throws IOException If any I/O exception occurs while printing; this method does not catch any exceptions */ public static void print(String string, File file) throws IOException { - PrintWriter out = null; - try { - out = new PrintWriter(new BufferedWriter(new FileWriter(file))); + try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)))) { out.print(string); out.flush(); - out.close(); - } finally { - if (out != null) out.close(); - } + } } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/GenbankProxySequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/GenbankProxySequenceReader.java index 2b74f9cacd..b1b6ebfe4c 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/GenbankProxySequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/GenbankProxySequenceReader.java @@ -32,11 +32,7 @@ import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; import org.biojava.nbio.core.sequence.compound.DNACompoundSet; import org.biojava.nbio.core.sequence.compound.NucleotideCompound; -import org.biojava.nbio.core.sequence.features.AbstractFeature; -import org.biojava.nbio.core.sequence.features.DBReferenceInfo; -import org.biojava.nbio.core.sequence.features.DatabaseReferenceInterface; -import org.biojava.nbio.core.sequence.features.FeatureRetriever; -import org.biojava.nbio.core.sequence.features.FeaturesKeyWordInterface; +import org.biojava.nbio.core.sequence.features.*; import org.biojava.nbio.core.sequence.io.GenbankSequenceParser; import org.biojava.nbio.core.sequence.io.GenericGenbankHeaderParser; import org.biojava.nbio.core.sequence.template.AbstractSequence; @@ -45,16 +41,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; +import java.io.*; import java.net.URL; -import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; @@ -69,10 +57,10 @@ public class GenbankProxySequenceReader extends StringProxyS private static final String eutilBaseURL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/"; // private String genbankDirectoryCache = null; - private GenbankSequenceParser, C> genbankParser; - private GenericGenbankHeaderParser, C> headerParser; - private String header; - private HashMap> features; + private final GenbankSequenceParser, C> genbankParser; + private final GenericGenbankHeaderParser, C> headerParser; + private final String header; + private final HashMap> features; /** @@ -92,7 +80,7 @@ public GenbankProxySequenceReader( String db = compoundSet instanceof AminoAcidCompoundSet ? "protein" : "nuccore"; InputStream inStream = getBufferedInputStream(accessionID, db); - genbankParser = new GenbankSequenceParser, C>(); + genbankParser = new GenbankSequenceParser<>(); setContents(genbankParser.getSequence(new BufferedReader(new InputStreamReader(inStream)), 0)); headerParser = genbankParser.getSequenceHeaderParser(); @@ -110,7 +98,7 @@ public GenbankProxySequenceReader( } private BufferedInputStream getBufferedInputStream(String accessionID, String db) throws IOException, InterruptedException { - BufferedInputStream inStream = null; + BufferedInputStream inStream; if (genbankDirectoryCache != null && genbankDirectoryCache.length() > 0) { File f = new File(genbankDirectoryCache + File.separatorChar + accessionID + ".gb"); if (f.exists()) { @@ -148,18 +136,17 @@ private InputStream getEutilsInputStream(String accessionID, String db) throws I String genbankURL = eutilBaseURL + "efetch.fcgi?db=" + db + "&id=" + accessionID + "&rettype=gb&retmode=text"; logger.trace("Loading: {}", genbankURL); URL genbank = new URL(genbankURL); - URLConnection genbankConnection = genbank.openConnection(); - return genbankConnection.getInputStream(); + return genbank.openConnection().getInputStream(); } - /** - * Local directory cache of Genbank that can be downloaded - * - * @return the uniprotDirectoryCache - */ - public String getGenbankDirectoryCache() { - return genbankDirectoryCache; - } +// /** +// * Local directory cache of Genbank that can be downloaded +// * +// * @return the uniprotDirectoryCache +// */ +// public String getGenbankDirectoryCache() { +// return genbankDirectoryCache; +// } /** * @param genbankDirectoryCache @@ -198,8 +185,8 @@ public ArrayList getKeyWords() { public static void main(String[] args) throws Throwable { - GenbankProxySequenceReader genbankProteinReader - = new GenbankProxySequenceReader("/tmp", "NP_000257", AminoAcidCompoundSet.getAminoAcidCompoundSet()); + GenbankProxySequenceReader genbankProteinReader + = new GenbankProxySequenceReader<>("/tmp", "NP_000257", AminoAcidCompoundSet.aminoAcidCompoundSet); ProteinSequence proteinSequence = new ProteinSequence(genbankProteinReader); genbankProteinReader.getHeaderParser().parseHeader(genbankProteinReader.getHeader(), proteinSequence); logger.info("Sequence ({},{})={}...", proteinSequence.getAccession(), proteinSequence.getLength(), proteinSequence.getSequenceAsString().substring(0, 10)); @@ -208,16 +195,18 @@ public static void main(String[] args) throws Throwable { proteinSequence.getFeatures(); GenbankProxySequenceReader genbankDNAReader - = new GenbankProxySequenceReader("/tmp", "NM_001126", DNACompoundSet.getDNACompoundSet()); + = new GenbankProxySequenceReader<>("/tmp", "NM_001126", DNACompoundSet.getDNACompoundSet()); DNASequence dnaSequence = new DNASequence(genbankDNAReader); genbankDNAReader.getHeaderParser().parseHeader(genbankDNAReader.getHeader(), dnaSequence); dnaSequence.setAccession(new AccessionID("NM_001126")); - logger.info("Sequence ({},{})={}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); - logger.info("Keywords: {}", genbankDNAReader.getKeyWords()); - logger.info("DatabaseReferences: {}", genbankDNAReader.getDatabaseReferences()); + if (logger.isInfoEnabled()) { + logger.info("Sequence ({},{})={}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); + logger.info("Keywords: {}", genbankDNAReader.getKeyWords()); + logger.info("DatabaseReferences: {}", genbankDNAReader.getDatabaseReferences()); + } genbankDNAReader - = new GenbankProxySequenceReader("/tmp", "NM_000266", DNACompoundSet.getDNACompoundSet()); + = new GenbankProxySequenceReader<>("/tmp", "NM_000266", DNACompoundSet.getDNACompoundSet()); dnaSequence = new DNASequence(genbankDNAReader); genbankDNAReader.getHeaderParser().parseHeader(genbankDNAReader.getHeader(), dnaSequence); logger.info("Sequence ({},{})={}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); @@ -225,7 +214,7 @@ public static void main(String[] args) throws Throwable { logger.info("DatabaseReferences: {}", genbankDNAReader.getDatabaseReferences()); genbankDNAReader - = new GenbankProxySequenceReader("/tmp", "AV254721", DNACompoundSet.getDNACompoundSet()); + = new GenbankProxySequenceReader<>("/tmp", "AV254721", DNACompoundSet.getDNACompoundSet()); dnaSequence = new DNASequence(genbankDNAReader); genbankDNAReader.getHeaderParser().parseHeader(genbankDNAReader.getHeader(), dnaSequence); logger.info("Sequence ({},{})={}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); @@ -233,7 +222,7 @@ public static void main(String[] args) throws Throwable { logger.info("DatabaseReferences: {}", genbankDNAReader.getDatabaseReferences()); genbankDNAReader - = new GenbankProxySequenceReader("/tmp", "AV254721.2", DNACompoundSet.getDNACompoundSet()); + = new GenbankProxySequenceReader<>("/tmp", "AV254721.2", DNACompoundSet.getDNACompoundSet()); dnaSequence = new DNASequence(genbankDNAReader); genbankDNAReader.getHeaderParser().parseHeader(genbankDNAReader.getHeader(), dnaSequence); logger.info("Sequence ({},{})={}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); @@ -241,7 +230,7 @@ public static void main(String[] args) throws Throwable { logger.info("DatabaseReferences: {}", genbankDNAReader.getDatabaseReferences()); genbankDNAReader - = new GenbankProxySequenceReader("/tmp", "U49845", DNACompoundSet.getDNACompoundSet()); + = new GenbankProxySequenceReader<>("/tmp", "U49845", DNACompoundSet.getDNACompoundSet()); dnaSequence = new DNASequence(genbankDNAReader); genbankDNAReader.getHeaderParser().parseHeader(genbankDNAReader.getHeader(), dnaSequence); logger.info("Sequence ({},{})={}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); @@ -249,7 +238,7 @@ public static void main(String[] args) throws Throwable { logger.info("DatabaseReferences: {}", genbankDNAReader.getDatabaseReferences()); genbankDNAReader - = new GenbankProxySequenceReader("/tmp", "GI:1293613", DNACompoundSet.getDNACompoundSet()); + = new GenbankProxySequenceReader<>("/tmp", "GI:1293613", DNACompoundSet.getDNACompoundSet()); dnaSequence = new DNASequence(genbankDNAReader); genbankDNAReader.getHeaderParser().parseHeader(genbankDNAReader.getHeader(), dnaSequence); logger.info("Sequence ({},{})={}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); @@ -257,7 +246,7 @@ public static void main(String[] args) throws Throwable { logger.info("DatabaseReferences: {}", genbankDNAReader.getDatabaseReferences()); genbankDNAReader - = new GenbankProxySequenceReader("/tmp", "14109166", DNACompoundSet.getDNACompoundSet()); + = new GenbankProxySequenceReader<>("/tmp", "14109166", DNACompoundSet.getDNACompoundSet()); dnaSequence = new DNASequence(genbankDNAReader); genbankDNAReader.getHeaderParser().parseHeader(genbankDNAReader.getHeader(), dnaSequence); logger.info("Sequence ({},{})={}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/SequenceFileProxyLoader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/SequenceFileProxyLoader.java index 78c08b7795..2585d1ae5e 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/SequenceFileProxyLoader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/SequenceFileProxyLoader.java @@ -55,12 +55,12 @@ */ public class SequenceFileProxyLoader implements ProxySequenceReader { - SequenceParserInterface sequenceParser; + final SequenceParserInterface sequenceParser; private CompoundSet compoundSet; - private List parsedCompounds = new ArrayList(); - File file; - long sequenceStartIndex = -1; - int sequenceLength = -1; + private final List parsedCompounds = new ArrayList<>(); + final File file; + final long sequenceStartIndex; + final int sequenceLength; //private boolean initialized = false; /** @@ -204,7 +204,7 @@ public String getSequenceAsString() { */ public String getSequenceAsString(Integer bioBegin, Integer bioEnd, Strand strand) { - SequenceAsStringHelper sequenceAsStringHelper = new SequenceAsStringHelper(); + SequenceAsStringHelper sequenceAsStringHelper = new SequenceAsStringHelper<>(); return sequenceAsStringHelper.getSequenceAsString(this.parsedCompounds, compoundSet, bioBegin, bioEnd, strand); } @@ -260,7 +260,7 @@ public int hashCode(){ @Override public SequenceView getSubSequence(final Integer bioBegin, final Integer bioEnd) { - return new SequenceProxyView(SequenceFileProxyLoader.this, bioBegin, bioEnd); + return new SequenceProxyView<>(SequenceFileProxyLoader.this, bioBegin, bioEnd); } /** @@ -296,8 +296,9 @@ public AccessionID getAccession() { * @param compounds * @return */ + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { return SequenceMixin.countCompounds(this, compounds); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/StringProxySequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/StringProxySequenceReader.java index 57c793ddc1..ee16f3c1d3 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/StringProxySequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/StringProxySequenceReader.java @@ -46,7 +46,7 @@ public class StringProxySequenceReader implements ProxySeque private String sequence; private CompoundSet compoundSet; - private List parsedCompounds = new ArrayList(); + private final List parsedCompounds = new ArrayList<>(); public StringProxySequenceReader() {} @@ -126,13 +126,13 @@ public List getAsList() { public String getSequenceAsString(Integer bioBegin, Integer bioEnd,Strand strand) { - SequenceAsStringHelper sequenceAsStringHelper = new SequenceAsStringHelper(); + SequenceAsStringHelper sequenceAsStringHelper = new SequenceAsStringHelper<>(); return sequenceAsStringHelper.getSequenceAsString(this.parsedCompounds, compoundSet, bioBegin, bioEnd, strand); } @Override public SequenceView getSubSequence(final Integer bioBegin, final Integer bioEnd) { - return new SequenceProxyView(StringProxySequenceReader.this,bioBegin,bioEnd); + return new SequenceProxyView<>(StringProxySequenceReader.this, bioBegin, bioEnd); } @Override @@ -152,8 +152,9 @@ public AccessionID getAccession() { } + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { throw new UnsupportedOperationException("Not supported yet."); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/UniprotProxySequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/UniprotProxySequenceReader.java index f7f51d89bb..05ab1c8c5f 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/UniprotProxySequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/UniprotProxySequenceReader.java @@ -50,10 +50,7 @@ import java.net.HttpURLConnection; import java.net.URL; import java.rmi.RemoteException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; +import java.util.*; import java.util.regex.Pattern; /** @@ -82,7 +79,7 @@ public class UniprotProxySequenceReader implements ProxySequ private static String uniprotDirectoryCache = null; private String sequence; private CompoundSet compoundSet; - private List parsedCompounds = new ArrayList(); + private final List parsedCompounds = new ArrayList<>(); Document uniprotDoc; /** @@ -128,7 +125,7 @@ public UniprotProxySequenceReader(Document document, CompoundSet compoundSet) public static UniprotProxySequenceReader parseUniprotXMLString(String xml, CompoundSet compoundSet) { try { Document document = XMLHelper.inputStreamToDocument(new ByteArrayInputStream(xml.getBytes())); - return new UniprotProxySequenceReader(document, compoundSet); + return new UniprotProxySequenceReader<>(document, compoundSet); } catch (Exception e) { logger.error("Exception on xml parse of: {}", xml); } @@ -284,7 +281,7 @@ public SequenceView getInverse() { * @return */ public String getSequenceAsString(Integer bioBegin, Integer bioEnd, Strand strand) { - SequenceAsStringHelper sequenceAsStringHelper = new SequenceAsStringHelper(); + SequenceAsStringHelper sequenceAsStringHelper = new SequenceAsStringHelper<>(); return sequenceAsStringHelper.getSequenceAsString(this.parsedCompounds, compoundSet, bioBegin, bioEnd, strand); } @@ -296,7 +293,7 @@ public String getSequenceAsString(Integer bioBegin, Integer bioEnd, Strand stran */ @Override public SequenceView getSubSequence(final Integer bioBegin, final Integer bioEnd) { - return new SequenceProxyView(UniprotProxySequenceReader.this, bioBegin, bioEnd); + return new SequenceProxyView<>(UniprotProxySequenceReader.this, bioBegin, bioEnd); } /** @@ -344,14 +341,13 @@ public AccessionID getAccession() { * @throws XPathExpressionException */ public ArrayList getAccessions() throws XPathExpressionException { - ArrayList accessionList = new ArrayList(); + ArrayList accessionList = new ArrayList<>(); if (uniprotDoc == null) { return accessionList; } Element uniprotElement = uniprotDoc.getDocumentElement(); Element entryElement = XMLHelper.selectSingleElement(uniprotElement, "entry"); - ArrayList keyWordElementList = XMLHelper.selectElements(entryElement, "accession"); - for (Element element : keyWordElementList) { + for (Element element : XMLHelper.selectElements(entryElement, "accession")) { AccessionID accessionID = new AccessionID(element.getTextContent(), DataSource.UNIPROT); accessionList.add(accessionID); } @@ -366,75 +362,71 @@ public ArrayList getAccessions() throws XPathExpressionException { * @return * @throws XPathExpressionException */ - public ArrayList getAliases() throws XPathExpressionException { + public List getAliases() throws XPathExpressionException { return getProteinAliases(); } + /** * Pull uniprot protein aliases associated with this sequence * @return * @throws XPathExpressionException */ - public ArrayList getProteinAliases() throws XPathExpressionException { - ArrayList aliasList = new ArrayList(); - if (uniprotDoc == null) { - return aliasList; - } + public List getProteinAliases() throws XPathExpressionException { + if (uniprotDoc == null) + return Collections.EMPTY_LIST; + + ArrayList a = new ArrayList<>(); + Element uniprotElement = uniprotDoc.getDocumentElement(); Element entryElement = XMLHelper.selectSingleElement(uniprotElement, "entry"); Element proteinElement = XMLHelper.selectSingleElement(entryElement, "protein"); - ArrayList keyWordElementList; - getProteinAliasesFromNameGroup(aliasList, proteinElement); + + getProteinAliasesFromNameGroup(a, proteinElement); - keyWordElementList = XMLHelper.selectElements(proteinElement, "component"); - for (Element element : keyWordElementList) { - getProteinAliasesFromNameGroup(aliasList, element); + + for (Element element : XMLHelper.selectElements(proteinElement, "component")) { + getProteinAliasesFromNameGroup(a, element); } - keyWordElementList = XMLHelper.selectElements(proteinElement, "domain"); - for (Element element : keyWordElementList) { - getProteinAliasesFromNameGroup(aliasList, element); + for (Element element : XMLHelper.selectElements(proteinElement, "domain")) { + getProteinAliasesFromNameGroup(a, element); } - keyWordElementList = XMLHelper.selectElements(proteinElement, "submittedName"); - for (Element element : keyWordElementList) { - getProteinAliasesFromNameGroup(aliasList, element); + for (Element element : XMLHelper.selectElements(proteinElement, "submittedName")) { + getProteinAliasesFromNameGroup(a, element); } - keyWordElementList = XMLHelper.selectElements(proteinElement, "cdAntigenName"); - for (Element element : keyWordElementList) { + for (Element element : XMLHelper.selectElements(proteinElement, "cdAntigenName")) { String cdAntigenName = element.getTextContent(); if(null != cdAntigenName && !cdAntigenName.trim().isEmpty()) { - aliasList.add(cdAntigenName); + a.add(cdAntigenName); } } - - keyWordElementList = XMLHelper.selectElements(proteinElement, "innName"); - for (Element element : keyWordElementList) { + + for (Element element : XMLHelper.selectElements(proteinElement, "innName")) { String cdAntigenName = element.getTextContent(); if(null != cdAntigenName && !cdAntigenName.trim().isEmpty()) { - aliasList.add(cdAntigenName); + a.add(cdAntigenName); } } - keyWordElementList = XMLHelper.selectElements(proteinElement, "biotechName"); - for (Element element : keyWordElementList) { + for (Element element : XMLHelper.selectElements(proteinElement, "biotechName")) { String cdAntigenName = element.getTextContent(); if(null != cdAntigenName && !cdAntigenName.trim().isEmpty()) { - aliasList.add(cdAntigenName); + a.add(cdAntigenName); } } - keyWordElementList = XMLHelper.selectElements(proteinElement, "allergenName"); - for (Element element : keyWordElementList) { + for (Element element : XMLHelper.selectElements(proteinElement, "allergenName")) { String cdAntigenName = element.getTextContent(); if(null != cdAntigenName && !cdAntigenName.trim().isEmpty()) { - aliasList.add(cdAntigenName); + a.add(cdAntigenName); } } - return aliasList; + return a; } /** @@ -444,15 +436,11 @@ public ArrayList getProteinAliases() throws XPathExpressionException { */ private void getProteinAliasesFromNameGroup(ArrayList aliasList, Element proteinElement) throws XPathExpressionException { - ArrayList keyWordElementList = XMLHelper.selectElements(proteinElement, "alternativeName"); - for (Element element : keyWordElementList) { - getProteinAliasesFromElement(aliasList, element); - } - - keyWordElementList = XMLHelper.selectElements(proteinElement, "recommendedName"); - for (Element element : keyWordElementList) { - getProteinAliasesFromElement(aliasList, element); - } + for (Element e : XMLHelper.selectElements(proteinElement, "alternativeName")) + getProteinAliasesFromElement(aliasList, e); + + for (Element e : XMLHelper.selectElements(proteinElement, "recommendedName")) + getProteinAliasesFromElement(aliasList, e); } /** @@ -479,15 +467,15 @@ private void getProteinAliasesFromElement(ArrayList aliasList, Element e * @throws XPathExpressionException */ public ArrayList getGeneAliases() throws XPathExpressionException { - ArrayList aliasList = new ArrayList(); + ArrayList aliasList = new ArrayList<>(); if (uniprotDoc == null) { return aliasList; } Element uniprotElement = uniprotDoc.getDocumentElement(); Element entryElement = XMLHelper.selectSingleElement(uniprotElement, "entry"); - ArrayList proteinElements = XMLHelper.selectElements(entryElement, "gene"); + List proteinElements = XMLHelper.selectElements(entryElement, "gene"); for(Element proteinElement : proteinElements) { - ArrayList keyWordElementList = XMLHelper.selectElements(proteinElement, "name"); + List keyWordElementList = XMLHelper.selectElements(proteinElement, "name"); for (Element element : keyWordElementList) { aliasList.add(element.getTextContent()); } @@ -500,8 +488,9 @@ public ArrayList getGeneAliases() throws XPathExpressionException { * @param compounds * @return */ + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { throw new UnsupportedOperationException("Not supported yet."); } @@ -511,7 +500,7 @@ public int countCompounds(C... compounds) { * @return * @throws IOException */ - private Document getUniprotXML(String accession) throws IOException, CompoundNotFoundException { + private Document getUniprotXML(String accession) throws IOException { StringBuilder sb = new StringBuilder(); // try in cache if (uniprotDirectoryCache != null && uniprotDirectoryCache.length() > 0) { @@ -538,9 +527,7 @@ private Document getUniprotXML(String accession) throws IOException, CompoundNot // logger.debug(sb.toString()); Document document = XMLHelper.inputStreamToDocument(new ByteArrayInputStream(sb.toString().getBytes())); return document; - } catch (SAXException e) { - logger.error("Exception on xml parse of: {}", sb.toString()); - } catch (ParserConfigurationException e) { + } catch (SAXException | ParserConfigurationException e) { logger.error("Exception on xml parse of: {}", sb.toString()); } return null; @@ -609,12 +596,12 @@ private static HttpURLConnection openURLConnection(URL url) throws IOException { } private StringBuilder fetchUniprotXML(String uniprotURL) - throws IOException, CompoundNotFoundException { + throws IOException { StringBuilder sb = new StringBuilder(); URL uniprot = new URL(uniprotURL); int attempt = 5; - List errorCodes = new ArrayList(); + List errorCodes = new ArrayList<>(); while(attempt > 0) { HttpURLConnection uniprotConnection = openURLConnection(uniprot); int statusCode = uniprotConnection.getResponseCode(); @@ -722,7 +709,7 @@ public static void setUniprotDirectoryCache(String aUniprotDirectoryCache) { public static void main(String[] args) { try { - UniprotProxySequenceReader uniprotSequence = new UniprotProxySequenceReader("YA745_GIBZE", AminoAcidCompoundSet.getAminoAcidCompoundSet()); + UniprotProxySequenceReader uniprotSequence = new UniprotProxySequenceReader<>("YA745_GIBZE", AminoAcidCompoundSet.aminoAcidCompoundSet); ProteinSequence proteinSequence = new ProteinSequence(uniprotSequence); logger.info("Accession: {}", proteinSequence.getAccession().getID()); logger.info("Sequence: {}", proteinSequence.getSequenceAsString()); @@ -790,22 +777,21 @@ public String getOrganismName() { * @return */ @Override - public ArrayList getKeyWords() { - ArrayList keyWordsList = new ArrayList(); - if (uniprotDoc == null) { - return keyWordsList; - } + public List getKeyWords() { + if (uniprotDoc == null) + return Collections.EMPTY_LIST; + + ArrayList keyWordsList = new ArrayList<>(); try { Element uniprotElement = uniprotDoc.getDocumentElement(); Element entryElement = XMLHelper.selectSingleElement(uniprotElement, "entry"); - ArrayList keyWordElementList = XMLHelper.selectElements(entryElement, "keyword"); - for (Element element : keyWordElementList) { + for (Element element : XMLHelper.selectElements(entryElement, "keyword")) keyWordsList.add(element.getTextContent()); - } + } catch (XPathExpressionException e) { logger.error("Problems while parsing keywords in UniProt XML: {}. No keywords will be available.",e.getMessage()); - return new ArrayList(); + return new ArrayList<>(); } return keyWordsList; @@ -817,7 +803,7 @@ public ArrayList getKeyWords() { */ @Override public LinkedHashMap> getDatabaseReferences() { - LinkedHashMap> databaseReferencesHashMap = new LinkedHashMap>(); + LinkedHashMap> databaseReferencesHashMap = new LinkedHashMap<>(); if (uniprotDoc == null) { return databaseReferencesHashMap; } @@ -825,28 +811,21 @@ public LinkedHashMap> getDatabaseReferences() try { Element uniprotElement = uniprotDoc.getDocumentElement(); Element entryElement = XMLHelper.selectSingleElement(uniprotElement, "entry"); - ArrayList dbreferenceElementList = XMLHelper.selectElements(entryElement, "dbReference"); - for (Element element : dbreferenceElementList) { + for (Element element : XMLHelper.selectElements(entryElement, "dbReference")) { String type = element.getAttribute("type"); String id = element.getAttribute("id"); - ArrayList idlist = databaseReferencesHashMap.get(type); - if (idlist == null) { - idlist = new ArrayList(); - databaseReferencesHashMap.put(type, idlist); - } + ArrayList idlist = databaseReferencesHashMap.computeIfAbsent(type, k -> new ArrayList<>()); DBReferenceInfo dbreferenceInfo = new DBReferenceInfo(type, id); - ArrayList propertyElementList = XMLHelper.selectElements(element, "property"); - for (Element propertyElement : propertyElementList) { - String propertyType = propertyElement.getAttribute("type"); - String propertyValue = propertyElement.getAttribute("value"); - dbreferenceInfo.addProperty(propertyType, propertyValue); - } + List propertyElementList = XMLHelper.selectElements(element, "property"); + + for (Element pe : propertyElementList) + dbreferenceInfo.addProperty(pe.getAttribute("type"), pe.getAttribute("value")); idlist.add(dbreferenceInfo); } } catch (XPathExpressionException e) { logger.error("Problems while parsing db references in UniProt XML: {}. No db references will be available.",e.getMessage()); - return new LinkedHashMap>(); + return new LinkedHashMap<>(); } return databaseReferencesHashMap; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/FuzzyPoint.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/FuzzyPoint.java index 7a97c7ad1c..ea3ccad87d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/FuzzyPoint.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/FuzzyPoint.java @@ -25,6 +25,8 @@ import org.biojava.nbio.core.util.Equals; import org.biojava.nbio.core.util.Hashcoder; +import java.util.Objects; + /** * Implementation for resolving fuzzy locations. Caches the calculated * value. @@ -36,32 +38,17 @@ public class FuzzyPoint extends SimplePoint { /** * Always uses the min point to resolve a location */ - public static final Resolver MIN_RESOLVER = new Resolver() { - @Override - public int resolve(FuzzyPoint point) { - return point.getMin(); - } - }; + public static final Resolver MIN_RESOLVER = FuzzyPoint::getMin; /** * Always uses the max point to resolve a location */ - public static final Resolver MAX_RESOLVER = new Resolver() { - @Override - public int resolve(FuzzyPoint point) { - return point.getMax(); - } - }; + public static final Resolver MAX_RESOLVER = FuzzyPoint::getMax; /** * Combines min and max and then gets the mean of it */ - public static final Resolver MEAN_RESOLVER = new Resolver() { - @Override - public int resolve(FuzzyPoint point) { - return (point.getMin() + point.getMax()) / 2; - } - }; + public static final Resolver MEAN_RESOLVER = point -> (point.getMin() + point.getMax()) / 2; private final int min; private final int max; @@ -85,11 +72,14 @@ public FuzzyPoint(int minPoint, int maxPoint, Resolver resolver, boo } @Override - public Integer getPosition() { - if(super.getPosition() == -1) { - super.setPosition(getResolver().resolve(this)); - } - return super.getPosition(); + public int getPosition() { + int prevPos = super.getPosition(); + if(prevPos == -1) { + int nextPos = getResolver().resolve(this); + super.setPosition(nextPos); + return nextPos; + } else + return prevPos; } protected Integer getMax() { @@ -121,13 +111,14 @@ public Point offset(int distance) { @Override public boolean equals(Object obj) { + if (this == obj) return true; boolean equals = false; if (Equals.classEqual(this, obj)) { FuzzyPoint p = (FuzzyPoint) obj; - equals = (Equals.equal(getMin(), p.getMin()) - && Equals.equal(getMax(), p.getMax()) - && Equals.equal(isUnknown(), p.isUnknown()) - && Equals.equal(isUncertain(), p.isUncertain()) + equals = (Objects.equals(getMin(), p.getMin()) + && Objects.equals(getMax(), p.getMax()) + && isUnknown() == p.isUnknown() + && isUncertain() == p.isUncertain() ); } return equals; @@ -145,6 +136,7 @@ public int hashCode() { @Override public int compareTo(Point point) { + if (this == point) return 0; //If we can assign this to a FuzzyPoint then work with a bit more info if(FuzzyPoint.class.isAssignableFrom(point.getClass())) { FuzzyPoint fuzzy = (FuzzyPoint)point; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/InsdcParser.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/InsdcParser.java index 2e8217ea43..53028b338b 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/InsdcParser.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/InsdcParser.java @@ -32,7 +32,6 @@ import org.biojava.nbio.core.sequence.template.AbstractSequence; import org.biojava.nbio.core.sequence.template.Compound; -import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; @@ -59,7 +58,7 @@ public class InsdcParser , C extends Compound>{ //protected static final Pattern singleLocationPattern = Pattern.compile("(?:[A-Z]([A-Za-z\\.0-9_]*?):)?(?)(\\d+)?(>?)?"); // fixed issue #254 - protected static final Pattern singleLocationPattern = Pattern.compile("(?:([A-Za-z\\.0-9_]*?):)?(?)(\\d+)?(>?)?"); + protected static final Pattern singleLocationPattern = Pattern.compile("(?:([A-Za-z.0-9_]*?):)?(?)(\\d+)?(>?)?"); /** * Decodes a split pattern. Split patterns are a composition of multiple * locationsString qualified by actions: join(location,location, ... @@ -96,11 +95,11 @@ public class InsdcParser , C extends Compound>{ protected Integer featureGlobalStart, featureGlobalEnd; //private S referenceSequence = new org.biojava.nbio.core.sequence.DNASequence(); - private AbstractSequence referenceSequence = new DNASequence(); + private final AbstractSequence referenceSequence = new DNASequence(); enum complexFeaturesAppendEnum { - FLATTEN, HIERARCHICAL; + FLATTEN, HIERARCHICAL } /** * define the mode in which complex features should be appended in FLATTEN @@ -160,17 +159,16 @@ public Location parse(String locationString) throws ParserException { * @param reader The source of the data; assumes that end of the reader * stream is the end of the location string to parse * @return The parsed location - * @throws IOException Thrown with any reader error * @throws ParserException Thrown with any error with parsing locations */ - public List parse(Reader reader) throws IOException, ParserException { + public List parse(Reader reader) throws ParserException { // use parse(String s) instead! return null; } private List parseLocationString(String string, int versus) throws ParserException { Matcher m; - List boundedLocationsCollection = new ArrayList(); + List boundedLocationsCollection = new ArrayList<>(); //String[] tokens = string.split(locationSplitPattern); List tokens = splitString(string); @@ -229,7 +227,7 @@ private List parseLocationString(String string, int versus) throws Par String accession = m.group(1); Strand s = versus == 1 ? Strand.POSITIVE : Strand.NEGATIVE; int start = Integer.parseInt(m.group(3)); - int end = m.group(6) == null ? start : new Integer(m.group(6)); + int end = m.group(6) == null ? start : Integer.parseInt(m.group(6)); if (featureGlobalStart > start) { featureGlobalStart = start; @@ -253,7 +251,7 @@ private List parseLocationString(String string, int versus) throws Par l.setPartialOn3prime(true); } - if (!(accession == null || "".equals(accession))) l.setAccession(new AccessionID(accession)); + if (!(accession == null || accession.isEmpty())) l.setAccession(new AccessionID(accession)); boundedLocationsCollection.add(l); @@ -265,7 +263,7 @@ private List parseLocationString(String string, int versus) throws Par private List splitString(String input) { - List result = new ArrayList(); + List result = new ArrayList<>(); int start = 0; int openedParenthesis = 0; for (int current = 0; current < input.length(); current++) { diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/LocationHelper.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/LocationHelper.java index efb02f6c64..e2a405badf 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/LocationHelper.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/LocationHelper.java @@ -153,7 +153,7 @@ public static Location circularLocation(int start, int end, Strand strand, int l end = (length * (numberOfPasses + 1)) + modEnd; } - List locations = new ArrayList(); + List locations = new ArrayList<>(); locations.add(new SimpleLocation(modStart, length, strand)); for (int i = 0; i < numberOfPasses; i++) { locations.add(new SimpleLocation(1, length, strand)); @@ -163,7 +163,7 @@ public static Location circularLocation(int start, int end, Strand strand, int l new SimplePoint(end), strand, true, false, locations); } - private static interface LocationPredicate { + private interface LocationPredicate { boolean accept(Location previous, Location current); } @@ -172,12 +172,9 @@ private static interface LocationPredicate { * lowest start */ public static Location getMin(List locations) { - return scanLocations(locations, new LocationPredicate() { - @Override - public boolean accept(Location previous, Location current) { - int res = current.getStart().compareTo(previous.getStart()); - return res < 0; - } + return scanLocations(locations, (previous, current) -> { + int res = current.getStart().compareTo(previous.getStart()); + return res < 0; }); } @@ -186,12 +183,9 @@ public boolean accept(Location previous, Location current) { * highest end */ public static Location getMax(List locations) { - return scanLocations(locations, new LocationPredicate() { - @Override - public boolean accept(Location previous, Location current) { - int res = current.getEnd().compareTo(previous.getEnd()); - return res > 0; - } + return scanLocations(locations, (previous, current) -> { + int res = current.getEnd().compareTo(previous.getEnd()); + return res > 0; }); } @@ -283,7 +277,7 @@ public static boolean detectCicular(List subLocations) { * @return Returns a boolean indicating if this is consistently accessioned */ public static boolean consistentAccessions(List subLocations) { - Set set = new HashSet(); + Set set = new HashSet<>(); for(Location sub: subLocations) { set.add(sub.getAccession()); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/SimpleLocation.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/SimpleLocation.java index 2175ba4282..f0bdd8a438 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/SimpleLocation.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/SimpleLocation.java @@ -61,7 +61,7 @@ public SimpleLocation(int start, int end, Strand strand, List subLocat public SimpleLocation(Point start, Point end, Strand strand) { - super(start, end, strand, false, false, new ArrayList()); + super(start, end, strand, false, false, new ArrayList<>()); } public SimpleLocation(Point start, Point end, Strand strand, AccessionID accession) { diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/SimplePoint.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/SimplePoint.java index 69c3aea801..c4ccb8510f 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/SimplePoint.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/SimplePoint.java @@ -21,12 +21,12 @@ */ package org.biojava.nbio.core.sequence.location; -import java.io.Serializable; - import org.biojava.nbio.core.sequence.location.template.Point; import org.biojava.nbio.core.util.Equals; import org.biojava.nbio.core.util.Hashcoder; +import java.io.Serializable; + /** * Basic implementation of the Point interface. * @@ -56,7 +56,7 @@ public SimplePoint(int position, boolean unknown, boolean uncertain) { } @Override - public Integer getPosition() { + public int getPosition() { return position; } @@ -100,12 +100,13 @@ protected int reverse(int position, int length) { @Override public boolean equals(Object obj) { + if (this == obj) return true; boolean equals = false; if (Equals.classEqual(this, obj)) { SimplePoint p = (SimplePoint) obj; - equals = (Equals.equal(getPosition(), p.getPosition()) - && Equals.equal(isUncertain(), p.isUncertain()) - && Equals.equal(isUnknown(), p.isUnknown())); + equals = (getPosition() == p.getPosition() + && isUncertain() == p.isUncertain() + && isUnknown() == p.isUnknown()); } return equals; } @@ -125,8 +126,9 @@ public String toString() { } @Override - public int compareTo(Point o) { - return getPosition().compareTo(o.getPosition()); + public int compareTo(Point point) { + if (this == point) return 0; + return Integer.compare(getPosition(), point.getPosition()); } @Override diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/AbstractLocation.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/AbstractLocation.java index 10ee98d1e8..10de177683 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/AbstractLocation.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/AbstractLocation.java @@ -33,14 +33,10 @@ import org.biojava.nbio.core.util.Hashcoder; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; +import java.util.*; import static java.lang.String.format; import static org.biojava.nbio.core.util.Equals.classEqual; -import static org.biojava.nbio.core.util.Equals.equal; /** * Base abstraction of a location which encodes for the majority of important @@ -224,7 +220,7 @@ public Iterator iterator() { list = getSubLocations(); } else { - list = new ArrayList(); + list = new ArrayList<>(); list.add(this); } return list.iterator(); @@ -244,13 +240,12 @@ public List getRelevantSubLocations() { /** * Here to allow for recursion */ - private List getAllSubLocations(Location location) { - List flatSubLocations = new ArrayList(); + private static List getAllSubLocations(Location location) { + List flatSubLocations = new ArrayList<>(); for (Location l : location.getSubLocations()) { if (l.isComplex()) { flatSubLocations.addAll(getAllSubLocations(l)); - } - else { + } else { flatSubLocations.add(l); } } @@ -260,16 +255,18 @@ private List getAllSubLocations(Location location) { @Override public boolean equals(Object obj) { + if (this == obj) return true; + boolean equals = false; if (classEqual(this, obj)) { AbstractLocation l = (AbstractLocation) obj; - equals = (equal(getStart(), l.getStart()) - && equal(getEnd(), l.getEnd()) - && equal(getStrand(), l.getStrand()) - && equal(isCircular(), l.isCircular()) - && equal(isBetweenCompounds(), l.isBetweenCompounds()) - && equal(getSubLocations(), l.getSubLocations()) - && equal(getAccession(), l.getAccession())); + equals = (Objects.equals(getStart(), l.getStart()) + && Objects.equals(getEnd(), l.getEnd()) + && Objects.equals(getStrand(), l.getStrand()) + && isCircular() == l.isCircular() + && isBetweenCompounds() == l.isBetweenCompounds() + && Objects.equals(getSubLocations(), l.getSubLocations()) + && Objects.equals(getAccession(), l.getAccession())); } return equals; } @@ -311,11 +308,11 @@ public boolean isBetweenCompounds() { @Override public Sequence getSubSequence(Sequence sequence) { if(isCircular()) { - List> sequences = new ArrayList>(); + List> sequences = new ArrayList<>(); for(Location l: this) { sequences.add(l.getSubSequence(sequence)); } - return new JoiningSequenceReader(sequence.getCompoundSet(), sequences); + return new JoiningSequenceReader<>(sequence.getCompoundSet(), sequences); } return reverseSequence(sequence.getSubSequence( getStart().getPosition(), getEnd().getPosition())); @@ -327,11 +324,11 @@ public Sequence getSubSequence(Sequence sequence) { @Override public Sequence getRelevantSubSequence(Sequence sequence) { - List> sequences = new ArrayList>(); + List> sequences = new ArrayList<>(); for(Location l: getRelevantSubLocations()) { sequences.add(l.getSubSequence(sequence)); } - return new JoiningSequenceReader(sequence.getCompoundSet(), sequences); + return new JoiningSequenceReader<>(sequence.getCompoundSet(), sequences); } /** @@ -345,12 +342,12 @@ protected Sequence reverseSequence(Sequence sequence) return sequence; } - Sequence reversed = new ReversedSequenceView(sequence); + Sequence reversed = new ReversedSequenceView<>(sequence); // "safe" operation as we have tried to check this if(canComplement(sequence)) { Sequence casted = (Sequence) reversed; ComplementSequenceView complement = - new ComplementSequenceView(casted); + new ComplementSequenceView<>(casted); return (Sequence)complement; } return reversed; @@ -360,7 +357,7 @@ protected Sequence reverseSequence(Sequence sequence) * Uses the Sequence's CompoundSet to decide if a compound can * be assgined to ComplementCompound meaning it can complement */ - protected boolean canComplement(Sequence sequence) { + protected static boolean canComplement(Sequence sequence) { CompoundSet compoundSet = sequence.getCompoundSet(); Compound c = compoundSet.getAllCompounds().iterator().next(); return ComplementCompound.class.isAssignableFrom(c.getClass()); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/Location.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/Location.java index 25cdf48f05..d57cab35dd 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/Location.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/Location.java @@ -45,7 +45,7 @@ public interface Location extends Iterable, Accessioned { * Basic location which is set to the minimum and maximum bounds of * {@link Integer}. {@link Strand} is set to {@link Strand#UNDEFINED}. */ - public static final Location EMPTY = + Location EMPTY = new SimpleLocation(Integer.MIN_VALUE, Integer.MAX_VALUE, Strand.UNDEFINED); /** @@ -128,7 +128,7 @@ public interface Location extends Iterable, Accessioned { * Helper methods for use with the Location classes. Taking its * inspiration from the RichSequence.Tools class from the old BioJava */ - public static class Tools { + class Tools { /** * Used for building a location from a series of sub-locations @@ -206,7 +206,7 @@ public static Location circularLocation(int start, int end, Strand strand, int l end = (length * (numberOfPasses + 1)) + modEnd; } - List locations = new ArrayList(); + List locations = new ArrayList<>(); locations.add(new SimpleLocation(modStart, length, strand)); for (int i = 0; i < numberOfPasses; i++) { locations.add(new SimpleLocation(1, length, strand)); @@ -216,7 +216,7 @@ public static Location circularLocation(int start, int end, Strand strand, int l new SimplePoint(end), strand, true, false, locations); } - private static interface LocationPredicate { + private interface LocationPredicate { boolean accept(Location previous, Location current); } @@ -226,13 +226,9 @@ private static interface LocationPredicate { * lowest start */ public static Location getMin(List locations) { - return scanLocations(locations, new LocationPredicate() { - - @Override - public boolean accept(Location previous, Location current) { - int res = current.getStart().compareTo(previous.getStart()); - return res < 0; - } + return scanLocations(locations, (previous, current) -> { + int res = current.getStart().compareTo(previous.getStart()); + return res < 0; }); } @@ -241,13 +237,9 @@ public boolean accept(Location previous, Location current) { * highest end */ public static Location getMax(List locations) { - return scanLocations(locations, new LocationPredicate() { - - @Override - public boolean accept(Location previous, Location current) { - int res = current.getEnd().compareTo(previous.getEnd()); - return res > 0; - } + return scanLocations(locations, (previous, current) -> { + int res = current.getEnd().compareTo(previous.getEnd()); + return res > 0; }); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/Point.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/Point.java index 52cefa711e..2319570917 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/Point.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/Point.java @@ -29,14 +29,14 @@ public interface Point extends Comparable { /** * Used to resolve a position about a point */ - public interface Resolver { + interface Resolver { int resolve(T point); } /** * Returns the position held by this object */ - Integer getPosition(); + int getPosition(); /** * Returns true if the current position is unknown but is diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/ArrayListSequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/ArrayListSequenceReader.java index 48ecb8aff4..3c7e4c9a79 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/ArrayListSequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/ArrayListSequenceReader.java @@ -35,6 +35,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.Objects; /** * Stores a Sequence as a collection of compounds in an ArrayList @@ -44,7 +45,7 @@ public class ArrayListSequenceReader implements SequenceReader { private CompoundSet compoundSet; - private ArrayList parsedCompounds = new ArrayList(); + private final ArrayList parsedCompounds = new ArrayList<>(); private volatile Integer hashcode = null; @@ -95,7 +96,7 @@ public String getSequenceAsString() { */ public String getSequenceAsString(Integer begin, Integer end, Strand strand) { // TODO Optimise/cache. - SequenceAsStringHelper sequenceAsStringHelper = new SequenceAsStringHelper(); + SequenceAsStringHelper sequenceAsStringHelper = new SequenceAsStringHelper<>(); return sequenceAsStringHelper.getSequenceAsString(this.parsedCompounds, compoundSet, begin, end, strand); } @@ -182,15 +183,14 @@ public CompoundSet getCompoundSet() { public void setContents(String sequence) throws CompoundNotFoundException { // Horrendously inefficient - pretty much the way the old BJ did things. // TODO Should be optimised. - this.parsedCompounds.clear(); - hashcode = null; - int maxCompoundLength = compoundSet.getMaxSingleCompoundStringLength(); - boolean maxCompundLengthEqual1 = true; - if (maxCompoundLength > 1) { - maxCompundLengthEqual1 = false; - } int length = sequence.length(); + parsedCompounds.clear(); parsedCompounds.ensureCapacity(length); //get the array size correct + + hashcode = null; + int maxCompoundLength = compoundSet.getMaxSingleCompoundStringLength(); + boolean maxCompundLengthEqual1 = maxCompoundLength <= 1; + for (int i = 0; i < length;) { String compoundStr = null; C compound = null; @@ -219,9 +219,7 @@ public void setContents(String sequence) throws CompoundNotFoundException { */ public void setContents(List list) { parsedCompounds.clear(); - for (C c : list) { - parsedCompounds.add(c); - } + parsedCompounds.addAll(list); } /** @@ -232,7 +230,7 @@ public void setContents(List list) { */ @Override public SequenceView getSubSequence(final Integer bioBegin, final Integer bioEnd) { - return new SequenceProxyView(ArrayListSequenceReader.this, bioBegin, bioEnd); + return new SequenceProxyView<>(ArrayListSequenceReader.this, bioBegin, bioEnd); } /** @@ -249,8 +247,9 @@ public AccessionID getAccession() { * @param compounds * @return */ + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { return SequenceMixin.countCompounds(this, compounds); } @@ -279,8 +278,8 @@ public int hashCode() { public boolean equals(Object o) { if(Equals.classEqual(this, o)) { ArrayListSequenceReader that = (ArrayListSequenceReader)o; - return Equals.equal(parsedCompounds, that.parsedCompounds) && - Equals.equal(compoundSet, that.compoundSet); + return Objects.equals(parsedCompounds, that.parsedCompounds) && + Objects.equals(compoundSet, that.compoundSet); } return false; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/BitSequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/BitSequenceReader.java index 326c8589c8..608e95c53b 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/BitSequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/BitSequenceReader.java @@ -20,16 +20,13 @@ */ package org.biojava.nbio.core.sequence.storage; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.AccessionID; import org.biojava.nbio.core.sequence.compound.NucleotideCompound; import org.biojava.nbio.core.sequence.template.*; import org.biojava.nbio.core.util.Equals; import org.biojava.nbio.core.util.Hashcoder; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; /** * An implementation of the popular bit encodings. This class provides the @@ -75,15 +72,16 @@ public void setCompoundSet(CompoundSet compoundSet) { * Class is immutable & so this is unsupported */ @Override - public void setContents(String sequence) throws CompoundNotFoundException { + public void setContents(String sequence) { throw new UnsupportedOperationException(getClass().getSimpleName() + " is an immutable data structure; cannot reset contents"); } /** * Counts the number of times a compound appears in this sequence store */ + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { return SequenceMixin.countCompounds(this, compounds); } @@ -193,8 +191,8 @@ public boolean equals(Object o) { if(Equals.classEqual(this, o)) { @SuppressWarnings("unchecked") BitSequenceReader that = (BitSequenceReader)o; - return Equals.equal(this.accession, that.accession) && - Equals.equal(this.worker, that.worker); + return Objects.equals(this.accession, that.accession) && + Objects.equals(this.worker, that.worker); } return false; } @@ -287,9 +285,8 @@ public int seqArraySize(int length) { */ public void populate(Sequence sequence) { int position = 1; - for (C c : sequence) { + for (C c : sequence) setCompoundAt(c, position++); - } } /** @@ -460,9 +457,9 @@ public int hashCode() { public boolean equals(Object o) { if(Equals.classEqual(this, o)) { BitArrayWorker that = (BitArrayWorker)o; - return Equals.equal(compoundSet, that.compoundSet) && - Equals.equal(indexToCompoundsLookup, that.indexToCompoundsLookup) && - Equals.equal(sequence, that.sequence); + return Objects.equals(compoundSet, that.compoundSet) && + Objects.equals(indexToCompoundsLookup, that.indexToCompoundsLookup) && + Arrays.equals(sequence, that.sequence); } return false; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/FourBitSequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/FourBitSequenceReader.java index 83f4c5dfd2..86bb3039a9 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/FourBitSequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/FourBitSequenceReader.java @@ -43,7 +43,7 @@ public class FourBitSequenceReader extends BitSequenceReader { public FourBitSequenceReader(Sequence sequence) { - super(new FourBitArrayWorker(sequence), sequence.getAccession()); + super(new FourBitArrayWorker<>(sequence), sequence.getAccession()); } public FourBitSequenceReader(String sequence, CompoundSet compoundSet) { @@ -51,7 +51,7 @@ public FourBitSequenceReader(String sequence, CompoundSet compoundSet) { } public FourBitSequenceReader(String sequence, CompoundSet compoundSet, AccessionID accession) { - super(new FourBitArrayWorker(sequence, compoundSet), accession); + super(new FourBitArrayWorker<>(sequence, compoundSet), accession); } public FourBitSequenceReader(FourBitArrayWorker worker) { @@ -114,7 +114,7 @@ protected int compoundsPerDatatype() { @Override protected Map generateCompoundsToIndex() { final CompoundSet cs = getCompoundSet(); - Map map = new HashMap(); + Map map = new HashMap<>(); int index = 0; for (C currentCompound : sortedCompounds(cs)) { C upperCasedCompound = getOptionalUpperCasedCompound(currentCompound, cs); @@ -132,7 +132,7 @@ protected Map generateCompoundsToIndex() { } private C getOptionalUpperCasedCompound(C currentCompound, CompoundSet cs) { - C upperCasedCompound = null; + C upperCasedCompound; String upperCasedString = cs.getStringForCompound(currentCompound).toUpperCase(); if (cs.getCompoundForString(upperCasedString) == null) { upperCasedCompound = currentCompound; @@ -143,16 +143,11 @@ private C getOptionalUpperCasedCompound(C currentCompound, CompoundSet cs) { } private List sortedCompounds(final CompoundSet cs) { - List compounds = new ArrayList(cs.getAllCompounds()); - Collections.sort(compounds, new Comparator() { - - - @Override - public int compare(C o1, C o2) { - String s1 = cs.getStringForCompound(o1); - String s2 = cs.getStringForCompound(o2); - return s1.compareTo(s2); - } + List compounds = new ArrayList<>(cs.getAllCompounds()); + compounds.sort((o1, o2) -> { + String s1 = cs.getStringForCompound(o1); + String s2 = cs.getStringForCompound(o2); + return s1.compareTo(s2); }); return compounds; } @@ -165,7 +160,7 @@ public int compare(C o1, C o2) { protected List generateIndexToCompounds() { CompoundSet cs = getCompoundSet(); Map lookup = getCompoundsToIndexLookup(); - Map tempMap = new HashMap(); + Map tempMap = new HashMap<>(); //First get the reverse lookup working for (C compound : lookup.keySet()) { C upperCasedCompound = getOptionalUpperCasedCompound(compound, cs); @@ -174,8 +169,8 @@ protected List generateIndexToCompounds() { } //Then populate the results by going back through the sorted integer keys - List compounds = new ArrayList(); - List keys = new ArrayList(tempMap.keySet()); + List compounds = new ArrayList<>(); + List keys = new ArrayList<>(tempMap.keySet()); Collections.sort(keys); for (Integer key : keys) { compounds.add(tempMap.get(key)); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/JoiningSequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/JoiningSequenceReader.java index 5c5a3999d9..eaa2c15dc5 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/JoiningSequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/JoiningSequenceReader.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.core.sequence.storage; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.AccessionID; import org.biojava.nbio.core.sequence.template.*; import org.biojava.nbio.core.util.Equals; @@ -61,6 +60,7 @@ public class JoiningSequenceReader implements ProxySequenceR * available during construction otherwise we will throw an illegal * state exception). */ + @SafeVarargs public JoiningSequenceReader(Sequence... sequences) { this(Arrays.asList(sequences)); } @@ -76,6 +76,7 @@ public JoiningSequenceReader(List> sequences) { this.compoundSet = grepCompoundSet(); } + @SafeVarargs public JoiningSequenceReader(CompoundSet compoundSet, Sequence... sequences) { this(compoundSet, Arrays.asList(sequences)); } @@ -86,7 +87,7 @@ public JoiningSequenceReader(CompoundSet compoundSet, List> seque } private List> grepSequences(List> sequences) { - List> seqs = new ArrayList>(); + List> seqs = new ArrayList<>(); for (Sequence s : sequences) { if (s.getLength() != 0) { seqs.add(s); @@ -277,13 +278,14 @@ public void setCompoundSet(CompoundSet compoundSet) { @Override - public void setContents(String sequence) throws CompoundNotFoundException { + public void setContents(String sequence) { throw new UnsupportedOperationException(); } + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { return SequenceMixin.countCompounds(this, compounds); } @@ -301,7 +303,7 @@ public List getAsList() { @Override public boolean equals(Object o) { - + if (this == o) return true; if(! Equals.classEqual(this, o)) { return false; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/SingleCompoundSequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/SingleCompoundSequenceReader.java index 554b7b8361..d523e1f817 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/SingleCompoundSequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/SingleCompoundSequenceReader.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.core.sequence.storage; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.AccessionID; import org.biojava.nbio.core.sequence.template.*; import org.biojava.nbio.core.util.Equals; @@ -28,6 +27,7 @@ import java.util.Iterator; import java.util.List; +import java.util.Objects; /** * An implementation of the SequenceReader interface which for every @@ -74,7 +74,7 @@ public void setCompoundSet(CompoundSet compoundSet) { */ @Override - public void setContents(String sequence) throws CompoundNotFoundException { + public void setContents(String sequence) { throw new UnsupportedOperationException("Not supported."); } @@ -146,7 +146,7 @@ public List getAsList() { @Override public SequenceView getSubSequence(Integer start, Integer end) { - return new SequenceProxyView(this, start, end); + return new SequenceProxyView<>(this, start, end); } /** @@ -171,8 +171,9 @@ public AccessionID getAccession() { * Delegates to {@link SequenceMixin#countCompounds(org.biojava.nbio.core.sequence.template.Sequence, C[]) } */ + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { return SequenceMixin.countCompounds(this, compounds); } @@ -182,7 +183,7 @@ public int countCompounds(C... compounds) { @Override public Iterator iterator() { - return new SequenceMixin.SequenceIterator(this); + return new SequenceMixin.SequenceIterator<>(this); } @Override @@ -204,9 +205,9 @@ public int hashCode() { public boolean equals(Object o) { if(Equals.classEqual(this, o)) { SingleCompoundSequenceReader that = (SingleCompoundSequenceReader)o; - return Equals.equal(compound, that.compound) && - Equals.equal(compoundSet, that.compoundSet) && - Equals.equal(length, that.length); + return Objects.equals(compound, that.compound) && + Objects.equals(compoundSet, that.compoundSet) && + length == that.length; } return false; } @@ -214,9 +215,9 @@ public boolean equals(Object o) { public boolean equals(Sequence o) { if(Equals.classEqual(this, o)) { SingleCompoundSequenceReader that = (SingleCompoundSequenceReader)o; - return Equals.equal(compound, that.compound) && - Equals.equal(compoundSet, that.compoundSet) && - Equals.equal(length, that.length); + return Objects.equals(compound, that.compound) && + Objects.equals(compoundSet, that.compoundSet) && + length == that.length; } return false; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/TwoBitSequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/TwoBitSequenceReader.java index c73482d04b..c17a634309 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/TwoBitSequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/TwoBitSequenceReader.java @@ -50,7 +50,7 @@ public class TwoBitSequenceReader extends BitSequenceReader { public TwoBitSequenceReader(Sequence sequence) { - super(new TwoBitArrayWorker(sequence), sequence.getAccession()); + super(new TwoBitArrayWorker<>(sequence), sequence.getAccession()); } public TwoBitSequenceReader(String sequence, CompoundSet compoundSet) { @@ -58,7 +58,7 @@ public TwoBitSequenceReader(String sequence, CompoundSet compoundSet) { } public TwoBitSequenceReader(String sequence, CompoundSet compoundSet, AccessionID accession) { - super(new TwoBitArrayWorker(sequence, compoundSet), accession); + super(new TwoBitArrayWorker<>(sequence, compoundSet), accession); } public TwoBitSequenceReader(TwoBitArrayWorker worker) { @@ -138,7 +138,7 @@ protected Map generateCompoundsToIndex() { @Override protected List generateIndexToCompounds() { CompoundSet cs = getCompoundSet(); - List result = new ArrayList(); + List result = new ArrayList<>(); result.add( cs.getCompoundForString("T")); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompound.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompound.java index b548f1b5ce..6a9ea1843b 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompound.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompound.java @@ -24,108 +24,90 @@ /** * The details of a Compound + * * @author Andy Yates */ public abstract class AbstractCompound implements Compound { - private final String base; - private final String upperedBase; - private String shortName = null; - private String longName = null; - private String description = null; - private Float molecularWeight = null; - - - // Added an empty constructor for Serialization - public AbstractCompound(){ - this.base = null; - this.upperedBase = null; - } - - public AbstractCompound(String base) { - this.base = base; - this.upperedBase = base.toUpperCase(); - } - - public String getBase() { - return base; - } - - public String getUpperedBase() { - return upperedBase; - } - - @Override -public String getDescription() { - return description; - } - - @Override -public void setDescription(String description) { - this.description = description; - } - - @Override -public String getShortName() { - return shortName; - } - - @Override -public void setShortName(String shortName) { - this.shortName = shortName; - } - - @Override -public String getLongName() { - return longName; - } - - @Override -public void setLongName(String longName) { - this.longName = longName; - } - - @Override -public Float getMolecularWeight() { - return molecularWeight; - } - - @Override -public void setMolecularWeight(Float molecularWeight) { - this.molecularWeight = molecularWeight; - } - - @Override - public String toString() { - return base; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof AbstractCompound)) { - return false; - } - AbstractCompound them = (AbstractCompound) obj; - return this.base.equals(them.base); - } - - @Override - public int hashCode() { - return this.base.hashCode(); - } - - @Override - public boolean equalsIgnoreCase(Compound compound) { - if (compound == null) { - return false; - } - if (!(compound instanceof AbstractCompound)) { - return false; - } - AbstractCompound them = (AbstractCompound) compound; - return this.base.equalsIgnoreCase(them.base); - } + private final String base; + private final String upperedBase; + private String shortName = null; + private String longName = null; + private String description = null; + protected float molecularWeight = Float.NaN; + final int hash; + + protected AbstractCompound(String base) { + this.base = base; + this.upperedBase = base.toUpperCase(); + this.hash = base.hashCode(); + } + + public String getBase() { + return base; + } + + public String getUpperedBase() { + return upperedBase; + } + + @Override + public String getDescription() { + return description; + } + + @Override + public void setDescription(String description) { + this.description = description; + } + + @Override + public String getShortName() { + return shortName; + } + + @Override + public void setShortName(String shortName) { + this.shortName = shortName; + } + + @Override + public String getLongName() { + return longName; + } + + @Override + public void setLongName(String longName) { + this.longName = longName; + } + + @Override + public final float getMolecularWeight() { + return molecularWeight; + } + + @Override + public final String toString() { + return base; + } + + @Override + public final boolean equals(Object obj) { + return obj == this || (obj instanceof AbstractCompound && this.base.equals(((AbstractCompound) obj).base)); + } + + @Override + public final int hashCode() { + return hash; + } + + @Override + public final boolean equalsIgnoreCase(Compound compound) { + if (this == compound) return true; + if (!(compound instanceof AbstractCompound)) { + return false; + } + AbstractCompound them = (AbstractCompound) compound; + return this.base.equalsIgnoreCase(them.base); + } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompoundSet.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompoundSet.java index 579153a2fd..edc8bd1096 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompoundSet.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompoundSet.java @@ -39,11 +39,11 @@ public abstract class AbstractCompoundSet implements Compoun private final static Logger logger = LoggerFactory.getLogger(AbstractCompoundSet.class); - private Map charSeqToCompound = new HashMap(); + private final Map charSeqToCompound = new HashMap<>(); private int maxCompoundCharSequenceLength = -1; private Boolean compoundStringLengthEqual = null; - Map> equivalentsMap = new HashMap>(); + final Map> equivalentsMap = new HashMap<>(); protected void addCompound(C compound, C lowerCasedCompound, Iterable equivalents) { addCompound(compound); @@ -60,18 +60,15 @@ protected void addCompound(C compound, C lowerCasedCompound, Iterable equival } } - protected void addCompound(C compound, C lowerCasedCompound, C... equivalents) { - List equiv = new ArrayList(equivalents.length); + @SafeVarargs + protected final void addCompound(C compound, C lowerCasedCompound, C... equivalents) { + List equiv = new ArrayList<>(equivalents.length); equiv.addAll(Arrays.asList(equivalents)); addCompound(compound, lowerCasedCompound, equiv); } protected void addEquivalent(C compound, C equivalent) { - Set s = equivalentsMap.get(compound); - if ( s == null){ - s = new HashSet(); - equivalentsMap.put(compound, s); - } + Set s = equivalentsMap.computeIfAbsent(compound, k -> new HashSet<>()); s.add( equivalent); } @@ -158,19 +155,22 @@ public boolean compoundsEqual(C compoundOne, C compoundTwo) { @Override public boolean isValidSequence(Sequence sequence) { - for (C compound: sequence) { - if (!hasCompound(compound)) { - return false; - } - } - return true; + for (C compound: sequence) { + if (!hasCompound(compound)) + return false; + } + return true; } @Override -public List getAllCompounds() { - return new ArrayList(charSeqToCompound.values()); + public Collection getAllCompounds() { + return + Collections.unmodifiableCollection( + //new ArrayList<>( + charSeqToCompound.values() + ); } private void assertCompound(C compound) { @@ -200,11 +200,12 @@ public int hashCode() { @Override @SuppressWarnings("unchecked") public boolean equals(Object o) { + if (this == o) return true; if (! (o instanceof AbstractCompoundSet)) return false; if(Equals.classEqual(this, o)) { AbstractCompoundSet that = (AbstractCompoundSet)o; - return Equals.equal(charSeqToCompound, that.charSeqToCompound) && - Equals.equal(equivalentsMap, that.equivalentsMap); + return Objects.equals(charSeqToCompound, that.charSeqToCompound) && + Objects.equals(equivalentsMap, that.equivalentsMap); } return false; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompoundTranslator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompoundTranslator.java index e11af2b1de..cdfde5944f 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompoundTranslator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompoundTranslator.java @@ -37,7 +37,7 @@ public abstract class AbstractCompoundTranslator creator, CompoundSet fromCompoundSet, CompoundSet toCompoundSet) { this.creator = creator; - this.mapper = new HashMap>(); + this.mapper = new HashMap<>(); this.fromCompoundSet = fromCompoundSet; this.toCompoundSet = toCompoundSet; } @@ -62,14 +62,11 @@ protected void addStrings(String source, String... targets) { } } - protected void addCompounds(F source, T... targets) { + @SafeVarargs + protected final void addCompounds(F source, T... targets) { - List l = mapper.get(source); - if ( l == null) { - l = new ArrayList(); - mapper.put(source, l); - } - l.addAll(Arrays.asList(targets)); + List l = mapper.computeIfAbsent(source, k -> new ArrayList<>()); + l.addAll(Arrays.asList(targets)); } @Override @@ -97,7 +94,7 @@ else if (compounds.size() > 1) { @Override public List> createSequences(Sequence originalSequence) { - List> workingList = new ArrayList>(); + List> workingList = new ArrayList<>(); for (F source : originalSequence) { List compounds = translateMany(source); @@ -126,7 +123,7 @@ public List> createSequences(Sequence originalSequence) { protected void addCompoundsToList(List compounds, List> workingList) { int size = compounds.size(); - List> currentWorkingList = new ArrayList>(); + List> currentWorkingList = new ArrayList<>(); for (int i = 0; i < size; i++) { boolean last = (i == (size - 1)); // If last run we add the compound to the top set of lists & then @@ -147,7 +144,7 @@ protected void addCompoundsToList(List compounds, List> workingList) } protected List> workingListToSequences(List> workingList) { - List> sequences = new ArrayList>(); + List> sequences = new ArrayList<>(); for (List seqList : workingList) { sequences.add(getCreator().getSequence(seqList)); } @@ -155,9 +152,9 @@ protected List> workingListToSequences(List> workingList) { } private List> duplicateList(List> incoming) { - List> outgoing = new ArrayList>(); + List> outgoing = new ArrayList<>(); for (List current : incoming) { - outgoing.add(new ArrayList(current)); + outgoing.add(new ArrayList<>(current)); } return outgoing; } @@ -165,7 +162,7 @@ private List> duplicateList(List> incoming) { protected void addCompoundToLists(List> list, T compound) { if (list.isEmpty()) { - list.add(new ArrayList()); + list.add(new ArrayList<>()); } for (List current : list) { diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractNucleotideCompoundSet.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractNucleotideCompoundSet.java index cb682ef347..26a0a983a4 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractNucleotideCompoundSet.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractNucleotideCompoundSet.java @@ -45,7 +45,7 @@ protected void addNucleotideCompound(String base, String complement, String... e C upper = newNucleotideCompound(base.toUpperCase(), complement.toUpperCase(), upperEquivalents); C lower = newNucleotideCompound(base.toLowerCase(), complement.toLowerCase(), lowerEquivalents); - List equivalentCompounds = new ArrayList(); + List equivalentCompounds = new ArrayList<>(equivalents.length*2); for(int i=0; i> equivalentsMap = new HashMap>(); + Map> equivalentsMap = new HashMap<>(); - List ambiguousCompounds = new ArrayList(); + List ambiguousCompounds = new ArrayList<>(); for(NucleotideCompound compound: getAllCompounds()) { - if (!compound.isAmbiguous()) { + if (!compound.isAmbiguous()) continue; - } ambiguousCompounds.add(compound); } @@ -101,8 +100,9 @@ protected void calculateIndirectAmbiguities() { //And once it's all done start adding them to the equivalents map - for ( NucleotideCompound key: equivalentsMap.keySet()){ - List vals = equivalentsMap.get(key); + for (Map.Entry> entry : equivalentsMap.entrySet()){ + NucleotideCompound key = entry.getKey(); + List vals = entry.getValue(); for (NucleotideCompound value: vals){ addEquivalent((C)key,(C)value); addEquivalent((C)value,(C)key); @@ -116,12 +116,8 @@ private void checkAdd( NucleotideCompound value) { - List listS = equivalentsMap.get(key); - if ( listS == null){ - listS = new ArrayList(); - equivalentsMap.put(key, listS); - } - listS.add(value); + List listS = equivalentsMap.computeIfAbsent(key, k -> new ArrayList<>()); + listS.add(value); } @@ -139,7 +135,7 @@ private NucleotideCompound toLowerCase(NucleotideCompound compound) { * @return The ambiguity symbol which represents this set of nucleotides best */ public NucleotideCompound getAmbiguity(NucleotideCompound... compounds) { - Set settedCompounds = new HashSet(); + Set settedCompounds = new HashSet<>(); for(NucleotideCompound compound: compounds) { for(NucleotideCompound subCompound: compound.getConstituents()) { settedCompounds.add(getCompoundForString(subCompound.getBase().toUpperCase())); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractSequence.java index 7e0228a976..87f0ef34dd 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractSequence.java @@ -35,6 +35,7 @@ import org.biojava.nbio.core.sequence.loader.UniprotProxySequenceReader; import org.biojava.nbio.core.sequence.location.SequenceLocation; import org.biojava.nbio.core.sequence.location.SimpleLocation; +import org.biojava.nbio.core.sequence.location.template.AbstractLocation; import org.biojava.nbio.core.sequence.location.template.Location; import org.biojava.nbio.core.sequence.reference.AbstractReference; import org.biojava.nbio.core.sequence.storage.ArrayListSequenceReader; @@ -65,15 +66,15 @@ public abstract class AbstractSequence implements Sequence parentSequence = null; private String source = null; - private ArrayList notesList = new ArrayList(); + private ArrayList notesList = new ArrayList<>(); private Double sequenceScore = null; private FeaturesKeyWordInterface featuresKeyWord = null; private DatabaseReferenceInterface databaseReferences = null; private FeatureRetriever featureRetriever = null; - private ArrayList, C>> features = - new ArrayList, C>>(); - private LinkedHashMap, C>>> groupedFeatures = - new LinkedHashMap, C>>>(); + private final ArrayList, C>> features = + new ArrayList<>(); + private final LinkedHashMap, C>>> groupedFeatures = + new LinkedHashMap<>(); private List comments = new ArrayList<>(); private List references; @@ -88,7 +89,7 @@ public AbstractSequence() { */ public AbstractSequence(String seqString, CompoundSet compoundSet) throws CompoundNotFoundException { setCompoundSet(compoundSet); - sequenceStorage = new ArrayListSequenceReader(); + sequenceStorage = new ArrayListSequenceReader<>(); sequenceStorage.setCompoundSet(this.getCompoundSet()); sequenceStorage.setContents(seqString); } @@ -126,9 +127,9 @@ public void setProxySequenceReader(SequenceReader proxyLoader) { if (proxyLoader instanceof FeatureRetriever) { this.setFeatureRetriever((FeatureRetriever) sequenceStorage); - HashMap> ff = getFeatureRetriever().getFeatures(); - for (String k: ff.keySet()){ - for (AbstractFeature f: ff.get(k)){ + Map> ff = getFeatureRetriever().getFeatures(); + for (ArrayList abstractFeatures : ff.values()){ + for (AbstractFeature f: abstractFeatures){ this.addFeature(f); } } @@ -153,11 +154,7 @@ public SequenceReader getProxySequenceReader() { * @return the bioBegin */ public Integer getBioBegin() { - if (bioBegin == null) { - return 1; - } else { - return bioBegin; - } + return bioBegin == null ? 1 : bioBegin; } /** @@ -171,11 +168,7 @@ public void setBioBegin(Integer bioBegin) { * @return the bioEnd */ public Integer getBioEnd() { - if (bioEnd == null) { - return this.getLength(); - } else { - return bioEnd; - } + return bioEnd == null ? this.getLength() : bioEnd; } /** @@ -265,13 +258,10 @@ public void setParentSequence(AbstractSequence parentSequence) { * @return the source */ public String getSource() { - if (source != null) { + if (source != null) return source; - } - if (parentSequence != null) { - return parentSequence.getSource(); - } - return null; + else + return parentSequence != null ? parentSequence.getSource() : null; } /** @@ -349,11 +339,12 @@ public void setReferences(List references) { */ public List, C>> getFeatures(String featureType, int bioSequencePosition) { ArrayList, C>> featureHits = - new ArrayList, C>>(); + new ArrayList<>(); List, C>> features = getFeaturesByType(featureType); if (features != null) { for (FeatureInterface, C> feature : features) { - if (bioSequencePosition >= feature.getLocations().getStart().getPosition() && bioSequencePosition <= feature.getLocations().getEnd().getPosition()) { + AbstractLocation locs = feature.getLocations(); + if (bioSequencePosition >= locs.getStart().getPosition() && bioSequencePosition <= locs.getEnd().getPosition()) { featureHits.add(feature); } } @@ -368,7 +359,7 @@ public List, C>> getFeatures(String feature */ public List, C>> getFeatures(int bioSequencePosition) { ArrayList, C>> featureHits = - new ArrayList, C>>(); + new ArrayList<>(); if (features != null) { for (FeatureInterface, C> feature : features) { if (bioSequencePosition >= feature.getLocations().getStart().getPosition() && bioSequencePosition <= feature.getLocations().getEnd().getPosition()) { @@ -396,7 +387,7 @@ public List, C>> getFeatures() { */ public void addFeature(int bioStart, int bioEnd, FeatureInterface, C> feature) { SequenceLocation, C> sequenceLocation = - new SequenceLocation, C>(bioStart, bioEnd, this); + new SequenceLocation<>(bioStart, bioEnd, this); feature.setLocation(sequenceLocation); addFeature(feature); } @@ -409,14 +400,10 @@ public void addFeature(int bioStart, int bioEnd, FeatureInterface, C> feature) { features.add(feature); - ArrayList, C>> featureList = groupedFeatures.get(feature.getType()); - if (featureList == null) { - featureList = new ArrayList, C>>(); - groupedFeatures.put(feature.getType(), featureList); - } + ArrayList, C>> featureList = groupedFeatures.computeIfAbsent(feature.getType(), k -> new ArrayList<>()); featureList.add(feature); - Collections.sort(features, AbstractFeature.LOCATION_LENGTH); - Collections.sort(featureList, AbstractFeature.LOCATION_LENGTH); + features.sort(AbstractFeature.LOCATION_LENGTH); + featureList.sort(AbstractFeature.LOCATION_LENGTH); } /** @@ -442,7 +429,7 @@ public void removeFeature(FeatureInterface, C> feature) { public List, C>> getFeaturesByType(String type) { List, C>> features = groupedFeatures.get(type); if (features == null) { - features = new ArrayList, C>>(); + features = new ArrayList<>(); } return features; } @@ -503,7 +490,7 @@ public void setFeatureRetriever(FeatureRetriever featureRetriever) { public enum AnnotationType { - CURATED, PREDICTED, UNKNOWN; + CURATED, PREDICTED, UNKNOWN } /** @@ -558,7 +545,7 @@ public void setCompoundSet(CompoundSet compoundSet) { @Override public boolean equals(Object o){ - + if (this == o) return true; if(! Equals.classEqual(this, o)) { return false; } @@ -604,7 +591,7 @@ private SequenceReader getSequenceStorage() { //return parentSequence.getSequenceStorage(); if ( this.compoundSet.equals(parentSequence.getCompoundSet())){ - sequenceStorage = new ArrayListSequenceReader(); + sequenceStorage = new ArrayListSequenceReader<>(); sequenceStorage.setCompoundSet(this.getCompoundSet()); try { sequenceStorage.setContents(parentSequence.getSequenceAsString()); @@ -701,7 +688,7 @@ public int getLength() { */ @Override public SequenceView getSubSequence(final Integer bioStart, final Integer bioEnd) { - return new SequenceProxyView(this, bioStart, bioEnd); + return new SequenceProxyView<>(this, bioStart, bioEnd); } /** @@ -718,8 +705,9 @@ public Iterator iterator() { * @param compounds * @return */ + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { return SequenceMixin.countCompounds(this, compounds); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/ComplementCompound.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/ComplementCompound.java index 66b0e29e32..74873d286d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/ComplementCompound.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/ComplementCompound.java @@ -29,5 +29,5 @@ public interface ComplementCompound extends Compound { - public ComplementCompound getComplement(); + ComplementCompound getComplement(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/Compound.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/Compound.java index 6dbeda2208..113fc05736 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/Compound.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/Compound.java @@ -28,21 +28,21 @@ public interface Compound { - public boolean equalsIgnoreCase(Compound compound); + boolean equalsIgnoreCase(Compound compound); - public String getDescription(); + String getDescription(); - public void setDescription(String description); + void setDescription(String description); - public String getShortName(); + String getShortName(); - public void setShortName(String shortName); + void setShortName(String shortName); - public String getLongName(); + String getLongName(); - public void setLongName(String longName); + void setLongName(String longName); - public Float getMolecularWeight(); + float getMolecularWeight(); - public void setMolecularWeight(Float molecularWeight); +// void setMolecularWeight(Float molecularWeight); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/CompoundSet.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/CompoundSet.java index 2dbc40603a..a0a6e91ab1 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/CompoundSet.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/CompoundSet.java @@ -25,7 +25,7 @@ */ package org.biojava.nbio.core.sequence.template; -import java.util.List; +import java.util.Collection; import java.util.Set; @@ -34,31 +34,31 @@ public interface CompoundSet { /** * Returns the maximum size of a compound String this set holds */ - public int getMaxSingleCompoundStringLength(); + int getMaxSingleCompoundStringLength(); /** * Returns true if all String representations of Compounds are of the * same length. */ - public boolean isCompoundStringLengthEqual(); + boolean isCompoundStringLengthEqual(); /** * Return null if not recognised. Throw IllegalArgumentException if string * is longer than maximum allowed by {@link #getStringForCompound(Compound)}. */ - public C getCompoundForString(String string); + C getCompoundForString(String string); - public String getStringForCompound(C compound); + String getStringForCompound(C compound); - public boolean compoundsEquivalent(C compoundOne, C compoundTwo); + boolean compoundsEquivalent(C compoundOne, C compoundTwo); - public boolean isValidSequence(Sequence sequence); + boolean isValidSequence(Sequence sequence); - public Set getEquivalentCompounds(C compound); + Set getEquivalentCompounds(C compound); - public boolean hasCompound(C compound); + boolean hasCompound(C compound); - public List getAllCompounds(); + Collection getAllCompounds(); boolean isComplementable(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/Sequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/Sequence.java index f05ed60ec7..da15aabb68 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/Sequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/Sequence.java @@ -41,7 +41,7 @@ public interface Sequence extends Iterable, Accessioned { /** * Returns the length of the Sequence */ - public int getLength(); + int getLength(); /** * Returns the Compound at the given biological index @@ -49,7 +49,7 @@ public interface Sequence extends Iterable, Accessioned { * @param position Biological index (1 to n) * @return Compound at the specified position */ - public C getCompoundAt(int position); + C getCompoundAt(int position); /** * Scans through the Sequence looking for the first occurrence of the given @@ -58,7 +58,7 @@ public interface Sequence extends Iterable, Accessioned { * @param compound Compounds to look for * @return Index of the first position of the compound in the sequence (1 to n) */ - public int getIndexOf(C compound); + int getIndexOf(C compound); /** * Scans through the Sequence looking for the last occurrence of the given @@ -67,17 +67,17 @@ public interface Sequence extends Iterable, Accessioned { * @param compound Compounds to look for * @return Index of the last position of the compound in the sequence (1 to n) */ - public int getLastIndexOf(C compound); +int getLastIndexOf(C compound); /** * Returns the String representation of the Sequence */ - public String getSequenceAsString(); + String getSequenceAsString(); /** * Returns the Sequence as a List of compounds */ - public List getAsList(); + List getAsList(); /** * Returns a portion of the sequence from the different positions. This is @@ -87,12 +87,12 @@ public interface Sequence extends Iterable, Accessioned { * @param end Biological end; must be less than length + 1 * @return A SequenceView of the offset */ - public SequenceView getSubSequence(Integer start, Integer end); + SequenceView getSubSequence(Integer start, Integer end); /** * Gets the compound set used to back this Sequence */ - public CompoundSet getCompoundSet(); + CompoundSet getCompoundSet(); /** * Returns the number of times we found a compound in the Sequence @@ -100,12 +100,12 @@ public interface Sequence extends Iterable, Accessioned { * @param compounds Vargs of the compounds to count * @return Number of times a compound was found */ - public int countCompounds(C... compounds); + int countCompounds(C... compounds); /** * Does the right thing to get the inverse of the current * Sequence. This means either reversing the Sequence and optionally * complementing the Sequence. */ - public SequenceView getInverse(); + SequenceView getInverse(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceMixin.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceMixin.java index d6efc03817..979f29278a 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceMixin.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceMixin.java @@ -59,6 +59,7 @@ public class SequenceMixin { * @param The type of compound we are looking for * @return The number of times the given compounds appear in this Sequence */ + @SafeVarargs public static int countCompounds( Sequence sequence, C... compounds) { int count = 0; @@ -113,7 +114,7 @@ public static int countAT(Sequence sequence) { * sequence. Any compound not in the Map will return a fraction of 0. */ public static Map getDistribution(Sequence sequence) { - Map results = new HashMap(); + Map results = new HashMap<>(); Map composition = getComposition(sequence); double length = sequence.getLength(); for (Map.Entry entry : composition.entrySet()) { @@ -133,7 +134,7 @@ public static Map getDistribution(Sequence se * @return Counts for the instances of all compounds in the sequence */ public static Map getComposition(Sequence sequence) { - Map results = new HashMap(); + Map results = new HashMap<>(); for (C currentCompound : sequence) { Integer currentInteger = results.get(currentCompound); @@ -187,7 +188,7 @@ public static String toString(Sequence sequence) { * the Compounds of that {@link Sequence}. */ public static List toList(Sequence sequence) { - List list = new ArrayList(sequence.getLength()); + List list = new ArrayList<>(sequence.getLength()); for (C compound : sequence) { list.add(compound); } @@ -218,7 +219,7 @@ public static int indexOf(Sequence sequence, */ public static int lastIndexOf(Sequence sequence, C compound) { - int index = indexOf(new ReversedSequenceView(sequence), compound); + int index = indexOf(new ReversedSequenceView<>(sequence), compound); return (sequence.getLength() - index)+1; } @@ -229,7 +230,7 @@ public static int lastIndexOf(Sequence sequence, */ public static Iterator createIterator( Sequence sequence) { - return new SequenceIterator(sequence); + return new SequenceIterator<>(sequence); } /** @@ -237,7 +238,7 @@ public static Iterator createIterator( */ public static SequenceView createSubSequence( Sequence sequence, int start, int end) { - return new SequenceProxyView(sequence, start, end); + return new SequenceProxyView<>(sequence, start, end); } /** @@ -250,7 +251,7 @@ public static SequenceView createSubSequence( public static Sequence shuffle(Sequence sequence) { List compounds = sequence.getAsList(); Collections.shuffle(compounds); - return new ArrayListSequenceReader(compounds, + return new ArrayListSequenceReader<>(compounds, sequence.getCompoundSet()); } @@ -275,8 +276,8 @@ public static String checksum(Sequence sequence) { * @return The list of non-overlapping K-mers */ public static List> nonOverlappingKmers(Sequence sequence, int kmer) { - List> l = new ArrayList>(); - WindowedSequence w = new WindowedSequence(sequence, kmer); + List> l = new ArrayList<>(); + WindowedSequence w = new WindowedSequence<>(sequence, kmer); for(SequenceView view: w) { l.add(view); } @@ -293,17 +294,17 @@ public static List> nonOverlappingKmers(Seq * @return The list of overlapping K-mers */ public static List> overlappingKmers(Sequence sequence, int kmer) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); List>> windows - = new ArrayList>>(); + = new ArrayList<>(); for(int i=1; i<=kmer; i++) { if(i == 1) { - windows.add(new WindowedSequence(sequence, kmer).iterator()); + windows.add(new WindowedSequence<>(sequence, kmer).iterator()); } else { SequenceView sv = sequence.getSubSequence(i, sequence.getLength()); - windows.add(new WindowedSequence(sv, kmer).iterator()); + windows.add(new WindowedSequence<>(sv, kmer).iterator()); } } @@ -333,7 +334,7 @@ public static List> overlappingKmers(Sequen */ @SuppressWarnings({ "unchecked" }) public static SequenceView inverse(Sequence sequence) { - SequenceView reverse = new ReversedSequenceView(sequence); + SequenceView reverse = new ReversedSequenceView<>(sequence); if(sequence.getCompoundSet().isComplementable()) { return new ComplementSequenceView(reverse); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceProxyView.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceProxyView.java index f6e51dfad7..15100c8cf5 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceProxyView.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceProxyView.java @@ -74,7 +74,7 @@ public List getAsList() { @Override public boolean equals(Object o) { - + if (this == o) return true; if(! Equals.classEqual(this, o)) { return false; } @@ -117,12 +117,12 @@ public CompoundSet getCompoundSet() { @Override public SequenceView getSubSequence(final Integer bioStart, final Integer bioEnd) { - return new SequenceProxyView(this, bioStart, bioEnd); + return new SequenceProxyView<>(this, bioStart, bioEnd); } @Override public Iterator iterator() { - return new SequenceMixin.SequenceIterator(this); + return new SequenceMixin.SequenceIterator<>(this); } @Override @@ -175,8 +175,9 @@ public void setBioEnd(Integer bioEnd) { this.bioEnd = bioEnd; } + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { return SequenceMixin.countCompounds(this, compounds); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceReader.java index 48eb728a94..e8380598b3 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceReader.java @@ -29,7 +29,7 @@ public interface SequenceReader extends Sequence { - public void setCompoundSet(CompoundSet compoundSet); + void setCompoundSet(CompoundSet compoundSet); - public void setContents(String sequence) throws CompoundNotFoundException; + void setContents(String sequence) throws CompoundNotFoundException; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceView.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceView.java index 4f98899355..7c2228e17f 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceView.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceView.java @@ -28,15 +28,15 @@ public interface SequenceView extends Sequence { - public Sequence getViewedSequence(); + Sequence getViewedSequence(); /** * 1-indexed, inclusive. */ - public Integer getBioStart(); + Integer getBioStart(); /** * 1-indexed, inclusive. */ - public Integer getBioEnd(); + Integer getBioEnd(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/CaseInsensitiveCompound.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/CaseInsensitiveCompound.java index 5c00b511d6..af2adba614 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/CaseInsensitiveCompound.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/CaseInsensitiveCompound.java @@ -1,115 +1,115 @@ -/* - * BioJava development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public Licence. This should - * be distributed with the code. If you do not have a copy, - * see: - * - * http://www.gnu.org/copyleft/lesser.html - * - * Copyright for this code is held jointly by the individual - * authors. These should be listed in @author doc comments. - * - * For more information on the BioJava project and its aims, - * or to join the biojava-l mailing list, visit the home page - * at: - * - * http://www.biojava.org/ - * - * Created on 01-21-2010 - */ -package org.biojava.nbio.core.sequence.transcription; - -import org.biojava.nbio.core.sequence.compound.NucleotideCompound; -import org.biojava.nbio.core.sequence.template.Compound; - -/** - * Attempts to wrap compounds so it is possible to view them - * in a case insensitive manner - */ -public class CaseInsensitiveCompound implements Compound { - - private final NucleotideCompound compound; - - public CaseInsensitiveCompound(NucleotideCompound compound) { - this.compound = compound; - } - - @Override -public boolean equalsIgnoreCase(Compound compound) { - if (compound == null) { - return false; - } - if (!(compound instanceof CaseInsensitiveCompound)) { - return false; - } - CaseInsensitiveCompound them = (CaseInsensitiveCompound) compound; - return toString().equalsIgnoreCase(them.toString()); - } - - @Override -public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof CaseInsensitiveCompound)) { - return false; - } - return equalsIgnoreCase((Compound)obj); - } - - @Override -public int hashCode() { - return toString().toUpperCase().hashCode(); - } - - public NucleotideCompound getUnderlyingCompound() { - return this.compound; - } - - @Override -public String getDescription() { - return getUnderlyingCompound().getDescription(); - } - - @Override -public String getLongName() { - return getUnderlyingCompound().getLongName(); - } - - @Override -public Float getMolecularWeight() { - return getUnderlyingCompound().getMolecularWeight(); - } - - @Override -public String getShortName() { - return getUnderlyingCompound().getShortName(); - } - - @Override -public String toString() { - return getUnderlyingCompound().toString(); - } - - @Override -public void setDescription(String description) { - //Nothing - } - - @Override -public void setLongName(String longName) { - //Nothing - } - - @Override -public void setMolecularWeight(Float molecularWeight) { - //Nothing - } - - @Override -public void setShortName(String shortName) { - //Nothing - } -} +///* +// * BioJava development code +// * +// * This code may be freely distributed and modified under the +// * terms of the GNU Lesser General Public Licence. This should +// * be distributed with the code. If you do not have a copy, +// * see: +// * +// * http://www.gnu.org/copyleft/lesser.html +// * +// * Copyright for this code is held jointly by the individual +// * authors. These should be listed in @author doc comments. +// * +// * For more information on the BioJava project and its aims, +// * or to join the biojava-l mailing list, visit the home page +// * at: +// * +// * http://www.biojava.org/ +// * +// * Created on 01-21-2010 +// */ +//package org.biojava.nbio.core.sequence.transcription; +// +//import org.biojava.nbio.core.sequence.compound.NucleotideCompound; +//import org.biojava.nbio.core.sequence.template.Compound; +// +///** +// * Attempts to wrap compounds so it is possible to view them +// * in a case insensitive manner +// */ +//public class CaseInsensitiveCompound implements Compound { +// +// private final NucleotideCompound compound; +// +// public CaseInsensitiveCompound(NucleotideCompound compound) { +// this.compound = compound; +// } +// +// @Override +//public boolean equalsIgnoreCase(Compound compound) { +// if (compound == null) { +// return false; +// } +// if (!(compound instanceof CaseInsensitiveCompound)) { +// return false; +// } +// CaseInsensitiveCompound them = (CaseInsensitiveCompound) compound; +// return toString().equalsIgnoreCase(them.toString()); +// } +// +// @Override +//public boolean equals(Object obj) { +// if (obj == null) { +// return false; +// } +// if (!(obj instanceof CaseInsensitiveCompound)) { +// return false; +// } +// return equalsIgnoreCase((Compound)obj); +// } +// +// @Override +//public int hashCode() { +// return toString().toUpperCase().hashCode(); +// } +// +// public NucleotideCompound getUnderlyingCompound() { +// return this.compound; +// } +// +// @Override +//public String getDescription() { +// return getUnderlyingCompound().getDescription(); +// } +// +// @Override +//public String getLongName() { +// return getUnderlyingCompound().getLongName(); +// } +// +// @Override +//public Float getMolecularWeight() { +// return getUnderlyingCompound().getMolecularWeight(); +// } +// +// @Override +//public String getShortName() { +// return getUnderlyingCompound().getShortName(); +// } +// +// @Override +//public String toString() { +// return getUnderlyingCompound().toString(); +// } +// +// @Override +//public void setDescription(String description) { +// //Nothing +// } +// +// @Override +//public void setLongName(String longName) { +// //Nothing +// } +// +// @Override +//public void setMolecularWeight(Float molecularWeight) { +// //Nothing +// } +// +// @Override +//public void setShortName(String shortName) { +// //Nothing +// } +//} diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/DNAToRNATranslator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/DNAToRNATranslator.java index 0016c86507..baafa9419d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/DNAToRNATranslator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/DNAToRNATranslator.java @@ -65,7 +65,7 @@ public DNAToRNATranslator(SequenceCreatorInterface rnaCreato @Override public List> createSequences(Sequence originalSequence) { if(shortCutTranslation) { - List> result = new ArrayList>(1); + List> result = new ArrayList<>(1); result.add(wrapToRna(originalSequence)); return result; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/Frame.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/Frame.java index 8f35c0eb03..c60695015e 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/Frame.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/Frame.java @@ -42,7 +42,7 @@ public enum Frame { private final boolean reverse; private final int start; - private Frame(int start, boolean reverse) { + Frame(int start, boolean reverse) { this.start = start; this.reverse = reverse; } @@ -83,7 +83,7 @@ public static Frame[] getAllFrames() { public Sequence wrap(Sequence incoming) { Sequence reversed; if(reverse) { - reversed = new ComplementSequenceView(new ReversedSequenceView(incoming)); + reversed = new ComplementSequenceView<>(new ReversedSequenceView<>(incoming)); } else { reversed = incoming; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/RNAToAminoAcidTranslator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/RNAToAminoAcidTranslator.java index e748b41387..56ee596811 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/RNAToAminoAcidTranslator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/RNAToAminoAcidTranslator.java @@ -81,20 +81,16 @@ public RNAToAminoAcidTranslator( this.initMetOnly = initMetOnly; this.translateNCodons = translateNCodons; - quickLookup = new HashMap(codons + quickLookup = new HashMap<>(codons .getAllCompounds().size()); - aminoAcidToCodon = new HashMap>(); + aminoAcidToCodon = new HashMap<>(); List codonList = table.getCodons(nucleotides, aminoAcids); for (Codon codon : codonList) { quickLookup.put(codon.getTriplet(), codon); codonArray[codon.getTriplet().intValue()] = codon; - List codonL = aminoAcidToCodon.get(codon.getAminoAcid()); - if (codonL == null) { - codonL = new ArrayList(); - aminoAcidToCodon.put(codon.getAminoAcid(), codonL); - } + List codonL = aminoAcidToCodon.computeIfAbsent(codon.getAminoAcid(), k -> new ArrayList<>()); codonL.add(codon); } @@ -114,9 +110,9 @@ public RNAToAminoAcidTranslator( public List> createSequences( Sequence originalSequence) { - List> workingList = new ArrayList>(); + List> workingList = new ArrayList<>(); - Iterable> iter = new WindowedSequence( + Iterable> iter = new WindowedSequence<>( originalSequence, 3); boolean first = true; @@ -132,7 +128,7 @@ public List> createSequences( element.getCompoundAt(i++), element.getCompoundAt(i++), element.getCompoundAt(i++)); - Codon target = null; + Codon target; target = quickLookup.get(triplet); @@ -152,7 +148,7 @@ public List> createSequences( } } - addCompoundsToList(Arrays.asList(aminoAcid), workingList); + addCompoundsToList(Collections.singletonList(aminoAcid), workingList); } if (doTranslate && stopAtStopCodons && target.isStop()) { diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/Table.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/Table.java index 7d75a10d6a..f765c6ea2e 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/Table.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/Table.java @@ -30,6 +30,7 @@ import org.biojava.nbio.core.util.Hashcoder; import java.util.List; +import java.util.Objects; /** * Provides a way of separating us from the specific {@link IUPACTable} even @@ -64,7 +65,7 @@ CompoundSet getCodonCompoundSet( * @author ayates * */ - public static class Codon implements Compound { + class Codon implements Compound { private final CaseInsensitiveTriplet triplet; private final boolean start; @@ -114,14 +115,15 @@ public CaseInsensitiveTriplet getTriplet() { } @Override - public boolean equals(Object obj) { + public boolean equals(Object o) { + if (this == o) return true; boolean equals = false; - if(Equals.classEqual(this, obj)) { - Codon casted = (Codon) obj; - equals = Equals.equal(getTriplet(), casted.getTriplet()) && - Equals.equal(isStart(), casted.isStart()) && - Equals.equal(isStop(), casted.isStop()) && - Equals.equal(getAminoAcid(), casted.getAminoAcid()); + if(Equals.classEqual(this, o)) { + Codon casted = (Codon) o; + equals = Objects.equals(getTriplet(), casted.getTriplet()) && + isStart() == casted.isStart() && + isStop() == casted.isStop() && + Objects.equals(getAminoAcid(), casted.getAminoAcid()); } return equals; } @@ -157,7 +159,7 @@ public String getLongName() { } @Override - public Float getMolecularWeight() { + public float getMolecularWeight() { throw new UnsupportedOperationException("Not supported"); } @@ -176,10 +178,10 @@ public void setLongName(String longName) { throw new UnsupportedOperationException("Not supported"); } - @Override - public void setMolecularWeight(Float molecularWeight) { - throw new UnsupportedOperationException("Not supported"); - } +// @Override +// public void setMolecularWeight(Float molecularWeight) { +// throw new UnsupportedOperationException("Not supported"); +// } @Override public void setShortName(String shortName) { @@ -191,7 +193,7 @@ public void setShortName(String shortName) { * Class used to hold three nucleotides together and allow for equality * to be assessed in a case insensitive manner. */ - public static class CaseInsensitiveTriplet { + class CaseInsensitiveTriplet { private final NucleotideCompound one; private final NucleotideCompound two; @@ -199,7 +201,7 @@ public static class CaseInsensitiveTriplet { private transient boolean hashSet = false; private transient int hash; - private transient boolean stringSet = false; + private final transient boolean stringSet = false; private transient String stringify; public CaseInsensitiveTriplet(NucleotideCompound one, @@ -223,10 +225,11 @@ public NucleotideCompound getThree() { } @Override - public boolean equals(Object obj) { + public boolean equals(Object o) { + if (this == o) return true; boolean equals = false; - if(Equals.classEqual(this, obj)) { - CaseInsensitiveTriplet casted = (CaseInsensitiveTriplet) obj; + if(Equals.classEqual(this, o)) { + CaseInsensitiveTriplet casted = (CaseInsensitiveTriplet) o; return toString().equals(casted.toString()); } return equals; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/TranscriptionEngine.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/TranscriptionEngine.java index 0ca5bc6f1a..0ee18cdb66 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/TranscriptionEngine.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/TranscriptionEngine.java @@ -125,7 +125,7 @@ public Sequence translate( */ public Map> multipleFrameTranslation( Sequence dna, Frame... frames) { - Map> results = new EnumMap>( + Map> results = new EnumMap<>( Frame.class); for (Frame frame : frames) { Sequence rna = getDnaRnaTranslator() @@ -327,8 +327,8 @@ private CompoundSet getAminoAcidCompounds() { if (aminoAcidCompounds != null) { return aminoAcidCompounds; } - return AminoAcidCompoundSet.getAminoAcidCompoundSet(); - } + return AminoAcidCompoundSet.aminoAcidCompoundSet; + } private DNAToRNATranslator getDnaRnaTranslator() { if (dnaRnaTranslator != null) { diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/views/RnaSequenceView.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/views/RnaSequenceView.java index b0c00d6a60..05eb1a86d8 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/views/RnaSequenceView.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/views/RnaSequenceView.java @@ -23,7 +23,6 @@ */ package org.biojava.nbio.core.sequence.views; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.compound.NucleotideCompound; import org.biojava.nbio.core.sequence.compound.RNACompoundSet; import org.biojava.nbio.core.sequence.template.*; @@ -39,7 +38,7 @@ */ public class RnaSequenceView extends SequenceProxyView implements ProxySequenceReader { - private CompoundSet rnaCompounds; + private final CompoundSet rnaCompounds; private Map dnaToRna = null; private Map rnaToDna = null; @@ -90,9 +89,9 @@ public Map getDnaToRna() { protected void buildTranslators() { Map localDnaToRna = - new HashMap(); + new HashMap<>(); Map localRnaToDna = - new HashMap(); + new HashMap<>(); NucleotideCompound thymine = getViewedSequence().getCompoundSet().getCompoundForString("T"); @@ -124,7 +123,7 @@ public void setCompoundSet(CompoundSet compoundSet) { } @Override - public void setContents(String sequence) throws CompoundNotFoundException { + public void setContents(String sequence) { throw new UnsupportedOperationException("Unsupported operation; create a new viewed sequence"); } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/views/WindowedSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/views/WindowedSequence.java index 72e2111407..9b21da105a 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/views/WindowedSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/views/WindowedSequence.java @@ -115,7 +115,7 @@ public SequenceView get(int index) { */ @Override public Iterator> iterator() { - return new WindowedSequenceIterator(this); + return new WindowedSequenceIterator<>(this); } /** diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/CRC64Checksum.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/CRC64Checksum.java index 3e99fec10b..81e0a9339d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/CRC64Checksum.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/CRC64Checksum.java @@ -81,7 +81,7 @@ public long getValue() { */ @Override public String toString() { - StringBuffer builder = new StringBuffer(); + StringBuilder builder = new StringBuilder(); builder.append(Long.toHexString(crc >>> 4)); builder.append(Long.toHexString(crc & 0xF)); for (int i = 16 - builder.length(); i > 0; --i) diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/ConcurrencyTools.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/ConcurrencyTools.java index 3e849a38a4..303da24403 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/ConcurrencyTools.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/ConcurrencyTools.java @@ -94,7 +94,7 @@ public static void setThreadPoolSingle() { public static void setThreadPoolSize(int threads) { setThreadPool( new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue())); + new LinkedBlockingQueue<>())); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/Equals.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/Equals.java index 85beddf1de..b335791b7f 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/Equals.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/Equals.java @@ -30,26 +30,6 @@ */ public class Equals { - public static boolean equal(int one, int two) { - return one == two; - } - - public static boolean equal(long one, long two) { - return (one == two); - } - - public static boolean equal(boolean one, boolean two) { - return one == two; - } - - /** - * Does not compare class types. - * @see #classEqual(Object, Object) - */ - public static boolean equal(Object one, Object two) { - return one == null && two == null || !(one == null || two == null) && (one == two || one.equals(two)); - } - /** * This method should be called before beginning any equals methods. In order * to return true the method: @@ -82,6 +62,7 @@ public static boolean equal(Object one, Object two) { * equal at the class level */ public static boolean classEqual(Object one, Object two) { - return one == two || !(one == null || two == null) && one.getClass() == two.getClass(); + return one == two || + (!(one == null || two == null) && one.getClass() == two.getClass()); } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/FileDownloadUtils.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/FileDownloadUtils.java index 2fd6f3f9e0..31f284209e 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/FileDownloadUtils.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/FileDownloadUtils.java @@ -21,28 +21,18 @@ */ package org.biojava.nbio.core.util; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.SocketTimeoutException; -import java.net.URL; -import java.net.URLConnection; -import java.nio.channels.Channels; -import java.nio.channels.FileChannel; -import java.nio.channels.ReadableByteChannel; -import java.nio.file.FileVisitResult; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.attribute.BasicFileAttributes; - +import okhttp3.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.*; +import java.net.*; +import java.nio.channels.FileChannel; +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.concurrent.TimeUnit; +import java.util.zip.GZIPInputStream; + public class FileDownloadUtils { private static final Logger logger = LoggerFactory.getLogger(FileDownloadUtils.class); @@ -61,95 +51,45 @@ public static void copy(File src, File dst) throws IOException { // Took following recipe from // http://stackoverflow.com/questions/106770/standard-concise-way-to-copy-a-file-in-java // The nio package seems to be the most efficient way to copy a file - FileChannel source = null; - FileChannel destination = null; - try { - // we need the supress warnings here (the warning that the stream is not closed is harmless) - // see http://stackoverflow.com/questions/12970407/does-filechannel-close-close-the-underlying-stream - source = new FileInputStream(src).getChannel(); - destination = new FileOutputStream(dst).getChannel(); - destination.transferFrom(source, 0, source.size()); - } finally { - if (source != null) { - source.close(); - } - if (destination != null) { - destination.close(); - } - } + try (FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dst).getChannel()) { + // we need the supress warnings here (the warning that the stream is not closed is harmless) + // see http://stackoverflow.com/questions/12970407/does-filechannel-close-close-the-underlying-stream + destination.transferFrom(source, 0, source.size()); + } } public static String getFileExtension(File f) { String fileName = f.getName(); - String ext = ""; - int mid = fileName.lastIndexOf("."); - ext = fileName.substring(mid + 1, fileName.length()); - return ext; + return fileName.substring(fileName.lastIndexOf('.') + 1); } public static String getFilePrefix(File f) { String fileName = f.getName(); - String fname = ""; - - int mid = fileName.indexOf("."); - fname = fileName.substring(0, mid); - - return fname; + return fileName.substring(0, fileName.indexOf('.')); } - /** - * Download the content provided at URL url and store the result to a local - * file, using a temp file to cache the content in case something goes wrong - * in download - * - * @param url - * @param destination - * @throws IOException - */ - public static void downloadFile(URL url, File destination) throws IOException { - int count = 0; - int maxTries = 10; - int timeout = 60000; //60 sec - - File tempFile = File.createTempFile(getFilePrefix(destination), "." + getFileExtension(destination)); - - // Took following recipe from stackoverflow: - // http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java - // It seems to be the most efficient way to transfer a file - // See: http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html - ReadableByteChannel rbc = null; - FileOutputStream fos = null; - while (true) { - try { - URLConnection connection = prepareURLConnection(url.toString(), timeout); - connection.connect(); - InputStream inputStream = connection.getInputStream(); - - rbc = Channels.newChannel(inputStream); - fos = new FileOutputStream(tempFile); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - break; - } catch (SocketTimeoutException e) { - if (++count == maxTries) throw e; - } finally { - if (rbc != null) { - rbc.close(); - } - if (fos != null) { - fos.close(); - } - } - } - - logger.debug("Copying temp file {} to final location {}", tempFile, destination); - copy(tempFile, destination); + static final OkHttpClient.Builder clients; + static { + /** https://square.github.io/okhttp/recipes/#response-caching-kt-java */ + int cacheSize = 512 * 1024 * 1024; //512m + OkHttpClient.Builder bb = new OkHttpClient.Builder(); + bb.followRedirects(true); + bb.followSslRedirects(true); - // delete the tmp file - tempFile.delete(); +// try { + File cacheDir = Paths.get(System.getProperty("java.io.tmpdir"), "biojava").toFile(); + cacheDir.mkdirs(); + Cache cache = new Cache(cacheDir, cacheSize); + bb.cache(cache); +// } catch (IOException e) { +// e.printStackTrace(); +// } + clients = bb; } + /** * Converts path to Unix convention and adds a terminating slash if it was * omitted @@ -264,36 +204,163 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { - if (e != null) { + if (e != null) throw e; - } Files.delete(dir); return FileVisitResult.CONTINUE; } }); } + /** - * Recursively delete a folder & contents - * - * @param dir directory to delete + * Open a URL and return an InputStream to it + * if acceptGzipEncoding == true, use GZIPEncoding to + * compress communication. + *

    + * The caller is responsible to close the returned InputStream not to cause + * resource leaks. + * @param url the input URL to be read + * @param timeoutMS + * @return an {@link InputStream} of response + * @throws IOException due to an error opening the URL */ - public static void deleteDirectory(String dir) throws IOException { - deleteDirectory(Paths.get(dir)); + public static InputStream downloadStream(URL url, int timeoutMS) throws IOException { +// InputStream inStream; +// URLConnection huc = URLConnectionTools.openURLConnection(url,timeout); +// +// if ( acceptGzipEncoding) huc.setRequestProperty("Accept-Encoding", "gzip"); +// +// String contentEncoding = huc.getContentEncoding(); +// +// inStream = huc.getInputStream(); + + OkHttpClient client = clients.build(); //TODO ThreadLocal + + Call c = client.newCall(new Request.Builder().url(url).cacheControl(CacheControl.FORCE_CACHE).build()); + + c.timeout().deadline(timeoutMS, TimeUnit.MILLISECONDS); + try (Response r = c.execute()) { + if (!r.isSuccessful()) { + //throw new IOException("Unexpected code " + r); + return new ByteArrayInputStream(new byte[] { } ); //HACK + } + + ResponseBody b = r.body(); + + InputStream inStream = new ByteArrayInputStream(b.bytes()); //b.byteStream(); + + if (b.contentType().toString().contains("gzip")) { + return new GZIPInputStream(inStream); + } + +// if (acceptGzipEncoding) { +//// if (contentEncoding != null) { +//// if (contentEncoding.contains("gzip")) { + +//// } +//// } +// } + + return inStream; + } + + } + /** + * Download the content provided at URL url and store the result to a local + * file, using a temp file to cache the content in case something goes wrong + * in download + * + * @param url + * @param destination + * @throws IOException + */ + public static void downloadFile(URL url, File destination) throws IOException { + + + OkHttpClient client = clients.build(); //TODO ThreadLocal + + try (Response r = client.newCall(new Request.Builder().url(url).build()).execute()) { + if (!r.isSuccessful()) { + //throw new IOException("Unexpected code " + r); + return; + } + + ResponseBody b = r.body(); + + FileChannel dst = new FileOutputStream(destination).getChannel(); + dst.transferFrom(b.source(), 0, b.contentLength()); + + System.out.println("Response 1 response: " + r); + System.out.println("Response 1 cache response: " + r.cacheResponse()); + System.out.println("Response 1 network response: " + r.networkResponse()); + } + + +// int count = 0; +// int maxTries = 10; +// int timeout = 60000; //60 sec +// +// File tempFile = File.createTempFile(getFilePrefix(destination), "." + getFileExtension(destination)); +// +// // Took following recipe from stackoverflow: +// // http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java +// // It seems to be the most efficient way to transfer a file +// // See: http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html +// ReadableByteChannel rbc = null; +// FileOutputStream fos = null; +// while (true) { +// try { +// URLConnection connection = prepareURLConnection(url.toString(), timeout); +// connection.connect(); +// +// rbc = Channels.newChannel(connection.getInputStream()); +// fos = new FileOutputStream(tempFile); +// fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); +// break; +// } catch (SocketTimeoutException e) { +// if (++count == maxTries) throw e; +// } finally { +// if (rbc != null) { +// rbc.close(); +// } +// if (fos != null) { +// fos.close(); +// } +// } +// } +// +// logger.debug("Copying temp file {} to final location {}", tempFile, destination); +// copy(tempFile, destination); +// +// // delete the tmp file +// tempFile.delete(); - public static void main(String[] args) { - String url; - url = "http://scop.mrc-lmb.cam.ac.uk/scop/parse/"; - System.out.format("%s\t%s%n", ping(url, 200), url); - url = "http://scop.mrc-lmb.cam.ac.uk/scop/parse/foo"; - System.out.format("%s\t%s%n", ping(url, 200), url); - url = "http://scopzzz.mrc-lmb.cam.ac.uk/scop/parse/"; - System.out.format("%s\t%s%n", ping(url, 200), url); - url = "scop.mrc-lmb.cam.ac.uk"; - System.out.format("%s\t%s%n", ping(url, 200), url); - url = "http://scop.mrc-lmb.cam.ac.uk"; - System.out.format("%s\t%s%n", ping(url, 200), url); } +// /** +// * Recursively delete a folder & contents +// * +// * @param dir directory to delete +// */ +// public static void deleteDirectory(String dir) throws IOException { +// deleteDirectory(Paths.get(dir)); +// } +// +// +// public static void main(String[] args) { +// String url; +// url = "http://scop.mrc-lmb.cam.ac.uk/scop/parse/"; +// System.out.format("%s\t%s%n", ping(url, 200), url); +// url = "http://scop.mrc-lmb.cam.ac.uk/scop/parse/foo"; +// System.out.format("%s\t%s%n", ping(url, 200), url); +// url = "http://scopzzz.mrc-lmb.cam.ac.uk/scop/parse/"; +// System.out.format("%s\t%s%n", ping(url, 200), url); +// url = "scop.mrc-lmb.cam.ac.uk"; +// System.out.format("%s\t%s%n", ping(url, 200), url); +// url = "http://scop.mrc-lmb.cam.ac.uk"; +// System.out.format("%s\t%s%n", ping(url, 200), url); +// } + } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/FlatFileCache.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/FlatFileCache.java index e8feeec8ac..0ca9f46c3e 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/FlatFileCache.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/FlatFileCache.java @@ -44,7 +44,7 @@ public class FlatFileCache { /** * The cache singleton. */ - private static SoftHashMap cache = new SoftHashMap(0); + private static final SoftHashMap cache = new SoftHashMap<>(0); // no public constructor; @@ -73,7 +73,7 @@ public static void addToCache(String key, File fileToCache){ // Read in the bytes int offset = 0; - int numRead = 0; + int numRead; while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { offset += numRead; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/InputStreamProvider.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/InputStreamProvider.java index f129dedb0b..8b7731ae5c 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/InputStreamProvider.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/InputStreamProvider.java @@ -100,7 +100,7 @@ public InputStream getInputStream(String pathToFile) * @return the magic number * @throws IOException */ - private int getMagicNumber(InputStream in) + private static int getMagicNumber(InputStream in) throws IOException { @@ -118,7 +118,7 @@ private int getMagicNumber(InputStream in) public InputStream getInputStream(URL u) throws IOException{ - int magic = 0; + int magic; InputStream inStream = u.openStream(); @@ -160,7 +160,7 @@ public InputStream getInputStream(File f) // use the magic numbers to determine the compression type, // use file extension only as 2nd choice - int magic = 0; + int magic; InputStream test = getInputStreamFromFile(f); @@ -168,7 +168,7 @@ public InputStream getInputStream(File f) test.close(); - InputStream inputStream = null; + InputStream inputStream; String fileName = f.getName(); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/PrettyXMLWriter.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/PrettyXMLWriter.java index 0027dbc7b4..eeca840485 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/PrettyXMLWriter.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/PrettyXMLWriter.java @@ -34,17 +34,17 @@ */ public class PrettyXMLWriter implements XMLWriter { - private int indentUnit = 2; + private final int indentUnit = 2; - private PrintWriter writer; + private final PrintWriter writer; private boolean isOpeningTag = false; private boolean afterNewline = true; private int indent = 0; - private Map namespacePrefixes = new HashMap(); + private final Map namespacePrefixes = new HashMap<>(); private int namespaceSeed = 0; - private LinkedList> namespaceBindings = new LinkedList>(); - private List namespacesDeclared = new ArrayList(); + private final LinkedList> namespaceBindings = new LinkedList<>(); + private final List namespacesDeclared = new ArrayList<>(); public PrettyXMLWriter(PrintWriter writer) { this.writer = writer; @@ -64,10 +64,9 @@ public void declareNamespace(String nsURI, String prefixHint) } } - private void handleDeclaredNamespaces() - throws IOException + private void handleDeclaredNamespaces() throws IOException { - if (namespacesDeclared.size() == 0) { + if (namespacesDeclared.size() > 0) { for (Iterator nsi = namespacesDeclared.iterator(); nsi.hasNext(); ) { String nsURI = nsi.next(); if (!namespacePrefixes.containsKey(nsURI)) { @@ -79,17 +78,13 @@ private void handleDeclaredNamespaces() } } - protected void writeIndent() - throws IOException - { + protected void writeIndent() { for (int i = 0; i < indent * indentUnit; ++i) { writer.write(' '); } } - private void _openTag() - throws IOException - { + private void _openTag() { if (isOpeningTag) { writer.println('>'); afterNewline = true; @@ -108,7 +103,7 @@ private String allocPrefix(String nsURI) { namespacePrefixes.put(nsURI, prefix); List bindings = namespaceBindings.getLast(); if (bindings == null) { - bindings = new ArrayList(); + bindings = new ArrayList<>(); namespaceBindings.removeLast(); namespaceBindings.add(bindings); } @@ -226,9 +221,7 @@ public void closeTag(String nsURI, String localName) } @Override - public void closeTag(String qName) - throws IOException - { + public void closeTag(String qName) { indent--; if (isOpeningTag) { @@ -245,9 +238,7 @@ public void closeTag(String qName) } @Override - public void println(String data) - throws IOException - { + public void println(String data) { if (isOpeningTag) { writer.println('>'); isOpeningTag = false; @@ -258,9 +249,7 @@ public void println(String data) } @Override - public void print(String data) - throws IOException - { + public void print(String data) { if (isOpeningTag) { writer.print('>'); isOpeningTag = false; @@ -270,15 +259,11 @@ public void print(String data) } @Override - public void printRaw(String data) - throws IOException - { + public void printRaw(String data) { writer.println(data); } - protected void printChars(String data) - throws IOException - { + protected void printChars(String data) { if (data == null) { printChars("null"); return; @@ -294,9 +279,7 @@ protected void printChars(String data) } } - protected void printAttributeValue(String data) - throws IOException - { + protected void printAttributeValue(String data) { if (data == null) { printAttributeValue("null"); return; @@ -312,18 +295,14 @@ protected void printAttributeValue(String data) } } - protected void numericalEntity(char c) - throws IOException - { + protected void numericalEntity(char c) { writer.print("&#"); writer.print((int) c); writer.print(';'); } @Override - public void close() - throws IOException - { + public void close() { writer.close(); } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/SingleLinkageClusterer.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/SingleLinkageClusterer.java index ca58257f48..1a62a232bb 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/SingleLinkageClusterer.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/SingleLinkageClusterer.java @@ -38,11 +38,11 @@ public class SingleLinkageClusterer { private static final Logger logger = LoggerFactory.getLogger(SingleLinkageClusterer.class); - private class LinkedPair { + private static class LinkedPair { - private int first; - private int second; - private double closestDistance; + private final int first; + private final int second; + private final double closestDistance; public LinkedPair(int first, int second, double minDistance) { this.first = first; @@ -65,7 +65,7 @@ public double getClosestDistance() { @Override public String toString() { - String closestDistStr = null; + String closestDistStr; if (closestDistance==Double.MAX_VALUE) { closestDistStr = String.format("%6s", "inf"); } else { @@ -77,11 +77,11 @@ public String toString() { } - private double[][] matrix; + private final double[][] matrix; - private boolean isScoreMatrix; + private final boolean isScoreMatrix; - private int numItems; + private final int numItems; private LinkedPair[] dendrogram; @@ -135,7 +135,7 @@ private void clusterIt() { dendrogram = new LinkedPair[numItems-1]; - logger.debug("Initial matrix: \n"+matrixToString()); + //logger.debug("Initial matrix: \n"+matrixToString()); for (int m=0;m(numItems); + indicesToCheck = new ArrayList<>(numItems); for (int i=0;i=max) { max = matrix[i][j]; - closestPair = new LinkedPair(i,j,max); + closestPair = new LinkedPair(i, j, max); } } @@ -229,7 +225,7 @@ private LinkedPair getClosestPair() { if (matrix[i][j]<=min) { min = matrix[i][j]; - closestPair = new LinkedPair(i,j,min); + closestPair = new LinkedPair(i, j, min); } } @@ -250,7 +246,7 @@ public Map> getClusters(double cutoff) { clusterIt(); } - Map> clusters = new TreeMap>(); + Map> clusters = new TreeMap<>(); int clusterId = 1; @@ -276,7 +272,7 @@ public Map> getClusters(double cutoff) { if (firstClusterId==-1 && secondClusterId==-1) { // neither member is in a cluster yet, let's assign a new cluster and put them both in - Set members = new TreeSet(); + Set members = new TreeSet<>(); members.add(dendrogram[i].getFirst()); members.add(dendrogram[i].getSecond()); clusters.put(clusterId, members); @@ -293,36 +289,32 @@ public Map> getClusters(double cutoff) { Set firstCluster = clusters.get(firstClusterId); Set secondCluster = clusters.get(secondClusterId); if (firstCluster.size()> finalClusters = new TreeMap>(); + Map> finalClusters = new TreeMap<>(); int newClusterId = 1; - for (int oldClusterId:clusters.keySet()) { - finalClusters.put(newClusterId, clusters.get(oldClusterId)); + for (Set integers : clusters.values()) { + finalClusters.put(newClusterId, integers); newClusterId++; } @@ -336,7 +328,7 @@ public Map> getClusters(double cutoff) { } } if (!isAlreadyClustered) { - Set members = new TreeSet(); + Set members = new TreeSet<>(); members.add(i); finalClusters.put(newClusterId, members); newClusterId++; @@ -344,7 +336,7 @@ public Map> getClusters(double cutoff) { } - logger.debug("Clusters: \n"+clustersToString(finalClusters)); + //logger.debug("Clusters: \n"+clustersToString(finalClusters)); return finalClusters; } @@ -367,9 +359,9 @@ private boolean isWithinCutoff(int i, double cutoff) { private String clustersToString(Map> finalClusters) { StringBuilder sb = new StringBuilder(); - for (int cId:finalClusters.keySet()) { - sb.append(cId).append(": "); - for (int member:finalClusters.get(cId)) { + for (Map.Entry> entry : finalClusters.entrySet()) { + sb.append((int) entry.getKey()).append(": "); + for (int member: entry.getValue()) { sb.append(member).append(" "); } sb.append("\n"); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/SoftHashMap.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/SoftHashMap.java index b13c246baa..48eaca4409 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/SoftHashMap.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/SoftHashMap.java @@ -37,11 +37,11 @@ public class SoftHashMap extends AbstractMap { private final static Logger logger = LoggerFactory.getLogger(SoftHashMap.class); - public static final int DEFAULT_LIMIT = 1; + //public static final int DEFAULT_LIMIT = 1; /** The internal HashMap that stores SoftReference to actual data. */ - private final Map> map = new HashMap>(); + private final Map> map = new HashMap<>(); /** Maximum Number of references you dont want GC to collect. */ @@ -49,11 +49,11 @@ public class SoftHashMap extends AbstractMap { /** The FIFO list of hard references, order of last access. */ - private final LinkedList hardCache = new LinkedList(); + private final LinkedList hardCache = new LinkedList<>(); /** Reference queue for cleared SoftReference objects. */ - private final ReferenceQueue queue = new ReferenceQueue(); + private final ReferenceQueue queue = new ReferenceQueue<>(); public SoftHashMap() { @@ -215,7 +215,7 @@ public synchronized V put(K key, V value) { logger.debug("Putting {} on cache. size: {}", key, size()); - map.put(key, new SoftValue(value, key, queue)); + map.put(key, new SoftValue<>(value, key, queue)); return value; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/StringManipulationHelper.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/StringManipulationHelper.java index f8aef6b35e..bd30662768 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/StringManipulationHelper.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/StringManipulationHelper.java @@ -75,7 +75,7 @@ public static String convertStreamToString(InputStream stream) { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder sb = new StringBuilder(); - String line = null; + String line; try { while ((line = reader.readLine()) != null) { @@ -136,24 +136,18 @@ public static boolean equalsToIgnoreEndline(String expected, String actual) { public static boolean equalsToXml(String expected, String actual) { - Document expectedDocument=null; - Document actualDocument=null; + Document expectedDocument; + Document actualDocument; try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); expectedDocument = documentBuilder.parse(new ByteArrayInputStream(expected.getBytes())); actualDocument = documentBuilder.parse(new ByteArrayInputStream(actual.getBytes())); - } catch (ParserConfigurationException e) { - logger.error("Exception: ", e); - throw new RuntimeException("Couldn't Parse XML", e); - } catch (SAXException e) { - logger.error("Exception: ", e); - throw new RuntimeException("Couldn't Parse XML", e); - } catch (IOException e) { + } catch (ParserConfigurationException | IOException | SAXException e) { logger.error("Exception: ", e); throw new RuntimeException("Couldn't Parse XML", e); } - final DocumentType doctype1 = expectedDocument.getDoctype(); + final DocumentType doctype1 = expectedDocument.getDoctype(); final DocumentType doctype2 = actualDocument.getDoctype(); if (doctype1==null ^ doctype2 == null) { return false; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/UncompressInputStream.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/UncompressInputStream.java index 07708f0f4d..98cc49fa26 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/UncompressInputStream.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/UncompressInputStream.java @@ -176,7 +176,7 @@ public synchronized int read(byte[] buf, int off, int len) // empty stack if stuff still left int s_size = l_stack.length - l_stackp; if (s_size > 0) { - int num = (s_size >= len) ? len : s_size; + int num = Math.min(s_size, len); System.arraycopy(l_stack, l_stackp, buf, off, num); off += num; len -= num; @@ -304,7 +304,7 @@ public synchronized int read(byte[] buf, int off, int len) // And put them out in forward order s_size = l_stack.length - l_stackp; - int num = (s_size >= len) ? len : s_size; + int num = Math.min(s_size, len); System.arraycopy(l_stack, l_stackp, buf, off, num); off += num; len -= num; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/XMLHelper.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/XMLHelper.java index 7d9e1cad63..0a58829228 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/XMLHelper.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/XMLHelper.java @@ -40,6 +40,8 @@ import javax.xml.xpath.XPathFactory; import java.io.*; import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import static org.biojava.nbio.core.sequence.io.util.IOUtils.close; import static org.biojava.nbio.core.sequence.io.util.IOUtils.openFile; @@ -76,9 +78,12 @@ static public Document loadXML(String fileName) throws SAXException, IOException static public Document inputStreamToDocument(InputStream inputStream) throws SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setIgnoringComments(true); + dbf.setIgnoringElementContentWhitespace(true); DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse(inputStream); doc.getDocumentElement().normalize(); @@ -123,13 +128,13 @@ static public Element selectParentElement(Element element, String parentName) { } static public Element selectSingleElement(Element element, String xpathExpression) throws XPathExpressionException { - if (xpathExpression.indexOf("/") == -1) { + if (!xpathExpression.contains("/")) { NodeList nodeList = element.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { + int nn = nodeList.getLength(); + for (int i = 0; i < nn; i++) { Node node = nodeList.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(xpathExpression)) { + if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(xpathExpression)) return (Element) node; - } } // NodeList nodes = element.getElementsByTagName(xpathExpression); // if (nodes.getLength() > 0) { @@ -139,34 +144,34 @@ static public Element selectSingleElement(Element element, String xpathExpressio // } } else { XPath xpath = XPathFactory.newInstance().newXPath(); - Element node = (Element) xpath.evaluate(xpathExpression, element, XPathConstants.NODE); - return node; + return (Element) xpath.evaluate(xpathExpression, element, XPathConstants.NODE); } } - static public ArrayList selectElements(Element element, String xpathExpression) throws XPathExpressionException { - ArrayList resultVector = new ArrayList(); + static public List selectElements(Element element, String xpathExpression) throws XPathExpressionException { if (element == null) { - return resultVector; + return Collections.EMPTY_LIST; } - if (xpathExpression.indexOf("/") == -1) { + ArrayList r = new ArrayList<>(); + if (!xpathExpression.contains("/")) { NodeList nodeList = element.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { + int nn = nodeList.getLength(); + for (int i = 0; i < nn; i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(xpathExpression)) { - resultVector.add((Element) node); + r.add((Element) node); } } } else { XPath xpath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xpath.evaluate(xpathExpression, element, XPathConstants.NODESET); - - for (int i = 0; i < nodes.getLength(); i++) { - Node node = nodes.item(i); - resultVector.add((Element) node); - } + int nn = nodes.getLength(); + for (int i = 0; i < nn; i++) + r.add((Element) nodes.item(i)); } - return resultVector; + return r.isEmpty() ? + Collections.EMPTY_LIST : + r; } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/XMLWriter.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/XMLWriter.java index b6d51d1f25..3a448292b0 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/XMLWriter.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/XMLWriter.java @@ -38,7 +38,7 @@ public interface XMLWriter { * @param s a string of data to include verbatim in the XML stream */ - public void printRaw(String s) throws IOException; + void printRaw(String s); /** * Open a new namespace-qualified XML tag. @@ -47,7 +47,7 @@ public interface XMLWriter { * @param localName The name of the tag */ - public void openTag(String nsURI, String localName) throws IOException; + void openTag(String nsURI, String localName) throws IOException; /** * Open a new unqualified XML tag. This may also be used if you want @@ -56,7 +56,7 @@ public interface XMLWriter { * @param name The name of the tag. */ - public void openTag(String name) throws IOException; + void openTag(String name) throws IOException; /** * Add an attribute to an element. This will throw an exception if it's not @@ -67,7 +67,7 @@ public interface XMLWriter { * @param value The textual value of the attribute */ - public void attribute(String nsURI, String localName, String value) throws IOException; + void attribute(String nsURI, String localName, String value) throws IOException; /** * Add an un-qualified attribute to an element. This will throw an exception if it's not @@ -77,19 +77,19 @@ public interface XMLWriter { * @param value The textual value of the attribute */ - public void attribute(String qName, String value) throws IOException; + void attribute(String qName, String value) throws IOException; /** * Prints some textual content in an element. */ - public void print(String data) throws IOException; + void print(String data); /** * Prints some textual content, terminated with a newline character. */ - public void println(String data) throws IOException; + void println(String data); /** * Closes an element @@ -98,7 +98,7 @@ public interface XMLWriter { * @param qName The name of the tag */ - public void closeTag(String nsURI, String qName) throws IOException; + void closeTag(String nsURI, String qName) throws IOException; /** * Closes an un-qualified element. @@ -106,7 +106,7 @@ public interface XMLWriter { * @param name The tag name */ - public void closeTag(String name) throws IOException; + void closeTag(String name); /** * Hints that a namespace is going to be used in a sub-tree. Use this method @@ -121,7 +121,7 @@ public interface XMLWriter { * @param prefixHint A suggested prefix-string for this namespace. */ - public void declareNamespace(String nsURI, String prefixHint) throws IOException; + void declareNamespace(String nsURI, String prefixHint) throws IOException; /** * Close this XMLWriter, and it's underlying stream. @@ -129,5 +129,5 @@ public interface XMLWriter { * @since 1.4 */ - public void close() throws IOException; + void close(); } diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/TestAmbiguityCompoundSet.java b/biojava-core/src/test/java/org/biojava/nbio/core/TestAmbiguityCompoundSet.java index 56abb5d802..9ce712581a 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/TestAmbiguityCompoundSet.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/TestAmbiguityCompoundSet.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.core; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.DNASequence; import org.biojava.nbio.core.sequence.RNASequence; import org.biojava.nbio.core.sequence.compound.AmbiguityDNACompoundSet; diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleAlignedSequenceTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleAlignedSequenceTest.java index 8bbc64c182..aba01a2820 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleAlignedSequenceTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleAlignedSequenceTest.java @@ -49,32 +49,29 @@ public class SimpleAlignedSequenceTest { public void setup() throws CompoundNotFoundException { go = new ProteinSequence("ARND"); lo = new ProteinSequence("CEQGHILKM"); - global = new SimpleAlignedSequence(go, Arrays.asList(new Step[] { - Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.GAP})); - local = new SimpleAlignedSequence(lo, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND, - Step.COMPOUND}), 1, 3); - local2 = new SimpleAlignedSequence(go, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND}), 1, 0); - cs = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + global = new SimpleAlignedSequence<>(go, Arrays.asList(Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.GAP)); + local = new SimpleAlignedSequence<>(lo, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND, + Step.COMPOUND), 1, 3); + local2 = new SimpleAlignedSequence<>(go, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND), 1, 0); + cs = AminoAcidCompoundSet.aminoAcidCompoundSet; } @Test(expected=IllegalArgumentException.class) public void testSimpleAlignedSequenceLocal() { - new SimpleAlignedSequence(lo, Arrays.asList(new Step[] {Step.COMPOUND, - Step.COMPOUND, Step.GAP, Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND})); + new SimpleAlignedSequence<>(lo, Arrays.asList(Step.COMPOUND, + Step.COMPOUND, Step.GAP, Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND)); } @Test(expected=IllegalArgumentException.class) public void testSimpleAlignedSequenceLong() { - new SimpleAlignedSequence(go, Arrays.asList(new Step[] {Step.GAP, - Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP})); + new SimpleAlignedSequence<>(go, Arrays.asList(Step.GAP, + Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP)); } @Test(expected=IllegalArgumentException.class) public void testSimpleAlignedSequenceShort() { - new SimpleAlignedSequence(go, Arrays.asList(new Step[] {Step.GAP, - Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.GAP})); + new SimpleAlignedSequence<>(go, Arrays.asList(Step.GAP, + Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.GAP)); } @Test @@ -120,9 +117,9 @@ public void testGetAlignmentIndexAtOutOfBounds4() { @Test public void testGetEnd() { - assertEquals(global.getEnd().getPosition(), Integer.valueOf(6)); - assertEquals(local.getEnd().getPosition(), Integer.valueOf(8)); - assertEquals(local2.getEnd().getPosition(), Integer.valueOf(3)); + assertEquals(6, global.getEnd().getPosition()); + assertEquals(8, local.getEnd().getPosition()); + assertEquals(3, local2.getEnd().getPosition()); } @Test @@ -214,9 +211,9 @@ public void testGetSequenceIndexAtOutOfBounds4() { @Test public void testGetStart() { - assertEquals(global.getStart().getPosition(), Integer.valueOf(2)); - assertEquals(local.getStart().getPosition(), Integer.valueOf(1)); - assertEquals(local2.getStart().getPosition(), Integer.valueOf(1)); + assertEquals(2, global.getStart().getPosition()); + assertEquals(1, local.getStart().getPosition()); + assertEquals(1, local2.getStart().getPosition()); } @Test diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleProfileTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleProfileTest.java index cfd857ac29..60e58cd002 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleProfileTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleProfileTest.java @@ -52,20 +52,17 @@ public void setup() throws CompoundNotFoundException { target = new ProteinSequence("RDG"); query.setAccession(new AccessionID("Query")); target.setAccession(new AccessionID("Target")); - global = new SimpleProfile(query, target, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP}), 0, 0, Arrays.asList( - new Step[] {Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND}), 0, 0); - local = new SimpleProfile(query, target, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND}), 1, 0, Arrays.asList(new Step[] { Step.COMPOUND, - Step.GAP, Step.COMPOUND}), 0, 1); - single = new SimpleProfile(query); + global = new SimpleProfile<>(query, target, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP), 0, 0, Arrays.asList( + Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND), 0, 0); + local = new SimpleProfile<>(query, target, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND), 1, 0, Arrays.asList(Step.COMPOUND, + Step.GAP, Step.COMPOUND), 0, 1); + single = new SimpleProfile<>(query); } @Test(expected=IllegalArgumentException.class) public void testSimpleProfile() { - new SimpleProfile(query, target, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP}), 0, 0, Arrays.asList( - new Step[] {Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND}), 0, 0); + new SimpleProfile<>(query, target, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP), 0, 0, Arrays.asList( + Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND), 0, 0); } @Test @@ -264,9 +261,9 @@ public void testGetCompoundAtSIntOutOfBounds5() { @Test public void testGetCompoundSet() { - assertEquals(global.getCompoundSet(), AminoAcidCompoundSet.getAminoAcidCompoundSet()); - assertEquals(local.getCompoundSet(), AminoAcidCompoundSet.getAminoAcidCompoundSet()); - assertEquals(single.getCompoundSet(), AminoAcidCompoundSet.getAminoAcidCompoundSet()); + assertEquals(global.getCompoundSet(), AminoAcidCompoundSet.aminoAcidCompoundSet); + assertEquals(local.getCompoundSet(), AminoAcidCompoundSet.aminoAcidCompoundSet); + assertEquals(single.getCompoundSet(), AminoAcidCompoundSet.aminoAcidCompoundSet); } @Test @@ -316,7 +313,7 @@ public void testGetCompoundsAtOutOfBounds6() { @Test public void testGetIndexOf() { - AminoAcidCompoundSet cs = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet cs = AminoAcidCompoundSet.aminoAcidCompoundSet; assertEquals(global.getIndexOf(cs.getCompoundForString("A")), 1); assertEquals(global.getIndexOf(cs.getCompoundForString("R")), 2); assertEquals(global.getIndexOf(cs.getCompoundForString("N")), 3); @@ -384,7 +381,7 @@ public void testGetIndicesAtOutOfBounds6() { @Test public void testGetLastIndexOf() { - AminoAcidCompoundSet cs = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet cs = AminoAcidCompoundSet.aminoAcidCompoundSet; assertEquals(global.getLastIndexOf(cs.getCompoundForString("A")), 1); assertEquals(global.getLastIndexOf(cs.getCompoundForString("R")), 2); assertEquals(global.getLastIndexOf(cs.getCompoundForString("N")), 3); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleSequencePairTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleSequencePairTest.java index 2c9aedfa91..9cea8140bf 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleSequencePairTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleSequencePairTest.java @@ -44,12 +44,9 @@ public class SimpleSequencePairTest { public void setup() throws CompoundNotFoundException { query = new ProteinSequence("ARND"); target = new ProteinSequence("RDG"); - global = new SimpleSequencePair(query, target, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP}), Arrays.asList(new Step[] { - Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND})); - local = new SimpleSequencePair(query, target, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND}), 1, 0, Arrays.asList(new Step[] { Step.COMPOUND, - Step.GAP, Step.COMPOUND}), 0, 1); + global = new SimpleSequencePair<>(query, target, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP), Arrays.asList(Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND)); + local = new SimpleSequencePair<>(query, target, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND), 1, 0, Arrays.asList(Step.COMPOUND, + Step.GAP, Step.COMPOUND), 0, 1); } @Test diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/fasta/TestFASTAReader.java b/biojava-core/src/test/java/org/biojava/nbio/core/fasta/TestFASTAReader.java index 75992962d1..6f8263fd91 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/fasta/TestFASTAReader.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/fasta/TestFASTAReader.java @@ -20,12 +20,6 @@ */ package org.biojava.nbio.core.fasta; -import java.io.InputStream; -import java.util.LinkedHashMap; - -import static org.junit.Assert.* ; -import static org.hamcrest.CoreMatchers.* ; - import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; @@ -35,6 +29,12 @@ import org.biojava.nbio.core.sequence.io.util.ClasspathResource; import org.junit.Test; +import java.io.InputStream; +import java.util.LinkedHashMap; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.assertThat; + public class TestFASTAReader { @@ -42,10 +42,10 @@ private void testProcessAll(String path) throws Exception { ClasspathResource r = new ClasspathResource(path); FastaReader fastaReader = null ; try( InputStream inStream = r.getInputStream() ) { - fastaReader = new FastaReader( + fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap sequences = fastaReader.process(); assertThat(sequences,is(notNullValue())); assertThat(sequences.size(),is(1)); @@ -82,10 +82,10 @@ private void testProcess1(String path) throws Exception { ClasspathResource r = new ClasspathResource(path); FastaReader fastaReader = null ; try( InputStream inStream = r.getInputStream() ) { - fastaReader = new FastaReader( + fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap out1 = fastaReader.process(1); assertThat(out1,is(notNullValue())); assertThat(out1.size(),is(1)); @@ -124,10 +124,10 @@ private void testProcess2(String path) throws Exception { ClasspathResource r = new ClasspathResource(path); FastaReader fastaReader = null ; try( InputStream inStream = r.getInputStream() ) { - fastaReader = new FastaReader( + fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap out1 = fastaReader.process(1); assertThat(out1,is(notNullValue())); assertThat(out1.size(),is(1)); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/search/io/HspTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/search/io/HspTest.java index 0dcaae2c33..0da89818a2 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/search/io/HspTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/search/io/HspTest.java @@ -24,12 +24,9 @@ import org.biojava.nbio.core.search.io.blast.BlastHspBuilder; import org.biojava.nbio.core.sequence.DNASequence; import org.biojava.nbio.core.sequence.compound.NucleotideCompound; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.*; + +import static org.junit.Assert.assertEquals; /** * @author Paolo Pavan @@ -37,7 +34,7 @@ public class HspTest { - Hsp hspImpl = new BlastHspBuilder() + final Hsp hspImpl = new BlastHspBuilder() .setHspNum(1) .setHspBitScore(377.211) .setHspEvalue(8.04143e-093) @@ -55,7 +52,7 @@ public class HspTest { .setHspIdentityString("||||||||| |||||||||||||||||| ||||||||| |||||||||||||||||||||||| |||||||| ||||||||||||||||||||||| ||||||| |||||||||||||||||||||||||||||||||||| |||||||||||||||||||||||||||||||||| ||||||||| ||||||| |||||||||||||||||||||||| |||||") .createBlastHsp(); - Hsp uncompleteHsp = new BlastHspBuilder() + final Hsp uncompleteHsp = new BlastHspBuilder() .setPercentageIdentity(100.00/100) .setHspAlignLen(48) .setMismatchCount(0) diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/search/io/SearchIOTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/search/io/SearchIOTest.java index a49dae544a..3f5a344c43 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/search/io/SearchIOTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/search/io/SearchIOTest.java @@ -20,15 +20,13 @@ */ package org.biojava.nbio.core.search.io; +import org.biojava.nbio.core.search.io.blast.BlastXMLParser; +import org.junit.*; + import java.io.File; import java.net.URL; -import org.biojava.nbio.core.search.io.blast.BlastXMLParser; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.junit.Assert.*; + +import static org.junit.Assert.fail; /** * Designed by Paolo Pavan. diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/search/io/blast/BlastTabularParserTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/search/io/blast/BlastTabularParserTest.java index c8343b3060..6c4f94926f 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/search/io/blast/BlastTabularParserTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/search/io/blast/BlastTabularParserTest.java @@ -20,19 +20,17 @@ */ package org.biojava.nbio.core.search.io.blast; +import org.biojava.nbio.core.search.io.Hit; +import org.biojava.nbio.core.search.io.Hsp; +import org.biojava.nbio.core.search.io.Result; +import org.junit.*; + import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; -import org.biojava.nbio.core.search.io.Hit; -import org.biojava.nbio.core.search.io.Hsp; -import org.biojava.nbio.core.search.io.Result; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.junit.Assert.*; + +import static org.junit.Assert.assertEquals; /** * @@ -67,7 +65,7 @@ public void testGetFileExtensions() { System.out.println("getFileExtensions"); BlastTabularParser instance = new BlastTabularParser(); - List expResult = new ArrayList(); + List expResult = new ArrayList<>(); expResult.add("blasttabular"); expResult.add("blasttxt"); @@ -143,7 +141,7 @@ public void testCreateObjects() throws Exception { .setHspBitScore(2894) .createBlastHsp(); - List hsplist = new ArrayList(); + List hsplist = new ArrayList<>(); hsplist.add(hsp1Hit1Res1); hsplist.add(hsp1Hit1Res2); @@ -151,7 +149,7 @@ public void testCreateObjects() throws Exception { .setHitDef("CP000411") .setHsps(hsplist) .createBlastHit(); - List hitlist = new ArrayList(); + List hitlist = new ArrayList<>(); hitlist.add(hit1Res1); BlastResult res1 = new BlastResultBuilder() diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/search/io/blast/BlastXMLParserTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/search/io/blast/BlastXMLParserTest.java index 45de0dbd19..ba107fe34e 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/search/io/blast/BlastXMLParserTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/search/io/blast/BlastXMLParserTest.java @@ -20,20 +20,17 @@ */ package org.biojava.nbio.core.search.io.blast; +import org.biojava.nbio.core.search.io.Hit; +import org.biojava.nbio.core.search.io.Hsp; +import org.biojava.nbio.core.search.io.Result; +import org.junit.*; + import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; -import org.biojava.nbio.core.search.io.Hit; -import org.biojava.nbio.core.search.io.Hsp; -import org.biojava.nbio.core.search.io.Result; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; + import static org.junit.Assert.*; -import org.junit.Ignore; /** * @@ -120,7 +117,7 @@ public void testCreateObjects() throws Exception { .setHspHseq("TTAAATTGAGAGTTTGATCCTGGCTCAGGATGAACGCTGGTGGCGTGCCTAATACATGCAAGTCGTACGCTAGCCGCTGAATTGATCCTTCGGGTGAAGTGAGGCAATGACTAGAGTGGCGAACTGGTGAGTAACACGTAAGAAACCTGCCCTTTAGTGGGGGATAACATTTGGAAACAGATGCTAATACCGCGTAACAACAAATCACACATGTGATCTGTTTGAAAGGTCCTTTTGGATCGCTAGAGGATGGTCTTGCGGCGTATTAGCTTGTTGGTAGGGTAGAAGCCTACCAAGGCAATGATGCGTAGCCGAGTTGAGAGACTGGCCGGCCACATTGGGACTGAGACACTGCCCAAACTCCTACGGGAGGCTGCAGTAGGGAATTTTCCGCAATGCACGAAAGTGTGACGGAGCGACGCCGCGTGTGTGATGAAGGCTTTCGGGTCGTAAAGCACTGTTGTAAGGGAAGAATAACTGAATTCAGAGAAAGTTTTCAGCTTGACGGTACCTTACCAGAAAGGGATGGCTAAATACGTGCCAGCAGCCGCGGTAATACGTATGTCCCGAGCGTTATCCGGATTTATTGGGCGTAAAGCGAGCGCAGACGGTTTATTAAGTCTGATGTGAAATCCCGAGGCCCAACCTCGGAACTGCATTGGAAACTGATTTACTTGAGTGCGATAGAGGCAAGTGGAACTCCATGTGTAGCGGTGAAATGCGTAGATATGTGGAAGAACACCAGTGGCGAAAGCGGCTTGCTAGATCGTAACTGACGTTGAGGCTCGAAAGTATGGGTAGCAAACGGGATTAGATACCCCGGTAGTCCATACCGTAAACGATGGGTGCTAGTTGTTAAGAGGTTTCCGCCTCCTAGTGACGTAGCAAACGCATTAAGCACCCCGCCTGAGGAGTACGGCCGCAAGGCTAAAACTTAAAGGAATTGACGGGGACCCGCACAAGCGGTGGAGCATGTGGTTTAATTCGAAGATACGCGAAAAACCTTACCAGGTCTTGACATACCAATGATCGCTTTTGTAATGAAAGCTTTTCTTCGGAACATTGGATACAGGTGGTGCATGGTCGTCGTCAGCTCGTGTCGTGAGATGTTGGGTTAAGTCCCGCAACGAGCGCAACCCTTGTTATTAGTTGCCAGCATTTAGTTGGGCACTCTAATGAGACTGCCGGTGATAAACCGGAGGAAGGTGGGGACGACGTCAGATCATCATGCCCCTTATGACCTGGGCAACACACGTGCTACAATGGGAAGTACAACGAGTCGCAAACCGGCGACGGTAAGCTAATCTCTTAAAACTTCTCTCAGTTCGGACTGGAGTCTGCAACTCGACTCCACGAAGGCGGAATCGCTAGTAATCGCGAATCAGCATGTCGCGGTGAATACGTTCCCGGGTCTTGTACACACCGCCCGTCAAATCATGGGAGTCGGAAGTACCCAAAGTCGCTTGGCTAACTTTTAGAGGCCGGTGCCTAAGGTAAAATCGATGACTGGGATTAAGTCGTAACAAGGTAGCCGTAGGAGAACCTGCGGCTGGATCACCTCCTTTCT") .setHspIdentityString("|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||") .createBlastHsp(); - List hsplist = new ArrayList(); + List hsplist = new ArrayList<>(); hsplist.add(hsp1hit1res1); hsplist.add(hsp1hit1res1); @@ -133,7 +130,7 @@ public void testCreateObjects() throws Exception { .setHsps(hsplist) .createBlastHit(); - List hitlist = new ArrayList(); + List hitlist = new ArrayList<>(); hitlist.add(hit1res1); BlastResult res1 = new BlastResultBuilder() @@ -200,7 +197,7 @@ public void testGetFileExtensions() { * Test of storeObjects method, of class BlastXMLParser. */ @Test - public void testStoreObjects() throws Exception { + public void testStoreObjects() { // not implemented yet } } diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/DNATest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/DNATest.java index f112284740..e2190ce7db 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/DNATest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/DNATest.java @@ -43,8 +43,8 @@ public class DNATest { - private DNACompoundSet set = new DNACompoundSet(); - private AmbiguityDNACompoundSet ambiguity = new AmbiguityDNACompoundSet(); + private final DNACompoundSet set = new DNACompoundSet(); + private final AmbiguityDNACompoundSet ambiguity = new AmbiguityDNACompoundSet(); @Test public void reverseComplement() throws CompoundNotFoundException { @@ -54,17 +54,17 @@ public void reverseComplement() throws CompoundNotFoundException { @Test public void complement() throws CompoundNotFoundException { - String s = new ComplementSequenceView(getSeq()).getSequenceAsString(); + String s = new ComplementSequenceView<>(getSeq()).getSequenceAsString(); assertThat("Complemented sequence not as expected", s, is("TACG")); } @Test public void reverse() throws CompoundNotFoundException { - SequenceView r = new ReversedSequenceView(getSeq()); + SequenceView r = new ReversedSequenceView<>(getSeq()); assertThat("Reversed sequence not as expected", r.getSequenceAsString(), is("CGTA")); assertThat("Base at 2 not right", r.getCompoundAt(2).toString(), is("G")); - List actual = new ArrayList(); + List actual = new ArrayList<>(); List expected = Arrays.asList("C", "G", "T", "A"); for (NucleotideCompound c : r) { actual.add(c.toString()); @@ -165,11 +165,11 @@ public void twoBit() throws CompoundNotFoundException { String expected = "ATGCAACTGA"; DNASequence seq = getSeq(expected); SequenceReader twoBitFromSeq = - new TwoBitSequenceReader(seq); + new TwoBitSequenceReader<>(seq); //being cheeky here & getting compound set from seq SequenceReader twoBitFromString = - new TwoBitSequenceReader(expected, seq.getCompoundSet()); + new TwoBitSequenceReader<>(expected, seq.getCompoundSet()); assertThat("TwoBit from Sequence not as expected", twoBitFromSeq.getSequenceAsString(), is(expected)); assertThat("TwoBit from String not as expected", twoBitFromString.getSequenceAsString(), is(expected)); @@ -180,11 +180,11 @@ public void fourBit() throws CompoundNotFoundException { String expected = "ATGCAACTGA"; DNASequence seq = getSeq(expected); SequenceReader bitFromSeq = - new FourBitSequenceReader(seq); + new FourBitSequenceReader<>(seq); //being cheeky here & getting compound set from seq SequenceReader bitFromString = - new FourBitSequenceReader(expected, seq.getCompoundSet()); + new FourBitSequenceReader<>(expected, seq.getCompoundSet()); assertThat("FourBit from Sequence not as expected", bitFromSeq.getSequenceAsString(), is(expected)); assertThat("FourBit from String not as expected", bitFromString.getSequenceAsString(), is(expected)); @@ -193,7 +193,7 @@ public void fourBit() throws CompoundNotFoundException { @Test(expected = IllegalStateException.class) public void badTwoBit() throws CompoundNotFoundException { DNASequence seq = getSeq(); - new TwoBitSequenceReader("ATNGC", seq.getCompoundSet()); + new TwoBitSequenceReader<>("ATNGC", seq.getCompoundSet()); } @Test @@ -203,7 +203,7 @@ public void singleCompoundSequence() { NucleotideCompound n = cs.getCompoundForString("N"); int length = 1000; - ProxySequenceReader sr = new SingleCompoundSequenceReader(n, cs, length); + ProxySequenceReader sr = new SingleCompoundSequenceReader<>(n, cs, length); DNASequence seq = new DNASequence(sr); int intCount = 0; @@ -268,8 +268,8 @@ public void sequenceEquality() throws CompoundNotFoundException { assertTrue("Asserting sequences are identical ignoring case & case different", SequenceMixin.sequenceEqualityIgnoreCase(d, getSeq("aTgC"))); assertFalse("Sequence lengths differ", SequenceMixin.sequenceEquality(d, getSeq("ATG"))); - DNASequence bsr = new DNASequence(new TwoBitSequenceReader("ATGC", DNACompoundSet.getDNACompoundSet())); - DNASequence bsrCI = new DNASequence(new TwoBitSequenceReader("ATGc", DNACompoundSet.getDNACompoundSet())); + DNASequence bsr = new DNASequence(new TwoBitSequenceReader<>("ATGC", DNACompoundSet.getDNACompoundSet())); + DNASequence bsrCI = new DNASequence(new TwoBitSequenceReader<>("ATGc", DNACompoundSet.getDNACompoundSet())); assertTrue("Asserting sequences are identical; backing stores differ", SequenceMixin.sequenceEquality(d, bsr)); assertTrue("Asserting sequences are identical ignoring case; backing stores differ", SequenceMixin.sequenceEqualityIgnoreCase(d, bsrCI)); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/JoiningSequenceReaderTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/JoiningSequenceReaderTest.java index 899247ebc6..353daaed51 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/JoiningSequenceReaderTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/JoiningSequenceReaderTest.java @@ -34,13 +34,13 @@ public class JoiningSequenceReaderTest { @Test public void canScan() throws CompoundNotFoundException { JoiningSequenceReader seq = - new JoiningSequenceReader( - new DNASequence("AAAA"), - new DNASequence("GGG"), - new JoiningSequenceReader(new DNASequence("A"), new DNASequence("C")), - new DNASequence("TT"), - new DNASequence("C") - ); + new JoiningSequenceReader<>( + new DNASequence("AAAA"), + new DNASequence("GGG"), + new JoiningSequenceReader<>(new DNASequence("A"), new DNASequence("C")), + new DNASequence("TT"), + new DNASequence("C") + ); String expected = "AAAAGGGACTTC"; @@ -59,12 +59,12 @@ public void canScan() throws CompoundNotFoundException { @Test public void empty() throws CompoundNotFoundException { JoiningSequenceReader seq = - new JoiningSequenceReader( - new DNASequence(""), - new DNASequence(""), - new DNASequence("A"), - new DNASequence("") - ); + new JoiningSequenceReader<>( + new DNASequence(""), + new DNASequence(""), + new DNASequence("A"), + new DNASequence("") + ); assertEquals("Testing empty sequences", "A", seq.getSequenceAsString()); } } diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/MultipleSequenceAlignmentTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/MultipleSequenceAlignmentTest.java index 20acfc2cd2..145e226ff4 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/MultipleSequenceAlignmentTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/MultipleSequenceAlignmentTest.java @@ -43,11 +43,11 @@ public class MultipleSequenceAlignmentTest { @Before public void setup() throws CompoundNotFoundException { - msaProteins = new MultipleSequenceAlignment(); + msaProteins = new MultipleSequenceAlignment<>(); for (int i = 0; i < 8; i++) { msaProteins.addAlignedSequence(new ProteinSequence("ARNDCEQGHILKMFPSTWYVBZJX")); } - msaDNA = new MultipleSequenceAlignment(); + msaDNA = new MultipleSequenceAlignment<>(); for (int i = 0; i < 7; i++) { msaDNA.addAlignedSequence(new DNASequence("ATCGATCGATCGATCG")); } @@ -55,14 +55,14 @@ public void setup() throws CompoundNotFoundException { @Test public void testGetCompoundsAt() { - AminoAcidCompound aminoAcid = AminoAcidCompoundSet.getAminoAcidCompoundSet().getCompoundForString("N"); - List colProteins = new ArrayList(); + AminoAcidCompound aminoAcid = AminoAcidCompoundSet.aminoAcidCompoundSet.getCompoundForString("N"); + List colProteins = new ArrayList<>(); for (int i = 0; i < 8; i++) { colProteins.add(aminoAcid); } assertEquals(msaProteins.getCompoundsAt(3), colProteins); NucleotideCompound nucleotide = DNACompoundSet.getDNACompoundSet().getCompoundForString("C"); - List colDNA = new ArrayList(); + List colDNA = new ArrayList<>(); for (int i = 0; i < 7; i++) { colDNA.add(nucleotide); } diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/TestSequenceEquals.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/TestSequenceEquals.java index 5fe57374d1..d3bac9e212 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/TestSequenceEquals.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/TestSequenceEquals.java @@ -22,7 +22,8 @@ import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; /** * Created by yana on 3/27/17. @@ -39,23 +40,23 @@ public void testSameCompounds() throws Exception{ ProteinSequence seq2 = new ProteinSequence("ARNDCEQGHILKMFPSTWYVBZJXARNDCEQGHILKMFPSTWYVBZJX"); - assertFalse(seq1.equals(seq2)); + assertNotEquals(seq1, seq2); - assertTrue(seq1.equals(seq1)); + assertEquals(seq1, seq1); - assertTrue(seq2.equals(seq2)); + assertEquals(seq2, seq2); ProteinSequence seq3 = new ProteinSequence("ARNDCEQGHILKMFPSTWYVBZJX"); - assertTrue(seq3.equals(seq1)); + assertEquals(seq3, seq1); - assertFalse(seq2.equals(seq3)); + assertNotEquals(seq2, seq3); DNASequence dnaSeq = new DNASequence("ATGGCGGCGCTGAGCGGT"); - assertFalse(seq1.equals(dnaSeq)); + assertNotEquals(seq1, dnaSeq); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/TranslationTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/TranslationTest.java index 00c520d586..a4abf15e7f 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/TranslationTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/TranslationTest.java @@ -51,9 +51,9 @@ public class TranslationTest { private final static Logger logger = LoggerFactory.getLogger(TranslationTest.class); - private static DNACompoundSet dnaCs = DNACompoundSet.getDNACompoundSet(); - private static AminoAcidCompoundSet aaCs = AminoAcidCompoundSet.getAminoAcidCompoundSet(); - private static DNASequence brca2Dna; + private static final DNACompoundSet dnaCs = DNACompoundSet.getDNACompoundSet(); + private static final AminoAcidCompoundSet aaCs = AminoAcidCompoundSet.aminoAcidCompoundSet; + private static DNASequence brca2Dna; private static Sequence brca2Pep; private static Sequence volvoxDna; private static Sequence volvoxPep; @@ -70,20 +70,20 @@ public static void parseSequences() { "org/biojava/nbio/core/sequence/volvox-peptide.fasta").getInputStream(); try { - FastaReader dnaReader = new FastaReader(cdsIs, - new GenericFastaHeaderParser(), new DNASequenceCreator(dnaCs)); + FastaReader dnaReader = new FastaReader<>(cdsIs, + new GenericFastaHeaderParser<>(), new DNASequenceCreator(dnaCs)); brca2Dna = dnaReader.process().values().iterator().next(); - FastaReader pReader = new FastaReader( - pepIs, new GenericFastaHeaderParser(), new ProteinSequenceCreator( - aaCs)); + FastaReader pReader = new FastaReader<>( + pepIs, new GenericFastaHeaderParser<>(), new ProteinSequenceCreator( + aaCs)); brca2Pep = pReader.process().values().iterator().next(); - FastaReader volvoxDnaReader = new FastaReader(volDnaIs, - new GenericFastaHeaderParser(), new DNASequenceCreator(dnaCs)); + FastaReader volvoxDnaReader = new FastaReader<>(volDnaIs, + new GenericFastaHeaderParser<>(), new DNASequenceCreator(dnaCs)); volvoxDna = volvoxDnaReader.process().values().iterator().next(); - FastaReader volvoxPepReader = new FastaReader( - volPepIs, new GenericFastaHeaderParser(), new ProteinSequenceCreator( - aaCs)); + FastaReader volvoxPepReader = new FastaReader<>( + volPepIs, new GenericFastaHeaderParser<>(), new ProteinSequenceCreator( + aaCs)); volvoxPep = volvoxPepReader.process().values().iterator().next(); } catch (IOException e) { diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/compound/AmbiguityDNACompoundTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/compound/AmbiguityDNACompoundTest.java index ce0cee1691..bcc3e09c2a 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/compound/AmbiguityDNACompoundTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/compound/AmbiguityDNACompoundTest.java @@ -29,7 +29,7 @@ public class AmbiguityDNACompoundTest { - private AmbiguityDNACompoundSet set = AmbiguityDNACompoundSet.getDNACompoundSet(); + private final AmbiguityDNACompoundSet set = AmbiguityDNACompoundSet.getDNACompoundSet(); @Test public void testAmbiguity() { @@ -44,7 +44,7 @@ public void testBasicAmbiguity() { } private NucleotideCompound[] getCompounds(String... compoundStrings) { - List c = new ArrayList(); + List c = new ArrayList<>(); for(String s: compoundStrings) { c.add(set.getCompoundForString(s)); } diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/ABITracerTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/ABITracerTest.java index 89aef23cbb..b27907b79b 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/ABITracerTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/ABITracerTest.java @@ -21,10 +21,11 @@ package org.biojava.nbio.core.sequence.io; +import org.junit.*; + import java.awt.image.BufferedImage; import java.io.File; import java.net.URL; -import org.junit.*; /** * Test file 3730.ab1 is from https://github.com/biopython/biopython/blob/master/Tests/Abi/3730.ab1 @@ -32,19 +33,19 @@ */ public class ABITracerTest { - private String sequence = "GGGCGAGCKYYAYATTTTGGCAAGAATTGAGCTCTATGGCCACAACCATGGTGAGCAAGGGCGAGGAGGATAACATGGCCATCATCAAGGAGTTCATGCGCTTCAAGGTGCACATGGAGGGCTCCGTGAACGGCCACGAGTTCGAGATCGAGGGCGAGGGCGAGGGCCGCCCCTACGAGGGCACCCAGACCGCCAAGCTGAAGGTGACCAAGGGTGGCCCCCTGCCCTTCGCCTGGGACATCCTGTCCCCTCAGTTCATGTACGGCTCCAAGGCCTACGTGAAGCACCCCGCCGACATCCCCGACTACTTGAAGCTGTCCTTCCCCGAGGGCTTCAAGTGGGAGCGCGTGATGAACTTCGAGGACGGCGGCGTGGTGACCGTGACCCAGGACTCCTCCCTGCAGGACGGCGAGTTCATCTACAAGGTGAAGCTGCGCGGCACCAACTTCCCCTCCGACGGCCCCGTAATGCAGAAGAAGACCATGGGCTGGGAGGCCTCCTCCGAGCGGATGTACCCCGAGGACGGCGCCCTGAAGGGCGAGATCAAGCAGAGGCTGAAGCTGAAGGACGGCGGCCACTACGACGCTGAGGTCAAGACCACCTACAAGGCCAAGAAGCCCGTGCAGCTGCCCGGCGCCTACAACGTCAACATCAAGTTGGACATCACCTCCCACAACGAGGACTACACCATCGTGGAACAGTACGAACGCGCCGAGGGCCGCCACTCCACCGGCGGCATGGACGAGCTGTACAAGGGCGGCAGCGGCATGGTGAGCAAGGGCGAGGAGCTGTTCACCGGGGTGGTGCCCATCCTGGTCGAGCTGGACGGCGACGTAAACGGCCACAAGTTCAGCGTGTCCGGCGAGGGCGAGGGCGATGCCACCTACGGCAAGCTGACCCTGAAGTTCATCTGCACCACCGGCAAGCTGCCCGTGCCCTGGCCCACCCTCGTGACCACCCTGACCTACGGCGTGCAGTGCTTCAGCCGCTACCCCGACCACATGAAGCAGCACGACTTCTTCAAGTCCGCCATGCCCGAAGGCTACGTCCAGGAGCGCACCATCTTCTTCAAGGACGACGGCAACTACAARACCCGCGCCGAGGTGAARTTCGAGGGCGACACCCTGGTGAACCGCATCGAGCTGAAAGGGGCAYCGCACCTTTC"; - private int[] qual = {20, 3, 4, 4, 4, 6, 4, 4, 0, 0, 0, 6, 0, 10, 20, 26, 22, 17, 21, 31, 29, 32, 28, 18, 23, 17, 19, 35, 36, 50, 39, 50, 50, 50, 50, 50, 25, 35, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 35, 39, 33, 20, 35, 31, 50, 50, 50, 50, 50, 50, 50, 50, 50, 31, 50, 35, 31, 23, 28, 31, 21, 43, 39, 35, 24, 30, 26, 35, 31, 50, 50, 50, 50, 50, 50, 50, 50, 50, 39, 31, 24, 39, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 31, 31, 43, 43, 50, 50, 50, 50, 50, 31, 31, 31, 31, 50, 50, 50, 50, 50, 50, 50, 50, 31, 31, 35, 50, 50, 50, 50, 31, 36, 55, 55, 55, 55, 36, 55, 55, 55, 55, 55, 36, 55, 55, 55, 55, 55, 36, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 40, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 36, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 40, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 43, 43, 50, 43, 43, 50, 43, 43, 50, 43, 43, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 43, 43, 50, 43, 43, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 28, 28, 35, 28, 28, 35, 28, 28, 35, 28, 28, 35, 28, 28, 35, 28, 21, 28, 35, 28, 28, 35, 35, 35, 35, 35, 37, 38, 21, 28, 35, 28, 28, 35, 35, 35, 35, 35, 35, 35, 36, 36, 21, 39, 35, 35, 35, 39, 35, 37, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 28, 28, 35, 35, 28, 28, 35, 35, 35, 36, 36, 22, 39, 35, 35, 35, 35, 35, 35, 37, 38, 28, 35, 21, 36, 36, 37, 35, 35, 20, 39, 39, 35, 35, 35, 35, 37, 38, 28, 35, 37, 34, 35, 24, 24, 27, 25, 20, 24, 37, 35, 27, 21, 20, 21, 27, 17, 20, 24, 32, 26, 20, 12, 20, 10, 20, 24, 25, 23, 20, 32, 24, 24, 23, 20, 24, 23, 18, 34, 34, 34, 22, 26, 24, 24, 18, 22, 22, 23, 25, 20, 12, 20, 24, 23, 24, 23, 22, 20, 20, 0, 20, 24, 23, 20, 8, 10, 4, 20, 20, 3, 7, 19, 20, 4, 4, 7, 7, 0, 7, 11, 18, 8, 3, 23, 23, 20, 11, 4, 20, 18, 12, 20, 20, 20, 4, 20, 4, 2, 3, 21, 21, 21, 21, 10, 15, 14, 15, 19, 2, 4, 3, 6, 11, 3, 4, 6, 21, 16, 20, 11, 1, 4, 12, 0, 15, 8, 1, 3, 3, 12, 1, 11, 20, 4}; - private int[] base = {2, 13, 38, 51, 67, 78, 92, 118, 138, 162, 181, 191, 210, 222, 239, 253, 266, 280, 288, 304, 317, 333, 347, 359, 375, 386, 394, 406, 418, 433, 444, 457, 472, 482, 496, 506, 519, 529, 544, 557, 569, 579, 590, 601, 614, 626, 638, 649, 663, 673, 686, 706, 715, 731, 740, 753, 765, 777, 787, 799, 813, 826, 838, 854, 863, 876, 892, 901, 913, 929, 937, 948, 960, 970, 981, 993, 1004, 1017, 1034, 1045, 1056, 1068, 1080, 1091, 1103, 1115, 1126, 1138, 1148, 1160, 1177, 1187, 1199, 1211, 1222, 1232, 1243, 1254, 1268, 1279, 1294, 1307, 1319, 1330, 1341, 1352, 1362, 1374, 1388, 1398, 1411, 1422, 1433, 1444, 1456, 1466, 1479, 1497, 1506, 1519, 1531, 1543, 1556, 1567, 1578, 1589, 1604, 1614, 1630, 1641, 1651, 1662, 1675, 1688, 1700, 1711, 1721, 1732, 1748, 1758, 1772, 1784, 1795, 1806, 1820, 1830, 1844, 1855, 1866, 1877, 1892, 1902, 1914, 1926, 1939, 1950, 1965, 1974, 1986, 1999, 2011, 2023, 2037, 2047, 2059, 2072, 2084, 2096, 2107, 2120, 2132, 2144, 2156, 2169, 2180, 2191, 2202, 2217, 2227, 2239, 2251, 2264, 2275, 2286, 2297, 2309, 2321, 2332, 2347, 2358, 2369, 2381, 2394, 2406, 2417, 2429, 2439, 2452, 2465, 2476, 2490, 2501, 2512, 2524, 2536, 2546, 2560, 2570, 2581, 2593, 2605, 2616, 2628, 2640, 2653, 2664, 2676, 2688, 2700, 2712, 2723, 2735, 2748, 2759, 2772, 2784, 2795, 2808, 2820, 2831, 2842, 2854, 2866, 2878, 2888, 2901, 2913, 2927, 2936, 2947, 2958, 2970, 2982, 2994, 3005, 3019, 3030, 3041, 3053, 3064, 3077, 3088, 3099, 3110, 3123, 3135, 3146, 3157, 3168, 3179, 3192, 3203, 3214, 3226, 3238, 3251, 3263, 3275, 3286, 3297, 3308, 3320, 3331, 3344, 3356, 3368, 3380, 3391, 3402, 3415, 3426, 3440, 3451, 3462, 3474, 3485, 3496, 3508, 3520, 3532, 3543, 3556, 3569, 3580, 3593, 3604, 3615, 3626, 3638, 3650, 3661, 3673, 3684, 3698, 3709, 3721, 3732, 3744, 3756, 3767, 3779, 3792, 3803, 3814, 3827, 3838, 3850, 3862, 3873, 3885, 3897, 3909, 3920, 3932, 3943, 3955, 3966, 3980, 3990, 4002, 4014, 4026, 4038, 4050, 4061, 4072, 4083, 4095, 4107, 4119, 4131, 4143, 4156, 4167, 4179, 4191, 4203, 4215, 4227, 4238, 4252, 4262, 4274, 4287, 4298, 4310, 4321, 4333, 4345, 4356, 4370, 4381, 4393, 4406, 4417, 4428, 4440, 4453, 4464, 4477, 4489, 4500, 4513, 4524, 4536, 4548, 4560, 4573, 4583, 4595, 4607, 4620, 4631, 4645, 4655, 4667, 4679, 4690, 4702, 4714, 4728, 4739, 4750, 4762, 4774, 4786, 4798, 4810, 4821, 4833, 4845, 4857, 4869, 4880, 4892, 4905, 4916, 4927, 4940, 4952, 4963, 4977, 4988, 5000, 5012, 5023, 5034, 5045, 5057, 5069, 5081, 5093, 5104, 5115, 5127, 5139, 5151, 5163, 5176, 5188, 5199, 5211, 5223, 5235, 5247, 5259, 5272, 5283, 5296, 5308, 5320, 5331, 5343, 5354, 5366, 5378, 5390, 5402, 5414, 5426, 5438, 5450, 5462, 5474, 5486, 5497, 5510, 5521, 5532, 5544, 5557, 5569, 5581, 5592, 5604, 5617, 5629, 5641, 5652, 5663, 5676, 5687, 5699, 5712, 5724, 5735, 5748, 5760, 5771, 5784, 5794, 5806, 5817, 5829, 5841, 5853, 5866, 5879, 5891, 5903, 5916, 5928, 5941, 5952, 5964, 5976, 5988, 6000, 6012, 6024, 6036, 6048, 6060, 6072, 6085, 6096, 6109, 6121, 6133, 6146, 6157, 6168, 6180, 6192, 6203, 6215, 6227, 6239, 6251, 6265, 6276, 6289, 6302, 6313, 6325, 6337, 6349, 6361, 6374, 6386, 6398, 6410, 6422, 6436, 6448, 6459, 6471, 6483, 6495, 6507, 6520, 6532, 6545, 6555, 6567, 6579, 6591, 6603, 6615, 6627, 6640, 6652, 6664, 6676, 6688, 6700, 6713, 6726, 6738, 6749, 6761, 6774, 6786, 6799, 6811, 6823, 6835, 6848, 6859, 6871, 6883, 6895, 6907, 6920, 6933, 6945, 6956, 6968, 6980, 6992, 7005, 7016, 7030, 7042, 7053, 7066, 7079, 7091, 7104, 7115, 7128, 7140, 7152, 7163, 7175, 7187, 7200, 7212, 7224, 7235, 7248, 7260, 7272, 7285, 7297, 7309, 7321, 7333, 7345, 7358, 7370, 7382, 7394, 7406, 7419, 7431, 7443, 7455, 7468, 7480, 7492, 7505, 7517, 7530, 7542, 7554, 7566, 7578, 7591, 7603, 7615, 7628, 7640, 7653, 7666, 7677, 7690, 7702, 7714, 7727, 7738, 7750, 7762, 7775, 7786, 7799, 7812, 7823, 7836, 7848, 7859, 7871, 7884, 7896, 7909, 7921, 7933, 7946, 7958, 7971, 7984, 7996, 8007, 8019, 8032, 8044, 8056, 8069, 8081, 8094, 8107, 8119, 8131, 8143, 8155, 8167, 8179, 8192, 8205, 8218, 8230, 8244, 8255, 8267, 8279, 8291, 8303, 8315, 8328, 8340, 8353, 8366, 8378, 8392, 8404, 8417, 8431, 8443, 8455, 8467, 8479, 8492, 8504, 8516, 8529, 8543, 8555, 8567, 8580, 8593, 8606, 8619, 8632, 8644, 8658, 8670, 8683, 8695, 8708, 8721, 8733, 8746, 8759, 8771, 8783, 8795, 8808, 8821, 8833, 8845, 8858, 8871, 8885, 8898, 8910, 8923, 8936, 8949, 8960, 8973, 8986, 9000, 9012, 9025, 9038, 9051, 9064, 9076, 9089, 9102, 9114, 9126, 9139, 9151, 9164, 9177, 9191, 9204, 9217, 9230, 9243, 9255, 9268, 9281, 9294, 9307, 9320, 9333, 9345, 9358, 9371, 9384, 9398, 9412, 9424, 9437, 9450, 9462, 9475, 9488, 9501, 9514, 9528, 9542, 9554, 9567, 9581, 9593, 9606, 9619, 9632, 9645, 9658, 9671, 9682, 9695, 9708, 9721, 9735, 9749, 9762, 9776, 9789, 9802, 9815, 9828, 9842, 9855, 9867, 9880, 9893, 9906, 9920, 9933, 9947, 9960, 9974, 9987, 10000, 10014, 10027, 10040, 10054, 10067, 10081, 10095, 10107, 10120, 10134, 10148, 10161, 10175, 10188, 10201, 10214, 10228, 10241, 10254, 10267, 10280, 10294, 10309, 10322, 10335, 10348, 10362, 10374, 10387, 10401, 10415, 10428, 10441, 10455, 10469, 10482, 10497, 10510, 10523, 10537, 10551, 10565, 10579, 10593, 10606, 10621, 10634, 10647, 10661, 10675, 10689, 10704, 10719, 10732, 10746, 10760, 10774, 10788, 10802, 10815, 10829, 10843, 10856, 10871, 10884, 10898, 10913, 10927, 10940, 10955, 10970, 10984, 10999, 11013, 11027, 11042, 11056, 11071, 11086, 11100, 11114, 11128, 11142, 11158, 11171, 11186, 11200, 11213, 11228, 11241, 11255, 11270, 11284, 11299, 11314, 11328, 11342, 11356, 11370, 11385, 11399, 11413, 11429, 11445, 11460, 11474, 11489, 11503, 11518, 11533, 11549, 11563, 11577, 11592, 11607, 11621, 11637, 11651, 11665, 11680, 11694, 11708, 11725, 11740, 11754, 11768, 11784, 11798, 11813, 11828, 11843, 11858, 11874, 11888, 11904, 11920, 11933, 11948, 11964, 11979, 11993, 12009, 12024, 12041, 12058, 12071, 12087, 12102, 12117, 12132, 12148, 12165, 12179, 12195, 12210, 12226, 12241, 12256, 12273, 12288, 12304, 12320, 12335, 12350, 12365, 12382, 12398, 12414, 12430, 12446, 12462, 12478, 12495, 12511, 12525, 12541, 12556, 12575, 12591, 12605, 12622, 12638, 12653, 12671, 12686, 12705, 12721, 12739, 12756, 12772, 12788, 12806, 12822, 12839, 12855, 12873, 12890, 12908, 12923, 12941, 12960, 12975, 12992, 13009, 13024, 13040, 13059, 13076, 13092, 13109, 13128, 13145, 13161, 13179, 13194, 13216, 13233, 13249, 13266, 13287, 13303, 13322, 13337, 13357, 13375, 13392, 13410, 13424, 13446, 13465, 13480, 13499, 13517, 13533, 13559, 13575, 13595, 13612, 13632, 13650, 13670, 13687, 13706, 13726, 13744, 13765, 13783, 13803, 13822, 13841, 13860, 13879, 13897, 13917, 13936, 13960, 13979, 13996, 14019, 14040, 14057, 14077, 14102, 14122, 14141, 14163, 14184, 14202, 14225, 14244, 14265, 14287, 14312, 14336, 14356, 14375, 14393, 14420, 14438, 14465, 14483, 14500, 14536, 14555, 14575, 14604, 14619, 14648, 14668, 14691, 14725, 14748, 14770, 14788, 14818, 14840, 14862, 14888, 14921, 14939, 14969, 14996, 15022, 15051, 15075, 15098, 15130, 15149, 15167, 15218, 15237, 15276, 15297, 15333, 15356, 15379, 15418, 15447, 15481, 15508, 15530, 15574, 15599, 15643, 15680, 15697, 15743, 15759, 15775, 15813, 15845, 15877, 15911, 15931, 15968, 16014, 16049, 16077, 16088, 16138, 16149, 16185, 16200, 16241, 16280, 16296}; + private final String sequence = "GGGCGAGCKYYAYATTTTGGCAAGAATTGAGCTCTATGGCCACAACCATGGTGAGCAAGGGCGAGGAGGATAACATGGCCATCATCAAGGAGTTCATGCGCTTCAAGGTGCACATGGAGGGCTCCGTGAACGGCCACGAGTTCGAGATCGAGGGCGAGGGCGAGGGCCGCCCCTACGAGGGCACCCAGACCGCCAAGCTGAAGGTGACCAAGGGTGGCCCCCTGCCCTTCGCCTGGGACATCCTGTCCCCTCAGTTCATGTACGGCTCCAAGGCCTACGTGAAGCACCCCGCCGACATCCCCGACTACTTGAAGCTGTCCTTCCCCGAGGGCTTCAAGTGGGAGCGCGTGATGAACTTCGAGGACGGCGGCGTGGTGACCGTGACCCAGGACTCCTCCCTGCAGGACGGCGAGTTCATCTACAAGGTGAAGCTGCGCGGCACCAACTTCCCCTCCGACGGCCCCGTAATGCAGAAGAAGACCATGGGCTGGGAGGCCTCCTCCGAGCGGATGTACCCCGAGGACGGCGCCCTGAAGGGCGAGATCAAGCAGAGGCTGAAGCTGAAGGACGGCGGCCACTACGACGCTGAGGTCAAGACCACCTACAAGGCCAAGAAGCCCGTGCAGCTGCCCGGCGCCTACAACGTCAACATCAAGTTGGACATCACCTCCCACAACGAGGACTACACCATCGTGGAACAGTACGAACGCGCCGAGGGCCGCCACTCCACCGGCGGCATGGACGAGCTGTACAAGGGCGGCAGCGGCATGGTGAGCAAGGGCGAGGAGCTGTTCACCGGGGTGGTGCCCATCCTGGTCGAGCTGGACGGCGACGTAAACGGCCACAAGTTCAGCGTGTCCGGCGAGGGCGAGGGCGATGCCACCTACGGCAAGCTGACCCTGAAGTTCATCTGCACCACCGGCAAGCTGCCCGTGCCCTGGCCCACCCTCGTGACCACCCTGACCTACGGCGTGCAGTGCTTCAGCCGCTACCCCGACCACATGAAGCAGCACGACTTCTTCAAGTCCGCCATGCCCGAAGGCTACGTCCAGGAGCGCACCATCTTCTTCAAGGACGACGGCAACTACAARACCCGCGCCGAGGTGAARTTCGAGGGCGACACCCTGGTGAACCGCATCGAGCTGAAAGGGGCAYCGCACCTTTC"; + private final int[] qual = {20, 3, 4, 4, 4, 6, 4, 4, 0, 0, 0, 6, 0, 10, 20, 26, 22, 17, 21, 31, 29, 32, 28, 18, 23, 17, 19, 35, 36, 50, 39, 50, 50, 50, 50, 50, 25, 35, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 35, 39, 33, 20, 35, 31, 50, 50, 50, 50, 50, 50, 50, 50, 50, 31, 50, 35, 31, 23, 28, 31, 21, 43, 39, 35, 24, 30, 26, 35, 31, 50, 50, 50, 50, 50, 50, 50, 50, 50, 39, 31, 24, 39, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 31, 31, 43, 43, 50, 50, 50, 50, 50, 31, 31, 31, 31, 50, 50, 50, 50, 50, 50, 50, 50, 31, 31, 35, 50, 50, 50, 50, 31, 36, 55, 55, 55, 55, 36, 55, 55, 55, 55, 55, 36, 55, 55, 55, 55, 55, 36, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 40, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 36, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 40, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 43, 43, 50, 43, 43, 50, 43, 43, 50, 43, 43, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 43, 43, 50, 43, 43, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 28, 28, 35, 28, 28, 35, 28, 28, 35, 28, 28, 35, 28, 28, 35, 28, 21, 28, 35, 28, 28, 35, 35, 35, 35, 35, 37, 38, 21, 28, 35, 28, 28, 35, 35, 35, 35, 35, 35, 35, 36, 36, 21, 39, 35, 35, 35, 39, 35, 37, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 28, 28, 35, 35, 28, 28, 35, 35, 35, 36, 36, 22, 39, 35, 35, 35, 35, 35, 35, 37, 38, 28, 35, 21, 36, 36, 37, 35, 35, 20, 39, 39, 35, 35, 35, 35, 37, 38, 28, 35, 37, 34, 35, 24, 24, 27, 25, 20, 24, 37, 35, 27, 21, 20, 21, 27, 17, 20, 24, 32, 26, 20, 12, 20, 10, 20, 24, 25, 23, 20, 32, 24, 24, 23, 20, 24, 23, 18, 34, 34, 34, 22, 26, 24, 24, 18, 22, 22, 23, 25, 20, 12, 20, 24, 23, 24, 23, 22, 20, 20, 0, 20, 24, 23, 20, 8, 10, 4, 20, 20, 3, 7, 19, 20, 4, 4, 7, 7, 0, 7, 11, 18, 8, 3, 23, 23, 20, 11, 4, 20, 18, 12, 20, 20, 20, 4, 20, 4, 2, 3, 21, 21, 21, 21, 10, 15, 14, 15, 19, 2, 4, 3, 6, 11, 3, 4, 6, 21, 16, 20, 11, 1, 4, 12, 0, 15, 8, 1, 3, 3, 12, 1, 11, 20, 4}; + private final int[] base = {2, 13, 38, 51, 67, 78, 92, 118, 138, 162, 181, 191, 210, 222, 239, 253, 266, 280, 288, 304, 317, 333, 347, 359, 375, 386, 394, 406, 418, 433, 444, 457, 472, 482, 496, 506, 519, 529, 544, 557, 569, 579, 590, 601, 614, 626, 638, 649, 663, 673, 686, 706, 715, 731, 740, 753, 765, 777, 787, 799, 813, 826, 838, 854, 863, 876, 892, 901, 913, 929, 937, 948, 960, 970, 981, 993, 1004, 1017, 1034, 1045, 1056, 1068, 1080, 1091, 1103, 1115, 1126, 1138, 1148, 1160, 1177, 1187, 1199, 1211, 1222, 1232, 1243, 1254, 1268, 1279, 1294, 1307, 1319, 1330, 1341, 1352, 1362, 1374, 1388, 1398, 1411, 1422, 1433, 1444, 1456, 1466, 1479, 1497, 1506, 1519, 1531, 1543, 1556, 1567, 1578, 1589, 1604, 1614, 1630, 1641, 1651, 1662, 1675, 1688, 1700, 1711, 1721, 1732, 1748, 1758, 1772, 1784, 1795, 1806, 1820, 1830, 1844, 1855, 1866, 1877, 1892, 1902, 1914, 1926, 1939, 1950, 1965, 1974, 1986, 1999, 2011, 2023, 2037, 2047, 2059, 2072, 2084, 2096, 2107, 2120, 2132, 2144, 2156, 2169, 2180, 2191, 2202, 2217, 2227, 2239, 2251, 2264, 2275, 2286, 2297, 2309, 2321, 2332, 2347, 2358, 2369, 2381, 2394, 2406, 2417, 2429, 2439, 2452, 2465, 2476, 2490, 2501, 2512, 2524, 2536, 2546, 2560, 2570, 2581, 2593, 2605, 2616, 2628, 2640, 2653, 2664, 2676, 2688, 2700, 2712, 2723, 2735, 2748, 2759, 2772, 2784, 2795, 2808, 2820, 2831, 2842, 2854, 2866, 2878, 2888, 2901, 2913, 2927, 2936, 2947, 2958, 2970, 2982, 2994, 3005, 3019, 3030, 3041, 3053, 3064, 3077, 3088, 3099, 3110, 3123, 3135, 3146, 3157, 3168, 3179, 3192, 3203, 3214, 3226, 3238, 3251, 3263, 3275, 3286, 3297, 3308, 3320, 3331, 3344, 3356, 3368, 3380, 3391, 3402, 3415, 3426, 3440, 3451, 3462, 3474, 3485, 3496, 3508, 3520, 3532, 3543, 3556, 3569, 3580, 3593, 3604, 3615, 3626, 3638, 3650, 3661, 3673, 3684, 3698, 3709, 3721, 3732, 3744, 3756, 3767, 3779, 3792, 3803, 3814, 3827, 3838, 3850, 3862, 3873, 3885, 3897, 3909, 3920, 3932, 3943, 3955, 3966, 3980, 3990, 4002, 4014, 4026, 4038, 4050, 4061, 4072, 4083, 4095, 4107, 4119, 4131, 4143, 4156, 4167, 4179, 4191, 4203, 4215, 4227, 4238, 4252, 4262, 4274, 4287, 4298, 4310, 4321, 4333, 4345, 4356, 4370, 4381, 4393, 4406, 4417, 4428, 4440, 4453, 4464, 4477, 4489, 4500, 4513, 4524, 4536, 4548, 4560, 4573, 4583, 4595, 4607, 4620, 4631, 4645, 4655, 4667, 4679, 4690, 4702, 4714, 4728, 4739, 4750, 4762, 4774, 4786, 4798, 4810, 4821, 4833, 4845, 4857, 4869, 4880, 4892, 4905, 4916, 4927, 4940, 4952, 4963, 4977, 4988, 5000, 5012, 5023, 5034, 5045, 5057, 5069, 5081, 5093, 5104, 5115, 5127, 5139, 5151, 5163, 5176, 5188, 5199, 5211, 5223, 5235, 5247, 5259, 5272, 5283, 5296, 5308, 5320, 5331, 5343, 5354, 5366, 5378, 5390, 5402, 5414, 5426, 5438, 5450, 5462, 5474, 5486, 5497, 5510, 5521, 5532, 5544, 5557, 5569, 5581, 5592, 5604, 5617, 5629, 5641, 5652, 5663, 5676, 5687, 5699, 5712, 5724, 5735, 5748, 5760, 5771, 5784, 5794, 5806, 5817, 5829, 5841, 5853, 5866, 5879, 5891, 5903, 5916, 5928, 5941, 5952, 5964, 5976, 5988, 6000, 6012, 6024, 6036, 6048, 6060, 6072, 6085, 6096, 6109, 6121, 6133, 6146, 6157, 6168, 6180, 6192, 6203, 6215, 6227, 6239, 6251, 6265, 6276, 6289, 6302, 6313, 6325, 6337, 6349, 6361, 6374, 6386, 6398, 6410, 6422, 6436, 6448, 6459, 6471, 6483, 6495, 6507, 6520, 6532, 6545, 6555, 6567, 6579, 6591, 6603, 6615, 6627, 6640, 6652, 6664, 6676, 6688, 6700, 6713, 6726, 6738, 6749, 6761, 6774, 6786, 6799, 6811, 6823, 6835, 6848, 6859, 6871, 6883, 6895, 6907, 6920, 6933, 6945, 6956, 6968, 6980, 6992, 7005, 7016, 7030, 7042, 7053, 7066, 7079, 7091, 7104, 7115, 7128, 7140, 7152, 7163, 7175, 7187, 7200, 7212, 7224, 7235, 7248, 7260, 7272, 7285, 7297, 7309, 7321, 7333, 7345, 7358, 7370, 7382, 7394, 7406, 7419, 7431, 7443, 7455, 7468, 7480, 7492, 7505, 7517, 7530, 7542, 7554, 7566, 7578, 7591, 7603, 7615, 7628, 7640, 7653, 7666, 7677, 7690, 7702, 7714, 7727, 7738, 7750, 7762, 7775, 7786, 7799, 7812, 7823, 7836, 7848, 7859, 7871, 7884, 7896, 7909, 7921, 7933, 7946, 7958, 7971, 7984, 7996, 8007, 8019, 8032, 8044, 8056, 8069, 8081, 8094, 8107, 8119, 8131, 8143, 8155, 8167, 8179, 8192, 8205, 8218, 8230, 8244, 8255, 8267, 8279, 8291, 8303, 8315, 8328, 8340, 8353, 8366, 8378, 8392, 8404, 8417, 8431, 8443, 8455, 8467, 8479, 8492, 8504, 8516, 8529, 8543, 8555, 8567, 8580, 8593, 8606, 8619, 8632, 8644, 8658, 8670, 8683, 8695, 8708, 8721, 8733, 8746, 8759, 8771, 8783, 8795, 8808, 8821, 8833, 8845, 8858, 8871, 8885, 8898, 8910, 8923, 8936, 8949, 8960, 8973, 8986, 9000, 9012, 9025, 9038, 9051, 9064, 9076, 9089, 9102, 9114, 9126, 9139, 9151, 9164, 9177, 9191, 9204, 9217, 9230, 9243, 9255, 9268, 9281, 9294, 9307, 9320, 9333, 9345, 9358, 9371, 9384, 9398, 9412, 9424, 9437, 9450, 9462, 9475, 9488, 9501, 9514, 9528, 9542, 9554, 9567, 9581, 9593, 9606, 9619, 9632, 9645, 9658, 9671, 9682, 9695, 9708, 9721, 9735, 9749, 9762, 9776, 9789, 9802, 9815, 9828, 9842, 9855, 9867, 9880, 9893, 9906, 9920, 9933, 9947, 9960, 9974, 9987, 10000, 10014, 10027, 10040, 10054, 10067, 10081, 10095, 10107, 10120, 10134, 10148, 10161, 10175, 10188, 10201, 10214, 10228, 10241, 10254, 10267, 10280, 10294, 10309, 10322, 10335, 10348, 10362, 10374, 10387, 10401, 10415, 10428, 10441, 10455, 10469, 10482, 10497, 10510, 10523, 10537, 10551, 10565, 10579, 10593, 10606, 10621, 10634, 10647, 10661, 10675, 10689, 10704, 10719, 10732, 10746, 10760, 10774, 10788, 10802, 10815, 10829, 10843, 10856, 10871, 10884, 10898, 10913, 10927, 10940, 10955, 10970, 10984, 10999, 11013, 11027, 11042, 11056, 11071, 11086, 11100, 11114, 11128, 11142, 11158, 11171, 11186, 11200, 11213, 11228, 11241, 11255, 11270, 11284, 11299, 11314, 11328, 11342, 11356, 11370, 11385, 11399, 11413, 11429, 11445, 11460, 11474, 11489, 11503, 11518, 11533, 11549, 11563, 11577, 11592, 11607, 11621, 11637, 11651, 11665, 11680, 11694, 11708, 11725, 11740, 11754, 11768, 11784, 11798, 11813, 11828, 11843, 11858, 11874, 11888, 11904, 11920, 11933, 11948, 11964, 11979, 11993, 12009, 12024, 12041, 12058, 12071, 12087, 12102, 12117, 12132, 12148, 12165, 12179, 12195, 12210, 12226, 12241, 12256, 12273, 12288, 12304, 12320, 12335, 12350, 12365, 12382, 12398, 12414, 12430, 12446, 12462, 12478, 12495, 12511, 12525, 12541, 12556, 12575, 12591, 12605, 12622, 12638, 12653, 12671, 12686, 12705, 12721, 12739, 12756, 12772, 12788, 12806, 12822, 12839, 12855, 12873, 12890, 12908, 12923, 12941, 12960, 12975, 12992, 13009, 13024, 13040, 13059, 13076, 13092, 13109, 13128, 13145, 13161, 13179, 13194, 13216, 13233, 13249, 13266, 13287, 13303, 13322, 13337, 13357, 13375, 13392, 13410, 13424, 13446, 13465, 13480, 13499, 13517, 13533, 13559, 13575, 13595, 13612, 13632, 13650, 13670, 13687, 13706, 13726, 13744, 13765, 13783, 13803, 13822, 13841, 13860, 13879, 13897, 13917, 13936, 13960, 13979, 13996, 14019, 14040, 14057, 14077, 14102, 14122, 14141, 14163, 14184, 14202, 14225, 14244, 14265, 14287, 14312, 14336, 14356, 14375, 14393, 14420, 14438, 14465, 14483, 14500, 14536, 14555, 14575, 14604, 14619, 14648, 14668, 14691, 14725, 14748, 14770, 14788, 14818, 14840, 14862, 14888, 14921, 14939, 14969, 14996, 15022, 15051, 15075, 15098, 15130, 15149, 15167, 15218, 15237, 15276, 15297, 15333, 15356, 15379, 15418, 15447, 15481, 15508, 15530, 15574, 15599, 15643, 15680, 15697, 15743, 15759, 15775, 15813, 15845, 15877, 15911, 15931, 15968, 16014, 16049, 16077, 16088, 16138, 16149, 16185, 16200, 16241, 16280, 16296}; public ABITracerTest() { } @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { } @AfterClass - public static void tearDownClass() throws Exception { + public static void tearDownClass() { } @Before @@ -84,7 +85,7 @@ public void testLocal() throws Exception { Assert.assertEquals(1165, tracer.getSequenceLength()); //Test sequence of tracer for file 3730.ab1 - Assert.assertTrue(sequence.equals(tracer.getSequence().getSequenceAsString())); + Assert.assertEquals(sequence, tracer.getSequence().getSequenceAsString()); //Test array that represents the quality of tracer for file 3730.ab1 Assert.assertArrayEquals(qual, tracer.getQcalls()); //Test array that represents the baseline of tracer for file 3730.ab1 diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/CasePreservingProteinSequenceCreatorTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/CasePreservingProteinSequenceCreatorTest.java index 42a11ff7cb..88be79397f 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/CasePreservingProteinSequenceCreatorTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/CasePreservingProteinSequenceCreatorTest.java @@ -33,7 +33,7 @@ public class CasePreservingProteinSequenceCreatorTest { @Test public void testConstructor() throws CompoundNotFoundException { - CasePreservingProteinSequenceCreator creator = new CasePreservingProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet()); + CasePreservingProteinSequenceCreator creator = new CasePreservingProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet); String seq = "aCDEfgHI-Jkl"; ProteinSequence prot = (ProteinSequence) creator.getSequence(seq, 0); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/FastaReaderTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/FastaReaderTest.java index 0222b54c47..6df7f1c31b 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/FastaReaderTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/FastaReaderTest.java @@ -30,7 +30,6 @@ import java.io.IOException; import java.io.InputStream; import java.util.LinkedHashMap; -import java.util.logging.Level; /** * @@ -44,11 +43,11 @@ public FastaReaderTest() { } @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { } @AfterClass - public static void tearDownClass() throws Exception { + public static void tearDownClass() { } @Before @@ -69,7 +68,7 @@ public void testProcess() throws Exception { Assert.assertNotNull(inStream); - FastaReader fastaReader = new FastaReader(inStream, new GenericFastaHeaderParser(), new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + FastaReader fastaReader = new FastaReader<>(inStream, new GenericFastaHeaderParser<>(), new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap proteinSequences = fastaReader.process(); inStream.close(); @@ -78,9 +77,8 @@ public void testProcess() throws Exception { Assert.assertEquals(proteinSequences.size(), 283); int seqNum = 0; - for(String id:proteinSequences.keySet()) { - ProteinSequence proteinSequence = proteinSequences.get(id); - switch(seqNum) { + for(ProteinSequence proteinSequence : proteinSequences.values()) { + switch(seqNum) { case 0: Assert.assertEquals(proteinSequence.getAccession().getID(), "A2D504_ATEGE/1-46"); Assert.assertEquals(proteinSequence.getSequenceAsString(), "-----------------FK-N----LP-LED----------------Q----ITL--IQY-----------SWM----------------------CL-SSFA------LSWRSYK---HTNSQFLYFAPDLVF-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"); @@ -106,7 +104,7 @@ public void processIntTest() throws Exception { logger.info("process(int)"); InputStream inStream = this.getClass().getResourceAsStream("/PF00104_small.fasta"); Assert.assertNotNull(inStream); - FastaReader fastaReader = new FastaReader(inStream, new GenericFastaHeaderParser(), new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + FastaReader fastaReader = new FastaReader<>(inStream, new GenericFastaHeaderParser<>(), new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap proteinSequences = fastaReader.process(200); //Should have 200 sequences @@ -114,9 +112,8 @@ public void processIntTest() throws Exception { Assert.assertEquals(proteinSequences.size(), 200); int seqNum = 0; - for(String id:proteinSequences.keySet()) { - ProteinSequence proteinSequence = proteinSequences.get(id); - switch(seqNum) { + for(ProteinSequence proteinSequence : proteinSequences.values()) { + switch(seqNum) { case 0: Assert.assertEquals(proteinSequence.getAccession().getID(), "A2D504_ATEGE/1-46"); Assert.assertEquals(proteinSequence.getSequenceAsString(), "-----------------FK-N----LP-LED----------------Q----ITL--IQY-----------SWM----------------------CL-SSFA------LSWRSYK---HTNSQFLYFAPDLVF-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"); @@ -134,9 +131,8 @@ public void processIntTest() throws Exception { proteinSequences = fastaReader.process(200); Assert.assertEquals(proteinSequences.size(), 83); seqNum = 0; - for(String id:proteinSequences.keySet()) { - ProteinSequence proteinSequence = proteinSequences.get(id); - switch(seqNum) { + for(ProteinSequence proteinSequence : proteinSequences.values()) { + switch(seqNum) { case 0: Assert.assertEquals(proteinSequence.getAccession().getID(), "RARA_CANFA/233-413"); Assert.assertEquals(proteinSequence.getSequenceAsString(), "TKCIIKTVEFAKQL-PGFT-T----LT-IAD----------------Q----ITL--LKA-----------ACL----------------------DI-LILR------ICTRYTP---EQDTMTFSEGLTLN-------------------------------------------------------------------------------------------------------------------------------------------------------------RTQMHKAGFGPLTDLVFAFA-NQL-LPL-E-MDDAET--------------------GLLSA-ICLI-CGDRQD-------------------------------------------LEQP--DRVDMLQEPLLEALKV-Y-----VRK---------RR---PS----------------------------RP------H--------MFP-KMLMKITD-LRSIS-----------------AKG-AERV--ITLKMEIPG--SMP--PLI-------QEM---"); @@ -164,10 +160,10 @@ public void testSmallFasta() throws IOException { InputStream inStream = this.getClass().getResourceAsStream("/test.fasta"); - FastaReader fastaReader = new FastaReader( + FastaReader fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap b; @@ -192,10 +188,10 @@ public void testSmallFasta2() throws IOException { InputStream inStream = this.getClass().getResourceAsStream("/test.fasta"); - FastaReader fastaReader = new FastaReader( + FastaReader fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); int nrSeq = 0; diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankCookbookTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankCookbookTest.java index d6018a5eaf..1ce4df936d 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankCookbookTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankCookbookTest.java @@ -46,11 +46,11 @@ public GenbankCookbookTest() { } @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { } @AfterClass - public static void tearDownClass() throws Exception { + public static void tearDownClass() { } @Before @@ -70,14 +70,14 @@ public void testProcess() throws Throwable { * Method 1: With the GenbankProxySequenceReader */ //Try with the GenbankProxySequenceReader - GenbankProxySequenceReader genbankProteinReader - = new GenbankProxySequenceReader(System.getProperty("java.io.tmpdir"), "NP_000257", AminoAcidCompoundSet.getAminoAcidCompoundSet()); + GenbankProxySequenceReader genbankProteinReader + = new GenbankProxySequenceReader<>(System.getProperty("java.io.tmpdir"), "NP_000257", AminoAcidCompoundSet.aminoAcidCompoundSet); ProteinSequence proteinSequence = new ProteinSequence(genbankProteinReader); genbankProteinReader.getHeaderParser().parseHeader(genbankProteinReader.getHeader(), proteinSequence); //logger.info("Sequence({},{}) = {}...", proteinSequence.getAccession(), proteinSequence.getLength(), proteinSequence.getSequenceAsString().substring(0, 10)); GenbankProxySequenceReader genbankDNAReader - = new GenbankProxySequenceReader(System.getProperty("java.io.tmpdir"), "NM_001126", DNACompoundSet.getDNACompoundSet()); + = new GenbankProxySequenceReader<>(System.getProperty("java.io.tmpdir"), "NM_001126", DNACompoundSet.getDNACompoundSet()); DNASequence dnaSequence = new DNASequence(genbankDNAReader); genbankDNAReader.getHeaderParser().parseHeader(genbankDNAReader.getHeader(), dnaSequence); //logger.info("Sequence({},{}) = {}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); @@ -104,9 +104,9 @@ public void testProcess() throws Throwable { */ //Try reading with the GanbankReader - GenbankReader dnaReader = new GenbankReader( + GenbankReader dnaReader = new GenbankReader<>( dnaResource.getInputStream(), - new GenericGenbankHeaderParser(), + new GenericGenbankHeaderParser<>(), new DNASequenceCreator(DNACompoundSet.getDNACompoundSet()) ); dnaSequences = dnaReader.process(); @@ -114,10 +114,10 @@ public void testProcess() throws Throwable { logger.debug("DNA Sequence: {}", dnaSequences); - GenbankReader protReader = new GenbankReader( + GenbankReader protReader = new GenbankReader<>( protResource.getInputStream(), - new GenericGenbankHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet()) + new GenericGenbankHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet) ); protSequences = protReader.process(); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankReaderTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankReaderTest.java index 5bcbecf672..7544a84247 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankReaderTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankReaderTest.java @@ -22,41 +22,24 @@ import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.DNASequence; -import org.biojava.nbio.core.sequence.RNASequence; import org.biojava.nbio.core.sequence.ProteinSequence; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; -import org.biojava.nbio.core.sequence.compound.DNACompoundSet; -import org.biojava.nbio.core.sequence.compound.RNACompoundSet; -import org.biojava.nbio.core.sequence.compound.NucleotideCompound; +import org.biojava.nbio.core.sequence.RNASequence; +import org.biojava.nbio.core.sequence.compound.*; import org.biojava.nbio.core.sequence.features.FeatureInterface; import org.biojava.nbio.core.sequence.features.Qualifier; import org.biojava.nbio.core.sequence.template.AbstractSequence; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; +import java.io.*; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; /** * @@ -72,11 +55,11 @@ public GenbankReaderTest() { } @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { } @AfterClass - public static void tearDownClass() throws Exception { + public static void tearDownClass() { } @Before @@ -97,11 +80,11 @@ public void testProcess() throws Exception { InputStream inStream = this.getClass().getResourceAsStream("/BondFeature.gb"); assertNotNull(inStream); - GenbankReader genbankProtein + GenbankReader genbankProtein = new GenbankReader<>( inStream, new GenericGenbankHeaderParser<>(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet()) + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet) ); LinkedHashMap proteinSequences = genbankProtein.process(); @@ -169,7 +152,7 @@ public void testProcess() throws Exception { * The underlying {@link InputStream} should remain open until the last call. */ @Test - public void testPartialProcess() throws IOException, CompoundNotFoundException, NoSuchFieldException { + public void testPartialProcess() throws IOException, CompoundNotFoundException { CheckableInputStream inStream = new CheckableInputStream(this.getClass().getResourceAsStream("/two-dnaseqs.gb")); GenbankReader genbankDNA @@ -207,17 +190,17 @@ public void CDStest() throws Exception { CheckableInputStream inStream = new CheckableInputStream(this.getClass().getResourceAsStream("/BondFeature.gb")); assertNotNull(inStream); - GenbankReader GenbankProtein + GenbankReader GenbankProtein = new GenbankReader<>( inStream, new GenericGenbankHeaderParser<>(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet()) + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet) ); LinkedHashMap proteinSequences = GenbankProtein.process(); assertTrue(inStream.isclosed()); - Assert.assertTrue(proteinSequences.size() == 1); + assertEquals(1, proteinSequences.size()); logger.debug("protein sequences: {}", proteinSequences); ProteinSequence protein = new ArrayList<>(proteinSequences.values()).get(0); @@ -228,7 +211,7 @@ public void CDStest() throws Exception { List dbrefs = quals.get("db_xref"); Assert.assertNotNull(codedBy); - Assert.assertTrue(!codedBy.isEmpty()); + assertFalse(codedBy.isEmpty()); assertEquals(codedBy, "NM_000266.2:503..904"); assertEquals(5, dbrefs.size()); @@ -260,11 +243,11 @@ private RNASequence readGenbankRNAResource(final String resource) throws IOExcep private ProteinSequence readGenbankProteinResource(final String resource) throws IOException, CompoundNotFoundException { InputStream inputStream = getClass().getResourceAsStream(resource); - GenbankReader genbankProtein + GenbankReader genbankProtein = new GenbankReader<>( inputStream, new GenericGenbankHeaderParser<>(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet()) + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet) ); LinkedHashMap proteinSequences = genbankProtein.process(); return proteinSequences.values().iterator().next(); @@ -353,7 +336,7 @@ public void testLegacyLocusCompatable() throws IOException, CompoundNotFoundExce /** * Helper class to be able to verify the closed state of the input stream. */ - private class CheckableInputStream extends BufferedInputStream { + private static class CheckableInputStream extends BufferedInputStream { private boolean closed; diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankWriterTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankWriterTest.java index 6b54346226..33bfaced9c 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankWriterTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankWriterTest.java @@ -49,10 +49,7 @@ public void testProcess() throws Exception { //File dnaFile = new File("src/test/resources/NM_000266.gb"); LinkedHashMap dnaSequences = GenbankReaderHelper.readGenbankDNASequence( inStream ); ByteArrayOutputStream fragwriter = new ByteArrayOutputStream(); - ArrayList seqs = new ArrayList(); - for(DNASequence seq : dnaSequences.values()) { - seqs.add(seq); - } + ArrayList seqs = new ArrayList<>(dnaSequences.values()); GenbankWriterHelper.writeNucleotideSequence(fragwriter, seqs, GenbankWriterHelper.LINEAR_DNA); //System.out.println(fragwriter.toString()); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenericFastaHeaderParserTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenericFastaHeaderParserTest.java index 1d41e734ac..13d27418f9 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenericFastaHeaderParserTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenericFastaHeaderParserTest.java @@ -42,11 +42,11 @@ public GenericFastaHeaderParserTest() { } @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { } @AfterClass - public static void tearDownClass() throws Exception { + public static void tearDownClass() { } @Before @@ -78,9 +78,9 @@ public void tearDown() { @Test public void testParseHeader() throws CompoundNotFoundException { logger.info("parseHeader"); - String header = ""; + String header; ProteinSequence sequence = new ProteinSequence(""); - GenericFastaHeaderParser instance = new GenericFastaHeaderParser(); + GenericFastaHeaderParser instance = new GenericFastaHeaderParser<>(); header = "gi|gi-number|gb|accession|locus"; instance.parseHeader(header, sequence); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/loader/GenbankProxySequenceReaderTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/loader/GenbankProxySequenceReaderTest.java index 647d86df4d..a56cc6ecdd 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/loader/GenbankProxySequenceReaderTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/loader/GenbankProxySequenceReaderTest.java @@ -55,7 +55,7 @@ @RunWith(Parameterized.class) public class GenbankProxySequenceReaderTest { - private String gi; + private final String gi; private final static Logger logger = LoggerFactory.getLogger(GenbankProxySequenceReaderTest.class); public GenbankProxySequenceReaderTest(String gi) { @@ -127,7 +127,7 @@ public void testFeatures() throws IOException, InterruptedException, CompoundNot GenbankProxySequenceReader genbankReader = new GenbankProxySequenceReader<>(System.getProperty("java.io.tmpdir"), this.gi, - AminoAcidCompoundSet.getAminoAcidCompoundSet()); + AminoAcidCompoundSet.aminoAcidCompoundSet); // why only tests on protein sequences? ProteinSequence seq = new ProteinSequence(genbankReader); @@ -166,7 +166,7 @@ so it should be done here (manualy). logger.info("CDS: {}", CDS); String codedBy = CDS.getQualifiers().get("coded_by").get(0).getValue(); Assert.assertNotNull(codedBy); - Assert.assertTrue(!codedBy.isEmpty()); + Assert.assertFalse(codedBy.isEmpty()); logger.info("\t\tcoded_by: {}", codedBy); } @@ -182,7 +182,7 @@ public void testProteinSequenceFactoring() throws Exception { GenbankProxySequenceReader genbankReader = new GenbankProxySequenceReader<>(System.getProperty("java.io.tmpdir"), this.gi, - AminoAcidCompoundSet.getAminoAcidCompoundSet()); + AminoAcidCompoundSet.aminoAcidCompoundSet); ProteinSequence seq = new ProteinSequence(genbankReader); @@ -205,7 +205,7 @@ public void testProteinSequenceFactoring() throws Exception { That test is always failed */ //Assert.assertTrue(parentSeq.getAccession()); - Assert.assertTrue(!parentSeq.getSequenceAsString().isEmpty()); + Assert.assertFalse(parentSeq.getSequenceAsString().isEmpty()); } } } else { diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/loader/SimpleGenbankProxySequenceReaderTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/loader/SimpleGenbankProxySequenceReaderTest.java index 4150e90ffc..6bcd55360d 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/loader/SimpleGenbankProxySequenceReaderTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/loader/SimpleGenbankProxySequenceReaderTest.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.core.sequence.loader; -import java.io.IOException; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; @@ -28,6 +27,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; + /** * Testing example for issue #834 @@ -47,10 +48,10 @@ public void testWrongSequence() throws Exception { String wrongGi = "34567"; - GenbankProxySequenceReader genbankReader - = new GenbankProxySequenceReader(System.getProperty("java.io.tmpdir"), - wrongGi, - AminoAcidCompoundSet.getAminoAcidCompoundSet()); + GenbankProxySequenceReader genbankReader + = new GenbankProxySequenceReader<>(System.getProperty("java.io.tmpdir"), + wrongGi, + AminoAcidCompoundSet.aminoAcidCompoundSet); ProteinSequence seq = new ProteinSequence(genbankReader); } diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/InsdcParserTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/InsdcParserTest.java index 01094c84ba..144aba0058 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/InsdcParserTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/InsdcParserTest.java @@ -20,8 +20,6 @@ */ package org.biojava.nbio.core.sequence.location; -import java.util.Arrays; -import java.util.Collection; import org.biojava.nbio.core.sequence.DataSource; import org.biojava.nbio.core.sequence.location.template.Location; import org.junit.Assert; @@ -31,6 +29,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Arrays; +import java.util.Collection; + /** * * @author Jacek Grzebyta @@ -38,9 +39,9 @@ @RunWith(Parameterized.class) public class InsdcParserTest { - private Logger log = LoggerFactory.getLogger(getClass()); - private String data; - private String expected; + private final Logger log = LoggerFactory.getLogger(getClass()); + private final String data; + private final String expected; public InsdcParserTest(String data, String expected) { this.data = data; @@ -58,10 +59,9 @@ public static Collection data() { /** * Test for issue #254 * - * @throws Exception */ @Test - public void extractAccessionTest() throws Exception { + public void extractAccessionTest() { log.info("test accession"); log.debug("data: '{}' expected: '{}'", data, expected); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/LocationParserTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/LocationParserTest.java index 3c562498b5..14cf3ebaaa 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/LocationParserTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/LocationParserTest.java @@ -54,7 +54,7 @@ public class LocationParserTest { public static final InsdcParser PARSER = new InsdcParser(); - private Logger log = LoggerFactory.getLogger(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); @Test @Ignore diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/TargetedLocationParserTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/TargetedLocationParserTest.java index 6ea7c9f869..1681619b3e 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/TargetedLocationParserTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/TargetedLocationParserTest.java @@ -40,10 +40,10 @@ @RunWith(Parameterized.class) public class TargetedLocationParserTest { - private Data request; + private final Data request; public static class Data { - private String Insdc; + private final String Insdc; /** * Parser data input. Based on that input it should be able to identity the origin and wanted target @@ -55,17 +55,17 @@ public static class Data { public Data(String gi, CompoundSet originType, String Insdc, CompoundSet compound) { this.Insdc = Insdc; } - }; + } @Parameterized.Parameters - public static Collection getLocations() throws Exception { + public static Collection getLocations() { - Data[][] out = new Data[][]{ - {new Data("7525057", AminoAcidCompoundSet.getAminoAcidCompoundSet(), + Data[][] out = new Data[][]{ + {new Data("7525057", AminoAcidCompoundSet.aminoAcidCompoundSet, "join(complement(NC_000932.1:69611..69724),NC_000932.1:139856..140087,NC_000932.1:140625..140650)", DNACompoundSet.getDNACompoundSet())}, - {new Data("7525059", AminoAcidCompoundSet.getAminoAcidCompoundSet(), + {new Data("7525059", AminoAcidCompoundSet.aminoAcidCompoundSet, "NC_000932.1:72371..73897", DNACompoundSet.getDNACompoundSet())}, {new Data("7525073", DNACompoundSet.getDNACompoundSet() , @@ -85,7 +85,7 @@ public TargetedLocationParserTest(Data request) { @Test - public void locationTest() throws Exception { + public void locationTest() { InsdcParser parser = new InsdcParser(DataSource.GENBANK); Location loc = parser.parse(request.Insdc); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/views/WindowViewTests.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/views/WindowViewTests.java index 90d4da3a01..e27962adb4 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/views/WindowViewTests.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/views/WindowViewTests.java @@ -38,7 +38,7 @@ public class WindowViewTests { @Test public void basicWindow() throws CompoundNotFoundException { RNASequence rna = new RNASequence("AUGCCU"); - WindowedSequence window = new WindowedSequence(rna, 3); + WindowedSequence window = new WindowedSequence<>(rna, 3); Iterator> iter = window.iterator(); assertTrue("hasNext() returns true", iter.hasNext()); @@ -57,8 +57,8 @@ public void basicWindow() throws CompoundNotFoundException { @Test public void reaminderWindow() throws CompoundNotFoundException { RNASequence rna = new RNASequence("AUGCC"); - WindowedSequence window = new WindowedSequence(rna, 3); - List> list = new ArrayList>(); + WindowedSequence window = new WindowedSequence<>(rna, 3); + List> list = new ArrayList<>(); for(SequenceView c: window) { list.add(c); } diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/util/TestUncompressInputStream.java b/biojava-core/src/test/java/org/biojava/nbio/core/util/TestUncompressInputStream.java index 470eacfbbf..008d57e600 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/util/TestUncompressInputStream.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/util/TestUncompressInputStream.java @@ -20,13 +20,14 @@ */ package org.biojava.nbio.core.util; -import java.io.BufferedInputStream; +import org.junit.Assert; import org.junit.Test; -import static org.junit.Assert.*; +import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; -import org.junit.Assert; + +import static org.junit.Assert.assertEquals; public class TestUncompressInputStream { @@ -60,7 +61,7 @@ public void testUncompression() throws Exception { ByteArrayOutputStream obaos = new ByteArrayOutputStream(); try (BufferedInputStream oin = new BufferedInputStream( this.getClass().getClassLoader() - .getResourceAsStream(ORIG_OF_BIGGER_TEST_FILE));) { + .getResourceAsStream(ORIG_OF_BIGGER_TEST_FILE))) { byte[] buf = new byte[100000]; int len; while ((len = oin.read(buf)) >= 0) diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/GeneFeatureHelper.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/GeneFeatureHelper.java index 7f7294801e..b8828a99cd 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/GeneFeatureHelper.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/GeneFeatureHelper.java @@ -20,18 +20,15 @@ */ package org.biojava.nbio.genome; -import org.biojava.nbio.genome.parsers.gff.*; import org.biojava.nbio.core.sequence.*; import org.biojava.nbio.core.sequence.io.FastaReaderHelper; +import org.biojava.nbio.genome.parsers.gff.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileWriter; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; +import java.util.*; /** * @@ -42,13 +39,13 @@ public class GeneFeatureHelper { private static final Logger logger = LoggerFactory.getLogger(GeneFeatureHelper.class); static public LinkedHashMap loadFastaAddGeneFeaturesFromUpperCaseExonFastaFile(File fastaSequenceFile, File uppercaseFastaFile, boolean throwExceptionGeneNotFound) throws Exception { - LinkedHashMap chromosomeSequenceList = new LinkedHashMap(); + LinkedHashMap chromosomeSequenceList = new LinkedHashMap<>(); LinkedHashMap dnaSequenceList = FastaReaderHelper.readFastaDNASequence(fastaSequenceFile); - for (String accession : dnaSequenceList.keySet()) { - DNASequence contigSequence = dnaSequenceList.get(accession); + for (Map.Entry entry : dnaSequenceList.entrySet()) { + DNASequence contigSequence = entry.getValue(); ChromosomeSequence chromsomeSequence = new ChromosomeSequence(contigSequence.getSequenceAsString()); chromsomeSequence.setAccession(contigSequence.getAccession()); - chromosomeSequenceList.put(accession, chromsomeSequence); + chromosomeSequenceList.put(entry.getKey(), chromsomeSequence); } @@ -91,7 +88,7 @@ static public LinkedHashMap loadFastaAddGeneFeatures dnaSequence.getAccession().toString(), contigDNASequence.getAccession().toString(), bioStart, bioEnd, strand); ChromosomeSequence chromosomeSequence = chromosomeSequenceList.get(accession); - ArrayList exonBoundries = new ArrayList(); + ArrayList exonBoundries = new ArrayList<>(); //look for transitions from lowercase to upper case for (int i = 0; i < geneSequence.length(); i++) { @@ -314,12 +311,12 @@ static public void addGeneIDGFF2GeneFeatures(LinkedHashMap getChromosomeSequenceFromDNASequence(LinkedHashMap dnaSequenceList) { - LinkedHashMap chromosomeSequenceList = new LinkedHashMap(); - for (String key : dnaSequenceList.keySet()) { - DNASequence dnaSequence = dnaSequenceList.get(key); + LinkedHashMap chromosomeSequenceList = new LinkedHashMap<>(); + for (Map.Entry entry : dnaSequenceList.entrySet()) { + DNASequence dnaSequence = entry.getValue(); ChromosomeSequence chromosomeSequence = new ChromosomeSequence(dnaSequence.getProxySequenceReader()); //we want the underlying sequence but don't need storage chromosomeSequence.setAccession(dnaSequence.getAccession()); - chromosomeSequenceList.put(key, chromosomeSequence); + chromosomeSequenceList.put(entry.getKey(), chromosomeSequence); } return chromosomeSequenceList; } @@ -361,10 +358,10 @@ static public void addGmodGFF3GeneFeatures(LinkedHashMap getProteinSequences(Collection chromosomeSequences) throws Exception { - LinkedHashMap proteinSequenceHashMap = new LinkedHashMap(); + static public LinkedHashMap getProteinSequences(Collection chromosomeSequences) { + LinkedHashMap proteinSequenceHashMap = new LinkedHashMap<>(); for (ChromosomeSequence dnaSequence : chromosomeSequences) { for (GeneSequence geneSequence : dnaSequence.getGeneSequences().values()) { for (TranscriptSequence transcriptSequence : geneSequence.getTranscripts().values()) { @@ -864,8 +861,8 @@ static public LinkedHashMap getProteinSequences(Collect return proteinSequenceHashMap; } - static public LinkedHashMap getGeneSequences(Collection chromosomeSequences) throws Exception { - LinkedHashMap geneSequenceHashMap = new LinkedHashMap(); + static public LinkedHashMap getGeneSequences(Collection chromosomeSequences) { + LinkedHashMap geneSequenceHashMap = new LinkedHashMap<>(); for (ChromosomeSequence chromosomeSequence : chromosomeSequences) { for (GeneSequence geneSequence : chromosomeSequence.getGeneSequences().values()) { geneSequenceHashMap.put(geneSequence.getAccession().getID(), geneSequence); @@ -875,7 +872,7 @@ static public LinkedHashMap getGeneSequences(Collection chromosomeSequenceList = GeneFeatureHelper.loadFastaAddGeneFeaturesFromGeneMarkGTF(new File("Scaffolds.fna"), new File("genemark_hmm.gtf")); LinkedHashMap proteinSequenceList = GeneFeatureHelper.getProteinSequences(chromosomeSequenceList.values()); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/homology/BlastHomologyHits.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/homology/BlastHomologyHits.java index 88881b37eb..831a8875bc 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/homology/BlastHomologyHits.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/homology/BlastHomologyHits.java @@ -25,6 +25,7 @@ import java.io.File; import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.Map; /** * @@ -33,13 +34,13 @@ public class BlastHomologyHits { static public LinkedHashMap> getMatches(File xmlBlastHits, double ecutoff) throws Exception { - LinkedHashMap> homologyHits = new LinkedHashMap>(); + LinkedHashMap> homologyHits = new LinkedHashMap<>(); BlastXMLQuery blastXMLQuery = new BlastXMLQuery(xmlBlastHits.getAbsolutePath()); LinkedHashMap> hits = blastXMLQuery.getHitsQueryDef(ecutoff); - for (String accessionid : hits.keySet()) { - String[] data = accessionid.split(" "); // deal with notes/comments in blast results + for (Map.Entry> entry : hits.entrySet()) { + String[] data = entry.getKey().split(" "); // deal with notes/comments in blast results String id = data[0]; - ArrayList uniprotProteinHits = hits.get(accessionid); + ArrayList uniprotProteinHits = entry.getValue(); homologyHits.put(id, uniprotProteinHits); } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/homology/GFF3FromUniprotBlastHits.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/homology/GFF3FromUniprotBlastHits.java index 0910b6b68d..4a51dfebc8 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/homology/GFF3FromUniprotBlastHits.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/homology/GFF3FromUniprotBlastHits.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.genome.homology; -import org.biojava.nbio.genome.GeneFeatureHelper; import org.biojava.nbio.alignment.Alignments; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; import org.biojava.nbio.alignment.SimpleGapPenalty; @@ -33,6 +32,7 @@ import org.biojava.nbio.core.sequence.features.DatabaseReferenceInterface; import org.biojava.nbio.core.sequence.features.FeaturesKeyWordInterface; import org.biojava.nbio.core.sequence.loader.UniprotProxySequenceReader; +import org.biojava.nbio.genome.GeneFeatureHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,27 +41,33 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; /** * * @author Scooter Willis * @author Mark Chapman + * + * TODO test + * */ public class GFF3FromUniprotBlastHits { private static final Logger logger = LoggerFactory.getLogger(GFF3FromUniprotBlastHits.class); - public void process(File xmlBlastHits, double ecutoff, LinkedHashMap geneSequenceHashMap, OutputStream gff3Output) throws Exception { - LinkedHashMap> hits = BlastHomologyHits.getMatches(xmlBlastHits, ecutoff); - process(hits, geneSequenceHashMap, gff3Output); - } +// public void process(File xmlBlastHits, double ecutoff, LinkedHashMap geneSequenceHashMap, OutputStream gff3Output) throws Exception { +// LinkedHashMap> hits = BlastHomologyHits.getMatches(xmlBlastHits, ecutoff); +// process(hits, geneSequenceHashMap, gff3Output); +// } - public void process(LinkedHashMap> hits, LinkedHashMap geneSequenceHashMap, OutputStream gff3Output) throws Exception { + public void process(LinkedHashMap> hits, LinkedHashMap geneSequenceHashMap, OutputStream gff3Output) { int size = hits.size(); int index = 0; // HashMap scaffoldsReferencedHashMap = new HashMap(); - for (String accessionid : hits.keySet()) { - index++; + for (Map.Entry> stringArrayListEntry : hits.entrySet()) { + String accessionid = stringArrayListEntry.getKey(); + index++; if (index == 12) { index = 12; } @@ -75,9 +81,9 @@ public void process(LinkedHashMap> hits, LinkedHashMap logger.error("Not found " + id); continue; } - ArrayList uniprotProteinHits = hits.get(accessionid); + ArrayList uniprotProteinHits = stringArrayListEntry.getValue(); String uniprotBestHit = uniprotProteinHits.get(0); - UniprotProxySequenceReader uniprotSequence = new UniprotProxySequenceReader(uniprotBestHit, AminoAcidCompoundSet.getAminoAcidCompoundSet()); + UniprotProxySequenceReader uniprotSequence = new UniprotProxySequenceReader<>(uniprotBestHit, AminoAcidCompoundSet.aminoAcidCompoundSet); ProteinSequence proteinSequence = new ProteinSequence(uniprotSequence); String hitSequence = proteinSequence.getSequenceAsString(); @@ -87,18 +93,20 @@ public void process(LinkedHashMap> hits, LinkedHashMap String predictedProteinSequence = transcriptSequence.getProteinSequence().getSequenceAsString(); ArrayList cdsProteinList = transcriptSequence.getProteinCDSSequences(); - ArrayList cdsSequenceList = new ArrayList(transcriptSequence.getCDSSequences().values()); + ArrayList cdsSequenceList = new ArrayList<>(transcriptSequence.getCDSSequences().values()); String testSequence = ""; for (ProteinSequence cdsProteinSequence : cdsProteinList) { testSequence = testSequence + cdsProteinSequence.getSequenceAsString(); } if (!testSequence.equals(predictedProteinSequence) && (!predictedProteinSequence.equals(testSequence.substring(0, testSequence.length() - 1)))) { DNASequence codingSequence = transcriptSequence.getDNACodingSequence(); - logger.info("Coding Sequence: {}", codingSequence.getSequenceAsString()); - logger.info("Sequence agreement error"); - logger.info("CDS seq={}", testSequence); - logger.info("PRE seq={}", predictedProteinSequence); - logger.info("UNI seq={}", hitSequence); + if (logger.isInfoEnabled()) { + logger.info("Coding Sequence: {}", codingSequence.getSequenceAsString()); + logger.info("Sequence agreement error"); + logger.info("CDS seq={}", testSequence); + logger.info("PRE seq={}", predictedProteinSequence); + logger.info("UNI seq={}", hitSequence); + } // throw new Exception("Protein Sequence compare error " + id); } @@ -112,35 +120,31 @@ PairwiseSequenceAlignerType.LOCAL, new SimpleGapPenalty(), // System.out.println(new Pair().format(alignment)); int proteinIndex = 0; int gff3Index = 0; - for (int i = 0; i < cdsProteinList.size(); i++) { + int cdsProteins = cdsProteinList.size(); + for (int i = 0; i < cdsProteins; i++) { ProteinSequence peptideSequence = cdsProteinList.get(i); - String seq = peptideSequence.getSequenceAsString(); - Integer startIndex = null; + final String seq = peptideSequence.getSequenceAsString(); + int startIndex; int offsetStartIndex = 0; - for (int s = 0; s < seq.length(); s++) { - startIndex = alignment.getIndexInTargetForQueryAt(proteinIndex + s); - if (startIndex != null) { - startIndex = startIndex + 1; - offsetStartIndex = s; - break; - } - } - Integer endIndex = null; + int seqLen = seq.length(); + //for (int s = 0; s < seqLen; s++) { + startIndex = alignment.getIndexInTargetForQueryAt(proteinIndex); + startIndex = startIndex + 1; +// offsetStartIndex = 0; + //} + int endIndex; int offsetEndIndex = 0; - for (int e = 0; e < seq.length(); e++) { - endIndex = alignment.getIndexInTargetForQueryAt(proteinIndex + seq.length() - 1 - e); - if (endIndex != null) { - endIndex = endIndex + 1; - offsetEndIndex = e; - break; - } - } - - proteinIndex = proteinIndex + seq.length(); - if (startIndex != null && endIndex != null && startIndex != endIndex) { +// for (int e = 0; e < seqLen; e++) { + endIndex = alignment.getIndexInTargetForQueryAt(proteinIndex + seqLen - 1); + endIndex = endIndex + 1; +// offsetEndIndex = 0; +// } + + proteinIndex = proteinIndex + seqLen; + if (startIndex != endIndex) { CDSSequence cdsSequence = cdsSequenceList.get(i); - String hitLabel = ""; + String hitLabel; if (transcriptSequence.getStrand() == Strand.POSITIVE) { hitLabel = uniprotBestHit + "_" + startIndex + "_" + endIndex; } else { @@ -160,19 +164,20 @@ PairwiseSequenceAlignerType.LOCAL, new SimpleGapPenalty(), FeaturesKeyWordInterface featureKeyWords = proteinSequence.getFeaturesKeyWord(); String notes = ""; if (featureKeyWords != null) { - ArrayList keyWords = featureKeyWords.getKeyWords(); + List keyWords = featureKeyWords.getKeyWords(); if (keyWords.size() > 0) { notes = ";Note="; for (String note : keyWords) { - if (note.equals("Complete proteome")) { - continue; - } - if (note.equals("Direct protein sequencing")) { - continue; - } + switch (note) { + case "Complete proteome": + case "Direct protein sequencing": + continue; + default: + notes = notes + " " + note; + geneSequence.addNote(note); // add note/keyword which can be output in fasta header if needed + break; - notes = notes + " " + note; - geneSequence.addNote(note); // add note/keyword which can be output in fasta header if needed + } } } @@ -180,7 +185,7 @@ PairwiseSequenceAlignerType.LOCAL, new SimpleGapPenalty(), DatabaseReferenceInterface databaseReferences = proteinSequence.getDatabaseReferences(); if (databaseReferences != null) { - LinkedHashMap> databaseReferenceHashMap = databaseReferences.getDatabaseReferences(); + Map> databaseReferenceHashMap = databaseReferences.getDatabaseReferences(); ArrayList pfamList = databaseReferenceHashMap.get("Pfam"); ArrayList cazyList = databaseReferenceHashMap.get("CAZy"); ArrayList goList = databaseReferenceHashMap.get("GO"); @@ -227,15 +232,14 @@ PairwiseSequenceAlignerType.LOCAL, new SimpleGapPenalty(), notes = notes + " " + note.getId(); geneSequence.addNote(note.getId()); // add note/keyword which can be output in fasta header if needed LinkedHashMap properties = note.getProperties(); - for (String propertytype : properties.keySet()) { - if (propertytype.equals("evidence")) { + for (Map.Entry entry : properties.entrySet()) { + if (entry.getKey().equals("evidence")) continue; - } - String property = properties.get(propertytype); - if (property.startsWith("C:")) { + String property = entry.getValue(); + if (property.startsWith("C:")) continue; // skip over the location - } + if (property.endsWith("...")) { property = property.substring(0, property.length() - 3); } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/AbstractFastqReader.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/AbstractFastqReader.java index 17ca61205c..3fe2767711 100755 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/AbstractFastqReader.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/AbstractFastqReader.java @@ -26,7 +26,7 @@ import java.io.*; import java.net.URL; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.List; /** @@ -100,7 +100,7 @@ public final Iterable read(final URL url) throws IOException Collect collect = new Collect(); try { - reader = Resources.asCharSource(url, Charset.forName("UTF-8")).openBufferedStream(); + reader = Resources.asCharSource(url, StandardCharsets.UTF_8).openBufferedStream(); stream(reader, collect); } finally diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/AbstractFastqWriter.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/AbstractFastqWriter.java index 5df7443995..305977f633 100755 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/AbstractFastqWriter.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/AbstractFastqWriter.java @@ -20,14 +20,7 @@ */ package org.biojava.nbio.genome.io.fastq; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; - +import java.io.*; import java.util.Arrays; /** @@ -100,27 +93,11 @@ public final void write(final File file, final Iterable fastq) throws IOE { throw new IllegalArgumentException("fastq must not be null"); } - Writer writer = null; - try - { - writer = new BufferedWriter(new FileWriter(file)); - append(writer, fastq); - } - finally - { - if (writer != null) - { - try - { - writer.close(); - } - catch (IOException e) - { - // ignore - } - } - } - } + try (Writer writer = new BufferedWriter(new FileWriter(file))) { + append(writer, fastq); + } + // ignore + } @Override public final void write(final OutputStream outputStream, final Fastq... fastq) throws IOException diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/Fastq.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/Fastq.java index 2de9e05713..75fb3d4054 100755 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/Fastq.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/Fastq.java @@ -141,7 +141,7 @@ public Fastq convertTo(final FastqVariant variant) * * @return a new FastqBuilder */ - public static final FastqBuilder builder() + public static FastqBuilder builder() { return new FastqBuilder(); } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqParser.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqParser.java index 52f5141df2..1ba652c669 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqParser.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqParser.java @@ -63,7 +63,7 @@ static void parse(final Readable readable, final ParseListener listener) /** * FASTQ formatted sequence parser line processor. */ - private static final class FastqParserLineProcessor implements LineProcessor + private static final class FastqParserLineProcessor implements LineProcessor { /** Parser state. */ private State state = State.DESCRIPTION; @@ -114,22 +114,22 @@ private void setState(final State state) } @Override - public Object getResult() + public Void getResult() { return null; } @Override - public boolean processLine(final String line) throws IOException + public boolean processLine(String line) throws IOException { - String sequence = null; - String quality = null; + line = line.trim(); + switch (state) { case DESCRIPTION: if (line.startsWith("@")) { - listener.description(line.substring(1).trim()); + listener.description(line.substring(1)); state = State.SEQUENCE; } else @@ -138,28 +138,25 @@ public boolean processLine(final String line) throws IOException } break; case SEQUENCE: - sequence = line.trim(); - listener.sequence(sequence); - sequenceLength = sequence.length(); + listener.sequence(line); + sequenceLength = line.length(); state = State.REPEAT_DESCRIPTION; break; case REPEAT_DESCRIPTION: if (line.startsWith("+")) { - listener.repeatDescription(line.substring(1).trim()); + listener.repeatDescription(line.substring(1)); state = State.QUALITY; } else { - sequence = line.trim(); - listener.appendSequence(sequence); - sequenceLength += sequence.length(); + listener.appendSequence(line); + sequenceLength += line.length(); } break; case QUALITY: - quality = line.trim(); - listener.quality(quality); - qualityLength = quality.length(); + listener.quality(line); + qualityLength = line.length(); state = State.COMPLETE; break; case COMPLETE: @@ -169,7 +166,7 @@ public boolean processLine(final String line) throws IOException if (line.startsWith("@")) { - listener.description(line.substring(1).trim()); + listener.description(line.substring(1)); state = State.SEQUENCE; } else @@ -179,9 +176,8 @@ public boolean processLine(final String line) throws IOException } else { - quality = line.trim(); - listener.appendQuality(quality); - qualityLength += quality.length(); + listener.appendQuality(line); + qualityLength += line.length(); } break; default: @@ -192,7 +188,7 @@ public boolean processLine(final String line) throws IOException } /** Parser state. */ - private static enum State + private enum State { /** Description parser state. */ DESCRIPTION, @@ -207,6 +203,6 @@ private static enum State QUALITY, /** Complete parser state. */ - COMPLETE; - }; + COMPLETE + } } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqTools.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqTools.java index 437d7bd435..78191a7655 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqTools.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqTools.java @@ -133,7 +133,7 @@ public static QualityFeature, NucleotideCom { throw new IllegalArgumentException("fastq must not be null"); } - QualityFeature, NucleotideCompound> qualityScores = new QualityFeature, NucleotideCompound>("qualityScores", "sequencing"); + QualityFeature, NucleotideCompound> qualityScores = new QualityFeature<>("qualityScores", "sequencing"); qualityScores.setQualities(toList(qualityScores(fastq))); return qualityScores; } @@ -153,7 +153,7 @@ public static QuantityFeature, NucleotideCo { throw new IllegalArgumentException("fastq must not be null"); } - QuantityFeature, NucleotideCompound> errorProbabilities = new QuantityFeature, NucleotideCompound>("errorProbabilities", "sequencing"); + QuantityFeature, NucleotideCompound> errorProbabilities = new QuantityFeature<>("errorProbabilities", "sequencing"); errorProbabilities.setQuantities(toList(errorProbabilities(fastq))); return errorProbabilities; } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqVariant.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqVariant.java index efffbf4f78..8df5972166 100755 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqVariant.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqVariant.java @@ -186,7 +186,7 @@ public double errorProbability(final int qualityScore) /** Map of FASTQ sequence format variants keyed by name and lowercase-with-dashes name. */ - private static final Map FASTQ_VARIANTS = new HashMap(6); + private static final Map FASTQ_VARIANTS = new HashMap<>(6); static { @@ -206,7 +206,7 @@ public double errorProbability(final int qualityScore) * * @param description description of this FASTQ sequence format variant, must not be null */ - private FastqVariant(final String description) + FastqVariant(final String description) { if (description == null) { diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/ParseListener.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/ParseListener.java index f03f77fc92..14890b9ead 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/ParseListener.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/ParseListener.java @@ -33,9 +33,8 @@ public interface ParseListener * Notify this parse listener of a description line. * * @param description description line - * @throws IOException if an I/O error occurs - */ - void description(String description) throws IOException; + */ + void description(String description); /** * Notify this parse listener of a sequence line. @@ -47,9 +46,8 @@ public interface ParseListener *

    * * @param sequence sequence line - * @throws IOException if an I/O error occurs - */ - void sequence(String sequence) throws IOException; + */ + void sequence(String sequence); /** * Notify this parse listener of an additional sequence line. @@ -60,9 +58,8 @@ public interface ParseListener *

    * * @param sequence additional sequence line - * @throws IOException if an I/O error occurs - */ - void appendSequence(String sequence) throws IOException; + */ + void appendSequence(String sequence); /** * Notify this parse listener of a repeat description line. diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/StreamingFastqParser.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/StreamingFastqParser.java index a0455381ed..c22db24fc7 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/StreamingFastqParser.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/StreamingFastqParser.java @@ -58,20 +58,17 @@ static void stream(final Readable readable, final FastqVariant variant, final St FastqParser.parse(readable, new ParseListener() { @Override - public void description(final String description) throws IOException - { + public void description(final String description) { builder.withDescription(description); } @Override - public void sequence(final String sequence) throws IOException - { + public void sequence(final String sequence) { builder.withSequence(sequence); } @Override - public void appendSequence(final String sequence) throws IOException - { + public void appendSequence(final String sequence) { builder.appendSequence(sequence); } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/cytoband/CytobandParser.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/cytoband/CytobandParser.java index 560566b0b2..5655976e2f 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/cytoband/CytobandParser.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/cytoband/CytobandParser.java @@ -52,11 +52,10 @@ public static void main(String[] args) { try { SortedSet cytobands = me.getAllCytobands(new URL( DEFAULT_LOCATION)); - SortedSet types = new TreeSet(); + SortedSet types = new TreeSet<>(); for (Cytoband c : cytobands) { logger.info("Cytoband: {}", c); - if (!types.contains(c.getType())) - types.add(c.getType()); + types.add(c.getType()); } logger.info("Strain Type: {}", types); } catch (Exception e) { @@ -76,8 +75,8 @@ public SortedSet getAllCytobands(InputStream instream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader( instream)); - String line = null; - SortedSet cytobands = new TreeSet(); + String line; + SortedSet cytobands = new TreeSet<>(); while ((line = reader.readLine()) != null) { String[] spl = line.split("\t"); if (spl.length != 5) { diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/geneid/GeneIDXMLReader.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/geneid/GeneIDXMLReader.java index a573a7062d..d2559768bf 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/geneid/GeneIDXMLReader.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/geneid/GeneIDXMLReader.java @@ -31,8 +31,8 @@ import org.w3c.dom.Element; import java.io.File; -import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.List; /** * @@ -42,7 +42,7 @@ public class GeneIDXMLReader { private static final Logger logger = LoggerFactory.getLogger(GeneIDXMLReader.class); - Document geneidDoc = null; + Document geneidDoc; public GeneIDXMLReader(String geneidXMLFile) throws Exception { logger.info("Start read of {}", geneidXMLFile); @@ -51,8 +51,8 @@ public GeneIDXMLReader(String geneidXMLFile) throws Exception { } public LinkedHashMap getProteinSequences() throws Exception { - LinkedHashMap proteinSequenceList = new LinkedHashMap(); - ArrayList elementList = XMLHelper.selectElements(geneidDoc.getDocumentElement(), "prediction/gene/protein"); + LinkedHashMap proteinSequenceList = new LinkedHashMap<>(); + List elementList = XMLHelper.selectElements(geneidDoc.getDocumentElement(), "prediction/gene/protein"); logger.info("{} hits", elementList.size()); for (Element proteinElement : elementList) { @@ -68,11 +68,9 @@ public LinkedHashMap getProteinSequences() throws Excep } public LinkedHashMap getDNACodingSequences() throws Exception { - LinkedHashMap dnaSequenceList = new LinkedHashMap(); - ArrayList elementList = XMLHelper.selectElements(geneidDoc.getDocumentElement(), "prediction/gene/cDNA"); - logger.info("{} hits", elementList.size()); + LinkedHashMap dnaSequenceList = new LinkedHashMap<>(); - for (Element dnaElement : elementList) { + for (Element dnaElement : XMLHelper.selectElements(geneidDoc.getDocumentElement(), "prediction/gene/cDNA")) { Element geneElement = (Element) dnaElement.getParentNode(); String sequence = dnaElement.getTextContent().replaceAll("\\W",""); DNASequence dnaSequence = new DNASequence(sequence); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneChromosomePositionParser.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneChromosomePositionParser.java index df6a1a4373..eb6d9682c6 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneChromosomePositionParser.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneChromosomePositionParser.java @@ -23,8 +23,8 @@ package org.biojava.nbio.genome.parsers.genename; -import org.biojava.nbio.genome.App; import org.biojava.nbio.core.util.InputStreamProvider; +import org.biojava.nbio.genome.App; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -66,22 +66,15 @@ public static void main(String[] args){ } public static List getChromosomeMappings() throws IOException { - - URL url = new URL(DEFAULT_MAPPING_URL); - - InputStreamProvider prov = new InputStreamProvider(); - - InputStream inStream = prov.getInputStream(url); - - return getChromosomeMappings(inStream); + return getChromosomeMappings(new InputStreamProvider().getInputStream(new URL(DEFAULT_MAPPING_URL))); } public static List getChromosomeMappings(InputStream inStream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); - ArrayList gcps = new ArrayList(); + ArrayList gcps = new ArrayList<>(1024); - String line = null; + String line; while ((line = reader.readLine()) != null) { GeneChromosomePosition gcp = getGeneChromosomePosition(line); if ( gcp != null) @@ -94,8 +87,7 @@ public static List getChromosomeMappings(InputStream inS } private static GeneChromosomePosition getGeneChromosomePosition(String line) { - if ( line == null) - return null; + String[] spl = line.split("\t"); if ( spl.length != 11) { @@ -114,10 +106,8 @@ private static GeneChromosomePosition getGeneChromosomePosition(String line) { g.setCdsStart(Integer.parseInt(spl[6])); g.setCdsEnd(Integer.parseInt(spl[7])); g.setExonCount(Integer.parseInt(spl[8])); - String exonStarts = spl[9]; - String exonEnds = spl[10]; - g.setExonStarts(getIntegerList(exonStarts)); - g.setExonEnds(getIntegerList(exonEnds)); + g.setExonStarts(getIntegerList(spl[9])); + g.setExonEnds(getIntegerList(spl[10])); //System.out.println(line); //System.out.println(Arrays.asList(spl) + " " + spl.length); @@ -126,7 +116,7 @@ private static GeneChromosomePosition getGeneChromosomePosition(String line) { private static List getIntegerList(String lst){ String[] spl = lst.split(","); - ArrayList l = new ArrayList(); + ArrayList l = new ArrayList<>(); for (String s : spl){ l.add(Integer.parseInt(s)); } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneNamesParser.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneNamesParser.java index e9158c015a..1e13df5107 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneNamesParser.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneNamesParser.java @@ -92,7 +92,7 @@ public static List getGeneNames() throws IOException{ */ public static List getGeneNames(InputStream inStream) throws IOException{ - ArrayList geneNames = new ArrayList(); + ArrayList geneNames = new ArrayList<>(); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); // skip reading first line (it is the legend) diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Feature.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Feature.java index 9d750f850e..7457f7048d 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Feature.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Feature.java @@ -51,8 +51,6 @@ public String seqname() { return mSeqname; } - ; - /** * Get source (aka method). (GFF field 2). This is often the name of * the program or procedure that created the features. @@ -63,8 +61,6 @@ public String source() { return mSource; } - ; - /** * Get feature type, such as "exon" or "CDS". (GFF field 3). * @@ -75,8 +71,6 @@ public String type() { return mType; } - ; - /** * Get location of feature. Note that feature objects have * no link or reference to the actual sequence object to which @@ -98,8 +92,6 @@ public double score() { return mScore; } - ; - /** * Get frame (aka phase). (GFF field 8). Specifies the offset of the * first nucleotide of the first in-frame codon, assuming this feature @@ -113,8 +105,6 @@ public int frame() { return mFrame; } - ; - /** * Get the string of key/value attributes. (GFF field 9). The format and * meaning of this field varies from flavor to flavor of GFF/GTF. This method @@ -127,13 +117,11 @@ public String attributes() { return mAttributes; } - ; - @SuppressWarnings("unused") private Feature() { } - ; //unavailable + //unavailable /** * Make a copy of the specified feature. The mappings in the userMap() HashMap @@ -153,7 +141,7 @@ public Feature(Feature feature) { mFrame = feature.mFrame; mAttributes = feature.mAttributes; initAttributeHashMap(); - mUserMap = new HashMap(feature.mUserMap); + mUserMap = new HashMap<>(feature.mUserMap); } /** @@ -177,7 +165,7 @@ public Feature(String seqname, String source, String type, Location location, Do mFrame = frame; mAttributes = attributes; initAttributeHashMap(); - mUserMap = new HashMap(); + mUserMap = new HashMap<>(); } @@ -199,13 +187,13 @@ public HashMap userData() { return mUserMap; } - HashMap attributeHashMap = new HashMap(); + final HashMap attributeHashMap = new HashMap<>(); private void initAttributeHashMap(){ String[] values = mAttributes.split(";"); for(String attribute : values){ attribute = attribute.trim(); - int equalindex = attribute.indexOf("="); + int equalindex = attribute.indexOf('='); String splitData = "="; if(equalindex == -1) //gtf uses space and gff3 uses = splitData = " "; @@ -300,7 +288,7 @@ public String toString() { s += mType + '\t'; s += mLocation.start() + "\t"; s += mLocation.end() + "\t"; - s += Double.toString(mScore) + "\t"; + s += mScore + "\t"; if (mFrame == -1) { s += ".\t"; diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureHelper.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureHelper.java index 1383276ce2..bcdc0bc32b 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureHelper.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureHelper.java @@ -38,7 +38,7 @@ public class FeatureHelper { */ static public LinkedHashMap buildFeatureAtrributeIndex(String attribute,FeatureList list){ - LinkedHashMap featureHashMap = new LinkedHashMap(); + LinkedHashMap featureHashMap = new LinkedHashMap<>(); FeatureList featureList = list.selectByAttribute(attribute); for(FeatureI feature : featureList){ String value = feature.getAttribute(attribute); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureI.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureI.java index 9fa7c02061..0e9c35359e 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureI.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureI.java @@ -36,7 +36,7 @@ public interface FeatureI * * @return The location. */ - public Location location(); + Location location(); /** * Get the group id of the feature. The group id is defined in the GFF1 @@ -50,21 +50,21 @@ public interface FeatureI * * @return The group id. This may be an empty string. */ - public String group(); + String group(); /** * Get the feature type, for example, "exon", "CDS", etc. * * @return The type. */ - public String type(); + String type(); /** * Get the sequence name. * * @return Sequence name. */ - public String seqname(); + String seqname(); /** * Get the attribute value for this key. @@ -72,7 +72,7 @@ public interface FeatureI * @param key The key. * @return The corresponding value. Null if the key has no value defined . */ - public String getAttribute( String key ); + String getAttribute(String key); /** @@ -81,7 +81,7 @@ public interface FeatureI * @param key The key. * @return True if a value is defined for this key. */ - public boolean hasAttribute( String key ); + boolean hasAttribute(String key); /** * Check if the feature attributes include the specified key/value pair. @@ -90,7 +90,7 @@ public interface FeatureI * @param value The value. * @return True if the feature's value for this key matches the specified value. */ - public boolean hasAttribute( String key, String value ); + boolean hasAttribute(String key, String value); /** * A string representation of the feature. @@ -98,15 +98,15 @@ public interface FeatureI * @return The string. */ @Override - public String toString(); + String toString(); /** * Get HashMap of user data. * * @return The user HashMap. */ - public HashMap userData(); + HashMap userData(); - public HashMap getAttributes(); + HashMap getAttributes(); } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureList.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureList.java index 19b7afec93..45aac4219c 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureList.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureList.java @@ -40,7 +40,7 @@ @SuppressWarnings("serial") public class FeatureList extends ArrayList { - Map>> featindex = new HashMap>>(); + final Map>> featindex = new HashMap<>(); Location mLocation; //genomic location (union of feature locations) /** @@ -81,11 +81,11 @@ public boolean add(FeatureI feature) { if (featindex.containsKey(entry.getKey())){ Map> feat = featindex.get(entry.getKey()); if (feat==null){ - feat= new HashMap>(); + feat= new HashMap<>(); } List features = feat.get(entry.getValue()); if (features==null){ - features = new ArrayList(); + features = new ArrayList<>(); } features.add(feature); feat.put(entry.getValue(), features); @@ -103,9 +103,7 @@ public boolean add(FeatureI feature) { * @param list The collection of FeatureI objects. */ public void add(Collection list) { - for (FeatureI f : list) { - add(f); - } + this.addAll(list); } /** @@ -185,7 +183,7 @@ public String splice(DNASequence sequence) { * the order of features in the list. */ public Collection groupValues() { - Set set = new HashSet(); + Set set = new HashSet<>(); for (FeatureI f : this) { //enter in a set -- removes duplicates set.add(f.group()); @@ -207,10 +205,10 @@ public Collection attributeValues(String key) { if (featindex.containsKey(key)){ Map> map = featindex.get(key); Collection result = map.keySet(); - if (result == null) result = new HashSet(); + if (result == null) result = new HashSet<>(); return Collections.unmodifiableCollection(result); } - LinkedHashMap hash = new LinkedHashMap(); + LinkedHashMap hash = new LinkedHashMap<>(); for (FeatureI f : this) { //enter as a key -- removes duplicates hash.put(f.getAttribute(key), null); @@ -353,8 +351,7 @@ public FeatureList selectByUserData(String key) { * on the same strand as the specified location will be considered for inclusion. * @return The new list of features that overlap the location. */ - public FeatureList selectOverlapping(String seqname, Location location, boolean useBothStrands) - throws Exception { + public FeatureList selectOverlapping(String seqname, Location location, boolean useBothStrands) { FeatureList list = new FeatureList(); for (FeatureI feature : this) { @@ -458,7 +455,7 @@ public boolean hasAttribute(String key, String value) { public String toString() { StringBuilder s = new StringBuilder("FeatureList: >>\n"); for (FeatureI f : this) { - s.append( f.seqname() + ":" + f.toString() + "\n"); + s.append(f.seqname()).append(":").append(f.toString()).append("\n"); } s.append("\n<<\n"); @@ -468,7 +465,7 @@ public String toString() { /** * used by sort routine */ - private class FeatureComparator implements Comparator, Serializable { + private static class FeatureComparator implements Comparator, Serializable { private static final long serialVersionUID = 1; @Override diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GFF3Reader.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GFF3Reader.java index a0f5b573f8..049dc68a55 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GFF3Reader.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GFF3Reader.java @@ -100,7 +100,7 @@ public static FeatureList read(String filename, List indexes) throws IOE public static FeatureList read(String filename) throws IOException { - return read(filename,new ArrayList(0)); + return read(filename, new ArrayList<>(0)); } @@ -122,7 +122,7 @@ private static Feature parseLine(String s) { String locEnd =line[4].trim(); - Double score; + double score; try { score = Double.parseDouble(line[5].trim()); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GFF3Writer.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GFF3Writer.java index c4bc070f21..9f1df17ea1 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GFF3Writer.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GFF3Writer.java @@ -20,15 +20,15 @@ */ package org.biojava.nbio.genome.parsers.gff; -import org.biojava.nbio.genome.GeneFeatureHelper; import org.biojava.nbio.core.sequence.*; +import org.biojava.nbio.genome.GeneFeatureHelper; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.ArrayList; -import java.util.Collections; import java.util.LinkedHashMap; +import java.util.Map; /** * @@ -45,9 +45,10 @@ public class GFF3Writer { public void write(OutputStream outputStream, LinkedHashMap chromosomeSequenceList) throws Exception { outputStream.write("##gff-version 3\n".getBytes()); - for (String key : chromosomeSequenceList.keySet()) { - ChromosomeSequence chromosomeSequence = chromosomeSequenceList.get(key); - String gff3line = ""; + for (Map.Entry entry : chromosomeSequenceList.entrySet()) { + String key = entry.getKey(); + ChromosomeSequence chromosomeSequence = entry.getValue(); + String gff3line; // if(source.length() == 0){ // Collection genes = chromosomeSequence.getGeneSequences().values(); // for(GeneSequence gene : genes){ @@ -94,8 +95,8 @@ public void write(OutputStream outputStream, LinkedHashMap cdsSequenceList = new ArrayList(transcriptSequence.getCDSSequences().values()); - Collections.sort(cdsSequenceList, new SequenceComparator()); + ArrayList cdsSequenceList = new ArrayList<>(transcriptSequence.getCDSSequences().values()); + cdsSequenceList.sort(new SequenceComparator()); for (CDSSequence cdsSequence : cdsSequenceList) { gff3line = key + "\t" + cdsSequence.getSource() + "\t" + "CDS" + "\t" + cdsSequence.getBioBegin() + "\t" + cdsSequence.getBioEnd() + "\t"; score = cdsSequence.getSequenceScore(); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GeneIDGFF2Reader.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GeneIDGFF2Reader.java index c7f59de102..2b8851c311 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GeneIDGFF2Reader.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GeneIDGFF2Reader.java @@ -24,7 +24,6 @@ import org.slf4j.LoggerFactory; import java.io.*; -import java.util.ListIterator; /** * http://www.bioperl.org/wiki/GTF @@ -93,7 +92,7 @@ private static Feature parseLine(String s) { //FIXME update to use regex split on tabs //FIXME better errors on parse failures - int start = 0; + int start; int end = 0; start = end; @@ -116,7 +115,7 @@ private static Feature parseLine(String s) { end = s.indexOf('\t', start); String locEnd = s.substring(start, end); - Double score; + double score; start = end + 1; end = s.indexOf('\t', start); try { @@ -145,11 +144,11 @@ private static Feature parseLine(String s) { //grab everything until end of line (or # comment) start = end + 1; end = s.indexOf('#', start); - String attributes = null; + String attributes; if (end < 0) { - attributes = new String(s.substring(start)); + attributes = s.substring(start); } else { - attributes = new String(s.substring(start, end)); + attributes = s.substring(start, end); } //need to add in attribute assignment for geneid where it just provides a gene name and will make it gtf like attributes = "gene_id " + '"' + attributes + '"' + ";"; @@ -170,9 +169,8 @@ public static void write(FeatureList features, String filename) throws IOExcepti BufferedWriter bw = new BufferedWriter(new FileWriter(filename)); - ListIterator iter = features.listIterator(); - while (iter.hasNext()) { - Feature feature = (Feature) iter.next(); + for (FeatureI featureI : features) { + Feature feature = (Feature) featureI; writeLine(feature, bw); } @@ -186,7 +184,7 @@ private static void writeLine(Feature f, BufferedWriter bw) throws IOException { s += f.location().bioStart() + "\t"; s += f.location().bioEnd() + "\t"; - s += Double.toString(f.score()) + "\t"; + s += f.score() + "\t"; s += f.location().bioStrand() + "\t"; if (f.frame() == -1) { diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GeneMarkGTFReader.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GeneMarkGTFReader.java index 8f0f53b026..c0c191d07a 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GeneMarkGTFReader.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GeneMarkGTFReader.java @@ -93,7 +93,7 @@ public static FeatureList read(String filename) throws IOException { private static Feature parseLine(String s) { //FIXME update to use regex split on tabs //FIXME better errors on parse failures - int start = 0; + int start; int end = 0; start = end; @@ -116,7 +116,7 @@ private static Feature parseLine(String s) { end = s.indexOf('\t', start); String locEnd = s.substring(start, end); - Double score; + double score; start = end + 1; end = s.indexOf('\t', start); try { @@ -145,11 +145,11 @@ private static Feature parseLine(String s) { //grab everything until end of line (or # comment) start = end + 1; end = s.indexOf('#', start); - String attributes = null; + String attributes; if (end < 0) { - attributes = new String(s.substring(start)); + attributes = s.substring(start); } else { - attributes = new String(s.substring(start, end)); + attributes = s.substring(start, end); } return new Feature(seqname, source, type, location, score, frame, attributes); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/LocIterator.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/LocIterator.java index c8ffd98974..06c94a92d6 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/LocIterator.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/LocIterator.java @@ -44,9 +44,9 @@ public class LocIterator implements Iterator { int mIncrement; @SuppressWarnings("unused") - private LocIterator() {}; + private LocIterator() {} - /** + /** * Construct an iterator that slides a window over a Location. * * @param bounds The location over which to iterate. @@ -138,7 +138,7 @@ public boolean hasNext() */ public Location remainder() { - Location remainder= null; + Location remainder; if( mPosition == 0 ) { diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Location.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Location.java index 91e71463f8..43463b92fb 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Location.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Location.java @@ -69,8 +69,8 @@ public class Location implements Iterable { - private int mStart; - private int mEnd; + private final int mStart; + private final int mEnd; /** @@ -267,8 +267,8 @@ public Location union( Location other ) } else { - int start= (other.mStart < mStart)? other.mStart: mStart; - int end= (other.mEnd > mEnd)? other.mEnd: mEnd; + int start= Math.min(other.mStart, mStart); + int end= Math.max(other.mEnd, mEnd); return new Location( start, end ); } @@ -368,15 +368,7 @@ public Iterable window( final int windowSize, final int increment ) final Location loc= this; //return iterable anonymous inner class - return new Iterable () - { - @Override - public LocIterator iterator() - { - return new LocIterator( loc, windowSize, increment ); - } - - }; + return () -> new LocIterator( loc, windowSize, increment ); } /** @@ -503,7 +495,7 @@ public Location prefix( Location other ) { if( other.mStart >= mStart ) { - return new Location( mStart, (other.mStart < mEnd)? other.mStart: mEnd ); + return new Location( mStart, Math.min(other.mStart, mEnd)); } else { @@ -531,7 +523,7 @@ public Location suffix( Location other ) { if( other.mEnd <= mEnd ) { - return new Location( (other.mEnd > mStart)? other.mEnd: mStart, mEnd ); + return new Location(Math.max(other.mEnd, mStart), mEnd ); } else { @@ -843,7 +835,7 @@ public boolean isSameStrand( Location other ) @Override public String toString() { - return new String( "[L=" + (mEnd - mStart) + "; S=" + mStart + "; E=" + mEnd +"]" ); + return "[L=" + (mEnd - mStart) + "; S=" + mStart + "; E=" + mEnd + "]"; } /* (non-Javadoc) @@ -865,24 +857,17 @@ public int hashCode() { public boolean equals(Object obj) { if (this == obj) return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) + if (obj == null || getClass() != obj.getClass()) return false; Location other = (Location) obj; - if (mEnd != other.mEnd) - return false; - if (mStart != other.mStart) - return false; - return true; + return mStart == other.mStart && mEnd == other.mEnd; } /** * */ - private boolean isHealthy() - { - return ( mStart <= mEnd ) && (( mStart <= 0 && mEnd <= 0 ) || (mStart >= 0 && mEnd >= 0)); + private boolean isHealthy() { + return ( mStart <= mEnd ) && (( mStart <= 0 && mEnd <= 0 ) || (mStart >= 0 /*&& mEnd >= 0*/)); } } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/TwoBitFacade.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/TwoBitFacade.java index 71dfc4174f..f90b33d4f2 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/TwoBitFacade.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/TwoBitFacade.java @@ -28,7 +28,7 @@ */ public class TwoBitFacade { - private TwoBitParser twoBitParser = null; + private final TwoBitParser twoBitParser; /** @@ -43,7 +43,7 @@ public TwoBitFacade(File file) throws Exception { /** * Closes .2bit file twoBitParser. */ - public void close() throws Exception { + public void close() { if (twoBitParser != null) twoBitParser.close(); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/TwoBitParser.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/TwoBitParser.java index 4f5733037d..9e74f1dda8 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/TwoBitParser.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/TwoBitParser.java @@ -46,13 +46,13 @@ public class TwoBitParser extends InputStream { private static final Logger logger = LoggerFactory.getLogger(TwoBitParser.class); - public int DEFAULT_BUFFER_SIZE = 10000; + public final int DEFAULT_BUFFER_SIZE = 10000; // - private RandomAccessFile raf; - private File f; + private final RandomAccessFile raf; + private final File f; private boolean reverse = false; - private String[] seq_names; - private HashMap seq2pos = new HashMap(); + private final String[] seq_names; + private final HashMap seq2pos = new HashMap<>(); private String cur_seq_name; private long[][] cur_nn_blocks; private long[][] cur_mask_blocks; @@ -98,7 +98,7 @@ else if(sign==0x4327411A) { } } private long readFourBytes() throws Exception { - long ret = 0; + long ret; if(!reverse) { ret = raf.read(); ret += raf.read()*0x100; @@ -170,7 +170,7 @@ public void setCurrentSequence(String seq_name) throws Exception { * Method resets current position to the begining of sequence stream. */ @Override - public synchronized void reset() throws IOException { + public synchronized void reset() { cur_seq_pos = 0; cur_nn_block_num = (cur_nn_blocks.length>0)?0:-1; cur_mask_block_num = (cur_mask_blocks.length>0)?0:-1; @@ -228,7 +228,7 @@ public int read() throws IOException { else if(bit_num==3) { file_pos++; } - char ret = 'N'; + char ret; if((cur_nn_block_num>=0)&& (cur_nn_blocks[cur_nn_block_num][0]<=cur_seq_pos)) { if(cur_bits[bit_num]!=0) { @@ -297,7 +297,7 @@ public synchronized long skip(long n) throws IOException { * new current sequence. */ @Override - public void close() throws IOException { + public void close() { cur_seq_name = null; cur_nn_blocks = null; cur_mask_blocks = null; diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/query/BlastXMLQuery.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/query/BlastXMLQuery.java index ff5e1318d0..241eb19df7 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/query/BlastXMLQuery.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/query/BlastXMLQuery.java @@ -29,6 +29,7 @@ import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.List; /** * @@ -38,7 +39,7 @@ public class BlastXMLQuery { private static final Logger logger = LoggerFactory.getLogger(BlastXMLQuery.class); - Document blastDoc = null; + Document blastDoc; public BlastXMLQuery(String blastFile) throws Exception { logger.info("Start read of {}", blastFile); @@ -47,31 +48,27 @@ public BlastXMLQuery(String blastFile) throws Exception { } public LinkedHashMap> getHitsQueryDef(double maxEScore) throws Exception { - LinkedHashMap> hitsHashMap = new LinkedHashMap>(); + LinkedHashMap> hitsHashMap = new LinkedHashMap<>(); logger.info("Query for hits"); - ArrayList elementList = XMLHelper.selectElements(blastDoc.getDocumentElement(), "BlastOutput_iterations/Iteration[Iteration_hits]"); + List elementList = XMLHelper.selectElements(blastDoc.getDocumentElement(), "BlastOutput_iterations/Iteration[Iteration_hits]"); logger.info("{} hits", elementList.size()); for (Element element : elementList) { Element iterationquerydefElement = XMLHelper.selectSingleElement(element, "Iteration_query-def"); String querydef = iterationquerydefElement.getTextContent(); Element iterationHitsElement = XMLHelper.selectSingleElement(element, "Iteration_hits"); - ArrayList hitList = XMLHelper.selectElements(iterationHitsElement, "Hit"); + List hitList = XMLHelper.selectElements(iterationHitsElement, "Hit"); for (Element hitElement : hitList) { Element hitaccessionElement = XMLHelper.selectSingleElement(hitElement, "Hit_accession"); String hitaccession = hitaccessionElement.getTextContent(); Element hithspsElement = XMLHelper.selectSingleElement(hitElement, "Hit_hsps"); - ArrayList hspList = XMLHelper.selectElements(hithspsElement, "Hsp"); + List hspList = XMLHelper.selectElements(hithspsElement, "Hsp"); for (Element hspElement : hspList) { Element evalueElement = XMLHelper.selectSingleElement(hspElement, "Hsp_evalue"); String value = evalueElement.getTextContent(); double evalue = Double.parseDouble(value); if (evalue <= maxEScore) { - ArrayList hits = hitsHashMap.get(querydef); - if (hits == null) { - hits = new ArrayList(); - hitsHashMap.put(querydef, hits); - } + ArrayList hits = hitsHashMap.computeIfAbsent(querydef, k -> new ArrayList<>()); hits.add(hitaccession); } } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/uniprot/UniprotToFasta.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/uniprot/UniprotToFasta.java index 66a9d2a086..2806e83d9d 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/uniprot/UniprotToFasta.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/uniprot/UniprotToFasta.java @@ -67,10 +67,10 @@ public void process( String uniprotDatFileName,String fastaFileName ) throws Exc String line = br.readLine(); String id = ""; StringBuffer sequence = new StringBuffer(); - ArrayList seqCodingRegionsList = new ArrayList(); + ArrayList seqCodingRegionsList = new ArrayList<>(); int count = 0; - HashMap uniqueGenes = new HashMap(); - HashMap uniqueSpecies = new HashMap(); + HashMap uniqueGenes = new HashMap<>(); + HashMap uniqueSpecies = new HashMap<>(); while(line != null){ if(line.startsWith("ID")){ String[] data = line.split(" "); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ChromosomeMappingTools.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ChromosomeMappingTools.java index a63a78a236..0c03ce9c2e 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ChromosomeMappingTools.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ChromosomeMappingTools.java @@ -49,10 +49,10 @@ public class ChromosomeMappingTools { public static final String CHROMOSOME = "CHROMOSOME"; public static final String CDS = "CDS"; - private static int base = 1; - public static void setCoordinateSystem(int baseInt) { - base = baseInt; - } +// private static final int base = 1; +// public static void setCoordinateSystem(int baseInt) { +// base = baseInt; +// } /** * Pretty print the details of a GeneChromosomePosition to a String @@ -100,7 +100,7 @@ private static String formatExonStructureForward(GeneChromosomePosition chromPos s.append(" <- Exon : ").append(format(start + 1)).append(" - ").append(format(cdsEnd)).append(" | ").append(Integer.toString(cdsEnd - start)).append(" | ").append(Integer.toString(codingLength)).append(" | ").append(Integer.toString(codingLength % 3)); s.append(newline); - s.append(" UTR : " + (cdsEnd +1) + " - " + format(end)); + s.append(" UTR : ").append(String.valueOf(cdsEnd + 1)).append(" - ").append(format(end)); s.append(newline); } else if (inCoding) { @@ -112,7 +112,7 @@ private static String formatExonStructureForward(GeneChromosomePosition chromPos } } s.append("Coding Length: "); - s.append((codingLength-3)+""); + s.append(String.valueOf(codingLength - 3)); s.append(newline); return s.toString(); } @@ -159,7 +159,7 @@ private static String formatExonStructureReverse(GeneChromosomePosition chromPos } codingLength += (cdsEnd - tmpstart); - s.append(" UTR :" + format(cdsEnd + 1) + " | " + format(end)); + s.append(" UTR :").append(format(cdsEnd + 1)).append(" | ").append(format(end)); s.append(newline); if (tmpstart == start) s.append(" -> "); @@ -169,16 +169,16 @@ private static String formatExonStructureReverse(GeneChromosomePosition chromPos s.append(newline); // single exon with UTR on both ends if (tmpstart != start) - s.append(" UTR :" + format(cdsStart ) + " - " + format(start + 1)); + s.append(" UTR :").append(format(cdsStart)).append(" - ").append(format(start + 1)); s.append(newline); } else if (start <= cdsStart && end >= cdsStart) { inCoding = false; codingLength += (end - cdsStart); - s.append(" <- Exon : " + format(cdsStart+1) + " - " + format(end) + " | " + (end - cdsStart) + " | " + codingLength + " | " + (codingLength % 3)); + s.append(" <- Exon : ").append(format(cdsStart + 1)).append(" - ").append(format(end)).append(" | ").append(String.valueOf(end - cdsStart)).append(" | ").append(String.valueOf(codingLength)).append(" | ").append(String.valueOf(codingLength % 3)); s.append(newline); - s.append(" UTR : " + format(start+1) + " - " + format(cdsStart )); + s.append(" UTR : ").append(format(start + 1)).append(" - ").append(format(cdsStart)); s.append(newline); @@ -186,7 +186,7 @@ private static String formatExonStructureReverse(GeneChromosomePosition chromPos // full exon is coding codingLength += (end - start); - s.append(" Exon : " + format(start+1) + " - " + format(end) + " | " + (end - start) + " | " + codingLength + " | " + (codingLength % 3)); + s.append(" Exon : ").append(format(start + 1)).append(" - ").append(format(end)).append(" | ").append(String.valueOf(end - start)).append(" | ").append(String.valueOf(codingLength)).append(" | ").append(String.valueOf(codingLength % 3)); s.append(newline); } else { // e.g. see UBQLN3 @@ -207,7 +207,7 @@ private static String formatExonStructureReverse(GeneChromosomePosition chromPos * @param chromPos * @return length of the CDS in nucleotides. */ - public static int getCDSLength(GeneChromosomePosition chromPos) { + public static int getCDSLength(GeneChromosomePosition chromPos, int base) { List exonStarts = chromPos.getExonStarts(); List exonEnds = chromPos.getExonEnds(); @@ -217,9 +217,9 @@ public static int getCDSLength(GeneChromosomePosition chromPos) { int codingLength; if (chromPos.getOrientation().equals('+')) - codingLength = ChromosomeMappingTools.getCDSLengthForward(exonStarts, exonEnds, cdsStart, cdsEnd); + codingLength = ChromosomeMappingTools.getCDSLengthForward(exonStarts, exonEnds, cdsStart, cdsEnd, base); else - codingLength = ChromosomeMappingTools.getCDSLengthReverse(exonStarts, exonEnds, cdsStart, cdsEnd); + codingLength = ChromosomeMappingTools.getCDSLengthReverse(exonStarts, exonEnds, cdsStart, cdsEnd, base); return codingLength; } @@ -242,7 +242,7 @@ public static ChromPos getChromosomePosForCDScoordinate(int cdsNucleotidePositio int cdsEnd = chromPos.getCdsEnd(); - ChromPos chromosomePos = null; + ChromPos chromosomePos; if (chromPos.getOrientation().equals('+')) @@ -333,18 +333,18 @@ public static ChromPos getChromPosReverse(int cdsPos, List exonStarts, if ( debug ) { - StringBuffer b = new StringBuffer(); + StringBuilder b = new StringBuilder(); - b.append(" UTR :" + format(cdsEnd + 1) + " - " + format(end) + newline); + b.append(" UTR :").append(format(cdsEnd + 1)).append(" - ").append(format(end)).append(newline); if (tmpstart == start) b.append(" -> "); else b.append(" <-> "); - b.append("Exon :" + format(tmpstart + 1) + " - " + (cdsEnd) + " | " + format(cdsEnd - tmpstart + 1) + " - " + codingLength + " | " + (codingLength % 3) + newline); + b.append("Exon :").append(format(tmpstart + 1)).append(" - ").append(cdsEnd).append(" | ").append(format(cdsEnd - tmpstart + 1)).append(" - ").append(codingLength).append(" | ").append(codingLength % 3).append(newline); // single exon with UTR on both ends if (tmpstart != start) - b.append(" UTR :" + format(cdsStart) + " - " + format(start + 1) + newline); + b.append(" UTR :").append(format(cdsStart)).append(" - ").append(format(start + 1)).append(newline); logger.debug(b.toString()); } @@ -498,7 +498,7 @@ public static ChromPos getChromPosForward(int cdsPos, List exonStarts, * @param cdsEnd * @return */ - public static int getCDSLengthReverse(List exonStarts, List exonEnds, int cdsStart, int cdsEnd) { + public static int getCDSLengthReverse(List exonStarts, List exonEnds, int cdsStart, int cdsEnd, int base) { int codingLength = 0; @@ -545,7 +545,7 @@ public static int getCDSLengthReverse(List exonStarts, List ex * @param cdsEnd * @return */ - public static int getCDSLengthForward(List exonStarts, List exonEnds, int cdsStart, int cdsEnd) { + public static int getCDSLengthForward(List exonStarts, List exonEnds, int cdsStart, int cdsEnd, int base) { int codingLength = 0; @@ -586,9 +586,9 @@ public static List> getCDSExonRanges(GeneChromosomePosition chrom * @return */ public static List> getChromosomalRangesForCDS(GeneChromosomePosition chromPos){ - if ( chromPos.getOrientation() == '+') - return getCDSExonRangesForward(chromPos,CHROMOSOME); - return getCDSExonRangesReverse(chromPos,CHROMOSOME); + return chromPos.getOrientation() == '+' ? + getCDSExonRangesForward(chromPos, CHROMOSOME) : + getCDSExonRangesReverse(chromPos, CHROMOSOME); } private static List> getCDSExonRangesReverse(GeneChromosomePosition chromPos, String responseType) { @@ -657,56 +657,46 @@ private static List> getCDSExonRangesReverse(GeneChromosomePositi } - Range r ; - if ( responseType.equals(CDS)) - r = Range.closed(0,codingLength); - else - r = Range.closed(tmpstart,cdsEnd); - data.add(r); + data.add(responseType.equals(CDS) ? + Range.closed(0, codingLength) : + Range.closed(tmpstart, cdsEnd)); } else if (start <= cdsStart && end >= cdsStart) { inCoding = false; - Range r; - if ( responseType.equals(CDS)) - r = Range.closed(codingLength,codingLength+(end-cdsStart)); - else - r = Range.closed(cdsStart+1,end); - - data.add(r); + data.add(responseType.equals(CDS) ? + Range.closed(codingLength, codingLength + (end - cdsStart)) : + Range.closed(cdsStart + 1, end)); codingLength += (end - cdsStart); if (debug) { - s.append(" <- Exon : " + format(cdsStart + 1) + " - " + format(end) + " | " + (end - cdsStart) + " | " + codingLength + " | " + (codingLength % 3)); + s.append(" <- Exon : ").append(format(cdsStart + 1)).append(" - ").append(format(end)).append(" | ").append(end - cdsStart).append(" | ").append(codingLength).append(" | ").append(codingLength % 3); s.append(newline); s.append(" UTR : ").append(format(start + 1)).append(" - ").append(format(cdsStart)); s.append(newline); } } else if (inCoding) { // full exon is coding - Range r; - if ( responseType.equals(CDS)) - r = Range.closed(codingLength,codingLength+(end-start)); - else - r = Range.closed(start,end); - data.add(r); + data.add(responseType.equals(CDS) ? + Range.closed(codingLength, codingLength + (end - start)) : + Range.closed(start, end)); codingLength += (end - start); if (debug) { - s.append(" Exon : " + format(start + 1) + " - " + format(end) + " | " + (end - start) + " | " + codingLength + " | " + (codingLength % 3)); + s.append(" Exon : ").append(format(start + 1)).append(" - ").append(format(end)).append(" | ").append(end - start).append(" | ").append(codingLength).append(" | ").append(codingLength % 3); s.append(newline); } } else { // e.g. see UBQLN3 if ( debug ) { - s.append(" no translation! UTR: " + format(start) + " - " + format(end)); + s.append(" no translation! UTR: ").append(format(start)).append(" - ").append(format(end)); s.append(newline); } } } if ( debug ) { - s.append("CDS length: ").append(Integer.toString(codingLength - 3)); + s.append("CDS length: ").append((codingLength - 3)); s.append(newline); logger.debug(s.toString()); } @@ -736,33 +726,24 @@ private static List> getCDSExonRangesForward(GeneChromosomePositi inCoding = true; codingLength += (end - cdsStart); - Range r; - if ( responseType.equals(CDS)) - r = Range.closed(0,codingLength); - else - r = Range.closed(cdsStart,end); - data.add(r); + data.add(responseType.equals(CDS) ? + Range.closed(0, codingLength) : + Range.closed(cdsStart, end)); } else if (start <= cdsEnd && end >= cdsEnd) { //logger.debug(" <-- CDS end at: " + cdsEnd ); inCoding = false; - Range r; - if ( responseType.equals(CDS)) - r = Range.closed(codingLength,codingLength+(cdsEnd-start)); - else - r = Range.closed(start,cdsEnd); - data.add(r); + data.add(responseType.equals(CDS) ? + Range.closed(codingLength, codingLength + (cdsEnd - start)) : + Range.closed(start, cdsEnd)); codingLength += (cdsEnd - start); } else if (inCoding) { // full exon is coding - Range r; - if ( responseType.equals(CDS)) - r = Range.closed(codingLength,codingLength+(end-start)); - else - r = Range.closed(start,end); - data.add(r); + data.add(responseType.equals(CDS) ? + Range.closed(codingLength, codingLength + (end - start)) : + Range.closed(start, end)); codingLength += (end - start); } } @@ -773,23 +754,24 @@ private static List> getCDSExonRangesForward(GeneChromosomePositi * I have a genomic coordinate, where is it on the mRNA * * @param coordinate - * @param chromosomePosition + * @param p * @return */ - public static int getCDSPosForChromosomeCoordinate(int coordinate, GeneChromosomePosition chromosomePosition) { + public static int getCDSPosForChromosomeCoordinate(int coordinate, GeneChromosomePosition p, int base) { - if ( chromosomePosition.getOrientation() == '+') + if ( p.getOrientation() == '+') return getCDSPosForward(coordinate, - chromosomePosition.getExonStarts(), - chromosomePosition.getExonEnds(), - chromosomePosition.getCdsStart(), - chromosomePosition.getCdsEnd()); - - return getCDSPosReverse(coordinate, - chromosomePosition.getExonStarts(), - chromosomePosition.getExonEnds(), - chromosomePosition.getCdsStart(), - chromosomePosition.getCdsEnd()); + p.getExonStarts(), + p.getExonEnds(), + p.getCdsStart(), + p.getCdsEnd(), base); + + else + return getCDSPosReverse(coordinate, + p.getExonStarts(), + p.getExonEnds(), + p.getCdsStart(), + p.getCdsEnd(), base); } /** @@ -807,7 +789,7 @@ public static int getCDSPosForChromosomeCoordinate(int coordinate, GeneChromosom * @author Yana Valasatava */ public static int getCDSPosForward(int chromPos, List exonStarts, List exonEnds, - int cdsStart, int cdsEnd) { + int cdsStart, int cdsEnd, int base) { // the genetic coordinate is not in a coding region if ( (chromPos < (cdsStart+base) ) || ( chromPos > (cdsEnd+base) ) ) { @@ -821,7 +803,7 @@ public static int getCDSPosForward(int chromPos, List exonStarts, List< List> cdsRegions = getCDSRegions(exonStarts, exonEnds, cdsStart, cdsEnd); int codingLength = 0; - int lengthExon = 0; + int lengthExon; for (Range range : cdsRegions) { int start = range.lowerEndpoint(); @@ -854,7 +836,7 @@ public static int getCDSPosForward(int chromPos, List exonStarts, List< * @author Yana Valasatava */ public static int getCDSPosReverse(int chromPos, List exonStarts, List exonEnds, - int cdsStart, int cdsEnd) { + int cdsStart, int cdsEnd, int base) { // the genetic coordinate is not in a coding region if ( (chromPos < (cdsStart+base)) || ( chromPos > (cdsEnd+base) ) ) { @@ -868,7 +850,7 @@ public static int getCDSPosReverse(int chromPos, List exonStarts, List< List> cdsRegions = getCDSRegions(exonStarts, exonEnds, cdsStart, cdsEnd); int codingLength = 0; - int lengthExon = 0; + int lengthExon; for ( int i=cdsRegions.size()-1; i>=0; i-- ) { int start = cdsRegions.get(i).lowerEndpoint(); @@ -899,8 +881,8 @@ public static int getCDSPosReverse(int chromPos, List exonStarts, List< public static List> getCDSRegions(List origExonStarts, List origExonEnds, int cdsStart, int cdsEnd) { // remove exons that are fully landed in UTRs - List exonStarts = new ArrayList(origExonStarts); - List exonEnds = new ArrayList(origExonEnds); + List exonStarts = new ArrayList<>(origExonStarts); + List exonEnds = new ArrayList<>(origExonEnds); int j=0; for (int i = 0; i < origExonStarts.size(); i++) { @@ -920,7 +902,7 @@ public static List> getCDSRegions(List origExonStarts, L exonEnds.remove(nExons-1); exonEnds.add(cdsEnd); - List> cdsRegion = new ArrayList>(); + List> cdsRegion = new ArrayList<>(); for ( int i=0; i r = Range.closed(exonStarts.get(i), exonEnds.get(i)); cdsRegion.add(r); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ProteinMappingTools.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ProteinMappingTools.java index 8fdb093c54..bff7888d08 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ProteinMappingTools.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ProteinMappingTools.java @@ -44,7 +44,7 @@ public static ProteinSequence convertDNAtoProteinSequence(String dnaSequence) th * * @return the protein sequence */ - public static ProteinSequence convertDNAtoProteinSequence(DNASequence dnaSequence) throws CompoundNotFoundException { + public static ProteinSequence convertDNAtoProteinSequence(DNASequence dnaSequence) { RNASequence mRNA = dnaSequence.getRNASequence(); return mRNA.getProteinSequence(); } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/util/SplitFasta.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/util/SplitFasta.java index 4948a62c76..fa7a4f6dfb 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/util/SplitFasta.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/util/SplitFasta.java @@ -40,7 +40,7 @@ public class SplitFasta { private static final Logger logger = LoggerFactory.getLogger(SplitFasta.class); - public void processNucleotides(File fastaFileName,String uniqueid, File outputDirectory ) throws Exception{ + public static void processNucleotides(File fastaFileName, String uniqueid, File outputDirectory) throws Exception{ if(!outputDirectory.exists()) outputDirectory.mkdirs(); @@ -52,7 +52,7 @@ public void processNucleotides(File fastaFileName,String uniqueid, File outputDi }else{ fileName = fileName + uniqueid + dnaSequence.getAccession().getID() + ".fna"; } - ArrayList dnaList = new ArrayList(); + ArrayList dnaList = new ArrayList<>(); dnaList.add(dnaSequence); FastaWriterHelper.writeNucleotideSequence(new File(fileName), dnaList); } @@ -61,8 +61,8 @@ public void processNucleotides(File fastaFileName,String uniqueid, File outputDi public static void main( String[] args ){ try{ - SplitFasta splitFasta = new SplitFasta(); - splitFasta.processNucleotides(new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/454Scaffolds.fna"), "", new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/individual")); +// SplitFasta splitFasta = new SplitFasta(); + SplitFasta.processNucleotides(new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/454Scaffolds.fna"), "", new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/individual")); }catch(Exception e){ logger.error("Exception: ", e); } diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/FeatureListTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/FeatureListTest.java index 6e1cae5d8b..ed554272ba 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/FeatureListTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/FeatureListTest.java @@ -35,8 +35,7 @@ */ public class FeatureListTest { @Test - public void testAddIndex() throws Exception - { + public void testAddIndex() { FeatureList fl = new FeatureList(); fl.add(new Feature("seqname", "source", "type", new Location(1, 2), (double)0, 0, "gene_id \"gene_id_1\"; transcript_id \"transcript_id_1\";")); fl.addIndex("transcript_id"); diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/GeneFeatureHelperTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/GeneFeatureHelperTest.java index db4fa31328..bf710a01f0 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/GeneFeatureHelperTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/GeneFeatureHelperTest.java @@ -21,13 +21,13 @@ package org.biojava.nbio.genome; import junitx.framework.FileAssert; -import org.biojava.nbio.genome.parsers.gff.FeatureList; -import org.biojava.nbio.genome.parsers.gff.GFF3Reader; -import org.biojava.nbio.genome.parsers.gff.GFF3Writer; import org.biojava.nbio.core.sequence.ChromosomeSequence; import org.biojava.nbio.core.sequence.GeneSequence; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.io.FastaWriterHelper; +import org.biojava.nbio.genome.parsers.gff.FeatureList; +import org.biojava.nbio.genome.parsers.gff.GFF3Reader; +import org.biojava.nbio.genome.parsers.gff.GFF3Writer; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -48,11 +48,11 @@ public class GeneFeatureHelperTest { private static final Logger logger = LoggerFactory.getLogger(GeneFeatureHelperTest.class); @Before - public void setUp() throws Exception { + public void setUp() { } @After - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/TestChromosomeMappingTools.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/TestChromosomeMappingTools.java index 9ddd43357a..59facf95e7 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/TestChromosomeMappingTools.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/TestChromosomeMappingTools.java @@ -43,8 +43,8 @@ public void testGetCDSLengthForward() { int cdsEnd = 75; int cdsDesired = 23 - 3; - ChromosomeMappingTools.setCoordinateSystem(0); - int cdsTest = ChromosomeMappingTools.getCDSLengthForward(exonStarts, exonEnds, cdsStart, cdsEnd); + + int cdsTest = ChromosomeMappingTools.getCDSLengthForward(exonStarts, exonEnds, cdsStart, cdsEnd, 0); assertEquals(cdsDesired, cdsTest); } @@ -58,8 +58,8 @@ public void testGetCDSLengthReverseAsc() { int cdsEnd = 75; int cdsDesired = 12 - 3; - ChromosomeMappingTools.setCoordinateSystem(0); - int cdsTest = ChromosomeMappingTools.getCDSLengthReverse(exonStarts, exonEnds, cdsStart, cdsEnd); + + int cdsTest = ChromosomeMappingTools.getCDSLengthReverse(exonStarts, exonEnds, cdsStart, cdsEnd, 0); assertEquals(cdsDesired, cdsTest); } @@ -73,8 +73,8 @@ public void testGetCDSLengthReverseDesc() { int cdsEnd = 50; int cdsDesired = 17 - 3; - ChromosomeMappingTools.setCoordinateSystem(0); - int cdsTest = ChromosomeMappingTools.getCDSLengthReverse(exonStarts, exonEnds, cdsStart, cdsEnd); + + int cdsTest = ChromosomeMappingTools.getCDSLengthReverse(exonStarts, exonEnds, cdsStart, cdsEnd, 0); assertEquals(cdsDesired, cdsTest); } diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/TestGenomeMapping.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/TestGenomeMapping.java index 8a19d041e4..395a66c401 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/TestGenomeMapping.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/TestGenomeMapping.java @@ -26,10 +26,9 @@ import org.biojava.nbio.genome.parsers.genename.GeneChromosomePositionParser; import org.biojava.nbio.genome.util.ChromosomeMappingTools; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; -import java.io.InputStream; +import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; @@ -43,14 +42,25 @@ public class TestGenomeMapping { private static final String geneChromosomeFile = "http://cdn.rcsb.org/gene/hg38/geneChromosome38.tsf.gz"; - private List gcps = null; + private static final List gcps; - @Before - public void setUp() throws Exception { - InputStream input = new GZIPInputStream(new URL(geneChromosomeFile).openStream()); - gcps = GeneChromosomePositionParser.getChromosomeMappings(input); + static { + List g; + try { + g = GeneChromosomePositionParser.getChromosomeMappings( + new GZIPInputStream(new URL(geneChromosomeFile).openStream())); + } catch (IOException e) { + e.printStackTrace(); + g = null; + } + gcps = g; } +// @Before +// public void setUp() throws Exception { +// +// } + @Test public void testAK1() { String geneName = "AK1"; @@ -74,9 +84,9 @@ public void testAK1() { if ( ! pos.getGenebankId().equals("NM_000476")) continue; - Assert.assertTrue(pos.getGeneName().equals(geneName)); - Assert.assertTrue(pos.getOrientation().equals('-')); - Assert.assertTrue(pos.getChromosome().equals("chr9")); + Assert.assertEquals(pos.getGeneName(), geneName); + Assert.assertEquals('-', (char) pos.getOrientation()); + Assert.assertEquals("chr9", pos.getChromosome()); List> cdsranges = ChromosomeMappingTools.getCDSExonRanges(pos); @@ -88,16 +98,16 @@ public void testAK1() { validateExon(5,516,585, cdsranges ); - int cdslength = ChromosomeMappingTools.getCDSLength(pos); + int cdslength = ChromosomeMappingTools.getCDSLength(pos, 1); - Assert.assertTrue("CDS length should be 582, but is " + cdslength, cdslength == (uniProtLength * 3)); + Assert.assertEquals("CDS length should be 582, but is " + cdslength, cdslength, (uniProtLength * 3)); List> chromranges = ChromosomeMappingTools.getChromosomalRangesForCDS(pos); // we are reverse strand. reverse the order chromranges = Lists.reverse(chromranges); - Assert.assertTrue(chromranges.size() == 6); + Assert.assertEquals(6, chromranges.size()); // compare with https://www.ncbi.nlm.nih.gov/CCDS/CcdsBrowse.cgi?REQUEST=CCDS&DATA=CCDS6881 validateExon(0,127868008,127868076, chromranges ); @@ -129,16 +139,16 @@ public void testHBA(){ if ( ! pos.getGeneName().equals(geneName)) continue; - Assert.assertTrue(pos.getGeneName().equals("HBA1")); - Assert.assertTrue(pos.getGenebankId().equals("NM_000558")); - Assert.assertTrue(pos.getChromosome().equals("chr16")); - Assert.assertTrue(pos.getTranscriptionStart().equals(176650)); - Assert.assertTrue(pos.getTranscriptionEnd().equals(177522)); - Assert.assertTrue(pos.getOrientation().equals('+')); + Assert.assertEquals("HBA1", pos.getGeneName()); + Assert.assertEquals("NM_000558", pos.getGenebankId()); + Assert.assertEquals("chr16", pos.getChromosome()); + Assert.assertEquals(176650, (int) pos.getTranscriptionStart()); + Assert.assertEquals(177522, (int) pos.getTranscriptionEnd()); + Assert.assertEquals('+', (char) pos.getOrientation()); List> cdsranges = ChromosomeMappingTools.getCDSExonRanges(pos); - Assert.assertTrue(cdsranges.size() == 3); + Assert.assertEquals(3, cdsranges.size()); validateExon(0,0,95,cdsranges); validateExon(1,95,300,cdsranges); @@ -163,8 +173,8 @@ public void testHBA(){ private void validateExon(int exonNr, int start, int stop, List> cdsranges) { Range exon = cdsranges.get(exonNr); - Assert.assertTrue("Exon " + exonNr + " boundary " + exon.lowerEndpoint() + " does not match " + start, exon.lowerEndpoint().equals(start)); - Assert.assertTrue("Exon " + exonNr + " boundary " + exon.upperEndpoint() + " does not match " + stop, exon.upperEndpoint().equals(stop)); + Assert.assertEquals("Exon " + exonNr + " boundary " + exon.lowerEndpoint() + " does not match " + start, (int) exon.lowerEndpoint(), start); + Assert.assertEquals("Exon " + exonNr + " boundary " + exon.upperEndpoint() + " does not match " + stop, (int) exon.upperEndpoint(), stop); } @@ -173,16 +183,19 @@ private void validateExon(int exonNr, int start, int stop, List> * * @author Yana Valasatava */ - private int getPositionInmRNA(String geneName, String genebankId, int posChrom) { + private int getPositionInmRNA(String geneName, String genebankId, int posChrom, int base) { for (GeneChromosomePosition gcp : gcps) { if ( gcp.getGeneName().equals(geneName) ) { if ( gcp.getGenebankId().equals(genebankId) ) { - return ChromosomeMappingTools.getCDSPosForChromosomeCoordinate(posChrom, gcp); + return ChromosomeMappingTools.getCDSPosForChromosomeCoordinate(posChrom, gcp, base); } } } return -1; } + private int getPositionInmRNA(String geneName, String genebankId, int posChrom) { + return getPositionInmRNA(geneName, genebankId, posChrom, 1); + } /** Make sure the mapping tool correctly retrieves the mRNA position for a gene * living on the forward DNA strand for different chromosome positions. @@ -336,39 +349,39 @@ public void testMappingCromosomePosTomRNAMultiUTRs() { @Test public void testGenomeMappingToolGetCDSRanges(){ - List lst1 = new ArrayList<>(Arrays.asList( new Integer[]{86346823, 86352858, 86354529})); - List lst2 = new ArrayList<>(Arrays.asList(new Integer[]{86348878, 86352984, 86354692})); + List lst1 = new ArrayList<>(Arrays.asList(86346823, 86352858, 86354529)); + List lst2 = new ArrayList<>(Arrays.asList(86348878, 86352984, 86354692)); - Integer cdsStart=86348749, cdsEnd=86387027; + int cdsStart=86348749, cdsEnd=86387027; List> result = ChromosomeMappingTools.getCDSRegions(lst1,lst2,cdsStart,cdsEnd); // makes sure the first list does not get changed; - Assert.assertTrue(lst1.get(0) == 86346823); + Assert.assertEquals(86346823, (int) lst1.get(0)); - Assert.assertTrue(result.get(0).lowerEndpoint() == 86348749); - Assert.assertTrue(result.get(1).lowerEndpoint() == 86352858); - Assert.assertTrue(result.get(2).lowerEndpoint() == 86354529); + Assert.assertEquals(86348749, (int) result.get(0).lowerEndpoint()); + Assert.assertEquals(86352858, (int) result.get(1).lowerEndpoint()); + Assert.assertEquals(86354529, (int) result.get(2).lowerEndpoint()); - Assert.assertTrue(result.get(0).upperEndpoint() == 86348878); - Assert.assertTrue(result.get(1).upperEndpoint() == 86352984); - Assert.assertTrue(result.get(2).upperEndpoint() == 86387027); + Assert.assertEquals(86348878, (int) result.get(0).upperEndpoint()); + Assert.assertEquals(86352984, (int) result.get(1).upperEndpoint()); + Assert.assertEquals(86387027, (int) result.get(2).upperEndpoint()); } @Test public void testGenomeMappingToolGetCDSRangesSERINC2(){ - List lst1 = new ArrayList<>(Arrays.asList( new Integer[]{31413812, 31415872, 31423692})); - List lst2 = new ArrayList<>(Arrays.asList(new Integer[]{31414777, 31415907, 31423854})); + List lst1 = new ArrayList<>(Arrays.asList(31413812, 31415872, 31423692)); + List lst2 = new ArrayList<>(Arrays.asList(31414777, 31415907, 31423854)); - Integer cdsStart=31423818, cdsEnd=31434199; + int cdsStart=31423818, cdsEnd=31434199; List> result = ChromosomeMappingTools.getCDSRegions(lst1,lst2,cdsStart,cdsEnd); // makes sure the first list does not get changed; - Assert.assertTrue(result.get(0).lowerEndpoint() == 31423818); + Assert.assertEquals(31423818, (int) result.get(0).lowerEndpoint()); } } diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/TestIssue355.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/TestIssue355.java index 5543682f17..3691555999 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/TestIssue355.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/TestIssue355.java @@ -20,11 +20,12 @@ */ package org.biojava.nbio.genome; -import static org.junit.Assert.*; - import org.biojava.nbio.genome.parsers.gff.Location; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + public class TestIssue355 { @Test diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/TestLocation.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/TestLocation.java index 1289cb757e..2153db9843 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/TestLocation.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/TestLocation.java @@ -20,11 +20,11 @@ */ package org.biojava.nbio.genome; -import static org.junit.Assert.*; - import org.biojava.nbio.genome.parsers.gff.Location; import org.junit.Test; +import static org.junit.Assert.*; + public class TestLocation { @Test @@ -64,11 +64,11 @@ public void testLocation() { //isBefore assertTrue( r2_5.isBefore( r5_8 )); - assertTrue( !r2_5.isBefore( r4_7 )); + assertFalse(r2_5.isBefore(r4_7)); //isAfter assertTrue(r5_8.isAfter( r2_5 )); - assertTrue(!r5_8.isAfter( r4_7 )); + assertFalse(r5_8.isAfter(r4_7)); //contains assertTrue(p15_19.contains( p16_19 )); @@ -76,8 +76,8 @@ public void testLocation() { //overlaps assertTrue(r2_5.overlaps( r4_7 )); assertTrue(r2_5.overlaps( r0_3 )); - assertTrue(!r5_8.overlaps( r2_5 )); - assertTrue(!r2_5.overlaps( r5_8 )); + assertFalse(r5_8.overlaps(r2_5)); + assertFalse(r2_5.overlaps(r5_8)); //prefix diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/AbstractFastqReaderTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/AbstractFastqReaderTest.java index 6dbfbe968c..c87079a1da 100755 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/AbstractFastqReaderTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/AbstractFastqReaderTest.java @@ -312,35 +312,17 @@ public void testMultipleWrappedQuality() throws Exception } @Test - public void testErrorExamples() throws Exception - { + public void testErrorExamples() { FastqReader reader = createFastqReader(); for (String errorExample : ERROR_EXAMPLES) { - InputStream inputStream = getClass().getResourceAsStream(errorExample); - try - { + try (InputStream inputStream = getClass().getResourceAsStream(errorExample)) { reader.read(inputStream); Assert.fail("error example " + errorExample + " expected IOException"); - } - catch (IOException e) - { + } catch (IOException e) { // expected } - finally - { - if (inputStream != null) - { - try - { - inputStream.close(); - } - catch (IOException e) - { - // ignore - } - } - } + // ignore } } @@ -351,37 +333,37 @@ public void testParse() throws Exception final String input = ""; reader.parse(new StringReader(input), new ParseListener() { @Override - public void description(final String description) throws IOException { + public void description(final String description) { // empty } @Override - public void sequence(final String sequence) throws IOException { + public void sequence(final String sequence) { // empty } @Override - public void appendSequence(final String sequence) throws IOException { + public void appendSequence(final String sequence) { // empty } @Override - public void repeatDescription(final String repeatDescription) throws IOException { + public void repeatDescription(final String repeatDescription) { // empty } @Override - public void quality(final String quality) throws IOException { + public void quality(final String quality) { // empty } @Override - public void appendQuality(final String quality) throws IOException { + public void appendQuality(final String quality) { // empty } @Override - public void complete() throws IOException { + public void complete() { // empty } }); @@ -393,39 +375,39 @@ public void testParseNullReadable() throws Exception FastqReader reader = createFastqReader(); try { - reader.parse((Readable) null, new ParseListener() { + reader.parse(null, new ParseListener() { @Override - public void description(final String description) throws IOException { + public void description(final String description) { // empty } @Override - public void sequence(final String sequence) throws IOException { + public void sequence(final String sequence) { // empty } @Override - public void appendSequence(final String sequence) throws IOException { + public void appendSequence(final String sequence) { // empty } @Override - public void repeatDescription(final String repeatDescription) throws IOException { + public void repeatDescription(final String repeatDescription) { // empty } @Override - public void quality(final String quality) throws IOException { + public void quality(final String quality) { // empty } @Override - public void appendQuality(final String quality) throws IOException { + public void appendQuality(final String quality) { // empty } @Override - public void complete() throws IOException { + public void complete() { // empty } }); diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/AbstractFastqWriterTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/AbstractFastqWriterTest.java index b2596dd51b..b3f39fa927 100755 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/AbstractFastqWriterTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/AbstractFastqWriterTest.java @@ -79,7 +79,7 @@ public void testAppendVararg() throws Exception try { - writer.append((Appendable) null, fastq0); + writer.append(null, fastq0); Assert.fail("append(null,) expected IllegalArgumentException"); } catch (IllegalArgumentException e) @@ -96,7 +96,7 @@ public void testAppendIterable() throws Exception Fastq fastq0 = createFastq(); Fastq fastq1 = createFastq(); Fastq fastq2 = createFastq(); - List list = new ArrayList(); + List list = new ArrayList<>(); Assert.assertSame(appendable, writer.append(appendable, list)); list.add(fastq0); Assert.assertSame(appendable, writer.append(appendable, list)); @@ -109,7 +109,7 @@ public void testAppendIterable() throws Exception try { - writer.append((Appendable) null, list); + writer.append(null, list); Assert.fail("append(null,) expected IllegalArgumentException"); } catch (IllegalArgumentException e) @@ -163,7 +163,7 @@ public void testWriteFileIterable() throws Exception Fastq fastq0 = createFastq(); Fastq fastq1 = createFastq(); Fastq fastq2 = createFastq(); - List list = new ArrayList(); + List list = new ArrayList<>(); File file0 = File.createTempFile("abstractFastqWriterTest", null); writer.write(file0, list); @@ -238,7 +238,7 @@ public void testWriteOutputStreamIterable() throws Exception Fastq fastq1 = createFastq(); Fastq fastq2 = createFastq(); OutputStream outputStream = new ByteArrayOutputStream(); - List list = new ArrayList(); + List list = new ArrayList<>(); writer.write(outputStream, list); list.add(fastq0); writer.write(outputStream, list); diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/ConvertTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/ConvertTest.java index 0c6775a659..aa32f8b7de 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/ConvertTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/ConvertTest.java @@ -20,16 +20,16 @@ */ package org.biojava.nbio.genome.io.fastq; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import org.junit.Test; + import java.io.File; import java.io.FileWriter; import java.util.List; import java.util.Map; -import org.junit.Test; -import static org.junit.Assert.*; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; +import static org.junit.Assert.assertEquals; /** * Round trip conversion functional tests. @@ -99,7 +99,7 @@ public void testConvert() throws Exception } } - private final class FastqVariantPair + private static final class FastqVariantPair { final FastqVariant variant1; final FastqVariant variant2; diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqBuilderTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqBuilderTest.java index b013e996d2..e2af4e776d 100755 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqBuilderTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqBuilderTest.java @@ -316,7 +316,7 @@ public void testBuildNonMatchingSequenceQualityScoreLengthsSequenceNull() .withQuality("0123") .withVariant(FastqVariant.FASTQ_SOLEXA); - Assert.assertEquals(false, fastqBuilder.sequenceAndQualityLengthsMatch()); + Assert.assertFalse(fastqBuilder.sequenceAndQualityLengthsMatch()); } @Test @@ -327,7 +327,7 @@ public void testBuildNonMatchingSequenceQualityScoreLengthsQualityNull() .withSequence("ACTG") .withVariant(FastqVariant.FASTQ_SOLEXA); - Assert.assertEquals(false, fastqBuilder.sequenceAndQualityLengthsMatch()); + Assert.assertFalse(fastqBuilder.sequenceAndQualityLengthsMatch()); } @Test diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqTest.java index b6fc3c98b0..d3454718e2 100755 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqTest.java @@ -77,7 +77,7 @@ public void testConstructor() public void testDescription() { Fastq fastq = new Fastq("description", "sequence", "quality_", FastqVariant.FASTQ_SANGER); - Assert.assertTrue(fastq.getDescription() != null); + Assert.assertNotNull(fastq.getDescription()); Assert.assertEquals("description", fastq.getDescription()); } @@ -85,7 +85,7 @@ public void testDescription() public void testSequence() { Fastq fastq = new Fastq("description", "sequence", "quality_", FastqVariant.FASTQ_SANGER); - Assert.assertTrue(fastq.getSequence() != null); + Assert.assertNotNull(fastq.getSequence()); Assert.assertEquals("sequence", fastq.getSequence()); } @@ -93,7 +93,7 @@ public void testSequence() public void testQuality() { Fastq fastq = new Fastq("description", "sequence", "quality_", FastqVariant.FASTQ_SANGER); - Assert.assertTrue(fastq.getQuality() != null); + Assert.assertNotNull(fastq.getQuality()); Assert.assertEquals("quality_", fastq.getQuality()); } @@ -101,7 +101,7 @@ public void testQuality() public void testVariant() { Fastq fastq = new Fastq("description", "sequence", "quality_", FastqVariant.FASTQ_SANGER); - Assert.assertTrue(fastq.getVariant() != null); + Assert.assertNotNull(fastq.getVariant()); Assert.assertEquals(FastqVariant.FASTQ_SANGER, fastq.getVariant()); } @@ -117,15 +117,15 @@ public void testEquals() Fastq fastq0 = new Fastq("description", "sequence", "quality_", FastqVariant.FASTQ_SANGER); Fastq fastq1 = new Fastq("description", "sequence", "quality_", FastqVariant.FASTQ_SANGER); - Assert.assertFalse(fastq0.equals(null)); - Assert.assertFalse(fastq1.equals(null)); - Assert.assertFalse(fastq0.equals(new Object())); - Assert.assertFalse(fastq1.equals(new Object())); - Assert.assertTrue(fastq0.equals(fastq0)); - Assert.assertTrue(fastq1.equals(fastq1)); - Assert.assertFalse(fastq0 == fastq1); - Assert.assertFalse(fastq0.equals(fastq1)); - Assert.assertFalse(fastq1.equals(fastq0)); + Assert.assertNotEquals(null, fastq0); + Assert.assertNotEquals(null, fastq1); + Assert.assertNotEquals(fastq0, new Object()); + Assert.assertNotEquals(fastq1, new Object()); + Assert.assertEquals(fastq0, fastq0); + Assert.assertEquals(fastq1, fastq1); + Assert.assertNotSame(fastq0, fastq1); + Assert.assertNotEquals(fastq0, fastq1); + Assert.assertNotEquals(fastq1, fastq0); } @Test diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqToolsTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqToolsTest.java index 469601e624..6aca0fda15 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqToolsTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqToolsTest.java @@ -30,7 +30,6 @@ import org.junit.Assert; import org.junit.Test; - import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; @@ -505,14 +504,14 @@ public void testConvertQualitiesIlluminaToSolexa() @Test public void testToList() { - List list = new ArrayList(); + List list = new ArrayList<>(); Assert.assertSame(list, FastqTools.toList(list)); } @Test public void testToListNotAList() { - Collection collection = new HashSet(); + Collection collection = new HashSet<>(); Assert.assertTrue(FastqTools.toList(collection) instanceof List); Assert.assertNotSame(collection, FastqTools.toList(collection)); } diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqVariantTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqVariantTest.java index f8b0855a8e..af7a33f79f 100755 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqVariantTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqVariantTest.java @@ -20,11 +20,11 @@ */ package org.biojava.nbio.genome.io.fastq; -import static org.biojava.nbio.genome.io.fastq.FastqVariant.*; - import org.junit.Assert; import org.junit.Test; +import static org.biojava.nbio.genome.io.fastq.FastqVariant.*; + /** * Unit test for FastqVariant. */ @@ -66,9 +66,9 @@ public void testIsIllumina() @Test public void testParseFastqVariant() { - Assert.assertEquals(null, parseFastqVariant(null)); - Assert.assertEquals(null, parseFastqVariant("")); - Assert.assertEquals(null, parseFastqVariant("not a valid FASTQ variant")); + Assert.assertNull(parseFastqVariant(null)); + Assert.assertNull(parseFastqVariant("")); + Assert.assertNull(parseFastqVariant("not a valid FASTQ variant")); Assert.assertEquals(FASTQ_SANGER, parseFastqVariant("FASTQ_SANGER")); Assert.assertEquals(FASTQ_SANGER, parseFastqVariant("fastq-sanger")); } diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/IlluminaFastqReaderTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/IlluminaFastqReaderTest.java index d7b0a8b9d2..54fd055615 100755 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/IlluminaFastqReaderTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/IlluminaFastqReaderTest.java @@ -21,12 +21,13 @@ package org.biojava.nbio.genome.io.fastq; import org.junit.Test; -import static org.junit.Assert.*; import java.io.IOException; import java.io.InputStream; import java.net.URL; +import static org.junit.Assert.*; + /** * Unit test for IlluminaFastqReader. @@ -59,8 +60,7 @@ public FastqWriter createFastqWriter() } @Test - public void testValidateDescription() throws Exception - { + public void testValidateDescription() { IlluminaFastqReader reader = new IlluminaFastqReader(); URL invalidDescription = getClass().getResource("illumina-invalid-description.fastq"); try @@ -75,8 +75,7 @@ public void testValidateDescription() throws Exception } @Test - public void testValidateRepeatDescription() throws Exception - { + public void testValidateRepeatDescription() { IlluminaFastqReader reader = new IlluminaFastqReader(); URL invalidRepeatDescription = getClass().getResource("illumina-invalid-repeat-description.fastq"); try diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/SangerFastqReaderTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/SangerFastqReaderTest.java index af6f67319f..e5d66dbc80 100755 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/SangerFastqReaderTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/SangerFastqReaderTest.java @@ -58,8 +58,7 @@ public FastqWriter createFastqWriter() return new SangerFastqWriter(); } - public void testValidateDescription() throws Exception - { + public void testValidateDescription() { SangerFastqReader reader = new SangerFastqReader(); URL invalidDescription = getClass().getResource("sanger-invalid-description.fastq"); try @@ -74,8 +73,7 @@ public void testValidateDescription() throws Exception } @Test - public void testValidateRepeatDescription() throws Exception - { + public void testValidateRepeatDescription() { SangerFastqReader reader = new SangerFastqReader(); URL invalidRepeatDescription = getClass().getResource("sanger-invalid-repeat-description.fastq"); try diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/SolexaFastqReaderTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/SolexaFastqReaderTest.java index 5f6f041c84..25909e97dd 100755 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/SolexaFastqReaderTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/SolexaFastqReaderTest.java @@ -60,8 +60,7 @@ public FastqWriter createFastqWriter() } @Test - public void testValidateDescription() throws Exception - { + public void testValidateDescription() { SolexaFastqReader reader = new SolexaFastqReader(); URL invalidDescription = getClass().getResource("solexa-invalid-description.fastq"); try @@ -76,8 +75,7 @@ public void testValidateDescription() throws Exception } @Test - public void testValidateRepeatDescription() throws Exception - { + public void testValidateRepeatDescription() { SolexaFastqReader reader = new SolexaFastqReader(); URL invalidRepeatDescription = getClass().getResource("solexa-invalid-repeat-description.fastq"); try diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/StreamingFastqParserTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/StreamingFastqParserTest.java index a80f44a43d..6818977adb 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/StreamingFastqParserTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/StreamingFastqParserTest.java @@ -36,11 +36,8 @@ public void testStreamNullReadable() throws Exception { try { - StreamingFastqParser.stream((Readable) null, FastqVariant.FASTQ_SANGER, new StreamListener() { - @Override - public void fastq(final Fastq fastq) { - // empty - } + StreamingFastqParser.stream(null, FastqVariant.FASTQ_SANGER, fastq -> { + // empty }); Assert.fail("stream(null,,) expected IllegalArgumentException"); } @@ -56,11 +53,8 @@ public void testStreamNullVariant() throws Exception try { final String input = ""; - StreamingFastqParser.stream(new StringReader(input), null, new StreamListener() { - @Override - public void fastq(final Fastq fastq) { - // empty - } + StreamingFastqParser.stream(new StringReader(input), null, fastq -> { + // empty }); Assert.fail("stream(null,,) expected IllegalArgumentException"); } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/MMcifTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/MMcifTest.java index 4947e0077a..284533d954 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/MMcifTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/MMcifTest.java @@ -28,7 +28,6 @@ import org.biojava.nbio.structure.io.mmcif.SimpleMMcifConsumer; import org.biojava.nbio.structure.io.mmcif.SimpleMMcifParser; import org.junit.Test; -import static org.junit.Assert.*; import java.io.BufferedReader; import java.io.IOException; @@ -36,6 +35,8 @@ import java.io.InputStreamReader; import java.util.List; +import static org.junit.Assert.*; + public class MMcifTest { private static boolean headerOnly; @@ -106,7 +107,7 @@ private void comparePDB2cif(String id, String chainId) throws IOException { // load the PDB file via the PDB parser - Structure pdbStructure = null; + Structure pdbStructure; InputStream pinStream = this.getClass().getResourceAsStream("/"+id+".pdb"); assertNotNull(inStream); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/PDBFileParserTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/PDBFileParserTest.java index 7bc3c2846d..9256483e15 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/PDBFileParserTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/PDBFileParserTest.java @@ -24,20 +24,7 @@ */ package org.biojava.nbio.structure.test; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ChainImpl; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.JournalArticle; -import org.biojava.nbio.structure.PDBHeader; -import org.biojava.nbio.structure.Site; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.FileParsingParameters; import org.biojava.nbio.structure.io.PDBFileParser; @@ -45,6 +32,11 @@ import org.junit.Before; import org.junit.Test; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; + import static org.junit.Assert.*; /** @@ -108,7 +100,7 @@ public void testCorrectFloatingPointDisplay() throws IOException { Structure s = parser.parsePDBFile(br); String pdb = s.toPDB(); - assertTrue("the created PDB file does not match the input file", pdb.equals(t)); + assertEquals("the created PDB file does not match the input file", pdb, t); } @@ -304,7 +296,7 @@ public void testSITE() throws IOException { // System.out.println("Got:"); // System.out.println(remark800.toString()); } - assertTrue("the created PDB REMARK800 section does not match the input file", remark800.toString().equals(remark800Test)); + assertEquals("the created PDB REMARK800 section does not match the input file", remark800.toString(), remark800Test); if (!sites.toString().equals(sitesTest)) { System.out.println("Expected:"); @@ -331,7 +323,7 @@ public void testMultiLineJRNL() throws IOException { BufferedReader br = new BufferedReader(new StringReader(jrnlString)); - Structure s = null; + Structure s; s = parser.parsePDBFile(br); @@ -357,7 +349,7 @@ public void testIncorrectDateFormatMultiLineJRNL() throws IOException{ BufferedReader br = new BufferedReader(new StringReader(jrnlString)); - Structure s = null; + Structure s; s = parser.parsePDBFile(br); // String jrnl = s.getJournalArticle().toString(); // System.out.println(jrnl); @@ -380,7 +372,7 @@ public void testInvalidFormatREFsectionJRNL() throws IOException{ BufferedReader br = new BufferedReader(new StringReader(jrnlString)); - Structure s = null; + Structure s; s = parser.parsePDBFile(br); // String jrnl = s.getJournalArticle().toString(); // System.out.println(jrnl); @@ -406,7 +398,7 @@ public void testSecondMultiLineJRNL() throws IOException{ BufferedReader br = new BufferedReader(new StringReader(jrnlString)); - Structure s = null; + Structure s; s = parser.parsePDBFile(br); // String jrnl = s.getJournalArticle().toString(); // System.out.println(jrnl); @@ -433,7 +425,7 @@ public void testSingleLineJRNL() throws IOException{ BufferedReader br = new BufferedReader(new StringReader(jrnlString)); - Structure s = null; + Structure s; s = parser.parsePDBFile(br); // String jrnl = s.getJournalArticle().toString(); // System.out.println(jrnl); @@ -459,7 +451,7 @@ public void testToBePublishedJRNL() throws IOException{ BufferedReader br = new BufferedReader(new StringReader(jrnlString)); - Structure s = null; + Structure s; s = parser.parsePDBFile(br); JournalArticle journalArticle = s.getJournalArticle(); @@ -552,7 +544,7 @@ public void testCorrectAtomNamePadding() throws IOException { String pdb = s.toPDB(); - assertTrue("the created PDB file does not match the input file", pdb.equals(atomLines)); + assertEquals("the created PDB file does not match the input file", pdb, atomLines); } @@ -619,13 +611,13 @@ public void testMissingElements() throws IOException { BufferedReader br = new BufferedReader(new StringReader(missingElement)); Structure s = parser.parsePDBFile(br); String pdb = s.toPDB(); - assertTrue("the Element column has not been filled correctly", pdb.equals(original)); + assertEquals("the Element column has not been filled correctly", pdb, original); br = new BufferedReader(new StringReader(emptyElement)); s = parser.parsePDBFile(br); pdb = s.toPDB(); - assertTrue("the Element column has not been filled correctly", pdb.equals(original)); + assertEquals("the Element column has not been filled correctly", pdb, original); } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/StructureTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/StructureTest.java index 15198acbfa..d13c3c2bf5 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/StructureTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/StructureTest.java @@ -25,16 +25,15 @@ import org.biojava.nbio.structure.io.FileParsingParameters; import org.biojava.nbio.structure.io.PDBFileParser; import org.biojava.nbio.structure.io.SSBondImpl; +import org.junit.BeforeClass; +import org.junit.Test; + +import javax.vecmath.Matrix4d; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Set; -import javax.vecmath.Matrix4d; - -import org.junit.BeforeClass; -import org.junit.Test; - import static org.junit.Assert.*; /** @@ -98,10 +97,9 @@ public void testSeqResParsing() { /** * Tests if a PDB file can be parsed - * @throws Exception */ @Test - public void testReadPDBFile() throws Exception { + public void testReadPDBFile() { assertEquals("pdb code not set!","5PTI",structure.getPDBCode()); @@ -126,7 +124,7 @@ public void testReadPDBFile() throws Exception { } @Test - public void testSSBondParsing() throws Exception { + public void testSSBondParsing() { assertNotNull(structure); List ssbonds = structure.getSSBonds(); @@ -164,16 +162,15 @@ private void assertDisulfideBond(String expectedChainId1, String expectedChainId /** * Tests that standard amino acids are working properly - * @throws Exception */ @Test - public void testStandardAmino() throws Exception { + public void testStandardAmino() { AminoAcid arg = StandardAminoAcid.getAminoAcid("ARG"); - assertTrue(arg.size() == 11 ); + assertEquals(11, arg.size()); AminoAcid gly = StandardAminoAcid.getAminoAcid("G"); - assertTrue(gly.size() == 4); + assertEquals(4, gly.size()); } @@ -182,7 +179,7 @@ public void testPDBHeader(){ PDBHeader header = structure.getPDBHeader(); String classification = header.getClassification(); - assertTrue(classification.equals("PROTEINASE INHIBITOR (TRYPSIN)")); + assertEquals("PROTEINASE INHIBITOR (TRYPSIN)", classification); String idCode = header.getIdCode(); assertEquals("the idCode in the Header is " + idCode + " and not 5PTI, as expected","5PTI",idCode); @@ -208,7 +205,7 @@ public void testPDBHeader(){ //assertEquals("did not find the right number of compounds! ", 2, compounds.size()); EntityInfo comp = compounds.get(0); - assertEquals("did not get the right compounds info",true,comp.getDescription().startsWith("TRYPSIN INHIBITOR")); + assertTrue("did not get the right compounds info", comp.getDescription().startsWith("TRYPSIN INHIBITOR")); List chainIds = comp.getChainIds(); List chains = comp.getChains(); @@ -224,12 +221,11 @@ public void testCreateVirtualCBAtom(){ if ( g1.getPDBName().equals("GLY")){ if ( g1 instanceof AminoAcid){ - try { - Atom cb = Calc.createVirtualCBAtom((AminoAcid)g1); - g1.addAtom(cb); - } catch (StructureException e){ - fail ("createVirtualCBAtom failed with " + e.getMessage()); - } +// try { + g1.addAtom(Calc.createVirtualCBAtom((AminoAcid)g1)); +// } catch (StructureException e){ +// fail ("createVirtualCBAtom failed with " + e.getMessage()); +// } } } else { fail("the group at position 11 is not a GLY!"); @@ -237,14 +233,14 @@ public void testCreateVirtualCBAtom(){ } @Test - public void testMutation() throws Exception { + public void testMutation() { Group g1 = (Group)structure.getChainByIndex(0).getAtomGroup(21).clone(); - assertTrue(g1 != null); + assertNotNull(g1); Group g2 = (Group)structure.getChainByIndex(0).getAtomGroup(53).clone(); - assertTrue(g2 != null); + assertNotNull(g2); assertEquals("The group at position 22 is not a PHE","PHE", g1.getPDBName()); @@ -292,13 +288,13 @@ public void testMutation() throws Exception { } @Test - public void testElement() throws Exception { + public void testElement() { // there should be no wild card elements // in a structure (!= Element.R) for (Chain c: structure.getChains()) { for (Group g: c.getAtomGroups()) { for (Atom a: g.getAtoms()) { - assertFalse(a.getElement().equals(Element.R)); + assertNotEquals(a.getElement(), Element.R); } } } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/StructureToolsTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/StructureToolsTest.java index b2ae39611c..337c8900cb 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/StructureToolsTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/StructureToolsTest.java @@ -35,8 +35,9 @@ import java.io.IOException; import java.io.InputStream; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assume.assumeNoException; -import static org.junit.Assert.*; public class StructureToolsTest { diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/Test1a4w.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/Test1a4w.java index 870c74a13a..5a67cbf67f 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/Test1a4w.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/Test1a4w.java @@ -82,7 +82,7 @@ public void test1a4wPDBFile() throws IOException - Structure structure2 = null; + Structure structure2; InputStream inStream = this.getClass().getResourceAsStream("/1a4w.cif"); Assert.assertNotNull(inStream); @@ -132,15 +132,15 @@ private void testStructure(Structure structure){ //System.out.println(structure); Assert.assertTrue("chain " + a.getName() + " length should be 26. was: " + a.getAtomGroups(GroupType.AMINOACID).size(), (a.getAtomGroups(GroupType.AMINOACID).size() == 26)); - Assert.assertTrue("chain " + a.getName() + " seqres length should be 36. was: " + a.getSeqResLength(), a.getSeqResLength() == 36); + Assert.assertEquals("chain " + a.getName() + " seqres length should be 36. was: " + a.getSeqResLength(), 36, a.getSeqResLength()); Assert.assertTrue("chain " + b.getName() + " length should be 248. was: " + b.getAtomGroups(GroupType.AMINOACID).size(), (b.getAtomGroups(GroupType.AMINOACID).size() == 248)); - Assert.assertTrue("chain " + b.getName() + " seqres length should be 259. was: " + b.getSeqResLength(), b.getSeqResLength() == 259); + Assert.assertEquals("chain " + b.getName() + " seqres length should be 259. was: " + b.getSeqResLength(), 259, b.getSeqResLength()); Assert.assertTrue("chain " + c.getName() + " length should be 9. was: " + c.getAtomGroups(GroupType.AMINOACID).size(), (c.getAtomGroups(GroupType.AMINOACID).size() == 9)); - Assert.assertTrue("chain " + c.getName() + " seqres length should be 12. was: " + c.getSeqResLength(), c.getSeqResLength() == 12); + Assert.assertEquals("chain " + c.getName() + " seqres length should be 12. was: " + c.getSeqResLength(), 12, c.getSeqResLength()); Assert.assertEquals("chain " + c.getName() + " seqres sequences is not correct!", "NGDFEEIPEEYL", c.getSeqResSequence()); } @@ -253,14 +253,18 @@ public void testSiteGroups(){ // before biojava 5.0 we were asserting for same chain, but now the DAR residue is in its own nonpoly chain, can't do it anymore //assertEquals(c2, g.getChain()); String pdbName = g.getPDBName(); - if ( pdbName.equals("DAR")) { - darPresent = true; - //System.out.println("darPresent"); + switch (pdbName) { + case "DAR": + darPresent = true; + //System.out.println("darPresent"); + break; + case "GLY": + glyPresent = true; + break; + case "H2O": + noWater = false; + break; } - else if ( pdbName.equals("GLY")) - glyPresent = true; - else if ( pdbName.equals("H2O")) - noWater = false; } } } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/Test1o2f.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/Test1o2f.java index 7acde4166e..d99b9a4153 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/Test1o2f.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/Test1o2f.java @@ -25,7 +25,6 @@ import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.LocalPDBDirectory.FetchBehavior; - import org.junit.Assert; import org.junit.Before; import org.junit.Test; diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/TestSECalignment.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/TestSECalignment.java index 6a9516251b..9716ce5d63 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/TestSECalignment.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/TestSECalignment.java @@ -23,6 +23,7 @@ package org.biojava.nbio.structure.test; import junit.framework.TestCase; +import org.biojava.nbio.core.util.StringManipulationHelper; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.align.StructureAlignment; import org.biojava.nbio.structure.align.StructureAlignmentFactory; @@ -33,7 +34,6 @@ import org.biojava.nbio.structure.align.xml.AFPChainXMLParser; import org.biojava.nbio.structure.test.align.fatcat.FlipAFPChainTest; import org.biojava.nbio.structure.test.util.StringManipulationTestsHelper; -import org.biojava.nbio.core.util.StringManipulationHelper; import java.io.InputStream; diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/AlignmentToolsTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/AlignmentToolsTest.java index 339f1e4eee..3c46c1b258 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/AlignmentToolsTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/AlignmentToolsTest.java @@ -97,7 +97,7 @@ public void testGetSymmetryOrderForMaps() { final float minimumMetricChange = .5f;// be liberal, since we have small alignments // noisy C3 alignment - Map alignment1 = new HashMap(); + Map alignment1 = new HashMap<>(); alignment1.put(1, 5); alignment1.put(2, 6); alignment1.put(4, 7); @@ -107,14 +107,14 @@ public void testGetSymmetryOrderForMaps() { alignment1.put(10, 3); alignment1.put(11, 4); - Map identity = new AlignmentTools.IdentityMap(); + Map identity = new AlignmentTools.IdentityMap<>(); order = AlignmentTools.getSymmetryOrder(alignment1, identity, maxSymmetry, minimumMetricChange); Assert.assertEquals("Wrong order for alignment 1", 3, order); // sequential alignment. Should be order 1, but we report this as "no symmetry" //TODO Change default return value in getSymmetry - Map alignment2 = new HashMap(); + Map alignment2 = new HashMap<>(); for(int i=1;i<10;i++) { alignment2.put(i, i+1); } @@ -123,7 +123,7 @@ public void testGetSymmetryOrderForMaps() { Assert.assertEquals("Wrong order for alignment 2", 1, order); // now try to get symmetry order with an imperfect identity - Map alignment3 = new HashMap(); + Map alignment3 = new HashMap<>(); alignment3.put(1, 15); alignment3.put(2, 16); alignment3.put(4, 17); @@ -133,7 +133,7 @@ public void testGetSymmetryOrderForMaps() { alignment3.put(10, 13); alignment3.put(11, 14); - Map identityMinus10 = new HashMap(); + Map identityMinus10 = new HashMap<>(); for(int i=1;i<=11;i++) { identityMinus10.put(i+10, i); } @@ -155,7 +155,7 @@ public void testGetSymmetryOrderForMaps() { @Test public void testGuessSequentialAlignment() { // noisy C3 alignment - Map alignment1 = new HashMap(); + Map alignment1 = new HashMap<>(); alignment1.put(1, 5); alignment1.put(2, 6); alignment1.put(4, 7); @@ -166,7 +166,7 @@ public void testGuessSequentialAlignment() { alignment1.put(11, 4); // Sequential version of the alignment - Map sequentialForward = new HashMap(); + Map sequentialForward = new HashMap<>(); sequentialForward.put(1, 2); sequentialForward.put(2, 3); sequentialForward.put(4, 4); @@ -177,7 +177,7 @@ public void testGuessSequentialAlignment() { sequentialForward.put(11, 11); // inverse of sequentialForward - Map sequentialBackward = new HashMap(); + Map sequentialBackward = new HashMap<>(); sequentialBackward.put(2, 1); sequentialBackward.put(3, 2); sequentialBackward.put(4, 4); @@ -254,7 +254,7 @@ public void testGetSymmetryOrderWithCECP() throws IOException, StructureExceptio @Test public void testApplyAlignment() { // noisy C3 alignment - Map alignment1 = new HashMap(); + Map alignment1 = new HashMap<>(); alignment1.put(1, 5); alignment1.put(2, 6); alignment1.put(4, 7); @@ -264,7 +264,7 @@ public void testApplyAlignment() { alignment1.put(10, 3); alignment1.put(11, 4); - Map image1 = new HashMap(); + Map image1 = new HashMap<>(); image1.put(1, null); image1.put(2, 9); image1.put(4, 11); @@ -284,7 +284,7 @@ public void testApplyAlignment() { @Test public void testApplyAlignmentNonIdentical() { // noisy C3 alignment - Map alignment1 = new HashMap(); + Map alignment1 = new HashMap<>(); alignment1.put(1, 15); alignment1.put(2, 16); alignment1.put(4, 17); @@ -294,7 +294,7 @@ public void testApplyAlignmentNonIdentical() { alignment1.put(10, 13); alignment1.put(11, 14); - Map image1 = new HashMap(); + Map image1 = new HashMap<>(); image1.put(1, null); image1.put(2, 19); image1.put(4, 21); @@ -306,7 +306,7 @@ public void testApplyAlignmentNonIdentical() { //image1.put(5, null); //image1.put(3, null); - Map identity1 = new HashMap(); + Map identity1 = new HashMap<>(); for(int i=1;i<12;i++) { identity1.put(i+10,i); } @@ -320,7 +320,7 @@ public void testToConciseAlignmentString() { String result,expected; int i=0; - test = new HashMap(); + test = new HashMap<>(); test.put(1, 2); test.put(2, 3); test.put(3, 4); @@ -331,7 +331,7 @@ public void testToConciseAlignmentString() { Assert.assertEquals((i++) + ". Linear strings.", expected, result); - test = new HashMap(); + test = new HashMap<>(); test.put(1, 2); test.put(2, 3); test.put(3, 1); @@ -341,7 +341,7 @@ public void testToConciseAlignmentString() { result = AlignmentTools.toConciseAlignmentString(test); Assert.assertEquals((i++) + ". Cycles.", expected, result); - test = new HashMap(); + test = new HashMap<>(); test.put(1, 2); test.put(2, 3); test.put(3, 1); @@ -351,7 +351,7 @@ public void testToConciseAlignmentString() { result = AlignmentTools.toConciseAlignmentString(test); Assert.assertEquals((i++) + ". Complex.", expected, result); - test = new HashMap(); + test = new HashMap<>(); test.put(1, 2); test.put(2, 3); test.put(3, 4); @@ -376,7 +376,7 @@ public void testToConciseAlignmentString() { result = AlignmentTools.toConciseAlignmentString(test); Assert.assertEquals((i++) + ". Sub-optimal arrangement", expected, result); - Map test2 = new HashMap(); + Map test2 = new HashMap<>(); test2.put(1, 12.); test2.put(2, 13.); test2.put(3, 14.); @@ -409,7 +409,7 @@ public void testUpdateSuperposition() throws IOException, StructureException { Atom[] ca2 = StructureTools.getRepresentativeAtomArray(s); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new FileReader("src/test/resources/align/31BI_symm_align.xml")); - String line = ""; + String line; while ((line = br.readLine()) != null) { sb.append(line); } @@ -429,7 +429,7 @@ public void testUpdateSuperposition() throws IOException, StructureException { */ public static class OffsetMap extends AbstractMap { - private int offset; + private final int offset; public OffsetMap(int offset) { this.offset = offset; } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/FlipAFPChainTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/FlipAFPChainTest.java index 6213503c64..b3f0752f86 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/FlipAFPChainTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/FlipAFPChainTest.java @@ -139,8 +139,7 @@ private void flip(String name1, String name2, String algorithmName) throws Struc * @param ca2 * @return */ - private double getRMSD(AFPChain afpChain, Atom[] ca1, Atom[] ca2) - throws StructureException { + private double getRMSD(AFPChain afpChain, Atom[] ca1, Atom[] ca2) { Atom[] ca2clone = StructureTools.cloneAtomArray(ca2); rotateAtoms2(afpChain,ca2clone); @@ -150,9 +149,9 @@ private double getRMSD(AFPChain afpChain, Atom[] ca1, Atom[] ca2) Atom[] catmp1 = AFPAlignmentDisplay.getAlignedAtoms1(afpChain, ca1); Atom[] catmp2 = AFPAlignmentDisplay.getAlignedAtoms2(afpChain, ca2clone); - assertTrue(catmp1.length == catmp2.length); + assertEquals(catmp1.length, catmp2.length); - assertTrue(catmp1.length == afpChain.getNrEQR()); + assertEquals(catmp1.length, afpChain.getNrEQR()); return Calc.rmsd(catmp1,catmp2); } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/TestSimilarityCalc.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/TestSimilarityCalc.java index 48e905a9e5..00ecaa6c3b 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/TestSimilarityCalc.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/TestSimilarityCalc.java @@ -26,14 +26,12 @@ import org.biojava.nbio.structure.align.StructureAlignment; import org.biojava.nbio.structure.align.StructureAlignmentFactory; import org.biojava.nbio.structure.align.model.AFPChain; -import org.biojava.nbio.structure.align.model.AfpChainWriter; import org.biojava.nbio.structure.align.seq.SmithWaterman3DParameters; import org.biojava.nbio.structure.align.seq.SmithWaterman3Daligner; import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Test; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; /** @@ -49,8 +47,8 @@ public void testSimilarityDisplay(){ AtomCache cache = new AtomCache(); - Structure structure1 = null; - Structure structure2 = null; + Structure structure1; + Structure structure2; try { @@ -71,9 +69,9 @@ public void testSimilarityDisplay(){ afpChain.setName2(name2); - assertTrue(afpChain.getAlnLength() == 71); + assertEquals(71, afpChain.getAlnLength()); - assertTrue(afpChain.getAlnLength() == 71); + assertEquals(71, afpChain.getAlnLength()); assertTrue(afpChain.getSimilarity() > .57); assertTrue(afpChain.getSimilarity() <= .6); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/ce/OptimalCECPMainTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/ce/OptimalCECPMainTest.java index bf7ee56be4..4b055b27eb 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/ce/OptimalCECPMainTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/ce/OptimalCECPMainTest.java @@ -25,8 +25,11 @@ import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.StructureAlignmentFactory; -import org.biojava.nbio.structure.align.ce.*; +import org.biojava.nbio.structure.align.ce.CECPParameters; import org.biojava.nbio.structure.align.ce.CECPParameters.DuplicationHint; +import org.biojava.nbio.structure.align.ce.CeCPMain; +import org.biojava.nbio.structure.align.ce.CeMain; +import org.biojava.nbio.structure.align.ce.OptimalCECPMain; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Assert; @@ -44,13 +47,13 @@ */ public class OptimalCECPMainTest { - private AtomCache cache = new AtomCache(); + private final AtomCache cache = new AtomCache(); /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ @Before - public void setUp() throws Exception { + public void setUp() { } /** @@ -183,22 +186,22 @@ public void testPermuteArray() throws Exception { arrP = Arrays.copyOf(arr0, arr0.length); Assert.assertTrue("Shallow equals!", Arrays.deepEquals(arr0, arrP)); permuteArray.invoke(null, arrP, 0); - Assert.assertTrue(String.format("Permuting by 0 gave %s%s%s%s%s%s", (Object[]) arrP), + Assert.assertTrue(String.format("Permuting by 0 gave %s%s%s%s%s%s", arrP), Arrays.deepEquals(arr0, arrP)); arrP = Arrays.copyOf(arr0, arr0.length); permuteArray.invoke(null, arrP, 1); - Assert.assertTrue(String.format("Permuting by 1 gave %s%s%s%s%s%s", (Object[]) arrP), + Assert.assertTrue(String.format("Permuting by 1 gave %s%s%s%s%s%s", arrP), Arrays.deepEquals(arr1, arrP)); arrP = Arrays.copyOf(arr0, arr0.length); permuteArray.invoke(null, arrP, 5); - Assert.assertTrue(String.format("Permuting by 7 gave %s%s%s%s%s%s", (Object[]) arrP), + Assert.assertTrue(String.format("Permuting by 7 gave %s%s%s%s%s%s", arrP), Arrays.deepEquals(arr5, arrP)); arrP = Arrays.copyOf(arr0, arr0.length); permuteArray.invoke(null, arrP, -1); - Assert.assertTrue(String.format("Permuting by -1 gave %s%s%s%s%s%s", (Object[]) arrP), + Assert.assertTrue(String.format("Permuting by -1 gave %s%s%s%s%s%s", arrP), Arrays.deepEquals(arr5, arrP)); try { diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/AFPChainSerialisationTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/AFPChainSerialisationTest.java index 9d0bc303b7..391e98506e 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/AFPChainSerialisationTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/AFPChainSerialisationTest.java @@ -29,7 +29,8 @@ import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; public class AFPChainSerialisationTest { @@ -148,13 +149,13 @@ private void testAlignment(String name1, String name2, Atom[] ca1, Atom[] ca2, b int blockNum = afpChain.getBlockNum(); int[] optLen = afpChain.getOptLen(); - assertTrue("The nr of aligned blocks is not the same! " + blockNum + " " + newChain.getBlockNum() , blockNum == newChain.getBlockNum()); + assertEquals("The nr of aligned blocks is not the same! " + blockNum + " " + newChain.getBlockNum(), blockNum, newChain.getBlockNum()); for ( int i =0 ; i < blockNum ; i++){ int newLenI = newChain.getOptLen()[i]; - assertTrue("The values in the optLen field don't match! pos:" + i + " orig:" + optLen[i] + " new:" + newLenI,optLen[i] == newLenI); + assertEquals("The values in the optLen field don't match! pos:" + i + " orig:" + optLen[i] + " new:" + newLenI, optLen[i], newLenI); } // test the internal optAlign data structure: @@ -170,8 +171,8 @@ private void testAlignment(String name1, String name2, Atom[] ca1, Atom[] ca2, b int n1 = optAln2[i][0][j]; int n2 = optAln2[i][1][j]; - assertTrue(p1 == n1); - assertTrue(p2 == n2); + assertEquals(p1, n1); + assertEquals(p2, n2); } } @@ -187,7 +188,7 @@ private void testAlignment(String name1, String name2, Atom[] ca1, Atom[] ca2, b } - private AFPChain doAlign(String name1, String name2, Atom[] ca1, Atom[] ca2 , boolean doRigid) throws StructureException,IOException{ + private AFPChain doAlign(String name1, String name2, Atom[] ca1, Atom[] ca2 , boolean doRigid) throws StructureException { FatCatParameters params = new FatCatParameters(); FatCat fatCat = new FatCat(); @@ -222,14 +223,14 @@ public String[] align (String name1, String name2, Atom[] ca1, Atom[] ca2 , bool @org.junit.Test public void testMulti() throws IOException, StructureException { - Atom[] ca1 = null; - Atom[] ca2 = null; - Atom[] ca3 = null; - Atom[] ca4 = null; - Atom[] ca5 = null; - Atom[] ca6 = null; - String[] result1 = null; - String[] result2 = null; + Atom[] ca1; + Atom[] ca2; + Atom[] ca3; + Atom[] ca4; + Atom[] ca5; + Atom[] ca6; + String[] result1; + String[] result2; String name1 = "5pti.A"; String name2 = "1znf.A"; @@ -264,7 +265,7 @@ public void testMulti() throws IOException, StructureException { //WARNING: THE ORDER CAN CHANGE: order of elements in XML is not necessarily the same! AFPChain[] chains = AFPChainXMLParser.parseMultiXML(xmlNew); - assertTrue(chains.length == 2); + assertEquals(2, chains.length); // recreate the correct chains... AFPChain new1 = getAfpFor(name1,chains); @@ -273,16 +274,16 @@ public void testMulti() throws IOException, StructureException { assertNotNull(new1); assertNotNull(new2); - assertTrue(new1.getName1().equals(name1)); + assertEquals(new1.getName1(), name1); //System.out.println(new2.getName1() + " " + new2.getName2() + " "+ name3); - assertTrue(new2.getName1().equals(name3)); + assertEquals(new2.getName1(), name3); AFPChainXMLParser.rebuildAFPChain(new1, ca1, ca3); String fatcat1 = new1.toFatcat(ca1, ca3); assertEquals(fatcat1, result1[0]); String xmlnew1 = AFPChainXMLConverter.toXML(new1, ca1, ca3); - assertTrue(xmlnew1.equals(result1[1])); + assertEquals(xmlnew1, result1[1]); AFPChainXMLParser.rebuildAFPChain(new2, ca4, ca6); String fatcat2 = new2.toFatcat(ca4, ca6); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/FlipAFPChainTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/FlipAFPChainTest.java index 41a03bee70..85fa4750ca 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/FlipAFPChainTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/FlipAFPChainTest.java @@ -24,7 +24,10 @@ package org.biojava.nbio.structure.test.align.fatcat; -import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.Atom; +import org.biojava.nbio.structure.Calc; +import org.biojava.nbio.structure.StructureException; +import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.StructureAlignment; import org.biojava.nbio.structure.align.StructureAlignmentFactory; import org.biojava.nbio.structure.align.ce.CeMain; @@ -118,7 +121,7 @@ private void align (StructureAlignment algorithm, String name1, String name2) Assert.assertNotNull("could not get nr. of eqr: ", afpChain.getNrEQR()); Assert.assertNotNull("could not get nr. of eqr: ", origFlip.getNrEQR()); - Assert.assertTrue("The nr. of equivalent positions is not equal!", afpChain.getNrEQR() == origFlip.getNrEQR()); + Assert.assertEquals("The nr. of equivalent positions is not equal!", afpChain.getNrEQR(), origFlip.getNrEQR()); Atom shift1 = afpChain.getBlockShiftVector()[0]; Atom shift2 = origFlip.getBlockShiftVector()[0]; @@ -158,8 +161,7 @@ private void align (StructureAlignment algorithm, String name1, String name2) * @param ca2 * @return */ - private double getRMSD(AFPChain afpChain, Atom[] ca1, Atom[] ca2) - throws StructureException { + private double getRMSD(AFPChain afpChain, Atom[] ca1, Atom[] ca2) { Atom[] ca2clone = StructureTools.cloneAtomArray(ca2); rotateAtoms2(afpChain,ca2clone); @@ -169,9 +171,9 @@ private double getRMSD(AFPChain afpChain, Atom[] ca1, Atom[] ca2) Atom[] catmp1 = AFPAlignmentDisplay.getAlignedAtoms1(afpChain, ca1); Atom[] catmp2 = AFPAlignmentDisplay.getAlignedAtoms2(afpChain, ca2clone); - Assert.assertTrue(catmp1.length == catmp2.length); + Assert.assertEquals(catmp1.length, catmp2.length); - Assert.assertTrue(catmp1.length == afpChain.getNrEQR()); + Assert.assertEquals(catmp1.length, afpChain.getNrEQR()); return Calc.rmsd(catmp1,catmp2); } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/MyTestHelper.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/MyTestHelper.java index 1905b173af..0fc48c7a5e 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/MyTestHelper.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/MyTestHelper.java @@ -41,7 +41,7 @@ public class MyTestHelper public static String compareAlignment(String pdb1, String chain1, String pdb2, String chain2, String originalOutput, boolean doRigid){ - AFPChain afpChain = null; + AFPChain afpChain; PDBFileReader pdbpars = new PDBFileReader(); pdbpars.setPath(pdbPath); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/TestFlexibleRotationMatrices.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/TestFlexibleRotationMatrices.java index 5a4709e2e0..e4e7cac756 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/TestFlexibleRotationMatrices.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/TestFlexibleRotationMatrices.java @@ -24,7 +24,10 @@ package org.biojava.nbio.structure.test.align.fatcat; -import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.Atom; +import org.biojava.nbio.structure.Calc; +import org.biojava.nbio.structure.StructureException; +import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.StructureAlignment; import org.biojava.nbio.structure.align.fatcat.FatCatFlexible; import org.biojava.nbio.structure.align.fatcat.FatCatRigid; @@ -38,12 +41,11 @@ import org.biojava.nbio.structure.jama.Matrix; import org.junit.Test; +import javax.vecmath.Matrix4d; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import javax.vecmath.Matrix4d; - import static org.junit.Assert.*; public class TestFlexibleRotationMatrices { @@ -86,7 +88,7 @@ private void compare(String name1, String name2, boolean doRigid){ //Atom[] shifts1 = afpChain.getBlockShiftVector(); double[] blockRmsd = afpChain.getBlockRmsd(); - assertTrue( afpChain.getBlockNum() == newChain.getBlockNum()); + assertEquals(afpChain.getBlockNum(), newChain.getBlockNum()); // make sure the XML conversion worked OK. for ( int i = 0 ; i < newChain.getBlockNum();i++) { @@ -96,7 +98,7 @@ private void compare(String name1, String name2, boolean doRigid){ assertTrue(compareRmsd(blockRmsd[i], newChain.getBlockRmsd()[i]) ); } - assertTrue(afpChain.getOptLength() == newChain.getOptLength()); + assertEquals(afpChain.getOptLength(), newChain.getOptLength()); // get the aligned blocks and check RMSD int[] blockSize =afpChain.getBlockSize(); @@ -122,9 +124,7 @@ private void compare(String name1, String name2, boolean doRigid){ } - } catch (IOException e){ - fail(e.getMessage()); - } catch (StructureException e){ + } catch (IOException | StructureException e){ fail(e.getMessage()); } @@ -142,7 +142,7 @@ private boolean compareRmsd(double rmsdOrig, double rmsdNew) { } private void compareBlock(int blockNr, AFPChain afpChain, AFPChain newChain, - Atom[] ca1, Atom[] ca2) throws StructureException { + Atom[] ca1, Atom[] ca2) { @@ -161,9 +161,9 @@ private void compareBlock(int blockNr, AFPChain afpChain, AFPChain newChain, // get the eqr atoms of block X: int[] optLen =afpChain.getOptLen(); - List eqrPos1 = new ArrayList(); - List eqrPos2 = new ArrayList(); - List eqrPos2copy = new ArrayList(); + List eqrPos1 = new ArrayList<>(); + List eqrPos2 = new ArrayList<>(); + List eqrPos2copy = new ArrayList<>(); for ( int z = 0 ; z < blocks2[blockNr][0].length && z < optLen[blockNr] ; z++){ int pos1 = blocks2[blockNr][0][z]; int pos2 = blocks2[blockNr][1][z]; @@ -177,15 +177,15 @@ private void compareBlock(int blockNr, AFPChain afpChain, AFPChain newChain, eqrPos2copy.add(c3); } - assertTrue("The nr of Atoms in block " + blockNr + " does not match the expected nr. Expected:" + afpChain.getOptLen()[blockNr] + " but found: " + eqrPos2.size() , eqrPos2.size() == afpChain.getOptLen()[blockNr]); + assertEquals("The nr of Atoms in block " + blockNr + " does not match the expected nr. Expected:" + afpChain.getOptLen()[blockNr] + " but found: " + eqrPos2.size(), eqrPos2.size(), afpChain.getOptLen()[blockNr]); // THIS IS ROTATING the coordinates according to what is in the file. - Atom[] blockSet1 = eqrPos1.toArray(new Atom[eqrPos1.size()]); - Atom[] blockSet2 = eqrPos2.toArray(new Atom[eqrPos2.size()]); - Atom[] blockSet2copy = eqrPos2copy.toArray(new Atom[eqrPos2copy.size()]); + Atom[] blockSet1 = eqrPos1.toArray(Atom.EmptyAtomArray); + Atom[] blockSet2 = eqrPos2.toArray(Atom.EmptyAtomArray); + Atom[] blockSet2copy = eqrPos2copy.toArray(Atom.EmptyAtomArray); //System.out.println(shift ); @@ -248,7 +248,7 @@ private void compareBlock(int blockNr, AFPChain afpChain, AFPChain newChain, } - private boolean compareVectors(Atom atom1, Atom atom2) throws StructureException { + private boolean compareVectors(Atom atom1, Atom atom2) { //System.out.println(Math.abs(atom1.getX()- atom2.getX())); assertTrue("The X coordinates are too far apart!", Math.abs(atom1.getX()- atom2.getX()) < 0.01); @@ -270,7 +270,7 @@ private boolean compareMatrices(Matrix matrix1, Matrix matrix2) { } - private AFPChain getAlignment (String name1, String name2, Atom[] ca1, Atom[] ca2 , boolean doRigid) throws StructureException,IOException{ + private AFPChain getAlignment (String name1, String name2, Atom[] ca1, Atom[] ca2 , boolean doRigid) throws StructureException { FatCatParameters params = new FatCatParameters(); StructureAlignment fatCat ; diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/TestOutputStrings.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/TestOutputStrings.java index 4917d67cf3..0b9c1a7c4a 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/TestOutputStrings.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/TestOutputStrings.java @@ -207,31 +207,10 @@ public void test1buz1aliFlexible(){ String pdb2 = "1ali"; String chain2 ="A"; - String originalOutput ="Align 1buzA.pdb 116 with 1aliA.pdb 446" +newline + - "Twists 1 ini-len 64 ini-rmsd 3.12 opt-equ 88 opt-rmsd 3.34 chain-rmsd 5.32 Score 103.72 align-len 199 gaps 111 (55.78%)" +newline + - "P-value 3.26e-01 Afp-num 15578 Identity 6.25% Similarity 25.89%" +newline + - "Block 0 afp 1 score 23.14 rmsd 0.76 gap 0 (0.00%)" +newline + - "Block 1 afp 7 score 100.08 rmsd 3.32 gap 17 (0.23%)" +newline + - "" +newline + - " . : . : . : . : . : . : . :" +newline + - "Chain 1: 5 DMNVKESVLCIRLTGELDH---------------------------------HTAETLKQKVTQSLEKDD" +newline + - " 1 11111111111111 222222222222222222" +newline + - "Chain 2: 246 VTEANQQKPLLGLFADGNMPVRWLGPKATYHGNIDKPAVTCTPNPQRNDSVPTLAQMTDKAIELLSKNEK" +newline + - "" +newline + - " . : . : . : . : . : . : . :" +newline + - "Chain 1: 42 IRHIVLNLEDLS------------FMDSSGLGVILGRYKQIK-QIGGEMVVCAISPAVKRLFDMSGLFKI" +newline + - " 222222222222 222222222222222222 2222222222222 " +newline + - "Chain 2: 316 GFFLQVEGASIDKQDHAANPCGQIGETVDLDEAVQRALEFAKKEGNTLVIVTADHAHASQIVAPDTKAPG" +newline + - "" +newline + - " . : . : . : . : . : ." +newline + - "Chain 1: 99 I---------------------------------RFEQSE--------QQALLTLGVAS" +newline + - " 22 222222 2222" +newline + - "Chain 2: 386 LTQALNTKDGAVMVMSYGNSEEDSQENTGSQLRIAAYGPHAANVVGLTDQTDLFYTMKA" +newline + - "" +newline + - "Note: positions are from PDB; the numbers between alignments are block index" +newline ; + String originalOutput = "Align 1buzA.pdb 116 with 1aliA.pdb 446" + newline + "Twists 1 ini-len 64 ini-rmsd 3.12 opt-equ 88 opt-rmsd 3.34 chain-rmsd 5.32 Score 103.72 align-len 199 gaps 111 (55.78%)" + newline + "P-value 3.26e-01 Afp-num 15578 Identity 6.25% Similarity 25.89%" + newline + "Block 0 afp 1 score 23.14 rmsd 0.76 gap 0 (0.00%)" + newline + "Block 1 afp 7 score 100.08 rmsd 3.32 gap 17 (0.23%)" + newline + newline + " . : . : . : . : . : . : . :" + newline + "Chain 1: 5 DMNVKESVLCIRLTGELDH---------------------------------HTAETLKQKVTQSLEKDD" + newline + " 1 11111111111111 222222222222222222" + newline + "Chain 2: 246 VTEANQQKPLLGLFADGNMPVRWLGPKATYHGNIDKPAVTCTPNPQRNDSVPTLAQMTDKAIELLSKNEK" + newline + newline + " . : . : . : . : . : . : . :" + newline + "Chain 1: 42 IRHIVLNLEDLS------------FMDSSGLGVILGRYKQIK-QIGGEMVVCAISPAVKRLFDMSGLFKI" + newline + " 222222222222 222222222222222222 2222222222222 " + newline + "Chain 2: 316 GFFLQVEGASIDKQDHAANPCGQIGETVDLDEAVQRALEFAKKEGNTLVIVTADHAHASQIVAPDTKAPG" + newline + newline + " . : . : . : . : . : ." + newline + "Chain 1: 99 I---------------------------------RFEQSE--------QQALLTLGVAS" + newline + " 22 222222 2222" + newline + "Chain 2: 386 LTQALNTKDGAVMVMSYGNSEEDSQENTGSQLRIAAYGPHAANVVGLTDQTDLFYTMKA" + newline + newline + "Note: positions are from PDB; the numbers between alignments are block index" + newline; String result = MyTestHelper.compareAlignment(pdb1, chain1, pdb2, chain2, originalOutput,false); - if (! result.equals("")){ + if (!result.isEmpty()){ String msg = "the created alignment images are not identical! "; printMismatch(originalOutput,result); printFirstMismatch(result, originalOutput); @@ -327,25 +306,9 @@ public void test1a641hngFlexible(){ String pdb2 = "1hng"; String chain2 ="B"; - String originalOutput="Align 1a64A.pdb 94 with 1hngB.pdb 175" +newline + - "Twists 1 ini-len 88 ini-rmsd 1.84 opt-equ 94 opt-rmsd 0.64 chain-rmsd 20.77 Score 235.94 align-len 96 gaps 2 (2.08%)" +newline + - "P-value 4.23e-13 Afp-num 6497 Identity 98.94% Similarity 100.00%" +newline + - "Block 0 afp 5 score 118.80 rmsd 0.75 gap 0 (0.00%)" +newline + - "Block 1 afp 6 score 143.14 rmsd 0.46 gap 0 (0.00%)" +newline + - "" +newline + - " . : . : . : . : . : . : . :" +newline + - "Chain 1: 4 GTVWGALGHGINLNIPNFQMTDDIDEVRWERGSTLVAEFKR--KPFLKSGAFEILANGDLKIKNLTRDDS" +newline + - " 11111111111111111111111111111111111111111 222222222222222222222222222" +newline + - "Chain 2: 4 GTVWGALGHGINLNIPNFQMTDDIDEVRWERGSTLVAEFKRKMKPFLKSGAFEILANGDLKIKNLTRDDS" +newline + - "" +newline + - " . : . : ." +newline + - "Chain 1: 74 GTYNVTVYSTNGTRILDKALDLRILE" +newline + - " 22222222222222222222222222" +newline + - "Chain 2: 74 GTYNVTVYSTNGTRILNKALDLRILE" +newline + - "" +newline + - "Note: positions are from PDB; the numbers between alignments are block index" +newline ; + String originalOutput= "Align 1a64A.pdb 94 with 1hngB.pdb 175" + newline + "Twists 1 ini-len 88 ini-rmsd 1.84 opt-equ 94 opt-rmsd 0.64 chain-rmsd 20.77 Score 235.94 align-len 96 gaps 2 (2.08%)" + newline + "P-value 4.23e-13 Afp-num 6497 Identity 98.94% Similarity 100.00%" + newline + "Block 0 afp 5 score 118.80 rmsd 0.75 gap 0 (0.00%)" + newline + "Block 1 afp 6 score 143.14 rmsd 0.46 gap 0 (0.00%)" + newline + newline + " . : . : . : . : . : . : . :" + newline + "Chain 1: 4 GTVWGALGHGINLNIPNFQMTDDIDEVRWERGSTLVAEFKR--KPFLKSGAFEILANGDLKIKNLTRDDS" + newline + " 11111111111111111111111111111111111111111 222222222222222222222222222" + newline + "Chain 2: 4 GTVWGALGHGINLNIPNFQMTDDIDEVRWERGSTLVAEFKRKMKPFLKSGAFEILANGDLKIKNLTRDDS" + newline + newline + " . : . : ." + newline + "Chain 1: 74 GTYNVTVYSTNGTRILDKALDLRILE" + newline + " 22222222222222222222222222" + newline + "Chain 2: 74 GTYNVTVYSTNGTRILNKALDLRILE" + newline + newline + "Note: positions are from PDB; the numbers between alignments are block index" + newline; String result = MyTestHelper.compareAlignment(pdb1, chain1, pdb2, chain2, originalOutput,false); - if (! result.equals("")){ + if (!result.isEmpty()){ String msg = "the created alignment images are not identical! "; printMismatch(originalOutput,result); printFirstMismatch(result, originalOutput); @@ -509,31 +472,10 @@ public void test1a211hwgFlexible(){ String pdb2 = "1hwg"; String chain2 ="C"; - String originalOutput="Align 1a21A.pdb 194 with 1hwgC.pdb 191" +newline + - "Twists 1 ini-len 120 ini-rmsd 3.04 opt-equ 150 opt-rmsd 2.96 chain-rmsd 4.21 Score 233.34 align-len 210 gaps 60 (28.57%)" +newline + - "P-value 1.15e-05 Afp-num 12696 Identity 11.98% Similarity 23.95%" +newline + - "Block 0 afp 4 score 66.42 rmsd 2.03 gap 6 (0.16%)" +newline + - "Block 1 afp 11 score 184.29 rmsd 3.24 gap 69 (0.44%)" +newline + - "" +newline + - " . : . : . : . : . : . : . :" +newline + - "Chain 1: 6 RAYNLTWKSTN-FKTILEWEPKSIDHVYTVQISTRLENWKSKCFLTAE---TECDLTDEVVKDVGQTYMA" +newline + - " 11111111111 111111111 111111111111111111 222222222 222222 " +newline + - "Chain 2: 32 EPKFTKCRSPERETFSCHWTD-----PIQLFYTRRNQEWKECPDYVSAGENSCYFNSSFT---SIWIPYC" +newline + - "" +newline + - " . : . : . : . : . : . : . :" +newline + - "Chain 1: 72 RVLSYPARNTTGFPEEPPFRNSPEFTPYLDTNLGQPTIQSFEQVG-------TKLNVTVQDARTLVTFLS" +newline + - " 22222222222222222222222 222222222222 222" +newline + - "Chain 2: 109 IKLTSNGGTVDE----------KCFSVDEIVQPDPPIALNWTLLNVSLTGIHADIQVRWEAPRN---ADI" +newline + - "" +newline + - " . : . : . : . : . : . : . :" +newline + - "Chain 1: 141 LRAVFGKDLNYTLYYWR-----KKTAT-TNTNEFLIDVDKGE-NYCFSVQAVIPSRKRKQRSPESLTECT" +newline + - " 222222 222222222 22222 22222222222222 2222222222222 222222222222" +newline + - "Chain 2: 166 QKGWMV--LEYELQYKEVNETKWKMMDPILTTSVPVYSLKVDKEYEVRVRSKQRNS--GNYGEFSEVLYV" +newline + - "" +newline + - "Note: positions are from PDB; the numbers between alignments are block index" +newline; + String originalOutput= "Align 1a21A.pdb 194 with 1hwgC.pdb 191" + newline + "Twists 1 ini-len 120 ini-rmsd 3.04 opt-equ 150 opt-rmsd 2.96 chain-rmsd 4.21 Score 233.34 align-len 210 gaps 60 (28.57%)" + newline + "P-value 1.15e-05 Afp-num 12696 Identity 11.98% Similarity 23.95%" + newline + "Block 0 afp 4 score 66.42 rmsd 2.03 gap 6 (0.16%)" + newline + "Block 1 afp 11 score 184.29 rmsd 3.24 gap 69 (0.44%)" + newline + newline + " . : . : . : . : . : . : . :" + newline + "Chain 1: 6 RAYNLTWKSTN-FKTILEWEPKSIDHVYTVQISTRLENWKSKCFLTAE---TECDLTDEVVKDVGQTYMA" + newline + " 11111111111 111111111 111111111111111111 222222222 222222 " + newline + "Chain 2: 32 EPKFTKCRSPERETFSCHWTD-----PIQLFYTRRNQEWKECPDYVSAGENSCYFNSSFT---SIWIPYC" + newline + newline + " . : . : . : . : . : . : . :" + newline + "Chain 1: 72 RVLSYPARNTTGFPEEPPFRNSPEFTPYLDTNLGQPTIQSFEQVG-------TKLNVTVQDARTLVTFLS" + newline + " 22222222222222222222222 222222222222 222" + newline + "Chain 2: 109 IKLTSNGGTVDE----------KCFSVDEIVQPDPPIALNWTLLNVSLTGIHADIQVRWEAPRN---ADI" + newline + newline + " . : . : . : . : . : . : . :" + newline + "Chain 1: 141 LRAVFGKDLNYTLYYWR-----KKTAT-TNTNEFLIDVDKGE-NYCFSVQAVIPSRKRKQRSPESLTECT" + newline + " 222222 222222222 22222 22222222222222 2222222222222 222222222222" + newline + "Chain 2: 166 QKGWMV--LEYELQYKEVNETKWKMMDPILTTSVPVYSLKVDKEYEVRVRSKQRNS--GNYGEFSEVLYV" + newline + newline + "Note: positions are from PDB; the numbers between alignments are block index" + newline; String result = MyTestHelper.compareAlignment(pdb1, chain1, pdb2, chain2, originalOutput,false); - if (! result.equals("")){ + if (!result.isEmpty()){ String msg = "the created alignment images are not identical! "; printMismatch(originalOutput,result); printFirstMismatch(result, originalOutput); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/qsalign/TestQsAlignExamples.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/qsalign/TestQsAlignExamples.java index b9ad316c4b..f30670097b 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/qsalign/TestQsAlignExamples.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/qsalign/TestQsAlignExamples.java @@ -20,10 +20,6 @@ */ package org.biojava.nbio.structure.test.align.qsalign; -import static org.junit.Assert.*; - -import java.io.IOException; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; @@ -34,6 +30,11 @@ import org.biojava.nbio.structure.cluster.SubunitClustererParameters; import org.junit.Test; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + /** * Test the correctness of the {@link QsAlign} algorithm with some examples of * different levels of quaternary structure similarity. diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/seq/TestSmithWaterman3Daligner.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/seq/TestSmithWaterman3Daligner.java index ce6ade5543..129717d1b2 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/seq/TestSmithWaterman3Daligner.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/seq/TestSmithWaterman3Daligner.java @@ -20,10 +20,6 @@ */ package org.biojava.nbio.structure.test.align.seq; -import static org.junit.Assert.*; - -import java.io.IOException; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; @@ -33,6 +29,11 @@ import org.biojava.nbio.structure.align.seq.SmithWaterman3Daligner; import org.junit.Test; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + /** * Test the superposition based on a sequence alignment on different cases. * diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/cluster/TestSubunitClustererExamples.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/cluster/TestSubunitClustererExamples.java index 161a4c8b96..6f5b8ffdba 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/cluster/TestSubunitClustererExamples.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/cluster/TestSubunitClustererExamples.java @@ -20,13 +20,6 @@ */ package org.biojava.nbio.structure.test.cluster; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.List; -import java.util.function.Function; -import java.util.stream.Collectors; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; @@ -37,6 +30,14 @@ import org.biojava.nbio.structure.symmetry.core.Stoichiometry; import org.junit.Test; +import java.io.IOException; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + /** * Test the {@link SubunitClusterer} clustering correctness on different real * structures with different types of chain clustering difficulties. diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/ecod/EcodInstallationTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/ecod/EcodInstallationTest.java index 8ab3f29fb3..63dc49048e 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/ecod/EcodInstallationTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/ecod/EcodInstallationTest.java @@ -20,24 +20,6 @@ package org.biojava.nbio.structure.test.ecod; -import static org.junit.Assert.*; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import org.biojava.nbio.core.util.ConcurrencyTools; import org.biojava.nbio.structure.ResidueNumber; import org.biojava.nbio.structure.ResidueRange; @@ -54,6 +36,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.concurrent.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.Assert.*; + /** * @author Spencer Bliven * @@ -148,7 +139,7 @@ public void testByPDB() throws IOException { private void matchNames(String pdbId,String[] expected,List actual) { assertEquals("Wrong number of domains for "+pdbId, expected.length, actual.size()); - Set exp = new HashSet(Arrays.asList(expected)); + Set exp = new HashSet<>(Arrays.asList(expected)); for(EcodDomain d : actual) { assertTrue("Unexpected domain "+d.getDomainId()+" in "+pdbId,exp.contains(d.getDomainId())); } @@ -175,7 +166,7 @@ public void testParsing() throws IOException { } expected = new EcodDomain( // Long uid, String domainId, Boolean manual, - 20669l, "e1lyw.1", false, + 20669L, "e1lyw.1", false, // Integer xGroup, Integer hGroup, Integer tGroup, Integer fGroup, String pdbId, 1,1,1,fGroup,"1lyw", // String chainName, String range, String seqId, String architectureName, @@ -184,7 +175,7 @@ public void testParsing() throws IOException { "cradle loop barrel", "RIFT-related","acid protease", // String fGroupName, Boolean isAssembly, List ligands fGroupName, - 20669l, Collections.singleton("EPE") + 20669L, Collections.singleton("EPE") ); assertEquals(ecodId,expected,domain); @@ -195,13 +186,13 @@ public void testParsing() throws IOException { } @Test - public void testMultithreaded() throws IOException { + public void testMultithreaded() { final EcodInstallation ecod = (EcodInstallation) EcodFactory.getEcodDatabase(VERSION); ecod.clear(); String[] ecodIds = new String[] { "e4s1gA1", "e4umoB1", "e4v0cA1", "e4v1af1", "e3j7yj1", "e4wfcA1","e4b0jP1", }; - List> futureDomains = new ArrayList>(); + List> futureDomains = new ArrayList<>(); for(final String ecodId : ecodIds) { Callable job = new Callable() { @Override @@ -246,8 +237,8 @@ public void testFilterByHierarchy() throws IOException { Set expected,actual; // expected members through at least develop133 - expected = new HashSet(Arrays.asList( - "e4il6R1 e4pj0R1 e4pj0r1 e4ub6R1 e4ub8R1".split(" ") )); + expected = new HashSet<>(Arrays.asList( + "e4il6R1 e4pj0R1 e4pj0r1 e4ub6R1 e4ub8R1".split(" "))); // expanded by develop204 if( ecod.getVersion().compareToIgnoreCase("develop204") >= 0) { expected.addAll(Arrays.asList( @@ -256,21 +247,21 @@ public void testFilterByHierarchy() throws IOException { } filtered = ecod.filterByHierarchy("6106.1.1"); - actual = new HashSet(); + actual = new HashSet<>(); for(EcodDomain d : filtered) { actual.add(d.getDomainId()); } assertEquals(expected,actual); filtered = ecod.filterByHierarchy("6106.1"); - actual = new HashSet(); + actual = new HashSet<>(); for(EcodDomain d : filtered) { actual.add(d.getDomainId()); } assertEquals(expected,actual); filtered = ecod.filterByHierarchy("6106"); - actual = new HashSet(); + actual = new HashSet<>(); for(EcodDomain d : filtered) { actual.add(d.getDomainId()); } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/ecod/EcodParseTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/ecod/EcodParseTest.java index 96d7e31d62..1d741033a7 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/ecod/EcodParseTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/ecod/EcodParseTest.java @@ -20,17 +20,7 @@ */ package org.biojava.nbio.structure.test.ecod; -import java.io.IOException; -import java.util.List; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.AtomPositionMap; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.ResidueRange; -import org.biojava.nbio.structure.ResidueRangeAndLength; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.ecod.EcodDatabase; import org.biojava.nbio.structure.ecod.EcodDomain; @@ -39,6 +29,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.List; + /** * This is not a unit test. * @@ -85,11 +78,7 @@ private static int testVersion(String ecodVersion) throws IOException { try { struct = cache.getStructure(d.getPdbId()); ca1 = StructureTools.getRepresentativeAtomArray(struct); - } catch (IOException e) { - logger.error("Error getting structure for "+d.getDomainId(),e); - errors++; - continue; - } catch (StructureException e) { + } catch (IOException | StructureException e) { logger.error("Error getting structure for "+d.getDomainId(),e); errors++; continue; @@ -111,6 +100,7 @@ private static int testVersion(String ecodVersion) throws IOException { for(ResidueRange r : ranges) { if( r == null ) { clean = false; + break; } } if( ! clean ) { @@ -128,12 +118,11 @@ private static int testVersion(String ecodVersion) throws IOException { Group g = struct.getPolyChainByPDB(range.getStart().getChainName()).getGroupByPDB(range.getStart()); if(g!=null) { logger.warn("No CA atom for starting residue "+d.getDomainId()+"_"+range); - clean = false; - } else { + } else { logger.error("Start doesn't exist for "+d.getDomainId()+"_"+range.toString()); - clean = false; - } - } + } + clean = false; + } } catch(Exception e) { logger.error("Start doesn't exist for "+d.getDomainId()+"_"+range.toString(),e); clean = false; @@ -147,12 +136,11 @@ private static int testVersion(String ecodVersion) throws IOException { } catch(StructureException e ) {} if(g!=null) { logger.warn("No CA atom for ending residue "+d.getDomainId()+"_"+range); - clean = false; - } else { + } else { logger.error("End doesn't exist for "+d.getDomainId()+"_"+range.toString()); - clean = false; - } - } + } + clean = false; + } } catch(Exception e) { logger.error("End doesn't exist for "+d.getDomainId()+"_"+range.toString(),e); clean = false; @@ -172,6 +160,7 @@ private static int testVersion(String ecodVersion) throws IOException { for(ResidueRange r : ranges) { if( r == null ) { clean = false; + break; } } if( ! clean ) { diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/geometry/TestProteinSuperposition.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/geometry/TestProteinSuperposition.java index 8d30a82f4d..4464b7d1dd 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/geometry/TestProteinSuperposition.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/geometry/TestProteinSuperposition.java @@ -20,18 +20,7 @@ */ package org.biojava.nbio.structure.test.geometry; -import static org.junit.Assert.*; - -import java.io.IOException; - -import javax.vecmath.Point3d; - -import org.biojava.nbio.structure.Calc; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.geometry.SuperPosition; import org.biojava.nbio.structure.geometry.SuperPositionQCP; import org.biojava.nbio.structure.geometry.SuperPositionQuat; @@ -39,6 +28,11 @@ import org.junit.BeforeClass; import org.junit.Test; +import javax.vecmath.Point3d; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + public class TestProteinSuperposition { private static Point3d[] chain1; diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/LoadOldXMLfileTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/LoadOldXMLfileTest.java index 69c52dd2de..97f10a7ca4 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/LoadOldXMLfileTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/LoadOldXMLfileTest.java @@ -94,7 +94,7 @@ public static String convertStreamToString(InputStream stream) throws IOExceptio BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder sb = new StringBuilder(); - String line = null; + String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/StructureIOTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/StructureIOTest.java index c6a3cdab86..7082c455f5 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/StructureIOTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/StructureIOTest.java @@ -20,14 +20,14 @@ */ package org.biojava.nbio.structure.test.io; -import static org.junit.Assert.*; - -import java.io.IOException; - import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; import org.junit.Test; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + /** * Test StructureIO methods. * diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/Test4v5a.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/Test4v5a.java index 006396e8cb..c9b65aa83e 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/Test4v5a.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/Test4v5a.java @@ -22,9 +22,6 @@ //import static org.junit.Assert.*; -import java.io.IOException; - - import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.util.AtomCache; @@ -32,6 +29,8 @@ import org.junit.Ignore; import org.junit.Test; +import java.io.IOException; + /** * Test for a difficult large mmCIF file (a ribosome) with many 2-letter chain ids. * Both tests are set to Ignore because the parsing of the file takes too long. diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestBioassemblies.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestBioassemblies.java index 23a73a7ae8..b8370dbd02 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestBioassemblies.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestBioassemblies.java @@ -20,11 +20,6 @@ */ package org.biojava.nbio.structure.test.io; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.List; - import org.biojava.nbio.structure.Chain; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; @@ -32,6 +27,11 @@ import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Test; +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.*; + public class TestBioassemblies { @@ -191,8 +191,8 @@ public void test4OPJ() throws IOException, StructureException { List model = multiModelBioAssemblies.get(0).getModel(modelIdx); for (Chain c:model) { System.out.println(c.getId()+" "+c.getName()); - assertTrue(!c.getId().contains("_")); - assertTrue(!c.getName().contains("_")); + assertFalse(c.getId().contains("_")); + assertFalse(c.getName().contains("_")); } } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestCrystallographicMetadata.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestCrystallographicMetadata.java index 26f83b7a28..f52a6d2524 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestCrystallographicMetadata.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestCrystallographicMetadata.java @@ -20,12 +20,12 @@ */ package org.biojava.nbio.structure.test.io; -import org.junit.Test; -import static org.junit.Assert.*; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.util.AtomCache; +import org.junit.Test; + +import static org.junit.Assert.*; /** * A test for the parsing of some crystallographic metadata: non standard space group and non standard coordinate frame convention. diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestLongPdbVsMmCifParsing.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestLongPdbVsMmCifParsing.java index daadcc7023..efcc5686f8 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestLongPdbVsMmCifParsing.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestLongPdbVsMmCifParsing.java @@ -26,11 +26,7 @@ import org.biojava.nbio.structure.io.LocalPDBDirectory.ObsoleteBehavior; import org.biojava.nbio.structure.quaternary.BioAssemblyInfo; import org.biojava.nbio.structure.xtal.CrystalCell; -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.ComparisonFailure; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -100,9 +96,9 @@ public static void setUpBeforeClass() { (cache.getPath().equals(System.getProperty("java.io.tmpdir")+File.separator)) ) { throw new IllegalArgumentException("PDB_DIR has not been set or it is set to the default temp directory. Please set PDB_DIR to run this test"); - }; + } - params = new FileParsingParameters(); + params = new FileParsingParameters(); cache.setFileParsingParams(params); cache.setObsoleteBehavior(ObsoleteBehavior.THROW_EXCEPTION); } @@ -130,7 +126,7 @@ public void testVeryLongPdbVsMmCif() throws IOException, StructureException { @Ignore @Test public void testSingle() throws IOException, StructureException { - testAll(Arrays.asList("4kro")); + testAll(Collections.singletonList("4kro")); } @After @@ -141,7 +137,7 @@ public void printInfo() { private void testAll(List pdbIds) throws IOException, StructureException { - pdbIdsWithMismatchingMolIds = new HashSet(); + pdbIdsWithMismatchingMolIds = new HashSet<>(); long start = System.currentTimeMillis(); @@ -229,7 +225,10 @@ private void testStructureMethods(Structure sPdb, Structure sCif) { // sugar polymers are not in pdb at all: we avoid them boolean canCompareEntityCounts = true; for (EntityInfo e:sCif.getEntityInfos()) { - if (e.getDescription().contains("SUGAR")) canCompareEntityCounts = false; + if (e.getDescription().contains("SUGAR")) { + canCompareEntityCounts = false; + break; + } } if (canCompareEntityCounts) { int entCountCif = 0; @@ -358,7 +357,7 @@ private void testHeader(Structure sPdb, Structure sCif) { if (ciPdb.getNcsOperators()==null) { - assertTrue(ciCif.getNcsOperators()==null); + assertNull(ciCif.getNcsOperators()); } else { Matrix4d[] ncsOpersPdb = ciPdb.getNcsOperators(); @@ -393,18 +392,19 @@ private void testHeader(Structure sPdb, Structure sCif) { hPdb.getNrBioAssemblies(),batPdb.size()); assertEquals("Size of bioassemblies maps don't coincide",batPdb.size(), batCif.size()); - for (int id:batPdb.keySet()) { + for (Map.Entry entry : batPdb.entrySet()) { + int id = entry.getKey(); assertTrue("Bioassembly id is not contained in mmCIF",batCif.containsKey(id)); // there's an inconsistency in 4amh pdb vs mmCIF in mmSize if (sPdb.getPDBCode().equalsIgnoreCase("4amh")) continue; assertEquals("Macromolecular size of assembly "+id+" doesn't coincide", - batPdb.get(id).getMacromolecularSize(), batCif.get(id).getMacromolecularSize()); + entry.getValue().getMacromolecularSize(), batCif.get(id).getMacromolecularSize()); } } } - private void testChains(Structure sPdb, Structure sCif) throws StructureException { + private void testChains(Structure sPdb, Structure sCif) { assertNotNull(sPdb.getChains()); assertNotNull(sCif.getChains()); @@ -432,7 +432,7 @@ private void testChains(Structure sPdb, Structure sCif) throws StructureExceptio - Set chainIds = new TreeSet(); + Set chainIds = new TreeSet<>(); for (Chain chain:sPdb.getPolyChains()){ chainIds.add(chain.getName()); } @@ -601,7 +601,7 @@ private List readTestSetFile(String testSetFile) throws IOException { InputStream inStream = this.getClass().getResourceAsStream(testSetFile); BufferedReader br = new BufferedReader(new InputStreamReader(inStream)); - List list = new ArrayList(); + List list = new ArrayList<>(); String line; while ((line=br.readLine())!=null) { diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestNcsOpsParsing.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestNcsOpsParsing.java index 390d68eab7..6ccb5e9fb8 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestNcsOpsParsing.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestNcsOpsParsing.java @@ -20,18 +20,17 @@ */ package org.biojava.nbio.structure.test.io; -import static org.junit.Assert.*; - -import java.io.IOException; - -import javax.vecmath.Matrix4d; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Test; +import javax.vecmath.Matrix4d; +import java.io.IOException; + +import static org.junit.Assert.*; + public class TestNcsOpsParsing { /** diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestSeqResParsing.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestSeqResParsing.java index de6c072719..3e45656211 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestSeqResParsing.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestSeqResParsing.java @@ -24,16 +24,11 @@ package org.biojava.nbio.structure.test.io; -import java.io.IOException; - -import org.biojava.nbio.structure.AminoAcid; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Test; -import org.biojava.nbio.structure.StructureIO; + +import java.io.IOException; import static org.junit.Assert.*; diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestStructWithMultiparentChemComp.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestStructWithMultiparentChemComp.java index cbedb5b108..7eefa0e010 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestStructWithMultiparentChemComp.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestStructWithMultiparentChemComp.java @@ -20,14 +20,13 @@ */ package org.biojava.nbio.structure.test.io; -import org.junit.Test; -import static org.junit.Assert.*; - - import org.biojava.nbio.structure.Chain; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.util.AtomCache; +import org.junit.Test; + +import static org.junit.Assert.*; public class TestStructWithMultiparentChemComp { diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/cif/CifFileConsumerIntegrationTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/cif/CifFileConsumerIntegrationTest.java index 9101ee5524..fc03ec003b 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/cif/CifFileConsumerIntegrationTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/cif/CifFileConsumerIntegrationTest.java @@ -1,17 +1,7 @@ package org.biojava.nbio.structure.test.io.cif; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.DBRef; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.GroupType; -import org.biojava.nbio.structure.PDBHeader; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.io.BcifFileReader; -import org.biojava.nbio.structure.io.CifFileReader; -import org.biojava.nbio.structure.io.FileParsingParameters; -import org.biojava.nbio.structure.io.LocalPDBDirectory; -import org.biojava.nbio.structure.io.PDBFileParser; +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.io.*; import org.junit.Test; import java.io.IOException; diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/cif/CifFileSupplierIntegrationTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/cif/CifFileSupplierIntegrationTest.java index 03e2f6f060..16076c1fea 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/cif/CifFileSupplierIntegrationTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/cif/CifFileSupplierIntegrationTest.java @@ -1,17 +1,6 @@ package org.biojava.nbio.structure.test.io.cif; -import org.biojava.nbio.structure.AminoAcidImpl; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.AtomImpl; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ChainImpl; -import org.biojava.nbio.structure.Element; -import org.biojava.nbio.structure.EntityInfo; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureImpl; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.io.cif.CifFileConverter; import org.junit.Test; diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/BerkeleyScopInstallationTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/BerkeleyScopInstallationTest.java index 96c01ae03c..5d47b6bbdb 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/BerkeleyScopInstallationTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/BerkeleyScopInstallationTest.java @@ -42,7 +42,7 @@ public BerkeleyScopInstallationTest(String tag,ScopDatabase scop) { } @Parameters(name="{0}") public static Collection availableDatabases() { - ArrayList databases = new ArrayList(); + ArrayList databases = new ArrayList<>(); ScopInstallation scop; for(String version : new String[] { diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/RemoteScopInstallationTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/RemoteScopInstallationTest.java index 2abe7d63ae..74cd9df51c 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/RemoteScopInstallationTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/RemoteScopInstallationTest.java @@ -46,7 +46,7 @@ public RemoteScopInstallationTest(String tag,ScopDatabase scop) { //@Parameters @Parameters(name="{0}") public static Collection availableDatabases() { - ArrayList databases = new ArrayList(); + ArrayList databases = new ArrayList<>(); RemoteScopInstallation scop; for(String version : new String[] { ScopFactory.LATEST_VERSION, diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopDatabaseTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopDatabaseTest.java index 2a34d017f1..3813498846 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopDatabaseTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopDatabaseTest.java @@ -46,8 +46,8 @@ */ @RunWith(Parameterized.class) public abstract class ScopDatabaseTest { - protected ScopDatabase scop; - String tag; + protected final ScopDatabase scop; + final String tag; /** * @@ -94,7 +94,7 @@ public void traverseHierarchy() desc = scop.getScopDescriptionBySunid(node.getSunid()); assertEquals(tag,46487,node.getSunid()); assertEquals(tag,"-",desc.getName()); - assertTrue(tag,Pattern.matches("Human \\(Homo sapiens\\)( \\[TaxId: 9606\\])?",desc.getDescription())); + assertTrue(tag,Pattern.matches("Human \\(Homo sapiens\\)( \\[TaxId: 9606])?",desc.getDescription())); assertEquals(tag,"a.1.1.2",desc.getClassificationId()); node = scop.getScopNode(node.getParentSunid()); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopInstallationTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopInstallationTest.java index c1c940da84..c1b7e3be5b 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopInstallationTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopInstallationTest.java @@ -47,7 +47,7 @@ public ScopInstallationTest(String tag,ScopDatabase scop) { //@Parameters @Parameters(name="{0}") public static Collection availableDatabases() { - ArrayList databases = new ArrayList(); + ArrayList databases = new ArrayList<>(); ScopInstallation scop; for(String version : new String[] { diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopTest.java index f7d5e8fdee..305916aea5 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopTest.java @@ -20,11 +20,7 @@ */ package org.biojava.nbio.structure.test.scop; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.GroupIterator; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.scop.ScopDatabase; import org.biojava.nbio.structure.scop.ScopDomain; @@ -35,7 +31,8 @@ import java.io.IOException; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; //import org.biojava.nbio.structure.scop.RemoteScopInstallation; @@ -43,7 +40,7 @@ public class ScopTest { - boolean debug = false; + final boolean debug = false; @Test public void testLocalScop() throws IOException, StructureException{ @@ -98,11 +95,11 @@ private void runSCOPTests() throws IOException, StructureException { List domains = scop.getDomainsForPDB("4HHB"); - assertTrue(domains.size() == 4); + assertEquals(4, domains.size()); // test case sensitivity; List domains2 = scop.getDomainsForPDB("4hhb"); - assertTrue(domains2.size() == domains.size()); + assertEquals(domains2.size(), domains.size()); //System.out.println(domains); @@ -110,7 +107,7 @@ private void runSCOPTests() throws IOException, StructureException { String scop1m02 = "d1m02a_ 1m02 A: k.36.1.1 74353 cl=58788,cf=75796,sf=75797,fa=75798,dm=75799,sp=75800,px=74353"; List domains1m02 = scop.getDomainsForPDB("1m02"); - assertTrue(domains1m02.size() == 1); + assertEquals(1, domains1m02.size()); ScopDomain d1 = domains1m02.get(0); assertNotNull(d1); @@ -119,7 +116,7 @@ private void runSCOPTests() throws IOException, StructureException { List domains1cdg = scop.getDomainsForPDB("1CDG"); - assertTrue(domains1cdg.size() == 4); + assertEquals(4, domains1cdg.size()); ScopDomain d2 = domains1cdg.get(0); assertEquals("Wrong SCOP Id", "d1cdga1", d2.getScopId()); AtomCache cache = new AtomCache(); @@ -146,7 +143,7 @@ private void runSCOPTests() throws IOException, StructureException { // check a domain with multiple ranges List domains1xzp = scop.getDomainsForPDB("1xzp"); - assertTrue(domains1xzp.size() ==4 ); + assertEquals(4, domains1xzp.size()); @@ -163,7 +160,7 @@ private void runSCOPTests() throws IOException, StructureException { // check insertion codes List domains2bq6 = scop.getDomainsForPDB("2bq6"); - assertTrue(domains2bq6.size() == 2); + assertEquals(2, domains2bq6.size()); ScopDomain target = scop.getDomainByScopID("d2bq6a1"); assertNotNull(target); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/symmetry/TestQuatSymmetryDetectorExamples.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/symmetry/TestQuatSymmetryDetectorExamples.java index a5cd0a9fb4..9ceec479d9 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/symmetry/TestQuatSymmetryDetectorExamples.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/symmetry/TestQuatSymmetryDetectorExamples.java @@ -20,11 +20,6 @@ */ package org.biojava.nbio.structure.test.symmetry; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.*; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; @@ -45,6 +40,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.*; + /** * Test the {@link QuatSymmetryDetector} algorithm for symmetry detection on a * variety of structures with different symmetries. @@ -267,7 +270,7 @@ public void testLocal() throws IOException, StructureException { for (QuatSymmetryResults local:foundLocal) { logger.info("Found stoichiometry "+local.getStoichiometry().toString()+" with symmetry "+local.getSymmetry()); assertTrue("Stoichiometry "+local.getStoichiometry().toString()+" not expected for "+testIds.get(iTest), - refLocal.keySet().contains(local.getStoichiometry().toString())); + refLocal.containsKey(local.getStoichiometry().toString())); assertEquals("Symmetry "+local.getSymmetry()+" with stoichiometry "+local.getStoichiometry().toString()+ " not expected for "+testIds.get(iTest), diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/xtal/TestCrystalBuilder.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/xtal/TestCrystalBuilder.java index 898e108a8e..710cac54f6 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/xtal/TestCrystalBuilder.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/xtal/TestCrystalBuilder.java @@ -33,7 +33,7 @@ import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; public class TestCrystalBuilder { diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/phosphosite/Dataset.java b/biojava-modfinder/src/main/java/org/biojava/nbio/phosphosite/Dataset.java index 71604d9bb3..a993a42ace 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/phosphosite/Dataset.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/phosphosite/Dataset.java @@ -82,11 +82,11 @@ public File[] getLocalFiles(){ File dir = getLocalDir(); - List files = new ArrayList(); + List files = new ArrayList<>(); for ( String f : rfiles) { - int slashIndex = f.lastIndexOf("/"); + int slashIndex = f.lastIndexOf('/'); String fileName = f.substring(slashIndex); @@ -98,7 +98,7 @@ public File[] getLocalFiles(){ } - return files.toArray(new File[files.size()]); + return files.toArray(new File[0]); } @@ -135,7 +135,7 @@ public void download(){ try { - int slashIndex = f.lastIndexOf("/"); + int slashIndex = f.lastIndexOf('/'); String fileName = f.substring(slashIndex); @@ -170,7 +170,7 @@ public void downloadFile(URL u, File localFile) throws IOException { FileOutputStream w = new FileOutputStream(tmp); - int i= 0; + int i; byte[] bytesIn = new byte[300000]; while ((i = in.read(bytesIn)) >= 0) { w.write(bytesIn,0,i); diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/phosphosite/Site.java b/biojava-modfinder/src/main/java/org/biojava/nbio/phosphosite/Site.java index ca5e4a5f2f..bb3c1f52e4 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/phosphosite/Site.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/phosphosite/Site.java @@ -25,6 +25,7 @@ import java.io.*; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.zip.GZIPInputStream; @@ -48,11 +49,11 @@ public static List parseSites(File f) throws IOException { Reader decoder = new InputStreamReader(gzipStream); BufferedReader buf = new BufferedReader(decoder); - String line = null; + String line; - List data = new ArrayList(); + List data = new ArrayList<>(); - List headerFields = null; + List headerFields; int proteinIndex = -1; int uniprotIndex = -1; @@ -131,11 +132,7 @@ public static List parseSites(File f) throws IOException { private static List parseHeaderFields(String line) { String[] spl = line.split("\t"); - List h = new ArrayList(); - for (String s: spl){ - h.add(s); - - } + List h = new ArrayList<>(Arrays.asList(spl)); return h; } @@ -215,26 +212,24 @@ public void setOrganism(String organism) { @Override public String toString() { - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(); - s.append("Site{" + - "protein='" + protein + '\''); + s.append("Site{" + "protein='").append(protein).append('\''); if ( uniprot != null) - s.append(", uniprot='" + uniprot + '\'' ); + s.append(", uniprot='").append(uniprot).append('\''); if ( geneSymb != null) - s.append( - ", geneSymb='" + geneSymb + '\'' ); + s.append(", geneSymb='").append(geneSymb).append('\''); if (chrLoc != null) - s.append(", chrLoc='" + chrLoc + '\'' ); + s.append(", chrLoc='").append(chrLoc).append('\''); if (modType != null) - s.append(", modType='" + modType + '\'' ); + s.append(", modType='").append(modType).append('\''); if (residue != null) - s.append( ", residue='" + residue + '\'' ); + s.append(", residue='").append(residue).append('\''); if ( group != null) - s.append(", group='" + group + '\'' ); + s.append(", group='").append(group).append('\''); if (organism != null) - s.append(", organism='" + organism + '\'' ); + s.append(", organism='").append(organism).append('\''); s.append( '}'); diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/Component.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/Component.java index ff4b0abb82..4a35ff5218 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/Component.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/Component.java @@ -50,10 +50,10 @@ public final class Component { */ private static void lazyInit() { if (components==null) { - components = new HashSet(); - nonTerminalComps = new HashMap, Component>(); - nTerminalAminoAcids = new HashMap, Component>(); - cTerminalAminoAcids = new HashMap, Component>(); + components = new HashSet<>(); + nonTerminalComps = new HashMap<>(); + nTerminalAminoAcids = new HashMap<>(); + cTerminalAminoAcids = new HashMap<>(); } } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationCategory.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationCategory.java index 89d9bd9720..170cf5cdbf 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationCategory.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationCategory.java @@ -93,7 +93,7 @@ public boolean isCrossLink() { /** * The variable is the same as the <Type> in the ptm_list XML file. */ - private String label; + private final String label; private String desc; @@ -106,9 +106,9 @@ public static ModificationCategory getByLabel(String label) { return mapLabelCat.get(label); } - private static Map mapLabelCat; + private static final Map mapLabelCat; static { - mapLabelCat = new HashMap(); + mapLabelCat = new HashMap<>(); for (ModificationCategory cat:ModificationCategory.values()) { mapLabelCat.put(cat.label, cat); } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationCondition.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationCondition.java index 3afc2f171a..ce4b0a491b 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationCondition.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationCondition.java @@ -37,11 +37,11 @@ public interface ModificationCondition { * * @return the involved components. */ - public List getComponents(); + List getComponents(); /** * * @return a list of all {Link ModificationLinkage}s. */ - public List getLinkages(); + List getLinkages(); } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationConditionImpl.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationConditionImpl.java index 2af28ed33f..5cb7857bdd 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationConditionImpl.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationConditionImpl.java @@ -49,7 +49,7 @@ public ModificationConditionImpl(final List components, if (components.size() > 1) { - Set indices = new HashSet(); + Set indices = new HashSet<>(); for (ModificationLinkage linkage : linkages) { indices.add(linkage.getIndexOfComponent1()); indices.add(linkage.getIndexOfComponent2()); diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationOccurrenceType.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationOccurrenceType.java index 30a4bad4e0..fde9dcee68 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationOccurrenceType.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationOccurrenceType.java @@ -60,7 +60,7 @@ public String toString() { /** * The variable is the same as the <Occurrence> in the ptm_list XML file. */ - private String label; + private final String label; /** * @@ -71,9 +71,9 @@ public static ModificationOccurrenceType getByLabel(String label) { return mapLabelOcc.get(label); } - private static Map mapLabelOcc; + private static final Map mapLabelOcc; static { - mapLabelOcc = new HashMap(); + mapLabelOcc = new HashMap<>(); for (ModificationOccurrenceType occ:ModificationOccurrenceType.values()) { mapLabelOcc.put(occ.label, occ); } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModification.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModification.java index b173f63f11..6f5b15633f 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModification.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModification.java @@ -39,84 +39,84 @@ public interface ProteinModification { * * @return modification id. */ - public String getId(); + String getId(); /** * * @return Protein Data Bank Chemical Component ID. */ - public String getPdbccId(); + String getPdbccId(); /** * * @return Protein Data Bank Chemical Component name. */ - public String getPdbccName(); + String getPdbccName(); /** * * @return RESID ID. */ - public String getResidId(); + String getResidId(); /** * * @return RESID name. */ - public String getResidName(); + String getResidName(); /** * * @return PSI-MOD ID. */ - public String getPsimodId(); + String getPsimodId(); /** * * @return PSI-MOD name. */ - public String getPsimodName(); + String getPsimodName(); /** * * @return Systematic name. */ - public String getSystematicName(); + String getSystematicName(); /** * * @return Description. */ - public String getDescription(); + String getDescription(); /** * * @return a set of keywords. */ - public Set getKeywords(); + Set getKeywords(); /** * * @return {@link ModificationCondition} */ - public ModificationCondition getCondition(); + ModificationCondition getCondition(); /** * * @return formula of the modified residue. */ - public String getFormula(); + String getFormula(); /** * * @return the modification category. */ - public ModificationCategory getCategory(); + ModificationCategory getCategory(); /** * * @return the modification occurrence type. */ - public ModificationOccurrenceType getOccurrenceType(); + ModificationOccurrenceType getOccurrenceType(); } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModificationImpl.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModificationImpl.java index a06ee41936..dd4f11d41f 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModificationImpl.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModificationImpl.java @@ -251,7 +251,7 @@ public static class Builder { private String sysName = null; private String formula = null; - private Set keywords = new LinkedHashSet(); + private Set keywords = new LinkedHashSet<>(); /** * @@ -289,7 +289,7 @@ public Builder(final ProteinModification copyFrom) { this.sysName = copyFrom.getSystematicName(); this.formula = copyFrom.getFormula(); - this.keywords = new LinkedHashSet(copyFrom.getKeywords()); + this.keywords = new LinkedHashSet<>(copyFrom.getKeywords()); } public Builder setCategory(final ModificationCategory cat) { @@ -448,7 +448,7 @@ private ProteinModificationImpl(Builder builder) { this.sysName = builder.sysName; this.formula = builder.formula; - this.keywords = new LinkedHashSet(builder.keywords); + this.keywords = new LinkedHashSet<>(builder.keywords); } @Override diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModificationRegistry.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModificationRegistry.java index 54babab8e1..95e08fe90f 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModificationRegistry.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModificationRegistry.java @@ -55,7 +55,7 @@ public class ProteinModificationRegistry { private static Map> byCategory = null; private static Map> byOccurrenceType = null; - private static String DIR_XML_PTM_LIST = "ptm_list.xml"; + private static final String DIR_XML_PTM_LIST = "ptm_list.xml"; @@ -109,22 +109,22 @@ private static synchronized void lazyInit() { private static synchronized void lazyInit(InputStream inStream) { if (registry==null) { - registry = new HashSet(); - byId = new HashMap(); - byResidId = new HashMap>(); - byPsimodId = new HashMap>(); - byPdbccId = new HashMap>(); - byKeyword = new HashMap>(); - byComponent = new HashMap>(); - byCategory = new EnumMap>( + registry = new HashSet<>(); + byId = new HashMap<>(); + byResidId = new HashMap<>(); + byPsimodId = new HashMap<>(); + byPdbccId = new HashMap<>(); + byKeyword = new HashMap<>(); + byComponent = new HashMap<>(); + byCategory = new EnumMap<>( ModificationCategory.class); for (ModificationCategory cat:ModificationCategory.values()) { - byCategory.put(cat, new HashSet()); + byCategory.put(cat, new HashSet<>()); } - byOccurrenceType = new EnumMap>( + byOccurrenceType = new EnumMap<>( ModificationOccurrenceType.class); for (ModificationOccurrenceType occ:ModificationOccurrenceType.values()) { - byOccurrenceType.put(occ, new HashSet()); + byOccurrenceType.put(occ, new HashSet<>()); } registerCommonProteinModifications(inStream); } @@ -156,50 +156,30 @@ public static void register(final ProteinModification modification) { ModificationCondition condition = modification.getCondition(); List comps = condition.getComponents(); for (Component comp:comps) { - Set mods = byComponent.get(comp); - if (mods==null) { - mods = new HashSet(); - byComponent.put(comp, mods); - } + Set mods = byComponent.computeIfAbsent(comp, k -> new HashSet<>()); mods.add(modification); } String pdbccId = modification.getPdbccId(); if (pdbccId!=null) { - Set mods = byPdbccId.get(pdbccId); - if (mods==null) { - mods = new HashSet(); - byPdbccId.put(pdbccId, mods); - } + Set mods = byPdbccId.computeIfAbsent(pdbccId, k -> new HashSet<>()); mods.add(modification); } String residId = modification.getResidId(); if (residId!=null) { - Set mods = byResidId.get(residId); - if (mods==null) { - mods = new HashSet(); - byResidId.put(residId, mods); - } + Set mods = byResidId.computeIfAbsent(residId, k -> new HashSet<>()); mods.add(modification); } String psimodId = modification.getPsimodId(); if (psimodId!=null) { - Set mods = byPsimodId.get(psimodId); - if (mods==null) { - mods = new HashSet(); - byPsimodId.put(psimodId, mods); - } + Set mods = byPsimodId.computeIfAbsent(psimodId, k -> new HashSet<>()); mods.add(modification); } for (String keyword : modification.getKeywords()) { - Set mods = byKeyword.get(keyword); - if (mods==null) { - mods = new HashSet(); - byKeyword.put(keyword, mods); - } + Set mods = byKeyword.computeIfAbsent(keyword, k -> new HashSet<>()); mods.add(modification); } } @@ -308,7 +288,7 @@ public static Set getByComponent(final Component comp1, if (comps.length==0) { return Collections.unmodifiableSet(mods); } else { - Set ret = new HashSet(mods); + Set ret = new HashSet<>(mods); for (Component comp:comps) { mods = byComponent.get(comp); if (mods==null) { diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ComponentXMLConverter.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ComponentXMLConverter.java index 138488b650..45ce14a428 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ComponentXMLConverter.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ComponentXMLConverter.java @@ -20,8 +20,8 @@ */ package org.biojava.nbio.protmod.io; -import org.biojava.nbio.protmod.Component; import org.biojava.nbio.core.util.PrettyXMLWriter; +import org.biojava.nbio.protmod.Component; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -46,8 +46,8 @@ public static String toXML(Component component) throws IOException{ public static void toXML(Component component, PrettyXMLWriter xml) throws IOException{ xml.openTag("component"); - xml.attribute("nTerminal" , component.isNTerminal()+""); - xml.attribute("cTerminal", component.isCTerminal()+""); + xml.attribute("nTerminal" , String.valueOf(component.isNTerminal())); + xml.attribute("cTerminal", String.valueOf(component.isCTerminal())); for (String pdbccId : component.getPdbccIds()){ xml.openTag("pdbccID"); xml.attribute("id", pdbccId); @@ -74,7 +74,7 @@ public static Component fromXML(Node componentN) { boolean isNTerminal = Boolean.parseBoolean(nTerminalS); boolean isCTerminal = Boolean.parseBoolean(cTerminalS); - SetpdbccIds = new HashSet(); + SetpdbccIds = new HashSet<>(); NodeList valList = componentN.getChildNodes(); int numChildren = valList.getLength(); diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ModifiedCompoundXMLConverter.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ModifiedCompoundXMLConverter.java index fb76e02340..6867d454e1 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ModifiedCompoundXMLConverter.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ModifiedCompoundXMLConverter.java @@ -20,10 +20,10 @@ */ package org.biojava.nbio.protmod.io; +import org.biojava.nbio.core.util.PrettyXMLWriter; import org.biojava.nbio.protmod.ProteinModification; import org.biojava.nbio.protmod.ProteinModificationRegistry; import org.biojava.nbio.protmod.structure.*; -import org.biojava.nbio.core.util.PrettyXMLWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; @@ -31,7 +31,6 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import javax.xml.parsers.DocumentBuilder; @@ -110,7 +109,7 @@ public static ModifiedCompound fromXML(String xml){ ProteinModification modification = null; //Collection linkages = new ArrayList(); StructureAtomLinkage[] linkages = null; - List structureGroups = new ArrayList(); + List structureGroups = new ArrayList<>(); try { //Convert string to XML document @@ -142,41 +141,41 @@ public static ModifiedCompound fromXML(String xml){ if(!listOfConditions.hasAttributes()) continue; - if ( listOfConditions.getNodeName().equals("proteinModification")) { - //modification = ProteinModificationXMLConverter.fromXML(listOfConditions); - String modId = getAttribute(listOfConditions, "id"); - modification = ProteinModificationRegistry.getById(modId); - if (modification==null) { - logger.warn("Error: no modification information."); - } - } else if ( listOfConditions.getNodeName().equals("linkage")) { - double dist = Double.parseDouble(getAttribute(listOfConditions, "distance")); - int pos = Integer.parseInt(getAttribute(listOfConditions,"pos")); - int total = Integer.parseInt(getAttribute(listOfConditions,"total")); - if ( linkages == null) - linkages = new StructureAtomLinkage[total]; - - StructureAtom atom1 = getAtom("atom1", listOfConditions); - StructureAtom atom2 = getAtom("atom2",listOfConditions); - StructureAtomLinkage linkage = new StructureAtomLinkage(atom1, atom2, dist); - //linkages.add(linkage); - linkages[pos] = linkage; - } else if (listOfConditions.getNodeName().equals("structureGroup")) { - StructureGroup group = StructureGroupXMLConverter.fromXML(listOfConditions); - structureGroups.add(group); + switch (listOfConditions.getNodeName()) { + case "proteinModification": + //modification = ProteinModificationXMLConverter.fromXML(listOfConditions); + String modId = getAttribute(listOfConditions, "id"); + modification = ProteinModificationRegistry.getById(modId); + if (modification == null) { + logger.warn("Error: no modification information."); + } + break; + case "linkage": + double dist = Double.parseDouble(getAttribute(listOfConditions, "distance")); + int pos = Integer.parseInt(getAttribute(listOfConditions, "pos")); + int total = Integer.parseInt(getAttribute(listOfConditions, "total")); + if (linkages == null) + linkages = new StructureAtomLinkage[total]; + + StructureAtom atom1 = getAtom("atom1", listOfConditions); + StructureAtom atom2 = getAtom("atom2", listOfConditions); + StructureAtomLinkage linkage = new StructureAtomLinkage(atom1, atom2, dist); + //linkages.add(linkage); + linkages[pos] = linkage; + break; + case "structureGroup": + StructureGroup group = StructureGroupXMLConverter.fromXML(listOfConditions); + structureGroups.add(group); // logger.info("structureGroups size:" + structureGroups.size()); + break; } } } } catch (SAXParseException err) { logger.error("** Parsing error, line: {}, uri: {}", err.getLineNumber (), err.getSystemId (), err); - } - catch (SAXException e) { + } catch (Throwable e) { logger.error("Exception: ", e); } - catch (Throwable t) { - logger.error("Exception: ", t); - } if ( linkages != null) { diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ProteinModificationXmlReader.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ProteinModificationXmlReader.java index 0a1c5f36e9..6f245e5c5a 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ProteinModificationXmlReader.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ProteinModificationXmlReader.java @@ -110,7 +110,7 @@ public static void registerProteinModificationFromXml(InputStream isXml) } // condition - ModificationCondition condition = null; + ModificationCondition condition; { nodes = infoNodes.get("Condition"); if (nodes==null || nodes.size()!=1) { @@ -121,14 +121,14 @@ public static void registerProteinModificationFromXml(InputStream isXml) Node compsNode = nodes.get(0); // keep track of the labels of component indices - Map mapLabelComp = new HashMap(); + Map mapLabelComp = new HashMap<>(); Map> compInfoNodes = getChildNodes(compsNode); // components List compNodes = compInfoNodes.get("Component"); int sizeComp = compNodes.size(); - List comps = new ArrayList(sizeComp); + List comps = new ArrayList<>(sizeComp); for (int iComp=0; iComp compIds = new HashSet(); + Set compIds = new HashSet<>(); List compIdNodes = getChildNodes(compNode).get("Id"); if (compIdNodes!=null) { for (Node compIdNode : compIdNodes) { @@ -199,7 +199,7 @@ public static void registerProteinModificationFromXml(InputStream isXml) List linkages = null; if (bondNodes!=null) { int sizeBonds = bondNodes.size(); - linkages = new ArrayList(sizeBonds); + linkages = new ArrayList<>(sizeBonds); for (int iBond=0; iBond> bondChildNodes = getChildNodes(bondNode); @@ -305,12 +305,16 @@ public static void registerProteinModificationFromXml(InputStream isXml) xrefName = xrefNode.get(0).getTextContent(); } - if (xrefDb.equals("PDBCC")) { - modBuilder.setPdbccId(xrefId).setPdbccName(xrefName); - } else if (xrefDb.equals("RESID")) { - modBuilder.setResidId(xrefId).setResidName(xrefName); - } else if (xrefDb.equals("PSI-MOD")) { - modBuilder.setPsimodId(xrefId).setPsimodName(xrefName); + switch (xrefDb) { + case "PDBCC": + modBuilder.setPdbccId(xrefId).setPdbccName(xrefName); + break; + case "RESID": + modBuilder.setResidId(xrefId).setResidName(xrefName); + break; + case "PSI-MOD": + modBuilder.setPsimodId(xrefId).setPsimodName(xrefName); + break; } } } // end of cross references @@ -342,7 +346,7 @@ private static Map> getChildNodes(Node parent) { if (parent==null) return Collections.emptyMap(); - Map> children = new HashMap>(); + Map> children = new HashMap<>(); NodeList nodes = parent.getChildNodes(); int nNodes = nodes.getLength(); @@ -352,11 +356,7 @@ private static Map> getChildNodes(Node parent) { continue; String name = node.getNodeName(); - List namesakes = children.get(name); - if (namesakes==null) { - namesakes = new ArrayList(); - children.put(name, namesakes); - } + List namesakes = children.computeIfAbsent(name, k -> new ArrayList<>()); namesakes.add(node); } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/StructureAtomXMLConverter.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/StructureAtomXMLConverter.java index 08f69725bf..8419c97dd8 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/StructureAtomXMLConverter.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/StructureAtomXMLConverter.java @@ -20,9 +20,9 @@ */ package org.biojava.nbio.protmod.io; +import org.biojava.nbio.core.util.PrettyXMLWriter; import org.biojava.nbio.protmod.structure.StructureAtom; import org.biojava.nbio.protmod.structure.StructureGroup; -import org.biojava.nbio.core.util.PrettyXMLWriter; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/StructureGroupXMLConverter.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/StructureGroupXMLConverter.java index 61a56e3b6b..71cec2c619 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/StructureGroupXMLConverter.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/StructureGroupXMLConverter.java @@ -20,9 +20,9 @@ */ package org.biojava.nbio.protmod.io; +import org.biojava.nbio.core.util.PrettyXMLWriter; import org.biojava.nbio.protmod.structure.StructureGroup; import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.core.util.PrettyXMLWriter; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; @@ -36,8 +36,8 @@ public static void toXML(StructureGroup group, PrettyXMLWriter xml) throws IOExc xml.attribute("chainID", group.getChainId()); xml.attribute("pdbName", group.getPDBName()); if ( group.getInsCode() != null) - xml.attribute("insCode",group.getInsCode()+""); - xml.attribute("residueNr", group.getResidueNumber()+""); + xml.attribute("insCode", String.valueOf(group.getInsCode())); + xml.attribute("residueNr", String.valueOf(group.getResidueNumber())); xml.attribute("isAminoAcid", Boolean.toString(group.isAminoAcid())); xml.closeTag("structureGroup"); } @@ -57,7 +57,7 @@ public static StructureGroup fromXML(Node n) { resNum.setInsCode(insCode.charAt(0)); resNum.setSeqNum(Integer.parseInt(resN)); - StructureGroup g = new StructureGroup(resNum, pdbName, Boolean.valueOf(isAminoAcid)); + StructureGroup g = new StructureGroup(resNum, pdbName, Boolean.parseBoolean(isAminoAcid)); return g; } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ModifiedCompound.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ModifiedCompound.java index 164c3d86d9..5d9937d9d2 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ModifiedCompound.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ModifiedCompound.java @@ -41,32 +41,32 @@ public interface ModifiedCompound { * * @return a description */ - public String getDescription(); + String getDescription(); - public void setDescription(String desc); + void setDescription(String desc); /** * * @return {@link ProteinModificationBean} occurred on the residue. */ - public ProteinModification getModification(); + ProteinModification getModification(); - public void setModification(ProteinModification modi); + void setModification(ProteinModification modi); /** * * @return a set of involved group. */ - public Set getGroups(); + Set getGroups(); - public void setGroups(Set groups); + void setGroups(Set groups); /** * * @param isAminoAcid true if amino acids. * @return a set of involved group of the type. */ - public Set getGroups(boolean isAminoAcid); + Set getGroups(boolean isAminoAcid); @@ -76,13 +76,13 @@ public interface ModifiedCompound { * @see #getLinkedGroupPairs * @see StructureAtomLinkage */ - public Set getAtomLinkages(); + Set getAtomLinkages(); /** Set atom linkages * * @return */ - public void setAtomLinkages(Set linkages); + void setAtomLinkages(Set linkages); /** * Add a linkage. Add new the involved groups first using {@link addGroup}. @@ -90,20 +90,20 @@ public interface ModifiedCompound { * @return true if this linkage was not already contained. * @see StructureAtomLinkage */ - public boolean addAtomLinkage(StructureAtomLinkage linkage); + boolean addAtomLinkage(StructureAtomLinkage linkage); /** * Add a collections of linkages. * @param linkages an atom linkage. */ - public void addAtomLinkages(Collection linkages); + void addAtomLinkages(Collection linkages); /** * * @return true if groups from multiple chains were involved */ - public boolean crossChains(); + boolean crossChains(); } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ModifiedCompoundImpl.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ModifiedCompoundImpl.java index e42d987e61..8e369f7c17 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ModifiedCompoundImpl.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ModifiedCompoundImpl.java @@ -75,7 +75,7 @@ public ModifiedCompoundImpl ( throw new IllegalArgumentException("Null argument(s)"); } - groups = new HashSet(1); + groups = new HashSet<>(1); groups.add(modifiedResidue); // is it possible that components be added by addLinkage later? @@ -101,7 +101,7 @@ public ModifiedCompoundImpl( ProteinModification modification, throw new IllegalArgumentException("at least one linkage."); } - this.groups = new HashSet(); + this.groups = new HashSet<>(); addAtomLinkages(linkages); @@ -128,7 +128,7 @@ else if (originalModification.getCategory()!=ModificationCategory.UNDEFINED) modification = originalModification; else { int nRes = 0; - Set ligands = new HashSet(); + Set ligands = new HashSet<>(); for (StructureGroup group : groups) { if (group.isAminoAcid()) { nRes ++; @@ -174,7 +174,7 @@ public Set getGroups() { @Override public Set getGroups(boolean isAminoAcid) { - Set result = new HashSet(); + Set result = new HashSet<>(); for (StructureGroup group : groups) { if (group.isAminoAcid() == isAminoAcid) { result.add(group); @@ -194,7 +194,7 @@ public Set getAtomLinkages() { if (atomLinkages==null) { return Collections.emptySet(); } else { - Set result = new HashSet(); + Set result = new HashSet<>(); for (Set linkages : atomLinkages.values()) { result.addAll(linkages); } @@ -218,20 +218,20 @@ public boolean addAtomLinkage(StructureAtomLinkage linkage) { throw new IllegalArgumentException("Null linkage"); } - Set gs = new HashSet(2); + Set gs = new HashSet<>(2); gs.add(linkage.getAtom1().getGroup()); gs.add(linkage.getAtom2().getGroup()); if (atomLinkages==null) { - atomLinkages = new HashMap, Set>(); + atomLinkages = new HashMap<>(); } Set linkages = atomLinkages.get(gs); if (linkages == null) { - linkages = new HashSet(); + linkages = new HashSet<>(); atomLinkages.put(gs, linkages); groups.addAll(gs); // it's possible of new groups - }; + } return linkages.add(linkage); } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ProteinModificationIdentifier.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ProteinModificationIdentifier.java index fdfd8cf312..63e19579ea 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ProteinModificationIdentifier.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ProteinModificationIdentifier.java @@ -267,9 +267,9 @@ public void identify(final List chains, } - residues = new ArrayList(); - List ligands = new ArrayList(); - Map> mapCompGroups = new HashMap>(); + residues = new ArrayList<>(); + List ligands = new ArrayList<>(); + Map> mapCompGroups = new HashMap<>(); for (Chain chain : chains) { @@ -292,7 +292,7 @@ public void identify(final List chains, } logger.warn("No amino acids found for {}. Either you did not parse the PDB file with alignSEQRES records, or this record does not contain any amino acids.", pdbId); } - List modComps = new ArrayList(); + List modComps = new ArrayList<>(); for (ProteinModification mod : potentialModifications) { ModificationCondition condition = mod.getCondition(); @@ -333,10 +333,10 @@ public void identify(final List chains, } private void reset() { - identifiedModifiedCompounds = new LinkedHashSet(); + identifiedModifiedCompounds = new LinkedHashSet<>(); if (recordUnidentifiableModifiedCompounds) { - unidentifiableAtomLinkages = new LinkedHashSet(); - unidentifiableModifiedResidues = new LinkedHashSet(); + unidentifiableAtomLinkages = new LinkedHashSet<>(); + unidentifiableModifiedResidues = new LinkedHashSet<>(); } } @@ -392,7 +392,7 @@ private void identifyAdditionalAttachments(ModifiedCompound mc, // ligands to amino acid bonds for same modification of unknown category // will be combined in mergeModComps() // TODO: how about chain-chain links? - List identifiedGroups = new ArrayList(); + List identifiedGroups = new ArrayList<>(); for (StructureGroup num : mc.getGroups(false)) { Group group; try { @@ -464,7 +464,7 @@ private Group getGroup(StructureGroup num, List chains) throws StructureE * Merge identified modified compounds if linked. */ private void mergeModComps(List modComps) { - TreeSet remove = new TreeSet(); + TreeSet remove = new TreeSet<>(); int n = modComps.size(); for (int icurr=1; icurr modComps, List ligands) { // first put identified linkages in a map for fast query - Set identifiedLinkages = new HashSet(); + Set identifiedLinkages = new HashSet<>(); for (ModifiedCompound mc : modComps) { identifiedLinkages.addAll(mc.getAtomLinkages()); } @@ -555,7 +555,7 @@ private void recordUnidentifiableAtomLinkages(List modComps, } private void recordUnidentifiableModifiedResidues(List modComps) { - Set identifiedComps = new HashSet(); + Set identifiedComps = new HashSet<>(); for (ModifiedCompound mc : modComps) { identifiedComps.addAll(mc.getGroups(true)); } @@ -592,18 +592,14 @@ private void addModificationGroups( throw new IllegalArgumentException("Null argument(s)."); } - Map> mapSingleMultiComps = new HashMap>(); + Map> mapSingleMultiComps = new HashMap<>(); for (ProteinModification mod : modifications) { ModificationCondition condition = mod.getCondition(); for (Component comp : condition.getComponents()) { for (String pdbccId : comp.getPdbccIds()) { Component single = Component.of(Collections.singleton(pdbccId), comp.isNTerminal(), comp.isCTerminal()); - Set mult = mapSingleMultiComps.get(single); - if (mult == null) { - mult = new HashSet(); - mapSingleMultiComps.put(single, mult); - } + Set mult = mapSingleMultiComps.computeIfAbsent(single, k -> new HashSet<>()); mult.add(comp); } } @@ -619,11 +615,7 @@ private void addModificationGroups( Component.of(pdbccId)); for (Component comp : unionComponentSet(ligandsWildCard, comps)) { - Set gs = saveTo.get(comp); - if (gs==null) { - gs = new LinkedHashSet(); - saveTo.put(comp, gs); - } + Set gs = saveTo.computeIfAbsent(comp, k -> new LinkedHashSet<>()); gs.add(group); } } @@ -645,11 +637,7 @@ private void addModificationGroups( Component.of(pdbccId)); for (Component comp : unionComponentSet(residuesWildCard, comps)) { - Set gs = saveTo.get(comp); - if (gs==null) { - gs = new LinkedHashSet(); - saveTo.put(comp, gs); - } + Set gs = saveTo.computeIfAbsent(comp, k -> new LinkedHashSet<>()); gs.add(group); } } @@ -669,11 +657,7 @@ private void addModificationGroups( Component.of(res.getPDBName(), true, false)); for (Component comp : unionComponentSet(nTermWildCard, comps)) { - Set gs = saveTo.get(comp); - if (gs==null) { - gs = new LinkedHashSet(); - saveTo.put(comp, gs); - } + Set gs = saveTo.computeIfAbsent(comp, k -> new LinkedHashSet<>()); gs.add(res); } } while (iRes gs = saveTo.get(comp); - if (gs==null) { - gs = new LinkedHashSet(); - saveTo.put(comp, gs); - } + Set gs = saveTo.computeIfAbsent(comp, k -> new LinkedHashSet<>()); gs.add(res); } } while (iRes>=0 && ligands.contains(res)); @@ -712,7 +692,7 @@ private Set unionComponentSet(Set set1, Set set if (set2 == null) return set1; - Set set = new HashSet(set1.size()+set2.size()); + Set set = new HashSet<>(set1.size() + set2.size()); set.addAll(set1); set.addAll(set2); @@ -728,7 +708,7 @@ private List> getMatchedAtomsOfLinkages( int nLink = linkages.size(); List> matchedAtomsOfLinkages = - new ArrayList>(nLink); + new ArrayList<>(nLink); for (int iLink=0; iLink> getMatchedAtomsOfLinkages( Set groups1 = mapCompGroups.get(comp1); Set groups2 = mapCompGroups.get(comp2); - List list = new ArrayList(); + List list = new ArrayList<>(); List potentialNamesOfAtomOnGroup1 = linkage.getPDBNameOfPotentialAtomsOnComponent1(); for (String name : potentialNamesOfAtomOnGroup1) { @@ -810,9 +790,9 @@ private void assembleLinkages(List> matchedAtomsOfLinkages, int nLink = matchedAtomsOfLinkages.size(); int[] indices = new int[nLink]; - Set identifiedCompounds = new HashSet(); + Set identifiedCompounds = new HashSet<>(); while (indices[0] atomLinkages = new ArrayList(nLink); + List atomLinkages = new ArrayList<>(nLink); for (int iLink=0; iLink> matchedAtomsOfLinkages, // matched int n = atomLinkages.size(); - List linkages = new ArrayList(n); + List linkages = new ArrayList<>(n); for (int i=0; i findAtomLinkages(final Group group1, throw new IllegalArgumentException("bondLengthTolerance cannot be negative."); } - List ret = new ArrayList(); + List ret = new ArrayList<>(); if (potentialNamesOfAtomOnGroup1 == null) { // if empty name, search for all atoms @@ -282,8 +282,8 @@ private static boolean hasMetalBond(Atom a1, Atom a2, MetalBondDistance definiti double distance = Calc.getDistance(a1,a2); - Float min = definition.getLowerLimit(); - Float max = definition.getUpperLimit(); + float min = definition.getLowerLimit(); + float max = definition.getUpperLimit(); return ( min < distance && max > distance); @@ -327,7 +327,7 @@ public static List getAtomNames(Group group) { } int n = atoms.size(); - List ret = new ArrayList(n); + List ret = new ArrayList<>(n); for (int i=0; i testXMLSerialization(String pdbId){ String xml = null; ModifiedCompound currentMC = null; - List all = new ArrayList(); + List all = new ArrayList<>(); try { Structure struc = TmpAtomCache.cache.getStructure(pdbId); @@ -220,7 +221,7 @@ public String convertStreamToString(InputStream is) char[] buffer = new char[1024]; try { Reader reader = new BufferedReader( - new InputStreamReader(is, "UTF-8")); + new InputStreamReader(is, StandardCharsets.UTF_8)); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); diff --git a/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/ProteinModificationParserTest.java b/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/ProteinModificationParserTest.java index cd7bd76a30..a5ffff2bc3 100644 --- a/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/ProteinModificationParserTest.java +++ b/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/ProteinModificationParserTest.java @@ -22,7 +22,9 @@ import org.biojava.nbio.protmod.ProteinModification; import org.biojava.nbio.protmod.ProteinModificationRegistry; -import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.ResidueNumber; +import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.StructureException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -477,7 +479,7 @@ private Set identifyAllModfications(Structure struc) { * http://www.biojava.org/wiki/BioJava:CookBook3:ProtMod */ private List identifyPhosphosites(Structure struc) { - List phosphosites = new ArrayList(); + List phosphosites = new ArrayList<>(); ProteinModificationIdentifier parser = new ProteinModificationIdentifier(); parser.identify(struc, ProteinModificationRegistry.getByKeyword("phosphoprotein")); Set mcs = parser.getIdentifiedModifiedCompound(); diff --git a/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/ProteinModificationRegistryTest.java b/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/ProteinModificationRegistryTest.java index 7590904de6..a25f76e8dc 100644 --- a/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/ProteinModificationRegistryTest.java +++ b/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/ProteinModificationRegistryTest.java @@ -49,7 +49,7 @@ public class ProteinModificationRegistryTest { @Test public void testRegisterModification() { // define the involved components, in this case two cystines (CYS) - List components = new ArrayList(2); + List components = new ArrayList<>(2); components.add(Component.of("CYS")); components.add(Component.of("CYS")); diff --git a/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/TmpAtomCache.java b/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/TmpAtomCache.java index 8d757a74a8..95ddb12e95 100644 --- a/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/TmpAtomCache.java +++ b/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/TmpAtomCache.java @@ -30,8 +30,8 @@ public class TmpAtomCache { - static String tmpDir = System.getProperty("java.io.tmpdir"); - public static AtomCache cache = new AtomCache(tmpDir, tmpDir); + static final String tmpDir = System.getProperty("java.io.tmpdir"); + public static final AtomCache cache = new AtomCache(tmpDir, tmpDir); static { FileParsingParameters params = new FileParsingParameters(); params.setAlignSeqRes(true); diff --git a/biojava-ontology/src/main/java/demo/ParseGO.java b/biojava-ontology/src/main/java/demo/ParseGO.java index c16dffed89..827a7e699e 100644 --- a/biojava-ontology/src/main/java/demo/ParseGO.java +++ b/biojava-ontology/src/main/java/demo/ParseGO.java @@ -34,7 +34,6 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; -import java.util.Iterator; import java.util.Set; public class ParseGO { @@ -56,11 +55,9 @@ public static void main(String[] args){ Ontology ontology = parser.parseOBO(oboFile, "BioSapiens", "the BioSapiens ontology"); Set keys = ontology.getTerms(); - Iterator iter = keys.iterator(); - while (iter.hasNext()){ - Term t = iter.next(); - logger.info("{} [{}]", t.getName(), t.getDescription()); - } + for (Term t : keys) { + logger.info("{} [{}]", t.getName(), t.getDescription()); + } } catch (Exception e){ logger.error("Exception: ", e); } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/IntegerOntology.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/IntegerOntology.java index c8ee792a5b..432400f979 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/IntegerOntology.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/IntegerOntology.java @@ -117,14 +117,13 @@ public Set getRemoteTerms() { } @Override - public Term createTerm(String name) throws AlreadyExistsException, IllegalArgumentException { + public Term createTerm(String name) throws IllegalArgumentException { throw new IllegalArgumentException(getName() + " is immutable"); } @Override public Term createTerm(String name, String description) throws - AlreadyExistsException, IllegalArgumentException { @@ -134,7 +133,6 @@ public Term createTerm(String name, String description) @Override public Term createTerm(String name, String description, Object[] synonyms) throws - AlreadyExistsException, IllegalArgumentException { @@ -144,7 +142,6 @@ public Term createTerm(String name, String description, Object[] synonyms) @Override public Variable createVariable(String name, String description) throws - AlreadyExistsException, IllegalArgumentException { @@ -160,10 +157,7 @@ public Term importTerm(Term t, String name) } @Override - public Triple createTriple(Term subject, Term object, Term predicate, String name, String description) - throws - AlreadyExistsException - { + public Triple createTriple(Term subject, Term object, Term predicate, String name, String description) { throw new IllegalArgumentException(getName() + " is immutable"); } @@ -190,7 +184,7 @@ public boolean containsTerm(String name) { } public IntTerm resolveInt(int val) { - Integer i = new Integer(val); + Integer i = val; IntTerm term = (IntTerm) termCache.get(i); if(term == null) { @@ -205,7 +199,7 @@ public final class IntTerm implements Term { private final int val; - private Set synonyms; + private final Set synonyms; public IntTerm(int val) { this(val, null); diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntoTools.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntoTools.java index 1b1d7afd27..c7b548e215 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntoTools.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntoTools.java @@ -73,13 +73,7 @@ public final class OntoTools { public static final Term PARTIAL_ORDER; static { - DEFAULT_FACTORY = new OntologyFactory() { - @Override - public Ontology createOntology(String name, String desc) - throws OntologyException { - return new Ontology.Impl(name, desc); - } - }; + DEFAULT_FACTORY = Ontology.Impl::new; try { BufferedReader reader = new BufferedReader( diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Ontology.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Ontology.java index 365aab4251..c63f9aad23 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Ontology.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Ontology.java @@ -51,14 +51,14 @@ public interface Ontology { * @return the name of the ontology */ - public String getName(); + String getName(); /** Set the name for this ontology * * @param name - the name * */ - public void setName(String name); + void setName(String name); /** * Return a human-readable description of this ontology, or the empty @@ -66,13 +66,13 @@ public interface Ontology { * @return the description of the term */ - public String getDescription(); + String getDescription(); /** set the description of this ontology * * @param description */ - public void setDescription(String description); + void setDescription(String description); @@ -81,7 +81,7 @@ public interface Ontology { * @return a Set of all Terms of the ontology. */ - public Set getTerms(); + Set getTerms(); /** * Fetch the term with the specified name. @@ -91,7 +91,7 @@ public interface Ontology { * @throws NoSuchElementException if no term exists with that name */ - public Term getTerm(String name) throws NoSuchElementException; + Term getTerm(String name) throws NoSuchElementException; /** * Return all triples from this ontology which match the supplied @@ -104,7 +104,7 @@ public interface Ontology { * @return a Set of triples */ - public Set getTriples(Term subject, Term object, Term predicate); + Set getTriples(Term subject, Term object, Term predicate); /** * Return the associated OntologyOps. @@ -118,7 +118,7 @@ public interface Ontology { * @return the OntologyOps instance associated with this instance. */ - public OntologyOps getOps(); + OntologyOps getOps(); /** * Create a new term in this ontology. @@ -132,7 +132,7 @@ public interface Ontology { * @throws ChangeVetoException */ - public Term createTerm(String name) + Term createTerm(String name) throws AlreadyExistsException, @@ -151,7 +151,7 @@ public Term createTerm(String name) * @throws ChangeVetoException */ - public Term createTerm(String name, String description) + Term createTerm(String name, String description) throws AlreadyExistsException, @@ -171,7 +171,7 @@ public Term createTerm(String name, String description) * @throws ChangeVetoException */ - public Term createTerm(String name, String description, Object[] synonyms) + Term createTerm(String name, String description, Object[] synonyms) throws AlreadyExistsException, @@ -190,7 +190,7 @@ public Term createTerm(String name, String description, Object[] synonyms) * @throws ChangeVetoException */ - public Variable createVariable(String name, String description) + Variable createVariable(String name, String description) throws AlreadyExistsException, @@ -212,7 +212,7 @@ public Variable createVariable(String name, String description) * @throws IllegalArgumentException */ - public Term importTerm(Term t, String localName) + Term importTerm(Term t, String localName) throws IllegalArgumentException; @@ -233,7 +233,7 @@ public Term importTerm(Term t, String localName) * @throws IllegalArgumentException if subject, object or predicate are not all * from the same ontology */ - public Triple createTriple(Term subject, Term object, Term predicate, String name, String description) + Triple createTriple(Term subject, Term object, Term predicate, String name, String description) throws AlreadyExistsException ; @@ -246,7 +246,7 @@ public Triple createTriple(Term subject, Term object, Term predicate, String nam * @return true if contained */ - public boolean containsTriple(Term subject, Term object, Term predicate); + boolean containsTriple(Term subject, Term object, Term predicate); /** * Remove a term from an ontology, together with all triples which refer to it. @@ -254,7 +254,7 @@ public Triple createTriple(Term subject, Term object, Term predicate, String nam * @throws ChangeVetoException */ - public void deleteTerm(Term t) ; + void deleteTerm(Term t) ; /** * Determines if this ontology currently contains a term named name @@ -262,7 +262,7 @@ public Triple createTriple(Term subject, Term object, Term predicate, String nam * @return true is contained */ - public boolean containsTerm(String name); + boolean containsTerm(String name); /** * A basic in-memory implementation of an ontology @@ -274,7 +274,7 @@ public Triple createTriple(Term subject, Term object, Term predicate, String nam // AP: I am setting name and description to public changeable fields // e.g during parsing of an .obo file we don't know them when the ontology is instanciated - public final class Impl + final class Impl implements Ontology, java.io.Serializable { /** @@ -294,13 +294,13 @@ public final class Impl private final OntologyOps ops; { - terms = new HashMap(); - triples = new HashSet(); - subjectTriples = new HashMap>(); - objectTriples = new HashMap>(); - relationTriples = new HashMap>(); - remoteTerms = new HashMap(); - localRemoteTerms = new HashSet(); + terms = new HashMap<>(); + triples = new HashSet<>(); + subjectTriples = new HashMap<>(); + objectTriples = new HashMap<>(); + relationTriples = new HashMap<>(); + remoteTerms = new HashMap<>(); + localRemoteTerms = new HashSet<>(); } public Impl(String name, String description) { @@ -337,7 +337,7 @@ public void setDescription(String description){ @Override public Set getTerms() { - return new HashSet(terms.values()); + return new HashSet<>(terms.values()); } @Override @@ -377,16 +377,15 @@ public Set getTriples(Term subject, Term object, Term predicate) { } } - private Set filterTriples(Set base, Term subject, Term object, Term predicate) { + private static Set filterTriples(Set base, Term subject, Term object, Term predicate) { if (base == null) { return Collections.EMPTY_SET; } else if (subject == null && object == null && predicate == null) { - return Collections.unmodifiableSet(new HashSet(base)); + return Collections.unmodifiableSet(new HashSet<>(base)); } - Set retval = new HashSet(); - for (Iterator i = base.iterator(); i.hasNext(); ) { - Triple t = i.next(); + Set retval = new HashSet<>(); + for (Triple t : base) { if (subject != null && t.getSubject() != subject) { continue; } @@ -531,8 +530,7 @@ public Triple createTriple(Term subject, String description) throws AlreadyExistsException, - IllegalArgumentException, - NullPointerException, + NullPointerException, IllegalArgumentException { Triple t = new Triple.Impl(subject, object, predicate, name, description); @@ -564,11 +562,7 @@ private void addTriple(Triple t) { } private void pushTriple(Map> m, Term key, Triple t) { - Set s = m.get(key); - if (s == null) { - s = new HashSet(); - m.put(key, s); - } + Set s = m.computeIfAbsent(key, k -> new HashSet<>()); s.add(t); } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyFactory.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyFactory.java index 1bac93c033..64f7d52221 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyFactory.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyFactory.java @@ -34,8 +34,7 @@ public interface OntologyFactory { * @param description the description for the ontology * @return an Ontology * @throws NullPointerException if either name or description are null - * @throws OntologyException if the ontology could not be created */ - public Ontology createOntology(String name, String description) - throws OntologyException; + Ontology createOntology(String name, String description) + ; } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyOps.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyOps.java index a4e1b243a0..97104b4620 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyOps.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyOps.java @@ -49,5 +49,5 @@ public interface OntologyOps { * * @return a Set containing all remote terms in the ontology */ - public Set getRemoteTerms(); + Set getRemoteTerms(); } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyTerm.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyTerm.java index 849bbc8ff0..e4256f46f8 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyTerm.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyTerm.java @@ -52,7 +52,7 @@ public interface OntologyTerm extends Term { */ @Override - public Ontology getOntology(); + Ontology getOntology(); /** * Simple in-memory implementation of a remote ontology term. @@ -60,7 +60,7 @@ public interface OntologyTerm extends Term { * This can be used to implement Ontology.importTerm */ - public final static class Impl + final class Impl implements OntologyTerm, java.io.Serializable { @@ -68,7 +68,7 @@ public final static class Impl private final Ontology ontology; private final Ontology target; - private Set synonyms; + private final Set synonyms; public Impl(Ontology ontology, Ontology target) { this(ontology, target, null); diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/RemoteTerm.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/RemoteTerm.java index c003bb8ff3..e6a9721f30 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/RemoteTerm.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/RemoteTerm.java @@ -60,7 +60,7 @@ public interface RemoteTerm extends Term { * @return the term */ - public Term getRemoteTerm(); + Term getRemoteTerm(); /** * Simple in-memory implementation of a remote ontology term. @@ -68,7 +68,7 @@ public interface RemoteTerm extends Term { * This can be used to implement Ontology.importTerm */ - public final static class Impl + final class Impl extends AbstractTerm implements RemoteTerm, java.io.Serializable { /** @@ -78,7 +78,7 @@ public final static class Impl private final Ontology ontology; private final Term remoteTerm; private final String name; - private Set synonyms; + private final Set synonyms; public Impl(Ontology ontology, Term remoteTerm, String name) { this(ontology, remoteTerm, name, null); diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Synonym.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Synonym.java index 968bac29e7..f2f2cd28df 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Synonym.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Synonym.java @@ -45,12 +45,7 @@ public String toString(){ return txt; } - public final static Comparator COMPARATOR = new Comparator() { - @Override - public int compare(Synonym a, Synonym b) { - return String.CASE_INSENSITIVE_ORDER.compare(a.toString(), b.toString()); - } - }; + public final static Comparator COMPARATOR = (a, b) -> String.CASE_INSENSITIVE_ORDER.compare(a.toString(), b.toString()); public Synonym() { } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Term.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Term.java index 387aa7c17a..ad20f570bf 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Term.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Term.java @@ -66,7 +66,7 @@ public interface Term extends Annotatable { * @return the name of the term */ - public String getName(); + String getName(); /** * Return a human-readable description of this term, or the empty string if @@ -74,42 +74,42 @@ public interface Term extends Annotatable { * @return the description of the term */ - public String getDescription(); + String getDescription(); /** set the description of the term; * * @param description * */ - public void setDescription(String description); + void setDescription(String description); /** * Return the ontology in which this term exists. * @return the ontology */ - public Ontology getOntology(); + Ontology getOntology(); /** * Return the synonyms for this term. * @return the synonyms */ - public Object[] getSynonyms(); + Object[] getSynonyms(); /** * Add a synonym for this term. * @param synonym the synonym */ - public void addSynonym(Object synonym); + void addSynonym(Object synonym); /** * Remove a synonym for this term. * @param synonym */ - public void removeSynonym(Object synonym); + void removeSynonym(Object synonym); /** * Simple in-memory implementation of an ontology term. @@ -117,7 +117,7 @@ public interface Term extends Annotatable { * This can be used to implement Ontology.createTerm */ - public static class Impl + class Impl extends AbstractTerm implements Term, java.io.Serializable { /** @@ -155,7 +155,7 @@ public Impl(Ontology ontology, String name, String description, Object[] synonym this.description = description; this.ontology = ontology; - this.synonyms = new TreeSet(); + this.synonyms = new TreeSet<>(); if (synonyms!=null) this.synonyms.addAll(Arrays.asList(synonyms)); } @@ -227,7 +227,7 @@ public boolean equals(Object obj) Term that = (Term) obj; return this.getOntology() == that.getOntology() && - this.getName() == that.getName(); + this.getName().equals(that.getName()); } } } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Triple.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Triple.java index 550c4d5651..5a1d2439c5 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Triple.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Triple.java @@ -51,21 +51,21 @@ public interface Triple * @return the subject term */ - public Term getSubject(); + Term getSubject(); /** * Return the object term of this triple. * @return the object term */ - public Term getObject(); + Term getObject(); /** * Return a Term which defines the type of relationship between the subject and object terms. * @return the predicate */ - public Term getPredicate(); + Term getPredicate(); /** * The hashcode for a Triple. @@ -82,7 +82,7 @@ public interface Triple *

    */ @Override - public int hashCode(); + int hashCode(); /** * Check to see if an object is an equivalent Triple. @@ -105,7 +105,7 @@ public interface Triple *

    */ @Override - public boolean equals(Object obj); + boolean equals(Object obj); /** * Basic in-memory implementation of a Triple in an ontology @@ -114,7 +114,7 @@ public interface Triple * @see org.biojavax.ontology.SimpleComparableTriple */ - public static final class Impl + final class Impl implements Triple, java.io.Serializable { /** @@ -126,7 +126,7 @@ public static final class Impl private final Term predicate; private /*final*/ String name; private /*final*/ String description; - private Set synonyms; + private final Set synonyms; public Impl(Term subject, Term object, Term predicate) { this(subject, object, predicate, null, null, null); @@ -182,7 +182,7 @@ public Impl(Term subject, this.name = name; this.description = description; - this.synonyms = new TreeSet(); + this.synonyms = new TreeSet<>(); if (synonyms!=null) this.synonyms.addAll(Arrays.asList(synonyms)); } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Variable.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Variable.java index 2c453f674b..014850d319 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Variable.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Variable.java @@ -27,7 +27,7 @@ */ public interface Variable extends Term { - public static class Impl + class Impl extends Term.Impl implements Variable { diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/GOParser.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/GOParser.java index 7754ec130a..e7f3a8ab8c 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/GOParser.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/GOParser.java @@ -25,7 +25,6 @@ import java.io.BufferedReader; import java.io.IOException; -import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; @@ -42,13 +41,13 @@ public Ontology parseGO(BufferedReader goFile, String ontoName, String ontoDescription, OntologyFactory factory) - throws ParseException, IOException + throws IOException { try { Ontology onto = factory.createOntology(ontoName, ontoDescription); Term isa = onto.importTerm(OntoTools.IS_A, null); Term partof = null; // fixme: onto.importTerm(OntoTools.PART_OF, null); - List termStack = new ArrayList(); + List termStack = new ArrayList<>(); String line; while ((line = goFile.readLine()) != null) { int leadSpaces = 0; @@ -101,7 +100,7 @@ private void safeAddTriple(Ontology onto, Term s, Term o, Term p) } private Term parseTerm(Ontology onto, String s) - throws ParseException, AlreadyExistsException + throws AlreadyExistsException { int semi = s.indexOf(';'); int semi2 = s.indexOf(';', semi + 1); @@ -122,7 +121,7 @@ private Term parseTerm(Ontology onto, String s) } else { Term t = onto.createTerm(termName, termDesc); if (toke.hasMoreTokens()) { - List secondaries = new ArrayList(); + List secondaries = new ArrayList<>(); while (toke.hasMoreTokens()) { secondaries.add(toke.nextToken()); } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/OboParser.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/OboParser.java index d772850e05..1f03130185 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/OboParser.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/OboParser.java @@ -23,16 +23,14 @@ package org.biojava.nbio.ontology.io; -import org.biojava.nbio.ontology.*; -import org.biojava.nbio.ontology.obo.OboFileEventListener; +import org.biojava.nbio.ontology.OntoTools; +import org.biojava.nbio.ontology.Ontology; +import org.biojava.nbio.ontology.OntologyFactory; import org.biojava.nbio.ontology.obo.OboFileHandler; import org.biojava.nbio.ontology.obo.OboFileParser; import java.io.BufferedReader; import java.io.IOException; -import java.text.ParseException; - - /** Parses an OBO file. @@ -70,7 +68,6 @@ public class OboParser { * @param ontoDescription * @return the ontology represented as a BioJava ontology file - * @throws ParseException * @throws IOException */ public Ontology parseOBO( @@ -78,27 +75,26 @@ public Ontology parseOBO( String ontoName, String ontoDescription ) - throws ParseException, IOException { + throws IOException { - try { +// try { OntologyFactory factory = OntoTools.getDefaultFactory(); - Ontology ontology = factory.createOntology(ontoName, ontoDescription); OboFileParser parser = new OboFileParser(); - OboFileEventListener handler = new OboFileHandler(ontology); + Ontology ontology = factory.createOntology(ontoName, ontoDescription); - parser.addOboFileEventListener(handler); + parser.addOboFileEventListener(new OboFileHandler(ontology)); parser.parseOBO(oboFile); return ontology; - - } catch (AlreadyExistsException ex) { - throw new RuntimeException( "Duplication in ontology"); - } catch (OntologyException ex) { - throw new RuntimeException(ex); - } +// +// } catch (AlreadyExistsException ex) { +// throw new RuntimeException( "Duplication in ontology"); +// } catch (OntologyException ex) { +// throw new RuntimeException(ex); +// } } } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/TabDelimParser.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/TabDelimParser.java index 2c0ed0a3ae..f035375236 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/TabDelimParser.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/TabDelimParser.java @@ -86,11 +86,9 @@ public class TabDelimParser { * @param of an OntologyFactory used to create the Ontology instance * @return a new Ontology * @throws IOException if there is some problem with the buffered reader - * @throws OntologyException if it was not possible to instantiate a new - * ontology - */ + */ public Ontology parse(BufferedReader in, OntologyFactory of) - throws IOException, OntologyException { + throws IOException { String name = ""; String description = ""; Ontology onto = null; @@ -139,8 +137,8 @@ public Ontology parse(BufferedReader in, OntologyFactory of) Term objT = resolveTerm(object, onto); Term relT = resolveTerm(predicate, onto); - Triple trip = resolveTriple(subT, objT, relT, onto); - trip = trip==null?null:trip; // prevent unused field error + /*Triple trip =*/ resolveTriple(subT, objT, relT, onto); + //trip = trip; // prevent unused field error } catch (StringIndexOutOfBoundsException e) { throw new IOException("Could not parse line: " + line); } @@ -159,8 +157,8 @@ private Term resolveTerm(String termName, Ontology onto) { } else { try { if(isTrippleTerm) { - int c1 = termName.indexOf(","); - int c2 = termName.indexOf(",", c1 + 1); + int c1 = termName.indexOf(','); + int c2 = termName.indexOf(',', c1 + 1); String source = termName.substring(1, c1); String target = termName.substring(c2 + 1, termName.length() - 1); diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileEventListener.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileEventListener.java index 7350b6a2cb..0e061bcf74 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileEventListener.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileEventListener.java @@ -37,36 +37,36 @@ public interface OboFileEventListener { * * */ - public void documentStart(); + void documentStart(); /** end of parsing a new OBO file * * */ - public void documentEnd(); + void documentEnd(); /** parsed a new OBO file header * * */ - public void newOboFileHeader(); + void newOboFileHeader(); /** parsed a new stanza in the file * * @param stanza */ - public void newStanza(String stanza); + void newStanza(String stanza); /**found a new key in the file * * @param key * @param value */ - public void newKey(String key, String value ); + void newKey(String key, String value); /** a new synonym has been found * * @param synonym */ - public void newSynonym(Synonym synonym); + void newSynonym(Synonym synonym); } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileHandler.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileHandler.java index 49e3c2b56c..a064859684 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileHandler.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileHandler.java @@ -43,7 +43,7 @@ public class OboFileHandler implements OboFileEventListener { private static final Logger logger = LoggerFactory.getLogger(OboFileEventListener.class); - Ontology ontology; + final Ontology ontology; List termStack ; public static final String TERM = "Term"; @@ -91,7 +91,7 @@ public void documentEnd() { @Override public void documentStart() { - termStack = new ArrayList(); + termStack = new ArrayList<>(); } @Override @@ -136,54 +136,68 @@ public void newKey(String key, String value) { logger.warn("did not find ID for Term! "); return; } - if (key.equals(NAMESPACE)){ - Annotation anno = currentTerm.getAnnotation(); - anno.setProperty(NAMESPACE, value); - } - else if (key.equals(NAME)){ - currentTerm.setDescription(value); - } else if (key.equals(DEF)){ - //TODO - // set definition - Annotation anno = currentTerm.getAnnotation(); - anno.setProperty(DEF, value); - } else if (key.equals(XREF_ANALOG)){ - // set xref analog - Annotation anno = currentTerm.getAnnotation(); - anno.setProperty(XREF_ANALOG, value); - } else if (key.equals(IS_OBSOLETE)) { - // ignore obsolete Terms... - //logger.info("obsolete: {}", currentTerm); - Annotation anno = currentTerm.getAnnotation(); - anno.setProperty(IS_OBSOLETE, new Boolean(true)); - - } else if (key.equals(IS_A) || - key.equals(RELATIONSHIP) || - key.equals(DISJOINT_FROM) || - key.equals(INTERSECTION_OF) || - key.equals(SUBSET)) { - try { - Term object = (ontology.containsTerm(value) ? - ontology.getTerm(value): ontology.createTerm(value)); - Term predicate = (ontology.containsTerm(key) ? ontology.getTerm(key) : ontology.createTerm(key)); - ontology.createTriple(currentTerm, object, predicate, currentTerm + " " + predicate + " " + object, key+"-relationship"); - } catch (AlreadyExistsException ex) { + switch (key) { + case NAMESPACE: { + Annotation anno = currentTerm.getAnnotation(); + anno.setProperty(NAMESPACE, value); + break; + } + case NAME: + currentTerm.setDescription(value); + break; + case DEF: { + //TODO + // set definition + Annotation anno = currentTerm.getAnnotation(); + anno.setProperty(DEF, value); + break; + } + case XREF_ANALOG: { + // set xref analog + Annotation anno = currentTerm.getAnnotation(); + anno.setProperty(XREF_ANALOG, value); + break; } + case IS_OBSOLETE: { + // ignore obsolete Terms... + //logger.info("obsolete: {}", currentTerm); + Annotation anno = currentTerm.getAnnotation(); + anno.setProperty(IS_OBSOLETE, Boolean.TRUE); - } else if (key.equals(COMMENT)){ - Annotation anno = currentTerm.getAnnotation(); - anno.setProperty(COMMENT, value); - } else if (key.equals(ALT_ID)){ - Annotation anno = currentTerm.getAnnotation(); - anno.setProperty(ALT_ID, value); - } - else if (key.equals(REPLACED_BY)) { - Annotation anno = currentTerm.getAnnotation(); - anno.setProperty(REPLACED_BY, value); - } + break; + } + case IS_A: + case RELATIONSHIP: + case DISJOINT_FROM: + case INTERSECTION_OF: + case SUBSET: + try { + Term object = (ontology.containsTerm(value) ? + ontology.getTerm(value) : ontology.createTerm(value)); + Term predicate = (ontology.containsTerm(key) ? ontology.getTerm(key) : ontology.createTerm(key)); + ontology.createTriple(currentTerm, object, predicate, currentTerm + " " + predicate + " " + object, key + "-relationship"); + } catch (AlreadyExistsException ex) { + } - else { - //logger.info("unknown key {}", key); + break; + case COMMENT: { + Annotation anno = currentTerm.getAnnotation(); + anno.setProperty(COMMENT, value); + break; + } + case ALT_ID: { + Annotation anno = currentTerm.getAnnotation(); + anno.setProperty(ALT_ID, value); + break; + } + case REPLACED_BY: { + Annotation anno = currentTerm.getAnnotation(); + anno.setProperty(REPLACED_BY, value); + break; + } + default: + //logger.info("unknown key {}", key); + break; } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileParser.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileParser.java index 76b7d673c2..76dd2d7819 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileParser.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileParser.java @@ -53,49 +53,47 @@ public class OboFileParser { List listeners; protected String line; - protected int linenum = 0; + protected final int linenum = 0; protected int totalSize = 0; protected int bytesRead = 0; - protected StringBuffer tempBuffer = new StringBuffer(); + protected final StringBuffer tempBuffer = new StringBuffer(); protected SimpleDateFormat dateFormat = new SimpleDateFormat("dd:MM:yyyy HH:mm", Locale.US); protected static final Map escapeChars = - new HashMap(); + new HashMap<>(); protected static final Map unescapeChars = - new HashMap(); + new HashMap<>(); static { - escapeChars.put(new Character('n'), new Character('\n')); - escapeChars.put(new Character('W'), new Character(' ')); - escapeChars.put(new Character('t'), new Character('\t')); - escapeChars.put(new Character(':'), new Character(':')); - escapeChars.put(new Character(','), new Character(',')); - escapeChars.put(new Character('"'), new Character('"')); - escapeChars.put(new Character('\''), new Character('\'')); - escapeChars.put(new Character('\\'), new Character('\\')); - escapeChars.put(new Character('{'), new Character('{')); - escapeChars.put(new Character('}'), new Character('}')); - escapeChars.put(new Character('('), new Character('(')); - escapeChars.put(new Character(')'), new Character(')')); - escapeChars.put(new Character('['), new Character('[')); - escapeChars.put(new Character(']'), new Character(']')); - escapeChars.put(new Character('!'), new Character('!')); - Iterator it = escapeChars.keySet().iterator(); - while (it.hasNext()) { - Character key = it.next(); - Character value = escapeChars.get(key); - unescapeChars.put(value, key); + escapeChars.put('n', '\n'); + escapeChars.put('W', ' '); + escapeChars.put('t', '\t'); + escapeChars.put(':', ':'); + escapeChars.put(',', ','); + escapeChars.put('"', '"'); + escapeChars.put('\'', '\''); + escapeChars.put('\\', '\\'); + escapeChars.put('{', '{'); + escapeChars.put('}', '}'); + escapeChars.put('(', '('); + escapeChars.put(')', ')'); + escapeChars.put('[', '['); + escapeChars.put(']', ']'); + escapeChars.put('!', '!'); + for (Map.Entry entry : escapeChars.entrySet()) { + Character value = entry.getValue(); + unescapeChars.put(value, entry.getKey()); } } public static class SOPair { - public String str = null; + public final String str; - public int index = -1; + public final int index; - public int endIndex = -1; + public final int endIndex; public SOPair(String str, int index) { this(str, index, -1); @@ -114,7 +112,7 @@ public SOPair(String str, int index, int endIndex) { public OboFileParser(){ - listeners = new ArrayList(); + listeners = new ArrayList<>(); } @@ -166,7 +164,7 @@ public void parseOBO(BufferedReader oboFile) throws IOException{ lineEnd = line.length(); // find nested values - NestedValue nv = null; + NestedValue nv; int trailingStartIndex = -1; int trailingEndIndex = -1; @@ -258,12 +256,17 @@ private Synonym parseSynonym(String key, String value) throws IOException{ StringTokenizer tokenizer = new StringTokenizer(leftovers, " \t"); int scope = Synonym.RELATED_SYNONYM; - if ( key.equals(OboFileHandler.EXACT_SYNONYM)) - scope = Synonym.EXACT_SYNONYM; - else if ( key.equals(OboFileHandler.BROAD_SYNONYM)) - scope = Synonym.BROAD_SYNONYM; - else if ( key.equals(OboFileHandler.NARROW_SYNONYM)) - scope = Synonym.NARROW_SYNONYM; + switch (key) { + case OboFileHandler.EXACT_SYNONYM: + scope = Synonym.EXACT_SYNONYM; + break; + case OboFileHandler.BROAD_SYNONYM: + scope = Synonym.BROAD_SYNONYM; + break; + case OboFileHandler.NARROW_SYNONYM: + scope = Synonym.NARROW_SYNONYM; + break; + } String catID = null; @@ -271,19 +274,24 @@ else if ( key.equals(OboFileHandler.NARROW_SYNONYM)) String token = tokenizer.nextToken(); //logger.info("TOKEN:" +token); if (i == 0) { - if (token.equals("RELATED")) - scope = Synonym.RELATED_SYNONYM; - else if (token.equals("UNSPECIFIED")) - scope = Synonym.RELATED_SYNONYM; - else if (token.equals("EXACT")) - scope = Synonym.EXACT_SYNONYM; - else if (token.equals("BROAD")) - scope = Synonym.BROAD_SYNONYM; - else if (token.equals("NARROW")) - scope = Synonym.NARROW_SYNONYM; - else - throw new IOException("Found unexpected scope " - + "identifier " + token + line); + switch (token) { + case "RELATED": + case "UNSPECIFIED": + scope = Synonym.RELATED_SYNONYM; + break; + case "EXACT": + scope = Synonym.EXACT_SYNONYM; + break; + case "BROAD": + scope = Synonym.BROAD_SYNONYM; + break; + case "NARROW": + scope = Synonym.NARROW_SYNONYM; + break; + default: + throw new IOException("Found unexpected scope " + + "identifier " + token + line); + } } else if (i == 1) { catID = token; } else @@ -316,7 +324,7 @@ else if (token.equals("NARROW")) } protected Map[] getDbxrefList(String line, int startoffset, int endoffset) throws IOException { - Vector> temp = new Vector>(); + Vector> temp = new Vector<>(); boolean stop = false; while (!stop) { int braceIndex = findUnescaped(line, '{', startoffset, endoffset); @@ -343,7 +351,7 @@ protected Map[] getDbxrefList(String line, int startoffset, int e startoffset++; continue; } - NestedValue nv = null; + NestedValue nv; if (trailing) { nv = new NestedValue(); endIndex = getNestedValue(nv, line, endIndex + 1); @@ -367,7 +375,7 @@ protected Map[] getDbxrefList(String line, int startoffset, int e protected Map parseXref(String line, int startoffset, int endoffset) throws IOException { - String xref_str = null; + String xref_str; String desc_str = null; SOPair xref = unescape(line, '"', startoffset, endoffset, false); @@ -381,7 +389,7 @@ protected Map parseXref(String line, } - Map m = new HashMap(); + Map m = new HashMap<>(); m.put("xref",xref_str); m.put("desc",desc_str); return m; @@ -390,34 +398,28 @@ protected Map parseXref(String line, private void triggerNewStanza(String stanza){ - Iterator iter = listeners.iterator(); - while (iter.hasNext()){ - OboFileEventListener li = iter.next(); + for (OboFileEventListener li : listeners) { li.newStanza(stanza); } } private void triggerNewKey(String key, String value){ - Iterator iter = listeners.iterator(); - while (iter.hasNext()){ - OboFileEventListener li = iter.next(); + for (OboFileEventListener li : listeners) { li.newKey(key, value); } } private void triggerNewSynonym(Synonym synonym){ - Iterator iter = listeners.iterator(); - while (iter.hasNext()){ - OboFileEventListener li = iter.next(); + for (OboFileEventListener li : listeners) { li.newSynonym(synonym); } } public static String escape(String str, boolean escapespaces) { - StringBuffer out = new StringBuffer(); + StringBuilder out = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); - Object o = unescapeChars.get(new Character(c)); + Object o = unescapeChars.get(c); if (o == null) out.append(c); else { @@ -441,7 +443,7 @@ public SOPair unescape(String str, char toChar, int startindex, public SOPair unescape(String str, char toChar, int startindex, int endindex, boolean mustFindChar) throws IOException { - StringBuffer out = new StringBuffer(); + StringBuilder out = new StringBuilder(); int endValue = -1; for (int i = startindex; i < endindex; i++) { char c = str.charAt(i); @@ -449,7 +451,7 @@ public SOPair unescape(String str, char toChar, int startindex, i++; c = str.charAt(i); Character mapchar = escapeChars - .get(new Character(c)); + .get(c); if (mapchar == null) throw new IOException("Unrecognized escape" + " character " + c + " found."); @@ -604,7 +606,7 @@ else if (str.charAt(startIndex) == ',') { class NestedValue { - protected Properties propertyValues = new Properties(); + protected final Properties propertyValues = new Properties(); protected String name; protected String suggestedComment; @@ -615,9 +617,8 @@ public NestedValue() { public String toString(){ String txt = "NestedValue: " ; Set keys = propertyValues.keySet(); - Iterator iter = keys.iterator(); - while (iter.hasNext()){ - String key = iter.next().toString(); + for (Object o : keys) { + String key = o.toString(); String value = propertyValues.get(key).toString(); txt += " [" + key + ":" + value + "]"; } @@ -636,9 +637,8 @@ public Properties getPropertyValues() { public void addPropertyValue(Properties pv) { Set keys = pv.keySet(); - Iterator iter = keys.iterator(); - while (iter.hasNext()){ - String key = iter.next().toString(); + for (Object o : keys) { + String key = o.toString(); String value = pv.get(key).toString(); propertyValues.setProperty(key, value); } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/AbstractAnnotation.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/AbstractAnnotation.java index d6f9374328..69e0630f9e 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/AbstractAnnotation.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/AbstractAnnotation.java @@ -135,7 +135,7 @@ public Set keys() { @Override public String toString() { - StringBuffer sb = new StringBuffer("{"); + StringBuilder sb = new StringBuilder("{"); Map prop = getProperties(); Iterator i = prop.keySet().iterator(); if(i.hasNext()) { diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/Annotation.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/Annotation.java index fccf023371..dabfa9ebf8 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/Annotation.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/Annotation.java @@ -113,7 +113,7 @@ void setProperty(Object key, Object value) * */ - public void removeProperty(Object key) + void removeProperty(Object key) throws NoSuchElementException; /** @@ -157,6 +157,6 @@ public void removeProperty(Object key) * an implementation to have annotation even though it should implement * Annotatable. */ - static final Annotation EMPTY_ANNOTATION = new EmptyAnnotation(); + Annotation EMPTY_ANNOTATION = new EmptyAnnotation(); } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/KeyedWeakReference.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/KeyedWeakReference.java index 46b345c368..6e10eae149 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/KeyedWeakReference.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/KeyedWeakReference.java @@ -35,7 +35,7 @@ */ public class KeyedWeakReference extends WeakReference { - private Object key; + private final Object key; public KeyedWeakReference(Object key, Object ref) { super(ref); diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/SmallMap.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/SmallMap.java index c1f37caae5..b00e4eadea 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/SmallMap.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/SmallMap.java @@ -222,7 +222,7 @@ public void remove() { } private class MapEntry implements Map.Entry { - private int offset; + private final int offset; private MapEntry(int offset) { this.offset = offset; diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/WeakValueHashMap.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/WeakValueHashMap.java index 7762642c76..f3ece73302 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/WeakValueHashMap.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/WeakValueHashMap.java @@ -110,7 +110,7 @@ public Set entrySet() { } private class WVEntrySet extends AbstractSet { - private Set keyRefEntrySet; + private final Set keyRefEntrySet; public WVEntrySet() { super(); @@ -130,9 +130,9 @@ public Iterator iterator() { } } - private class WVEntryIterator implements Iterator { + private static class WVEntryIterator implements Iterator { private Object cache; - private Iterator keyRefIterator; + private final Iterator keyRefIterator; public WVEntryIterator(Iterator keyRefIterator) { this.keyRefIterator = keyRefIterator; @@ -182,8 +182,8 @@ private void primeCache() { } private static class WVMapEntry implements Map.Entry { - private Object key; - private Object value; + private final Object key; + private final Object value; private WVMapEntry(Object key, Object value) { this.key = key; diff --git a/biojava-ontology/src/test/java/org/biojava/nbio/ontology/TestOboFileParsing.java b/biojava-ontology/src/test/java/org/biojava/nbio/ontology/TestOboFileParsing.java index 8c8bf3e3e2..ed9ab28709 100644 --- a/biojava-ontology/src/test/java/org/biojava/nbio/ontology/TestOboFileParsing.java +++ b/biojava-ontology/src/test/java/org/biojava/nbio/ontology/TestOboFileParsing.java @@ -25,6 +25,7 @@ package org.biojava.nbio.ontology; import org.biojava.nbio.ontology.io.OboParser; +import org.biojava.nbio.ontology.utils.Annotation; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; @@ -34,8 +35,6 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.util.Set; -import java.util.Iterator; -import org.biojava.nbio.ontology.utils.Annotation; public class TestOboFileParsing { @@ -71,24 +70,22 @@ public void testParsingHPOOBO() throws Exception { ontology = parser.parseOBO(oboFile, "Human_phenotype", "the Human Phenotype ontology"); Set keys = ontology.getTerms(); - Iterator iter = keys.iterator(); - - while (iter.hasNext()){ - Term term = (Term) iter.next(); - if(term.getName().equals("HP:0000057")) { - Annotation anno = term.getAnnotation(); - Assert.assertTrue(anno.containsProperty("replaced_by")); - Assert.assertEquals("HP:0008665", anno.getProperty("replaced_by")); - } - if(term.getName().equals("HP:0000006")) { - Assert.assertEquals("Autosomal dominant inheritance", term.getDescription()); - Object[] syns = term.getSynonyms(); - Assert.assertEquals(3, syns.length); - Assert.assertEquals("Autosomal dominant", ((Synonym) syns[0]).getName()); - Assert.assertEquals("Autosomal dominant form", ((Synonym) syns[1]).getName()); - Assert.assertEquals("Autosomal dominant type", ((Synonym) syns[2]).getName()); - } - } + + for (Term term : keys) { + if (term.getName().equals("HP:0000057")) { + Annotation anno = term.getAnnotation(); + Assert.assertTrue(anno.containsProperty("replaced_by")); + Assert.assertEquals("HP:0008665", anno.getProperty("replaced_by")); + } + if (term.getName().equals("HP:0000006")) { + Assert.assertEquals("Autosomal dominant inheritance", term.getDescription()); + Object[] syns = term.getSynonyms(); + Assert.assertEquals(3, syns.length); + Assert.assertEquals("Autosomal dominant", ((Synonym) syns[0]).getName()); + Assert.assertEquals("Autosomal dominant form", ((Synonym) syns[1]).getName()); + Assert.assertEquals("Autosomal dominant type", ((Synonym) syns[2]).getName()); + } + } } } diff --git a/biojava-ontology/src/test/java/org/biojava/nbio/ontology/TestParseOBO.java b/biojava-ontology/src/test/java/org/biojava/nbio/ontology/TestParseOBO.java index b9fe2df034..dcc7871f34 100644 --- a/biojava-ontology/src/test/java/org/biojava/nbio/ontology/TestParseOBO.java +++ b/biojava-ontology/src/test/java/org/biojava/nbio/ontology/TestParseOBO.java @@ -27,7 +27,6 @@ import org.junit.Test; import java.io.*; -import java.text.ParseException; import java.util.Set; import static org.biojava.nbio.ontology.obo.OboFileHandler.NAMESPACE; @@ -35,7 +34,7 @@ public class TestParseOBO { @Test - public void testNamespace() throws IOException, ParseException { + public void testNamespace() throws IOException { String testTermEntry = "\n[Term]\n" + "id: SO:0000691\n" + diff --git a/biojava-protein-disorder/src/main/java/demo/PredictDisorder.java b/biojava-protein-disorder/src/main/java/demo/PredictDisorder.java index f6013dadd2..7fad8197d8 100644 --- a/biojava-protein-disorder/src/main/java/demo/PredictDisorder.java +++ b/biojava-protein-disorder/src/main/java/demo/PredictDisorder.java @@ -36,7 +36,7 @@ public static void main(String[] args) throws Exception{ ProteinSequence seq = getUniprot(uniprotID); System.out.println("Protein Sequence: "+ seq.toString()); - AminoAcidCompoundSet compoundSet = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet compoundSet = AminoAcidCompoundSet.aminoAcidCompoundSet; if (!compoundSet.isValidSequence(seq) ) { System.err.println("Invalid sequence, exiting"); @@ -58,8 +58,8 @@ public static void main(String[] args) throws Exception{ */ private static ProteinSequence getUniprot(String uniProtID) throws Exception { - AminoAcidCompoundSet set = AminoAcidCompoundSet.getAminoAcidCompoundSet(); - UniprotProxySequenceReader uniprotSequence = new UniprotProxySequenceReader(uniProtID,set); + AminoAcidCompoundSet set = AminoAcidCompoundSet.aminoAcidCompoundSet; + UniprotProxySequenceReader uniprotSequence = new UniprotProxySequenceReader<>(uniProtID, set); ProteinSequence seq = new ProteinSequence(uniprotSequence); diff --git a/biojava-protein-disorder/src/main/java/org/biojava/nbio/data/sequence/FastaSequence.java b/biojava-protein-disorder/src/main/java/org/biojava/nbio/data/sequence/FastaSequence.java index 6af6f13712..b915989ebb 100644 --- a/biojava-protein-disorder/src/main/java/org/biojava/nbio/data/sequence/FastaSequence.java +++ b/biojava-protein-disorder/src/main/java/org/biojava/nbio/data/sequence/FastaSequence.java @@ -26,8 +26,7 @@ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import java.util.Objects; /** * A FASTA formatted sequence. Please note that this class does not make any @@ -41,173 +40,150 @@ */ @XmlAccessorType(XmlAccessType.FIELD) -public final class FastaSequence implements Comparable{ - - /** - * Sequence id - */ - private String id; - - // TODO what about gapped sequence here! should be indicated - /** - * Returns the string representation of sequence - */ - private String sequence; - - @SuppressWarnings("unused") - private FastaSequence() { - // Default constructor for JaxB - } - - /** - * Upon construction the any whitespace characters are removed from the - * sequence - * - * @param id - * @param sequence - */ - public FastaSequence(final String id, final String sequence) { - this.id = id.trim(); - this.sequence = SequenceUtil.cleanSequence(sequence); - } - - /** - * Gets the value of id - * - * @return the value of id - */ - public String getId() { - return id; - } - - /** - * Gets the value of sequence - * - * @return the value of sequence - */ - public String getSequence() { - return sequence; - } - - public static int countMatchesInSequence(final String theString, - final String theRegExp) { - final Pattern p = Pattern.compile(theRegExp); - final Matcher m = p.matcher(theString); - int cnt = 0; - while (m.find()) { - cnt++; - } - return cnt; - } - - public String getFormattedFasta() { - return getFormatedSequence(80); - } - - /** - * - * @return one line name, next line sequence, no matter what the sequence - * length is - */ - public String getOnelineFasta() { - String fasta = ">" + getId() + "\n"; - fasta += getSequence() + "\n"; - return fasta; - } - - /** - * Format sequence per width letter in one string. Without spaces. - * - * @return multiple line formated sequence, one line width letters length - * - */ - public String getFormatedSequence(final int width) { - if (sequence == null) { - return ""; - } - - assert width >= 0 : "Wrong width parameter "; - - final StringBuilder sb = new StringBuilder(sequence); - int nchunks = sequence.length() / width; - // add up inserted new line chars - nchunks = (nchunks + sequence.length()) / width; - int nlineCharcounter = 0; - for (int i = 1; i <= nchunks; i++) { - final int insPos = width * i + nlineCharcounter; - // to prevent inserting new line in the very end of a sequence then - // it would have failed. - // Also covers the case when the sequences shorter than width - if (sb.length() <= insPos) { - break; - } - sb.insert(insPos, "\n"); - nlineCharcounter++; - } - return sb.toString(); - } - - /** - * - * @return sequence length - */ - public int getLength() { - return sequence.length(); - } - - /** - * Same as oneLineFasta - */ - @Override - public String toString() { - return this.getOnelineFasta(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result - + ((sequence == null) ? 0 : sequence.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final FastaSequence other = (FastaSequence) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (sequence == null) { - if (other.sequence != null) { - return false; - } - } else if (!sequence.equals(other.sequence)) { - return false; - } - return true; - } - - @Override - public int compareTo(FastaSequence o) { - if(o==null || o.id==null) - return 1; - - return this.getId().compareTo(o.id); - } +public final class FastaSequence implements Comparable { + + /** + * Sequence id + */ + private String id; + + // TODO what about gapped sequence here! should be indicated + /** + * Returns the string representation of sequence + */ + private String sequence; + + @SuppressWarnings("unused") + private FastaSequence() { + // Default constructor for JaxB + } + + /** + * Upon construction the any whitespace characters are removed from the + * sequence + * + * @param id + * @param sequence + */ + public FastaSequence(final String id, final String sequence) { + this.id = id.trim(); + this.sequence = SequenceUtil.cleanSequence(sequence); + } + + /** + * Gets the value of id + * + * @return the value of id + */ + public String getId() { + return id; + } + + /** + * Gets the value of sequence + * + * @return the value of sequence + */ + public String getSequence() { + return sequence; + } + +// public static int countMatchesInSequence(final String theString, +// final String theRegExp) { +// final Pattern p = Pattern.compile(theRegExp); +// final Matcher m = p.matcher(theString); +// int cnt = 0; +// while (m.find()) { +// cnt++; +// } +// return cnt; +// } + + public String getFormattedFasta() { + return getFormatedSequence(80); + } + + /** + * @return one line name, next line sequence, no matter what the sequence + * length is + */ + public String getOnelineFasta() { + return ">" + getId() + "\n" + (getSequence() + "\n"); + } + + /** + * Format sequence per width letter in one string. Without spaces. + * + * @return multiple line formated sequence, one line width letters length + */ + public String getFormatedSequence(final int width) { + if (sequence == null) { + return ""; + } + + assert width >= 0 : "Wrong width parameter "; + + final StringBuilder sb = new StringBuilder(sequence); + int nchunks = sequence.length() / width; + // add up inserted new line chars + nchunks = (nchunks + sequence.length()) / width; + int nlineCharcounter = 0; + for (int i = 1; i <= nchunks; i++) { + final int insPos = width * i + nlineCharcounter; + // to prevent inserting new line in the very end of a sequence then + // it would have failed. + // Also covers the case when the sequences shorter than width + if (sb.length() <= insPos) { + break; + } + sb.insert(insPos, "\n"); + nlineCharcounter++; + } + return sb.toString(); + } + + /** + * @return sequence length + */ + public int getLength() { + return sequence.length(); + } + + /** + * Same as oneLineFasta + */ + @Override + public String toString() { + return this.getOnelineFasta(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((sequence == null) ? 0 : sequence.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + + if (obj == null || getClass() != obj.getClass()) + return false; + + final FastaSequence other = (FastaSequence) obj; + return Objects.equals(id, other.id) && Objects.equals(sequence, other.sequence); + } + + @Override + public int compareTo(FastaSequence o) { + if (o == null || o.id == null) + return 1; + + return this.getId().compareTo(o.id); + } } diff --git a/biojava-protein-disorder/src/main/java/org/biojava/nbio/data/sequence/SequenceUtil.java b/biojava-protein-disorder/src/main/java/org/biojava/nbio/data/sequence/SequenceUtil.java index 55b9bc5cc6..096927f51d 100644 --- a/biojava-protein-disorder/src/main/java/org/biojava/nbio/data/sequence/SequenceUtil.java +++ b/biojava-protein-disorder/src/main/java/org/biojava/nbio/data/sequence/SequenceUtil.java @@ -29,6 +29,7 @@ import org.slf4j.LoggerFactory; import java.io.*; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; @@ -43,255 +44,251 @@ */ public final class SequenceUtil { - private static final Logger logger = LoggerFactory.getLogger(SequenceUtil.class); - - /** - * A whitespace character: [\t\n\x0B\f\r] - */ - public static final Pattern WHITE_SPACE = Pattern.compile("\\s"); - - /** - * A digit - */ - public static final Pattern DIGIT = Pattern.compile("\\d"); - - /** - * Non word - */ - public static final Pattern NONWORD = Pattern.compile("\\W"); - - /** - * Valid Amino acids - */ - public static final Pattern AA = Pattern.compile("[ARNDCQEGHILKMFPSTWYVUO]+", - Pattern.CASE_INSENSITIVE); - - /** - * inversion of AA pattern - */ - public static final Pattern NON_AA = Pattern.compile( - "[^ARNDCQEGHILKMFPSTWYVXUO]+", Pattern.CASE_INSENSITIVE); - - /** - * Same as AA pattern but with one additional letters - X - */ - public static final Pattern AMBIGUOUS_AA = Pattern.compile( - "[ARNDCQEGHILKMFPSTWYVXUO]+", Pattern.CASE_INSENSITIVE); - - /** - * Nucleotides a, t, g, c, u - */ - public static final Pattern NUCLEOTIDE = Pattern.compile("[AGTCU]+", - Pattern.CASE_INSENSITIVE); - - /** - * Ambiguous nucleotide - */ - public static final Pattern AMBIGUOUS_NUCLEOTIDE = Pattern.compile( - "[AGTCRYMKSWHBVDNU]+", Pattern.CASE_INSENSITIVE); // see IUPAC - /** - * Non nucleotide - */ - public static final Pattern NON_NUCLEOTIDE = Pattern.compile("[^AGTCU]+", - Pattern.CASE_INSENSITIVE); - - private SequenceUtil() { - } // utility class, no instantiation - - /* - * public static void write_PirSeq(OutputStream os, FastaSequence seq) - * throws IOException { BufferedWriter pir_out = new BufferedWriter(new - * OutputStreamWriter(os)); pir_out.write(">P1;" + seq.getId() + - * SysPrefs.newlinechar); pir_out.write(seq.getSequence() + - * SysPrefs.newlinechar); pir_out.close(); } - * - * public static void write_FastaSeq(OutputStream os, FastaSequence seq) - * throws IOException { BufferedWriter fasta_out = new BufferedWriter( new - * OutputStreamWriter(os)); fasta_out.write(">" + seq.getId() + - * SysPrefs.newlinechar); fasta_out.write(seq.getSequence() + - * SysPrefs.newlinechar); fasta_out.close(); } - */ - - /** - * @return true is the sequence contains only letters a,c, t, g, u - */ - public static boolean isNucleotideSequence(final FastaSequence s) { - return SequenceUtil.isNonAmbNucleotideSequence(s.getSequence()); - } - - /** - * Ambiguous DNA chars : AGTCRYMKSWHBVDN // differs from protein in only one - * (!) - B char - */ - public static boolean isNonAmbNucleotideSequence(String sequence) { - sequence = SequenceUtil.cleanSequence(sequence); - if (SequenceUtil.DIGIT.matcher(sequence).find()) { - return false; - } - if (SequenceUtil.NON_NUCLEOTIDE.matcher(sequence).find()) { - return false; - /* - * System.out.format("I found the text starting at " + - * "index %d and ending at index %d.%n", nonDNAmatcher .start(), - * nonDNAmatcher.end()); - */ - } - final Matcher DNAmatcher = SequenceUtil.NUCLEOTIDE.matcher(sequence); - return DNAmatcher.find(); - } - - /** - * Removes all whitespace chars in the sequence string - * - * @param sequence - * @return cleaned up sequence - */ - public static String cleanSequence(String sequence) { - assert sequence != null; - final Matcher m = SequenceUtil.WHITE_SPACE.matcher(sequence); - sequence = m.replaceAll("").toUpperCase(); - return sequence; - } - - /** - * Removes all special characters and digits as well as whitespace chars - * from the sequence - * - * @param sequence - * @return cleaned up sequence - */ - public static String deepCleanSequence(String sequence) { - sequence = SequenceUtil.cleanSequence(sequence); - sequence = SequenceUtil.DIGIT.matcher(sequence).replaceAll(""); - sequence = SequenceUtil.NONWORD.matcher(sequence).replaceAll(""); - final Pattern othernonSeqChars = Pattern.compile("[_-]+"); - sequence = othernonSeqChars.matcher(sequence).replaceAll(""); - return sequence; - } - - /** - * - * @param sequence - * @return true is the sequence is a protein sequence, false overwise - */ - public static boolean isProteinSequence(String sequence) { - sequence = SequenceUtil.cleanSequence(sequence); - if (SequenceUtil.isNonAmbNucleotideSequence(sequence)) { - return false; - } - if (SequenceUtil.DIGIT.matcher(sequence).find()) { - return false; - } - if (SequenceUtil.NON_AA.matcher(sequence).find()) { - logger.info("Found non aa: {}", sequence); - return false; - } - final Matcher protmatcher = SequenceUtil.AA.matcher(sequence); - return protmatcher.find(); - } - - /** - * Check whether the sequence confirms to amboguous protein sequence - * - * @param sequence - * @return return true only if the sequence if ambiguous protein sequence - * Return false otherwise. e.g. if the sequence is non-ambiguous - * protein or DNA - */ - public static boolean isAmbiguosProtein(String sequence) { - sequence = SequenceUtil.cleanSequence(sequence); - if (SequenceUtil.isNonAmbNucleotideSequence(sequence)) { - return false; - } - if (SequenceUtil.DIGIT.matcher(sequence).find()) { - return false; - } - if (SequenceUtil.NON_AA.matcher(sequence).find()) { - return false; - } - if (SequenceUtil.AA.matcher(sequence).find()) { - return false; - } - final Matcher amb_prot = SequenceUtil.AMBIGUOUS_AA.matcher(sequence); - return amb_prot.find(); - } - - /** - * Writes list of FastaSequeces into the outstream formatting the sequence - * so that it contains width chars on each line - * - * @param outstream - * @param sequences - * @param width - * - the maximum number of characters to write in one line - * @throws IOException - */ - public static void writeFasta(final OutputStream outstream, - final List sequences, final int width) - throws IOException { - final OutputStreamWriter writer = new OutputStreamWriter(outstream); - final BufferedWriter fastawriter = new BufferedWriter(writer); - for (final FastaSequence fs : sequences) { - fastawriter.write(fs.getFormatedSequence(width)); - } - outstream.flush(); - fastawriter.close(); - writer.close(); - } - - /** - * Reads fasta sequences from inStream into the list of FastaSequence - * objects - * - * @param inStream - * from - * @return list of FastaSequence objects - * @throws IOException - */ - public static List readFasta(final InputStream inStream) - throws IOException { - final List seqs = new ArrayList(); - - final BufferedReader infasta = new BufferedReader( - new InputStreamReader(inStream, "UTF8"), 16000); - final Pattern pattern = Pattern.compile("//s+"); - - String line; - String sname = "", seqstr = null; - do { - line = infasta.readLine(); - if ((line == null) || line.startsWith(">")) { - if (seqstr != null) { - seqs.add(new FastaSequence(sname.substring(1), seqstr)); - } - sname = line; // remove > - seqstr = ""; - } else { - final String subseq = pattern.matcher(line).replaceAll(""); - seqstr += subseq; - } - } while (line != null); - - infasta.close(); - return seqs; - } - - /** - * Writes FastaSequence in the file, each sequence will take one line only - * - * @param os - * @param sequences - * @throws IOException - */ - public static void writeFasta(final OutputStream os, - final List sequences) throws IOException { - final OutputStreamWriter outWriter = new OutputStreamWriter(os); - final BufferedWriter fasta_out = new BufferedWriter(outWriter); - for (final FastaSequence fs : sequences) { - fasta_out.write(fs.getOnelineFasta()); - } - fasta_out.close(); - outWriter.close(); - } + private static final Logger logger = LoggerFactory.getLogger(SequenceUtil.class); + + /** + * A whitespace character: [\t\n\x0B\f\r] + */ + public static final Pattern WHITE_SPACE = Pattern.compile("\\s"); + + /** + * A digit + */ + public static final Pattern DIGIT = Pattern.compile("\\d"); + + /** + * Non word + */ + public static final Pattern NONWORD = Pattern.compile("\\W"); + + /** + * Valid Amino acids + */ + public static final Pattern AA = Pattern.compile("[ARNDCQEGHILKMFPSTWYVUO]+", + Pattern.CASE_INSENSITIVE); + + /** + * inversion of AA pattern + */ + public static final Pattern NON_AA = Pattern.compile( + "[^ARNDCQEGHILKMFPSTWYVXUO]+", Pattern.CASE_INSENSITIVE); + + /** + * Same as AA pattern but with one additional letters - X + */ + public static final Pattern AMBIGUOUS_AA = Pattern.compile( + "[ARNDCQEGHILKMFPSTWYVXUO]+", Pattern.CASE_INSENSITIVE); + + /** + * Nucleotides a, t, g, c, u + */ + public static final Pattern NUCLEOTIDE = Pattern.compile("[AGTCU]+", + Pattern.CASE_INSENSITIVE); + + /** + * Ambiguous nucleotide + */ + public static final Pattern AMBIGUOUS_NUCLEOTIDE = Pattern.compile( + "[AGTCRYMKSWHBVDNU]+", Pattern.CASE_INSENSITIVE); // see IUPAC + /** + * Non nucleotide + */ + public static final Pattern NON_NUCLEOTIDE = Pattern.compile("[^AGTCU]+", + Pattern.CASE_INSENSITIVE); + + private SequenceUtil() { + } // utility class, no instantiation + + /* + * public static void write_PirSeq(OutputStream os, FastaSequence seq) + * throws IOException { BufferedWriter pir_out = new BufferedWriter(new + * OutputStreamWriter(os)); pir_out.write(">P1;" + seq.getId() + + * SysPrefs.newlinechar); pir_out.write(seq.getSequence() + + * SysPrefs.newlinechar); pir_out.close(); } + * + * public static void write_FastaSeq(OutputStream os, FastaSequence seq) + * throws IOException { BufferedWriter fasta_out = new BufferedWriter( new + * OutputStreamWriter(os)); fasta_out.write(">" + seq.getId() + + * SysPrefs.newlinechar); fasta_out.write(seq.getSequence() + + * SysPrefs.newlinechar); fasta_out.close(); } + */ + + /** + * @return true is the sequence contains only letters a,c, t, g, u + */ + public static boolean isNucleotideSequence(final FastaSequence s) { + return SequenceUtil.isNonAmbNucleotideSequence(s.getSequence()); + } + + /** + * Ambiguous DNA chars : AGTCRYMKSWHBVDN // differs from protein in only one + * (!) - B char + */ + public static boolean isNonAmbNucleotideSequence(String sequence) { + + sequence = SequenceUtil.cleanSequence(sequence); + + if (SequenceUtil.DIGIT.matcher(sequence).find()) + return false; + + if (SequenceUtil.NON_NUCLEOTIDE.matcher(sequence).find()) + return false; + /* + * System.out.format("I found the text starting at " + + * "index %d and ending at index %d.%n", nonDNAmatcher .start(), + * nonDNAmatcher.end()); + */ + + return SequenceUtil.NUCLEOTIDE.matcher(sequence).find(); + } + + /** + * Removes all whitespace chars in the sequence string + * + * @param sequence + * @return cleaned up sequence + */ + public static String cleanSequence(String sequence) { + assert sequence != null; + return SequenceUtil.WHITE_SPACE.matcher(sequence).replaceAll("").toUpperCase(); + } + + /** + * Removes all special characters and digits as well as whitespace chars + * from the sequence + * + * @param sequence + * @return cleaned up sequence + */ + public static String deepCleanSequence(String sequence) { + sequence = SequenceUtil.cleanSequence(sequence); + sequence = SequenceUtil.DIGIT.matcher(sequence).replaceAll(""); + sequence = SequenceUtil.NONWORD.matcher(sequence).replaceAll(""); + final Pattern othernonSeqChars = Pattern.compile("[_-]+"); + sequence = othernonSeqChars.matcher(sequence).replaceAll(""); + return sequence; + } + + /** + * @param sequence + * @return true is the sequence is a protein sequence, false overwise + */ + public static boolean isProteinSequence(String sequence) { + sequence = SequenceUtil.cleanSequence(sequence); + if (SequenceUtil.isNonAmbNucleotideSequence(sequence)) { + return false; + } + if (SequenceUtil.DIGIT.matcher(sequence).find()) { + return false; + } + if (SequenceUtil.NON_AA.matcher(sequence).find()) { + logger.info("Found non aa: {}", sequence); + return false; + } + final Matcher protmatcher = SequenceUtil.AA.matcher(sequence); + return protmatcher.find(); + } + + /** + * Check whether the sequence confirms to amboguous protein sequence + * + * @param sequence + * @return return true only if the sequence if ambiguous protein sequence + * Return false otherwise. e.g. if the sequence is non-ambiguous + * protein or DNA + */ + public static boolean isAmbiguosProtein(String sequence) { + sequence = SequenceUtil.cleanSequence(sequence); + if (SequenceUtil.isNonAmbNucleotideSequence(sequence)) { + return false; + } + if (SequenceUtil.DIGIT.matcher(sequence).find()) { + return false; + } + if (SequenceUtil.NON_AA.matcher(sequence).find()) { + return false; + } + if (SequenceUtil.AA.matcher(sequence).find()) { + return false; + } + final Matcher amb_prot = SequenceUtil.AMBIGUOUS_AA.matcher(sequence); + return amb_prot.find(); + } + + /** + * Writes list of FastaSequeces into the outstream formatting the sequence + * so that it contains width chars on each line + * + * @param outstream + * @param sequences + * @param width - the maximum number of characters to write in one line + * @throws IOException + */ + public static void writeFasta(final OutputStream outstream, + final List sequences, final int width) + throws IOException { + final OutputStreamWriter writer = new OutputStreamWriter(outstream); + final BufferedWriter fastawriter = new BufferedWriter(writer); + for (final FastaSequence fs : sequences) { + fastawriter.write(fs.getFormatedSequence(width)); + } + outstream.flush(); + fastawriter.close(); + writer.close(); + } + + /** + * Reads fasta sequences from inStream into the list of FastaSequence + * objects + * + * @param inStream from + * @return list of FastaSequence objects + * @throws IOException + */ + public static List readFasta(final InputStream inStream) + throws IOException { + final List seqs = new ArrayList<>(); + + final BufferedReader infasta = new BufferedReader( + new InputStreamReader(inStream, StandardCharsets.UTF_8), 16000); + final Pattern pattern = Pattern.compile("//s+"); + + String line; + String sname = "", seqstr = null; + do { + line = infasta.readLine(); + if ((line == null) || line.startsWith(">")) { + if (seqstr != null) { + seqs.add(new FastaSequence(sname.substring(1), seqstr)); + } + sname = line; // remove > + seqstr = ""; + } else { + final String subseq = pattern.matcher(line).replaceAll(""); + seqstr += subseq; + } + } while (line != null); + + infasta.close(); + return seqs; + } + + /** + * Writes FastaSequence in the file, each sequence will take one line only + * + * @param os + * @param sequences + * @throws IOException + */ + public static void writeFasta(final OutputStream os, + final List sequences) throws IOException { + final OutputStreamWriter outWriter = new OutputStreamWriter(os); + final BufferedWriter fasta_out = new BufferedWriter(outWriter); + for (final FastaSequence fs : sequences) { + fasta_out.write(fs.getOnelineFasta()); + } + fasta_out.close(); + outWriter.close(); + } } diff --git a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/Jronn.java b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/Jronn.java index 60b259aff2..f886cfec54 100644 --- a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/Jronn.java +++ b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/Jronn.java @@ -58,9 +58,7 @@ public class Jronn implements Serializable { static { try { loader.loadModels(); - } catch (NumberFormatException e) { - throw new RuntimeException("Fails to load models!" + e.getMessage(), e); - } catch (IOException e) { + } catch (NumberFormatException | IOException e) { throw new RuntimeException("Fails to load models!" + e.getMessage(), e); } } @@ -157,7 +155,7 @@ public static float[] getDisorderScores(ProteinSequence sequence) { * @return */ public static FastaSequence convertProteinSequencetoFasta(ProteinSequence sequence){ - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); for (AminoAcidCompound compound : sequence) { String c = compound.getShortName(); @@ -175,14 +173,12 @@ public static FastaSequence convertProteinSequencetoFasta(ProteinSequence sequen private static float[] predictSerial(FastaSequence fsequence) { ORonn.validateSequenceForRonn(fsequence); ORonn ronn; - float[] disorder = null; + float[] disorder; try { ronn = new ORonn(fsequence, loader); disorder = ronn.call().getMeanScores(); } catch (NumberFormatException e) { throw new RuntimeException("Jronn fails to load models " + e.getLocalizedMessage(), e); - } catch (IOException e) { - throw new RuntimeException("Jronn fails to load models " + e.getLocalizedMessage(), e); } return disorder; } @@ -215,7 +211,7 @@ public static Range[] scoresToRanges(float[] scores, float probability) { int count=0; int regionLen=0; - List ranges = new ArrayList(); + List ranges = new ArrayList<>(); for(float score: scores) { count++; // Round to 2 decimal points before comparison @@ -233,7 +229,7 @@ public static Range[] scoresToRanges(float[] scores, float probability) { if(regionLen>1) { ranges.add(new Range(count-regionLen+1, count,scores[scores.length-1])); } - return ranges.toArray(new Range[ranges.size()]); + return ranges.toArray(new Range[0]); } @@ -246,7 +242,7 @@ public static Range[] scoresToRanges(float[] scores, float probability) { * @see #getDisorder(FastaSequence) */ public static Map getDisorderScores(List sequences) { - Map results = new TreeMap(); + Map results = new TreeMap<>(); for(FastaSequence fsequence : sequences) { results.put(fsequence, predictSerial(fsequence)); } @@ -261,7 +257,7 @@ public static Map getDisorderScores(List s * @see #getDisorder(FastaSequence) */ public static Map getDisorder(List sequences) { - Map disorderRanges = new TreeMap(); + Map disorderRanges = new TreeMap<>(); for(FastaSequence fs: sequences) { disorderRanges.put(fs, getDisorder(fs)); } diff --git a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ModelLoader.java b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ModelLoader.java index f6eb3aac47..7e6bc4e872 100644 --- a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ModelLoader.java +++ b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ModelLoader.java @@ -33,6 +33,7 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.Map; @@ -94,8 +95,8 @@ public static class Model { */ final float[] W;// = new float[RonnConstraint.maxD]; - int numOfDBAAseq; - int modelNum = -1; + final int numOfDBAAseq; + final int modelNum; public Model(final int modelNum, final int numberofSequence) { this.modelNum = modelNum; @@ -155,7 +156,7 @@ public String toString() { } - private static final Map models = new HashMap(); + private static final Map models = new HashMap<>(); public Model getModel(final int modelNum) { return ModelLoader.models.get(modelNum); @@ -167,8 +168,8 @@ void loadModels() throws NumberFormatException, IOException { final BufferedReader bfr = new BufferedReader( new InputStreamReader(ModelLoader.class.getResourceAsStream( "model" + i + ".rec"), - "ISO-8859-1")); - String line = null; + StandardCharsets.ISO_8859_1)); + String line; line = bfr.readLine().trim(); final int numberOfSeqs = Integer.parseInt(line); final Model model = new Model(i, numberOfSeqs); diff --git a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/NullOutputStream.java b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/NullOutputStream.java index 572e4ddee6..cfcae3d36e 100644 --- a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/NullOutputStream.java +++ b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/NullOutputStream.java @@ -27,7 +27,6 @@ package org.biojava.nbio.ronn; -import java.io.IOException; import java.io.OutputStream; /** @@ -40,7 +39,7 @@ public final class NullOutputStream extends OutputStream { @Override - public void write(final int b) throws IOException { + public void write(final int b) { // this methods does nothing. // This is an intention } diff --git a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ORonn.java b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ORonn.java index 16dbcb72a1..0440e56b06 100644 --- a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ORonn.java +++ b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ORonn.java @@ -26,7 +26,6 @@ import org.biojava.nbio.data.sequence.FastaSequence; import org.biojava.nbio.data.sequence.SequenceUtil; -import org.biojava.nbio.ronn.ModelLoader.Model; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -91,8 +90,7 @@ public final class ORonn implements Callable { timer = new Timer(TimeUnit.MILLISECONDS); } //This constructor is for API calls where the caller collects the results directly - ORonn(final FastaSequence sequence, final ModelLoader mloader) throws NumberFormatException, - IOException { + ORonn(final FastaSequence sequence, final ModelLoader mloader) throws NumberFormatException { this.sequence = sequence; this.mloader = mloader; out = new PrintWriter(new NullOutputStream()); @@ -136,23 +134,16 @@ static boolean isValidSequence(final FastaSequence fsequence) { } @Override - public ORonn call() throws NumberFormatException, IOException { + public ORonn call() throws NumberFormatException { final String seq = sequence.getSequence(); // Calculate for each model - for (int m = 0; m < ORonn.NUMBER_OF_MODELS; m++) { - final Model model = mloader.getModel(m); - final ORonnModel rmodel = new ORonnModel(seq, model, disorder); - final float[] scores = rmodel.detect(); - addScore(scores); - } + for (int m = 0; m < ORonn.NUMBER_OF_MODELS; m++) + addScore(new ORonnModel(seq, mloader.getModel(m), disorder).detect()); - final char[] ch = seq.toCharArray(); final float[] meanScores = getMeanScores(); - assert meanScores.length == seq.length() : "Scores are not calculated for " - + "all residues!"; - writeResults(meanScores, ch); - stat.println(timer.getTotalTime() + "ms prediction completed for " - + sequence.getId()); + assert meanScores.length == seq.length() : "Scores are not calculated for all residues!"; + writeResults(meanScores, seq.toCharArray()); + stat.println(timer.getTotalTime() + "ms prediction completed for " + sequence.getId()); return this; } @@ -172,8 +163,9 @@ private void addScore(final float[] scores) { } float[] getMeanScores() { - final float[] meanScores = new float[cummulativeScore.length]; - for (int i = 0; i < cummulativeScore.length; i++) { + int n = cummulativeScore.length; + final float[] meanScores = new float[n]; + for (int i = 0; i < n; i++) { meanScores[i] = cummulativeScore[i] / ORonn.NUMBER_OF_MODELS; } return meanScores; @@ -190,7 +182,7 @@ float[] getMeanScores() { * sequence. Letters and values separated by tabulation in this case. * */ - static enum ResultLayout { + enum ResultLayout { VERTICAL, HORIZONTAL } @@ -201,7 +193,7 @@ static void printUsage() { static boolean isValidSequenceForRonn(final FastaSequence fsequence, final PrintWriter stat) { boolean valid = true; - String message = ""; + String message; if (!ORonn.isValidSequence(fsequence)) { message = "IGNORING sequence " + fsequence.getId() @@ -225,7 +217,7 @@ static boolean isValidSequenceForRonn(final FastaSequence fsequence, static void validateSequenceForRonn(final FastaSequence fsequence) { - String message = ""; + String message; if (!ORonn.isValidSequence(fsequence)) { message = "IGNORING sequence " + fsequence.getId() @@ -353,7 +345,7 @@ static void predictParallel(final List fsequences, // Do parallel execution final ExecutorService executor = new ThreadPoolExecutor(prms .getThreadNum(), prms.getThreadNum(), 0L, TimeUnit.SECONDS, - new SynchronousQueue(), + new SynchronousQueue<>(), new ThreadPoolExecutor.CallerRunsPolicy()); try { for (final FastaSequence sequence : fsequences) { @@ -369,8 +361,7 @@ static void predictParallel(final List fsequences, executor.submit(ronn); } executor.shutdown(); - final int timeOut = (fsequences.size() < 60) ? 60 : fsequences - .size(); + final int timeOut = Math.max(fsequences.size(), 60); stat.println("All task submitted. Waiting for complition for " + "maximum of " + timeOut + " minutes"); executor.awaitTermination(timeOut, TimeUnit.MINUTES); diff --git a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ORonnModel.java b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ORonnModel.java index 41253be8c1..0f6dfca151 100644 --- a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ORonnModel.java +++ b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ORonnModel.java @@ -34,7 +34,6 @@ import java.io.PrintWriter; - /** * Fully re-factored version of RONN model. Based on the code in C version of * RONN. @@ -45,142 +44,143 @@ */ public final class ORonnModel { - private static final Logger logger = LoggerFactory.getLogger(ORonnModel.class); - - /** - * Order probability, corresponds to disorder as 1-order - */ - private final float disorder_weight; - - private final static int AA_ALPHABET = 19; - private final static int maxR = 110; - //private final static float coef = 1.0f; - /** - * Holds encoded query sequence - */ - private final short[] seqAA; - /** - * Holds query sequence - */ - private final char[] query; - - private final Model model; - - /** - * Disorder scores for all residues - */ - private float[] scores = null; - - final float[] detect() { - - scores = new float[query.length]; - int sResidue; - int dIndex; - int r; - float est, fOrder, pDisor, fDisor; - final float[][] Z = new float[seqAA.length][ORonnModel.maxR]; - final int[] Q = new int[seqAA.length]; - final Threshold thold = new ModelLoader.Threshold(model.modelNum); - - /* - * 19 looks like a size of the sliding window. So for any sequences - * shorted than 19 AA the score will be NaN. Original RONN segfault in - * such condition - */ - for (sResidue = 0; sResidue <= query.length - ORonnModel.AA_ALPHABET; sResidue++) { - est = 0.0f; - - for (dIndex = 0; dIndex < model.numOfDBAAseq; dIndex++) { - final float[] rho = align(sResidue, dIndex);// search for the - // maximum alignment between ith peptide from the - // query and the dIndex-th database sequence - est += model.W[dIndex] * Math.exp((rho[1] - rho[0]) / rho[0]); - } - - fOrder = (float) (Math.exp(-0.5 * Math.pow(est - thold.mu0, 2.0) - / thold.sigma0) / (Math.sqrt(6.28) * thold.sigma0)); - - fDisor = (float) (Math.exp(-0.5 * Math.pow(est - thold.mu1, 2.0) - / thold.sigma1) / (Math.sqrt(6.28) * thold.sigma1)); - - pDisor = (float) (disorder_weight * fDisor / ((1.0 - disorder_weight) - * fOrder + disorder_weight * fDisor)); - for (r = sResidue; r < sResidue + ORonnModel.AA_ALPHABET; r++) { - Z[r][Q[r]] = pDisor; - Q[r]++; - } - } - - for (sResidue = 0; sResidue < query.length; sResidue++) { - est = 0.0f; - float[] zRow = Z[sResidue]; - int numOfIterations = Q[sResidue]; - for (r = 0; r < numOfIterations; r++) { - est += zRow[r]; - } - scores[sResidue] = est / numOfIterations; - } - return scores; - } - - public void getScores(final File outfile) throws FileNotFoundException { - final PrintWriter output = new PrintWriter(outfile); - if (scores == null) { - synchronized (this) { - if (scores == null) { - detect(); - } - } - } - for (int i = 0; i < scores.length; i++) { - output.printf("%c\t%f\n", query[i], scores[i]); - } - output.close(); - } - - // sResidue query sequence index and dIndex database sequence index - private final float[] align(final int sResidue, final int dIndex) { - int dResidue, r; - float maxScore = -1000000; - float rho1 = 0; - int maxIdx = 0; - float rho0 = 0; - short[] dbAARow = model.dbAA[dIndex]; - int numOfIterations = model.Length[dIndex] - ORonnModel.AA_ALPHABET; - for (dResidue = 0; dResidue <= numOfIterations; dResidue++) { - // go though the database sequence for maximised alignment - rho1 = 0.0f; - for (r = 0; r < ORonnModel.AA_ALPHABET; r++) { - // go through the query sequence for one alignment - rho1 += RonnConstraint.Blosum62[seqAA[sResidue + r]][dbAARow[dResidue - + r]]; - } - if (rho1 > maxScore) { - maxScore = rho1; - maxIdx = dResidue; - } - } - for (r = 0; r < ORonnModel.AA_ALPHABET; r++) { - rho0 += RonnConstraint.Blosum62[dbAARow[maxIdx + r]][dbAARow[maxIdx - + r]]; - } - return new float[] { rho0, maxScore }; - } - - public ORonnModel(final String sequence, final Model model, - final float disorder) throws NumberFormatException { - this.disorder_weight = disorder; - this.model = model; - query = sequence.toCharArray(); - seqAA = new short[query.length]; - assert model != null; - assert model.numOfDBAAseq > 0; - for (int sResidue = 0; sResidue < sequence.length(); sResidue++) { - seqAA[sResidue] = RonnConstraint.INDEX[query[sResidue] - 'A']; - if ((seqAA[sResidue] < 0) || (seqAA[sResidue] > 19)) { - logger.error("seqAA[sResidue]={}({})", seqAA[sResidue], query[sResidue]); - System.exit(1); - } - } - } + private static final Logger logger = LoggerFactory.getLogger(ORonnModel.class); + + /** + * Order probability, corresponds to disorder as 1-order + */ + private final float disorder_weight; + + private final static int AA_ALPHABET = 19; + private final static int maxR = 110; + //private final static float coef = 1.0f; + /** + * Holds encoded query sequence + */ + private final short[] seqAA; + /** + * Holds query sequence + */ + private final char[] query; + + private final Model model; + + /** + * Disorder scores for all residues + */ + private float[] scores = null; + + final float[] detect() { + + scores = new float[query.length]; + int sResidue; + int dIndex; + int r; + float est, fOrder, pDisor, fDisor; + final float[][] Z = new float[seqAA.length][ORonnModel.maxR]; + final int[] Q = new int[seqAA.length]; + final Threshold thold = new ModelLoader.Threshold(model.modelNum); + + /* + * 19 looks like a size of the sliding window. So for any sequences + * shorted than 19 AA the score will be NaN. Original RONN segfault in + * such condition + */ + for (sResidue = 0; sResidue <= query.length - ORonnModel.AA_ALPHABET; sResidue++) { + est = 0.0f; + + for (dIndex = 0; dIndex < model.numOfDBAAseq; dIndex++) { + final float[] rho = align(sResidue, dIndex);// search for the + // maximum alignment between ith peptide from the + // query and the dIndex-th database sequence + est += model.W[dIndex] * Math.exp((rho[1] - rho[0]) / rho[0]); + } + + fOrder = (float) (Math.exp(-0.5 * Math.pow(est - thold.mu0, 2.0) + / thold.sigma0) / (Math.sqrt(6.28) * thold.sigma0)); + + fDisor = (float) (Math.exp(-0.5 * Math.pow(est - thold.mu1, 2.0) + / thold.sigma1) / (Math.sqrt(6.28) * thold.sigma1)); + + pDisor = (float) (disorder_weight * fDisor / ((1.0 - disorder_weight) + * fOrder + disorder_weight * fDisor)); + for (r = sResidue; r < sResidue + ORonnModel.AA_ALPHABET; r++) { + Z[r][Q[r]] = pDisor; + Q[r]++; + } + } + + for (sResidue = 0; sResidue < query.length; sResidue++) { + est = 0.0f; + float[] zRow = Z[sResidue]; + int numOfIterations = Q[sResidue]; + for (r = 0; r < numOfIterations; r++) { + est += zRow[r]; + } + scores[sResidue] = est / numOfIterations; + } + return scores; + } + + public void getScores(final File outfile) throws FileNotFoundException { + final PrintWriter output = new PrintWriter(outfile); + if (scores == null) { + synchronized (this) { + if (scores == null) { + detect(); + } + } + } + for (int i = 0; i < scores.length; i++) { + output.printf("%c\t%f\n", query[i], scores[i]); + } + output.close(); + } + + // sResidue query sequence index and dIndex database sequence index + private float[] align(final int sResidue, final int dIndex) { + int dResidue, r; + float maxScore = Float.NEGATIVE_INFINITY; + float rho1; + int maxIdx = 0; + float rho0 = 0; + short[] dbAARow = model.dbAA[dIndex]; + int numOfIterations = model.Length[dIndex] - ORonnModel.AA_ALPHABET; + for (dResidue = 0; dResidue <= numOfIterations; dResidue++) { + // go though the database sequence for maximised alignment + rho1 = 0.0f; + for (r = 0; r < ORonnModel.AA_ALPHABET; r++) { + // go through the query sequence for one alignment + rho1 += RonnConstraint.Blosum62[seqAA[sResidue + r]][dbAARow[dResidue + + r]]; + } + if (rho1 > maxScore) { + maxScore = rho1; + maxIdx = dResidue; + } + } + for (r = 0; r < ORonnModel.AA_ALPHABET; r++) { + rho0 += RonnConstraint.Blosum62[dbAARow[maxIdx + r]][dbAARow[maxIdx + r]]; + } + return new float[]{rho0, maxScore}; + } + + public ORonnModel(final String sequence, final Model model, + final float disorder) throws NumberFormatException { + this.disorder_weight = disorder; + this.model = model; + query = sequence.toCharArray(); + seqAA = new short[query.length]; + assert model != null; + assert model.numOfDBAAseq > 0; + int sLen = sequence.length(); + for (int sResidue = 0; sResidue < sLen; sResidue++) { + short r = RonnConstraint.INDEX[query[sResidue] - 'A']; + if ((r < 0) || (r > 19)) { + logger.error("seqAA[sResidue]={}({})", r, query[sResidue]); + System.exit(1); + } + seqAA[sResidue] = r; + } + } } diff --git a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/RonnConstraint.java b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/RonnConstraint.java index dacf3067bd..995ecbda6b 100644 --- a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/RonnConstraint.java +++ b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/RonnConstraint.java @@ -91,7 +91,7 @@ public final class RonnConstraint { { -2, -2, -3, -2, 3, -3, 2, -1, -2, -1, -1, -2, -3, -1, -2, -2, -2, -1, 2, 7 } }; - public static enum Threshold { + public enum Threshold { T0(0, RonnConstraint.THRESHOLD0), T1(1, RonnConstraint.THRESHOLD1), T2( 2, RonnConstraint.THRESHOLD2), T3(3, RonnConstraint.THRESHOLD3), T4( 4, RonnConstraint.THRESHOLD4), T5(5, RonnConstraint.THRESHOLD5), T6( @@ -101,7 +101,7 @@ public static enum Threshold { private final int tnum; private final float[] values; - private Threshold(final int tnum, final float[] values) { + Threshold(final int tnum, final float[] values) { this.tnum = tnum; this.values = values; } diff --git a/biojava-protein-disorder/src/test/java/org/biojava/nbio/ronn/JronnTest.java b/biojava-protein-disorder/src/test/java/org/biojava/nbio/ronn/JronnTest.java index 65bfc5ed36..2783477538 100644 --- a/biojava-protein-disorder/src/test/java/org/biojava/nbio/ronn/JronnTest.java +++ b/biojava-protein-disorder/src/test/java/org/biojava/nbio/ronn/JronnTest.java @@ -79,7 +79,7 @@ public void checkJronn() { * Credit Thomas Klambauer, but here have removed the implement of * AutoCloseable (Java 7) for BioJava support of Java 6. */ - public class ScopedProperty { + public static class ScopedProperty { private final String key; private final String oldValue; diff --git a/biojava-protein-disorder/src/test/java/org/biojava/nbio/ronn/NonstandardProteinCompoundTest.java b/biojava-protein-disorder/src/test/java/org/biojava/nbio/ronn/NonstandardProteinCompoundTest.java index d3c50fd61b..e71e4351b5 100644 --- a/biojava-protein-disorder/src/test/java/org/biojava/nbio/ronn/NonstandardProteinCompoundTest.java +++ b/biojava-protein-disorder/src/test/java/org/biojava/nbio/ronn/NonstandardProteinCompoundTest.java @@ -69,7 +69,7 @@ private void testUniprot(String uniprotID) throws CompoundNotFoundException, IOE ProteinSequence seq = getUniprot(uniprotID); - AminoAcidCompoundSet compoundSet = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet compoundSet = AminoAcidCompoundSet.aminoAcidCompoundSet; /* for (AminoAcidCompound compound : seq) { System.out.println(compound.getShortName() + " " + compound.getLongName() + " " + compound.getDescription() + " | " + compoundSet.getEquivalentCompounds(compound) + " " + compound.getMolecularWeight() + " " + compound.getBase()); @@ -94,9 +94,9 @@ private void testUniprot(String uniprotID) throws CompoundNotFoundException, IOE */ private static ProteinSequence getUniprot(String uniProtID) throws CompoundNotFoundException, IOException { - AminoAcidCompoundSet set = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet set = AminoAcidCompoundSet.aminoAcidCompoundSet; UniprotProxySequenceReader uniprotSequence = - new UniprotProxySequenceReader(uniProtID,set); + new UniprotProxySequenceReader<>(uniProtID, set); ProteinSequence seq = new ProteinSequence(uniprotSequence); diff --git a/biojava-structure-gui/pom.xml b/biojava-structure-gui/pom.xml index e6605344bc..8dfa407860 100644 --- a/biojava-structure-gui/pom.xml +++ b/biojava-structure-gui/pom.xml @@ -42,7 +42,7 @@ net.sourceforge.jmol jmol - 14.29.17 + 14.29.27 diff --git a/biojava-structure-gui/src/main/java/demo/AFPFromFasta.java b/biojava-structure-gui/src/main/java/demo/AFPFromFasta.java index 5327b18e2f..8eec576679 100644 --- a/biojava-structure-gui/src/main/java/demo/AFPFromFasta.java +++ b/biojava-structure-gui/src/main/java/demo/AFPFromFasta.java @@ -26,7 +26,6 @@ import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.StructureAlignment; import org.biojava.nbio.structure.align.gui.StructureAlignmentDisplay; @@ -37,8 +36,6 @@ import org.biojava.nbio.structure.io.FastaAFPChainConverter; import org.biojava.nbio.structure.io.FastaStructureParser; -import java.io.IOException; - /** * Demo displaying a structural alignment from a FASTA file using {@link FastaAFPChainConverter}. * @@ -48,7 +45,7 @@ */ public class AFPFromFasta { - public static void main(String[] args) throws IOException, StructureException, Exception { + public static void main(String[] args) throws Exception { Structure structure1 = StructureTools.getStructure("1w0p"); Structure structure2 = StructureTools.getStructure("1w0p"); String first = "alfdynatgdtefdspakqgwmqdntnngsgvltnadgmpawlvqgiggraqwtyslstnqhaqassfgwrmttemkvlsggmitnyyangtqrvlpiisldssgnlvvefegqtgrtvlatgtaateyhkfelvflpgsnpsasfyfdgklirdniqptaskQNMIVWGNGSSntdgvaayrdikfei------------------------------------------------------------------------------------------------------------------QGDVIf------------RGPDRIPSIVASsvTPGVVTAFAEKRVGGgdpgalsntNDIITRTSRDGGITWDTELNLTEQinvsdeFDFSDPRPIYDPs---SNTVLVSYARWPtdaaqngdrikpwmpNGIFYSVYDVASgnWQAPIDVTdqvkersfqiagwggselyrrntslnsqqdwqsnakirivdgaanqiqvadgsrkyvvtlsidesgglvanlngvsapiilqsehakvhsfhdyelqysalnhtttlfvdgqqittwagevsqenniqfgnadaqidgrlhvqkivltqqghnlvefdafylaqqtpevekdleklgwtkiktgntmslygNASVNPGpgHGITLtrqqnisgsqNGRLIYPAIVLdrfFLNVMSIYSDDGgsnwq-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------TGSTLpipfrwksssileTLEPSEADMVELQN--GDLLLTARLDFNQivngvny--SPRQQFLSKDGGITWSLLEANNANvfsnistgTVDASITRFEqsdgSHFLLFTNPQGnpagTNgr------------QNLGLWFSFDEG--VTWKGPIQ--LVNGasaysdiyqldsenaivivetdnsnmrilrmpitllkqklt"; diff --git a/biojava-structure-gui/src/main/java/demo/DemoAlignmentFromFasta.java b/biojava-structure-gui/src/main/java/demo/DemoAlignmentFromFasta.java index fbd3ecc74d..8cf8fafc44 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoAlignmentFromFasta.java +++ b/biojava-structure-gui/src/main/java/demo/DemoAlignmentFromFasta.java @@ -20,11 +20,6 @@ */ package demo; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; - import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; @@ -32,11 +27,7 @@ import org.biojava.nbio.core.sequence.io.GenericFastaHeaderParser; import org.biojava.nbio.core.sequence.io.template.SequenceCreatorInterface; import org.biojava.nbio.core.sequence.io.template.SequenceHeaderParserInterface; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.gui.StructureAlignmentDisplay; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AlignmentTools; @@ -44,6 +35,11 @@ import org.biojava.nbio.structure.io.FastaStructureParser; import org.biojava.nbio.structure.io.StructureSequenceMatcher; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + /** * Demo of how to use the {@link FastaStructureParser} class to read protein * structures from a FASTA file. @@ -53,7 +49,7 @@ */ public class DemoAlignmentFromFasta { - public static void getAlignmentFromFasta() throws StructureException { + public static void getAlignmentFromFasta() { // Load a test sequence // Normally this would come from a file, eg @@ -68,26 +64,21 @@ public static void getAlignmentFromFasta() throws StructureException { InputStream fasta; - try { - fasta = new ByteArrayInputStream(fastaStr.getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - return; - } + fasta = new ByteArrayInputStream(fastaStr.getBytes(StandardCharsets.UTF_8)); - // Create a header parser to parse the header lines into valid structure accessions. + // Create a header parser to parse the header lines into valid structure accessions. // The resulting accession can be anything interpretable by AtomCache.getStructure. // Possible Examples: "4HHB" (whole structure), "d4hhba_" (SCOP domain), // "4HHB.A:1-15" (residue range) // For this example, the built-in fasta parser will extract the correct accession. SequenceHeaderParserInterface headerParser; - headerParser = new GenericFastaHeaderParser(); + headerParser = new GenericFastaHeaderParser<>(); // Create AtomCache to fetch structures from the PDB AtomCache cache = new AtomCache(); // Create SequenceCreator. This converts a String to a ProteinSequence - AminoAcidCompoundSet aaSet = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet aaSet = AminoAcidCompoundSet.aminoAcidCompoundSet; SequenceCreatorInterface creator; creator = new CasePreservingProteinSequenceCreator(aaSet); @@ -96,10 +87,7 @@ public static void getAlignmentFromFasta() throws StructureException { fasta, headerParser, creator, cache); try { parser.process(); - } catch (IOException e) { - e.printStackTrace(); - return; - } catch (StructureException e) { + } catch (IOException | StructureException e) { e.printStackTrace(); return; } @@ -133,7 +121,7 @@ public static void getAlignmentFromFasta() throws StructureException { } - public static void main(String[] args) throws StructureException { + public static void main(String[] args) { getAlignmentFromFasta(); } } diff --git a/biojava-structure-gui/src/main/java/demo/DemoCE.java b/biojava-structure-gui/src/main/java/demo/DemoCE.java index 5e2bb0aabb..81630472f0 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoCE.java +++ b/biojava-structure-gui/src/main/java/demo/DemoCE.java @@ -60,8 +60,8 @@ public static void main(String[] args){ ChemCompGroupFactory.setChemCompProvider(prov); - Structure structure1 = null; - Structure structure2 = null; + Structure structure1; + Structure structure2; try { diff --git a/biojava-structure-gui/src/main/java/demo/DemoCeSymm.java b/biojava-structure-gui/src/main/java/demo/DemoCeSymm.java index a7fc6eeacd..a120793c96 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoCeSymm.java +++ b/biojava-structure-gui/src/main/java/demo/DemoCeSymm.java @@ -20,7 +20,6 @@ */ package demo; -import java.io.IOException; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; @@ -33,6 +32,8 @@ import org.biojava.nbio.structure.symmetry.internal.CeSymm; import org.biojava.nbio.structure.symmetry.internal.CeSymmResult; +import java.io.IOException; + /** * Quick demo of how to call CE-Symm programmatically. * Some examples of different symmetry types are proposed. diff --git a/biojava-structure-gui/src/main/java/demo/DemoFATCAT.java b/biojava-structure-gui/src/main/java/demo/DemoFATCAT.java index ac7a0542f6..173bd90436 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoFATCAT.java +++ b/biojava-structure-gui/src/main/java/demo/DemoFATCAT.java @@ -53,8 +53,8 @@ public static void main(String[] args){ AtomCache cache = new AtomCache(); - Structure structure1 = null; - Structure structure2 = null; + Structure structure1; + Structure structure2; try { diff --git a/biojava-structure-gui/src/main/java/demo/DemoMultipleMC.java b/biojava-structure-gui/src/main/java/demo/DemoMultipleMC.java index 062bc6d8d7..d365e4242c 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoMultipleMC.java +++ b/biojava-structure-gui/src/main/java/demo/DemoMultipleMC.java @@ -20,12 +20,6 @@ */ package demo; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.ArrayList; -import java.util.concurrent.ExecutionException; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIdentifier; @@ -38,6 +32,11 @@ import org.biojava.nbio.structure.align.multiple.mc.MultipleMcParameters; import org.biojava.nbio.structure.align.util.AtomCache; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + /** * Demo for running the CEMC Algorithm on a protein family and * visualizing the results. @@ -48,7 +47,7 @@ */ public class DemoMultipleMC { - public static void main(String[] args) throws IOException, StructureException, InterruptedException, ExecutionException { + public static void main(String[] args) throws IOException, StructureException { //ASP-proteinases (CEMC paper) //List names = Arrays.asList("3app", "4ape", "2apr", "5pep", "1psn", "4cms", "1bbs.A", "1smr.A", "2jxr.A", "1mpp", "2asi", "1am5"); @@ -97,9 +96,9 @@ public static void main(String[] args) throws IOException, StructureException, I //Load the CA atoms of the structures AtomCache cache = new AtomCache(); - List identifiers = new ArrayList(); + List identifiers = new ArrayList<>(); - List atomArrays = new ArrayList(); + List atomArrays = new ArrayList<>(); for (String name:names) { atomArrays.add(cache.getAtoms(name)); identifiers.add(new SubstructureIdentifier(name)); diff --git a/biojava-structure-gui/src/main/java/demo/DemoRotationAxis.java b/biojava-structure-gui/src/main/java/demo/DemoRotationAxis.java index 83b676eb8f..06faf0faf3 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoRotationAxis.java +++ b/biojava-structure-gui/src/main/java/demo/DemoRotationAxis.java @@ -118,10 +118,8 @@ public static void main(String[] args) { jmolPanel.evalString("draw ID z VECTOR {0,0,0} {0,0,5} WIDTH 0.5 COLOR blue \">z\";"); */ - } catch (IOException e) { - e.printStackTrace(); - } catch (StructureException e) { + } catch (IOException | StructureException e) { e.printStackTrace(); } - } + } } diff --git a/biojava-structure-gui/src/main/java/demo/DemoSW3DAligner.java b/biojava-structure-gui/src/main/java/demo/DemoSW3DAligner.java index bcb4ac1e96..cc9ef9b874 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoSW3DAligner.java +++ b/biojava-structure-gui/src/main/java/demo/DemoSW3DAligner.java @@ -44,8 +44,8 @@ public static void main(String[] args){ AtomCache cache = new AtomCache(); - Structure structure1 = null; - Structure structure2 = null; + Structure structure1; + Structure structure2; try { diff --git a/biojava-structure-gui/src/main/java/demo/DemoShowBiolAssembly.java b/biojava-structure-gui/src/main/java/demo/DemoShowBiolAssembly.java index 1293af91a6..273da76812 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoShowBiolAssembly.java +++ b/biojava-structure-gui/src/main/java/demo/DemoShowBiolAssembly.java @@ -21,8 +21,8 @@ package demo; import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; public class DemoShowBiolAssembly { diff --git a/biojava-structure-gui/src/main/java/demo/DemoShowCATHDomain.java b/biojava-structure-gui/src/main/java/demo/DemoShowCATHDomain.java index 7ddf7671f6..00d5a7e7fd 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoShowCATHDomain.java +++ b/biojava-structure-gui/src/main/java/demo/DemoShowCATHDomain.java @@ -23,6 +23,7 @@ package demo; +import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.client.StructureName; import org.biojava.nbio.structure.align.util.UserConfiguration; import org.biojava.nbio.structure.cath.CathDatabase; @@ -30,7 +31,6 @@ import org.biojava.nbio.structure.cath.CathInstallation; import org.biojava.nbio.structure.cath.CathSegment; import org.biojava.nbio.structure.gui.BiojavaJmol; -import org.biojava.nbio.structure.StructureIO; import java.util.List; diff --git a/biojava-structure-gui/src/main/java/demo/DemoShowLargeAssembly.java b/biojava-structure-gui/src/main/java/demo/DemoShowLargeAssembly.java index c626e90f8a..7719d32442 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoShowLargeAssembly.java +++ b/biojava-structure-gui/src/main/java/demo/DemoShowLargeAssembly.java @@ -1,10 +1,10 @@ package demo; import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.FileParsingParameters; -import org.biojava.nbio.structure.StructureIO; /* * BioJava development code @@ -90,7 +90,7 @@ public static Structure readStructure(String pdbId, int bioAssemblyId) { // download missing files - Structure structure = null; + Structure structure; try { structure = StructureIO.getBiologicalAssembly(pdbId,bioAssemblyId); } catch (Exception e){ diff --git a/biojava-structure-gui/src/main/java/demo/DemoShowValidationResults.java b/biojava-structure-gui/src/main/java/demo/DemoShowValidationResults.java index 80001fd6bf..b695ca5fe2 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoShowValidationResults.java +++ b/biojava-structure-gui/src/main/java/demo/DemoShowValidationResults.java @@ -24,8 +24,8 @@ package demo; import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; import org.biojava.nbio.structure.validation.*; import javax.xml.bind.JAXBContext; @@ -46,7 +46,7 @@ public static void main(String[] args){ private static void showPdbValidation(String pdbId) { try { - JAXBContext ctx = JAXBContext.newInstance(new Class[] {WwPDBValidationInformation.class}); + JAXBContext ctx = JAXBContext.newInstance(WwPDBValidationInformation.class); Unmarshaller um = ctx.createUnmarshaller(); @@ -87,7 +87,7 @@ private static void showPdbValidation(String pdbId) { pos +="^" + iCode; pos +=":" + chainId; - BigDecimal base = new BigDecimal(0.5); + BigDecimal base = new BigDecimal("0.5"); for (Clash clash : clashes){ String clashatom = clash.getAtom(); diff --git a/biojava-structure-gui/src/main/java/demo/DemoStructureFromFasta.java b/biojava-structure-gui/src/main/java/demo/DemoStructureFromFasta.java index c99678d4b9..11bfb74fa4 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoStructureFromFasta.java +++ b/biojava-structure-gui/src/main/java/demo/DemoStructureFromFasta.java @@ -20,12 +20,6 @@ */ package demo; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.align.util.AtomCache; -import org.biojava.nbio.structure.gui.BiojavaJmol; -import org.biojava.nbio.structure.io.FastaStructureParser; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; @@ -33,11 +27,17 @@ import org.biojava.nbio.core.sequence.io.ProteinSequenceCreator; import org.biojava.nbio.core.sequence.io.template.SequenceCreatorInterface; import org.biojava.nbio.core.sequence.io.template.SequenceHeaderParserInterface; +import org.biojava.nbio.structure.ResidueNumber; +import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.StructureException; +import org.biojava.nbio.structure.align.util.AtomCache; +import org.biojava.nbio.structure.gui.BiojavaJmol; +import org.biojava.nbio.structure.io.FastaStructureParser; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; /** * Demo of how to use the {@link FastaStructureParser} class to read protein @@ -60,26 +60,21 @@ public static void getStructureFromFasta() { "KVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTPA\n" + "VHASLDKFLASVSTVLTSKYR\n"; InputStream fasta; - try { - fasta = new ByteArrayInputStream(fastaStr.getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - return; - } + fasta = new ByteArrayInputStream(fastaStr.getBytes(StandardCharsets.UTF_8)); - // Create a header parser to parse the header lines into valid structure accessions. + // Create a header parser to parse the header lines into valid structure accessions. // The resulting accession can be anything interpretable by AtomCache.getStructure. // Possible Examples: "4HHB" (whole structure), "d4hhba_" (SCOP domain), // "4HHB.A:1-15" (residue range) // For this example, the built-in fasta parser will extract the correct accession. SequenceHeaderParserInterface headerParser; - headerParser = new GenericFastaHeaderParser(); + headerParser = new GenericFastaHeaderParser<>(); // Create AtomCache to fetch structures from the PDB AtomCache cache = new AtomCache(); // Create SequenceCreator. This converts a String to a ProteinSequence - AminoAcidCompoundSet aaSet = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet aaSet = AminoAcidCompoundSet.aminoAcidCompoundSet; SequenceCreatorInterface creator; creator = new ProteinSequenceCreator(aaSet); @@ -88,10 +83,7 @@ public static void getStructureFromFasta() { fasta, headerParser, creator, cache); try { parser.process(); - } catch (IOException e) { - e.printStackTrace(); - return; - } catch (StructureException e) { + } catch (IOException | StructureException e) { e.printStackTrace(); return; } diff --git a/biojava-structure-gui/src/main/java/demo/ShowStructureInJmol.java b/biojava-structure-gui/src/main/java/demo/ShowStructureInJmol.java index adeda7dac1..b451f32a9f 100644 --- a/biojava-structure-gui/src/main/java/demo/ShowStructureInJmol.java +++ b/biojava-structure-gui/src/main/java/demo/ShowStructureInJmol.java @@ -21,8 +21,8 @@ package demo; import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; /** Demo how to load and display a structure in Jmol diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AboutDialog.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AboutDialog.java index 1d978876cf..afa66cb16d 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AboutDialog.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AboutDialog.java @@ -26,10 +26,7 @@ import javax.swing.*; import javax.swing.event.HyperlinkEvent; -import javax.swing.event.HyperlinkListener; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; public class AboutDialog { @@ -66,22 +63,18 @@ public void showDialog(){ vBox= Box.createVerticalBox(); vBox.add(scroll); - txt.addHyperlinkListener(new HyperlinkListener(){ - - @Override - public void hyperlinkUpdate(HyperlinkEvent e) { - - if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { - String href = e.getDescription(); - BrowserOpener.showDocument(href); - } - if ( e.getEventType() == HyperlinkEvent.EventType.ENTERED) { - // change the mouse curor - vBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - } - if (e.getEventType() == HyperlinkEvent.EventType.EXITED) { - vBox.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } + txt.addHyperlinkListener(e -> { + + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + String href = e.getDescription(); + BrowserOpener.showDocument(href); + } + if ( e.getEventType() == HyperlinkEvent.EventType.ENTERED) { + // change the mouse curor + vBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + } + if (e.getEventType() == HyperlinkEvent.EventType.EXITED) { + vBox.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } }); @@ -90,17 +83,14 @@ public void hyperlinkUpdate(HyperlinkEvent e) { JButton close = new JButton("Close"); - close.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { - Object source = event.getSource(); + close.addActionListener(event -> { + Object source = event.getSource(); - JButton but = (JButton)source; - Container parent = but.getParent().getParent().getParent().getParent().getParent().getParent() ; + JButton but = (JButton)source; + Container parent = but.getParent().getParent().getParent().getParent().getParent().getParent() ; - JDialog dia = (JDialog) parent; - dia.dispose(); - } + JDialog dia = (JDialog) parent; + dia.dispose(); }); Box hBoxb = Box.createHorizontalBox(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalc.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalc.java index 98ed76f7a4..4bda6f155f 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalc.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalc.java @@ -52,8 +52,8 @@ public class AlignmentCalc implements AlignmentCalculationRunnable { String pdb1; String pdb2; - String name1; - String name2; + final String name1; + final String name2; Structure structure1; Structure structure2; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalcDB.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalcDB.java index 74637e4617..b0b8899410 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalcDB.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalcDB.java @@ -40,11 +40,11 @@ public class AlignmentCalcDB implements AlignmentCalculationRunnable { - public static String SCOP_VERSION = "1.75"; + public static final String SCOP_VERSION = "1.75"; //private static final Logger logger = LoggerFactory.getLogger(AlignmentCalcDB.class); - AtomicBoolean interrupted ; + final AtomicBoolean interrupted ; String name1; @@ -56,10 +56,10 @@ public class AlignmentCalcDB implements AlignmentCalculationRunnable { UserConfiguration config; - String outFile; + final String outFile; int nrCPUs; - Boolean domainSplit ; + final Boolean domainSplit ; StructureAlignment customAlgorithm; @@ -97,7 +97,7 @@ public AlignmentCalcDB(AlignmentGui parent, Structure s1, String name1, UserCon @Override public void run() { - StructureAlignment algorithm = null; + StructureAlignment algorithm; if ( parent != null ) algorithm = parent.getStructureAlignment(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalculationRunnable.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalculationRunnable.java index e50de3f637..d9559b2227 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalculationRunnable.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalculationRunnable.java @@ -27,8 +27,8 @@ public interface AlignmentCalculationRunnable extends Runnable { - public void interrupt(); - public void cleanup(); - public void setNrCPUs(int useNrCPUs); + void interrupt(); + void cleanup(); + void setNrCPUs(int useNrCPUs); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentGui.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentGui.java index c55e6689e3..c3d9813f67 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentGui.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentGui.java @@ -22,23 +22,6 @@ */ package org.biojava.nbio.structure.align.gui; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.io.File; -import java.io.IOException; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenuBar; -import javax.swing.JOptionPane; -import javax.swing.JProgressBar; -import javax.swing.JTabbedPane; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.StructureAlignment; @@ -52,6 +35,12 @@ import org.biojava.nbio.structure.gui.util.ScopSelectPanel; import org.biojava.nbio.structure.gui.util.StructurePairSelector; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.io.File; +import java.io.IOException; + /** A JFrame that allows to trigger a pairwise structure alignment, * either from files in a directory, * or after manual upload. @@ -65,24 +54,24 @@ */ public class AlignmentGui extends JFrame{ - private final static long serialVersionUID =0l; + private final static long serialVersionUID = 0L; StructureAlignment algorithm; JButton abortB; - SelectPDBPanel tab1 ; - PDBUploadPanel tab2; - ScopSelectPanel tab3; + final SelectPDBPanel tab1 ; + final PDBUploadPanel tab2; + final ScopSelectPanel tab3; Thread thread; AlignmentCalculationRunnable alicalc; - JTabbedPane masterPane; - JTabbedPane tabPane; + final JTabbedPane masterPane; + final JTabbedPane tabPane; JProgressBar progress; - private DBSearchGUI dbsearch; + private final DBSearchGUI dbsearch; public static void main(String[] args){ @@ -93,7 +82,7 @@ public static void main(String[] args){ static final ResourceManager resourceManager = ResourceManager.getResourceManager("ce"); - private static final String MAIN_TITLE = "Pairwise Structure Alignment - Main - V." + resourceManager.getString("ce.version");; + private static final String MAIN_TITLE = "Pairwise Structure Alignment - Main - V." + resourceManager.getString("ce.version"); private static final AlignmentGui me = new AlignmentGui(); @@ -208,7 +197,7 @@ private Box setupAlgorithm() algorithmList.setSelectedIndex(0); Action actionAlgorithm = new AbstractAction("Algorithm") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -226,7 +215,7 @@ public void actionPerformed(ActionEvent evt) { Action paramAction = new AbstractAction("Parameters") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -269,7 +258,7 @@ private Box initButtons(){ // hBox42.add(Box.createGlue()); // vBox.add(hBox42); Action action1 = new AbstractAction("Align") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -290,7 +279,7 @@ else if ( selectedIndex == 1) JButton submitB = new JButton(action1); Action action3 = new AbstractAction("Abort") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -304,7 +293,7 @@ public void actionPerformed(ActionEvent evt) { abortB.setEnabled(false); Action action2 = new AbstractAction("Exit") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -377,8 +366,8 @@ private void calcAlignment() { return; } - String name1 = "custom1"; - String name2 = "custom2"; + String name1; + String name2; if ( pos == 0){ name1 = tab1.getName1().getIdentifier(); @@ -400,9 +389,7 @@ private void calcAlignment() { progress.setIndeterminate(true); ProgressThreadDrawer drawer = new ProgressThreadDrawer(progress); drawer.start(); - } catch (StructureException e){ - JOptionPane.showMessageDialog(null,"Could not align structures. Exception: " + e.getMessage()); - } catch (IOException e) { + } catch (StructureException | IOException e){ JOptionPane.showMessageDialog(null,"Could not align structures. Exception: " + e.getMessage()); } @@ -449,14 +436,14 @@ private void calcDBSearch() { } String name1 = s.getName(); - if ( name1 == null || name1.equals("")) + if ( name1 == null || name1.isEmpty()) name1 = s.getPDBCode(); System.out.println("name1 in alig gui:" + name1); String file = dbsearch.getOutFileLocation(); - if ( file == null || file.equals("") ){ + if ( file == null || file.isEmpty()){ JOptionPane.showMessageDialog(null,"Please select a directory to contain the DB search results."); return; } @@ -550,7 +537,7 @@ private void updateAlgorithm(String algorithmName) { class ProgressThreadDrawer extends Thread { JProgressBar progress; - static int interval = 300; + static final int interval = 300; public ProgressThreadDrawer(JProgressBar progress) { this.progress = progress; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentTextPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentTextPanel.java index d5aea38c5d..caee4ee93d 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentTextPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentTextPanel.java @@ -33,7 +33,7 @@ public class AlignmentTextPanel extends JPrintPanel { * */ private static final long serialVersionUID = 5092386365924879073L; - JEditorPane tp; + final JEditorPane tp; public AlignmentTextPanel(){ super(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ChooseDirAction.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ChooseDirAction.java index c603392c08..cdf02e8154 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ChooseDirAction.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ChooseDirAction.java @@ -39,14 +39,14 @@ */ public class ChooseDirAction extends AbstractAction{ - JTextField textField; + final JTextField textField; UserConfiguration config; public ChooseDirAction (JTextField textField, UserConfiguration config){ super("Choose"); this.config = config; this.textField = textField; } - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ConfigPDBInstallPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ConfigPDBInstallPanel.java index 637183a3af..028e464591 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ConfigPDBInstallPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ConfigPDBInstallPanel.java @@ -44,11 +44,11 @@ public class ConfigPDBInstallPanel extends JPanel private static final long serialVersionUID = -1055193854675583808L; JCheckBox fromFtp; - JComboBox fileType; + final JComboBox fileType; JTextField pdbDir; - private static ConfigPDBInstallPanel instance = new ConfigPDBInstallPanel(); + private static final ConfigPDBInstallPanel instance = new ConfigPDBInstallPanel(); static JDialog dialog; @@ -137,22 +137,14 @@ public static void showDialog(){ vBox.add(Box.createGlue()); JButton apply = new JButton("Apply"); - apply.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { - instance.applyValues(); - dialog.dispose(); - } + apply.addActionListener(event -> { + instance.applyValues(); + dialog.dispose(); }); JButton close = new JButton("Cancel"); - close.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { - dialog.dispose(); - } - }); + close.addActionListener(event -> dialog.dispose()); Box hBoxb = Box.createHorizontalBox(); hBoxb.add(Box.createGlue()); @@ -206,7 +198,7 @@ public void setPDBDirField(JTextField dir){ } class MyAction implements ActionListener{ - JDialog dialog; + final JDialog dialog; public MyAction(JDialog dialog) { this.dialog= dialog; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DBResultTable.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DBResultTable.java index b71b040f8e..700b8707cd 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DBResultTable.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DBResultTable.java @@ -96,7 +96,7 @@ public DBResultTable(){ public void show(BufferedReader in, UserConfiguration config) throws IOException{ String str; - List tmpdat = new ArrayList(); + List tmpdat = new ArrayList<>(); while ((str = in.readLine()) != null) { if ( str.startsWith("#")) { if ( str.startsWith("# algorithm:")) { @@ -142,9 +142,7 @@ else if ( str.startsWith("#param:scoring=")){ ceParams.setScoringStrategy(scoreS); } } - } catch (IndexOutOfBoundsException e){ - System.err.println("Unknown scoring strategy from line: " + str); - } catch (IllegalArgumentException e) { + } catch (IndexOutOfBoundsException | IllegalArgumentException e){ System.err.println("Unknown scoring strategy from line: " + str); } catch (Exception e) { System.err.println("Unknown parameter can't read parameters from line: " + str); @@ -260,7 +258,7 @@ private void initAlgorithm(String algorithmName) { } private void outputSelection() { - StringBuffer output = new StringBuffer(); + StringBuilder output = new StringBuilder(); output.append(String.format("Lead: %d, %d. ", table.getSelectionModel().getLeadSelectionIndex(), table.getColumnModel().getSelectionModel(). @@ -309,7 +307,7 @@ private void showAlignment( String name1, String name2){ } try { - Structure structure1 = null; + Structure structure1; if ( name1.equals("CUSTOM")) { // user uploaded a custom PDB file... structure1 = loadCustomStructure(userPath,userChain); @@ -348,7 +346,7 @@ private void showAlignment( String name1, String name2){ private Structure loadCustomStructure(String userPath2, String userChain2) throws StructureException{ StructureIOFile reader = new PDBFileReader(); - Structure s = null; + Structure s; try { s = reader.getStructure(userPath2); } catch (IOException e){ diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DBSearchGUI.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DBSearchGUI.java index 885a544d28..6b982cb872 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DBSearchGUI.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DBSearchGUI.java @@ -31,8 +31,6 @@ import org.biojava.nbio.structure.gui.util.ScopSelectPanel; import javax.swing.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.io.File; public class DBSearchGUI extends JPanel { @@ -44,13 +42,13 @@ public class DBSearchGUI extends JPanel { StructureAlignment algorithm; - SelectPDBPanel tab1; + final SelectPDBPanel tab1; JTabbedPane tabPane; - PDBUploadPanel tab2; - ScopSelectPanel tab3; + final PDBUploadPanel tab2; + final ScopSelectPanel tab3; - JPanel listPane; + final JPanel listPane; JButton abortB; AlignmentCalcDB alicalc; JProgressBar progress; @@ -155,30 +153,26 @@ private JPanel createListPane() { dir.add(hBox); - chB.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - JFileChooser chooser = new JFileChooser(); - chooser.setMultiSelectionEnabled(false); - chooser.setDialogTitle("Select Output Directory"); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - // - // disable the "All files" option. - // - chooser.setAcceptAllFileFilterUsed(false); - // - - - // In response to a button click: - int returnVal = chooser.showSaveDialog(null); - if ( returnVal == JFileChooser.APPROVE_OPTION) { - File file = chooser.getSelectedFile(); - outFileLocation.setText(file.getPath()); - outFileLocation.repaint(); - } - + chB.addActionListener(e -> { + JFileChooser chooser = new JFileChooser(); + chooser.setMultiSelectionEnabled(false); + chooser.setDialogTitle("Select Output Directory"); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + // + // disable the "All files" option. + // + chooser.setAcceptAllFileFilterUsed(false); + // + + + // In response to a button click: + int returnVal = chooser.showSaveDialog(null); + if ( returnVal == JFileChooser.APPROVE_OPTION) { + File file = chooser.getSelectedFile(); + outFileLocation.setText(file.getPath()); + outFileLocation.repaint(); } + }); //tabP.addTab("Select Output Directory", null, dir, @@ -203,18 +197,14 @@ private Box createDomainSelectPane() { JComboBox domainList = new JComboBox(petStrings); domainList.setSelectedIndex(0); domainList.setToolTipText("Either align whole chains or SCOP domains and domains assigned with PDP, where no SCOP available."); - domainList.addActionListener(new ActionListener() { + domainList.addActionListener(arg0 -> { + JComboBox box = (JComboBox)arg0.getSource(); + int index = box.getSelectedIndex(); + if ( index == 0) + useDomainSplit = true; + else + useDomainSplit = false; - @Override - public void actionPerformed(ActionEvent arg0) { - JComboBox box = (JComboBox)arg0.getSource(); - int index = box.getSelectedIndex(); - if ( index == 0) - useDomainSplit = true; - else - useDomainSplit = false; - - } }); JLabel label= new JLabel("Domains:"); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DisplayAFP.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DisplayAFP.java index 03aa7d5084..5ce33ee02c 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DisplayAFP.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DisplayAFP.java @@ -19,32 +19,23 @@ package org.biojava.nbio.structure.align.gui; -import java.awt.Dimension; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.swing.Box; -import javax.swing.JFrame; -import javax.swing.JMenuBar; -import javax.swing.JScrollPane; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.gui.aligpanel.AligPanel; import org.biojava.nbio.structure.align.gui.aligpanel.StatusDisplay; import org.biojava.nbio.structure.align.gui.jmol.AbstractAlignmentJmol; import org.biojava.nbio.structure.align.gui.jmol.JmolTools; import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; import org.biojava.nbio.structure.align.model.AFPChain; -import org.biojava.nbio.structure.align.util.AFPAlignmentDisplay; import org.biojava.nbio.structure.align.util.AlignmentTools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.swing.*; +import java.awt.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + /** A utility class for visualistion of structure alignments * * @author Andreas Prlic @@ -55,8 +46,8 @@ public class DisplayAFP { private static final Logger logger = LoggerFactory.getLogger(DisplayAFP.class); //TODO: same as getEqrPos??? !!! - public static final List getEQRAlignmentPos(AFPChain afpChain){ - List lst = new ArrayList(); + public static List getEQRAlignmentPos(AFPChain afpChain){ + List lst = new ArrayList<>(); char[] s1 = afpChain.getAlnseq1(); char[] s2 = afpChain.getAlnseq2(); @@ -106,8 +97,8 @@ private static boolean isAlignedPosition(int i, char c1, char c2, boolean isFatC * @param afpChain * @param ca */ - public static final List getPDBresnum(int aligPos, AFPChain afpChain, Atom[] ca){ - List lst = new ArrayList(); + public static List getPDBresnum(int aligPos, AFPChain afpChain, Atom[] ca){ + List lst = new ArrayList<>(); if ( aligPos > 1) { System.err.println("multiple alignments not supported yet!"); return lst; @@ -145,7 +136,7 @@ public static final List getPDBresnum(int aligPos, AFPChain afpChain, At * @param getPrevious gives the previous position if false, gives the next posible atom * @return a CA atom that is at a particular position of the alignment */ - public static final Atom getAtomForAligPos(AFPChain afpChain,int chainNr, int aligPos, Atom[] ca , boolean getPrevious ) throws StructureException{ + public static Atom getAtomForAligPos(AFPChain afpChain, int chainNr, int aligPos, Atom[] ca , boolean getPrevious ) throws StructureException{ int[] optLen = afpChain.getOptLen(); // int[][][] optAln = afpChain.getOptAln(); @@ -230,7 +221,7 @@ private static int getNextFatCatPos(AFPChain afpChain, int chainNr, if(len > 0) { - int lmax = (p1 - p1b - 1)>(p2 - p2b - 1)?(p1 - p1b - 1):(p2 - p2b - 1); + int lmax = Math.max((p1 - p1b - 1), (p2 - p2b - 1)); // lmax gives the length of an alignment gap @@ -312,7 +303,7 @@ private static int getNextFatCatPos(AFPChain afpChain, int chainNr, } - private static final int getUngappedFatCatPos(AFPChain afpChain, int chainNr, int aligPos){ + private static int getUngappedFatCatPos(AFPChain afpChain, int chainNr, int aligPos){ char[] aseq; if ( chainNr == 0 ) aseq = afpChain.getAlnseq1(); @@ -343,7 +334,7 @@ private static final int getUngappedFatCatPos(AFPChain afpChain, int chainNr, in if(len > 0) { - int lmax = (p1 - p1b - 1)>(p2 - p2b - 1)?(p1 - p1b - 1):(p2 - p2b - 1); + int lmax = Math.max((p1 - p1b - 1), (p2 - p2b - 1)); // lmax gives the length of an alignment gap @@ -404,10 +395,9 @@ private static final int getUngappedFatCatPos(AFPChain afpChain, int chainNr, in * @param ca * @param hetatms * @return - * @throws StructureException */ - public static final Atom[] getAtomArray(Atom[] ca,List hetatms ) throws StructureException{ - List atoms = new ArrayList(); + public static Atom[] getAtomArray(Atom[] ca, List hetatms ) { + List atoms = new ArrayList<>(); Collections.addAll(atoms, ca); logger.debug("got {} hetatoms", hetatms.size()); @@ -425,7 +415,7 @@ public static final Atom[] getAtomArray(Atom[] ca,List hetatms ) throws S atoms.add(a); } - Atom[] arr = atoms.toArray(new Atom[atoms.size()]); + Atom[] arr = atoms.toArray(Atom.EmptyAtomArray); return arr; } @@ -434,9 +424,9 @@ public static final Atom[] getAtomArray(Atom[] ca,List hetatms ) throws S /** Note: ca2, hetatoms2 and nucleotides2 should not be rotated. This will be done here... * */ - public static final StructureAlignmentJmol display(AFPChain afpChain,Group[] twistedGroups, Atom[] ca1, Atom[] ca2,List hetatms1, List hetatms2 ) throws StructureException { + public static StructureAlignmentJmol display(AFPChain afpChain, Group[] twistedGroups, Atom[] ca1, Atom[] ca2, List hetatms1, List hetatms2 ) { - List twistedAs = new ArrayList(); + List twistedAs = new ArrayList<>(); for ( Group g: twistedGroups){ if ( g == null ) @@ -446,7 +436,7 @@ public static final StructureAlignmentJmol display(AFPChain afpChain,Group[] twi Atom a = g.getAtom(0); twistedAs.add(a); } - Atom[] twistedAtoms = twistedAs.toArray(new Atom[twistedAs.size()]); + Atom[] twistedAtoms = twistedAs.toArray(Atom.EmptyAtomArray); twistedAtoms = StructureTools.cloneAtomArray(twistedAtoms); Atom[] arr1 = getAtomArray(ca1, hetatms1); @@ -476,7 +466,7 @@ public static final StructureAlignmentJmol display(AFPChain afpChain,Group[] twi return jmol; } - public static void showAlignmentPanel(AFPChain afpChain, Atom[] ca1, Atom[] ca2, AbstractAlignmentJmol jmol) throws StructureException { + public static void showAlignmentPanel(AFPChain afpChain, Atom[] ca1, Atom[] ca2, AbstractAlignmentJmol jmol) { AligPanel me = new AligPanel(); me.setAlignmentJmol(jmol); @@ -548,10 +538,9 @@ public static void showAlignmentImage(AFPChain afpChain, String result) { * @param ca1 atoms for protein 1 * @param ca2 atoms for protein 2 * @return a protein structure with 2 models. - * @throws StructureException - */ + */ public static Structure createArtificalStructure(AFPChain afpChain, Atom[] ca1, - Atom[] ca2) throws StructureException{ + Atom[] ca2) { if ( afpChain.getNrEQR() < 1){ @@ -560,7 +549,7 @@ public static Structure createArtificalStructure(AFPChain afpChain, Atom[] ca1, Group[] twistedGroups = AlignmentTools.prepareGroupsForDisplay(afpChain,ca1, ca2); - List twistedAs = new ArrayList(); + List twistedAs = new ArrayList<>(); for ( Group g: twistedGroups){ if ( g == null ) @@ -570,7 +559,7 @@ public static Structure createArtificalStructure(AFPChain afpChain, Atom[] ca1, Atom a = g.getAtom(0); twistedAs.add(a); } - Atom[] twistedAtoms = twistedAs.toArray(new Atom[twistedAs.size()]); + Atom[] twistedAtoms = twistedAs.toArray(Atom.EmptyAtomArray); List hetatms = StructureTools.getUnalignedGroups(ca1); List hetatms2 = StructureTools.getUnalignedGroups(ca2); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DotPlotPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DotPlotPanel.java index 22f4ad1822..cc1b3f15cf 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DotPlotPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DotPlotPanel.java @@ -76,7 +76,7 @@ public DotPlotPanel(AFPChain alignment ){ int[][][] optAln = alignment.getOptAln(); // [block #][{0,1} chain index][pos] for(;alignNumber < optAln.length;alignNumber++) { - List alignPairs = new ArrayList(); + List alignPairs = new ArrayList<>(); for(int pos = 0; pos createAndShowGUI(progressListener)); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/HelpDialog.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/HelpDialog.java index 0a83191339..81113bc20c 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/HelpDialog.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/HelpDialog.java @@ -29,10 +29,7 @@ import javax.swing.*; import javax.swing.event.HyperlinkEvent; -import javax.swing.event.HyperlinkListener; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; public class HelpDialog { Box vBox; @@ -55,40 +52,33 @@ public void showDialog(){ vBox= Box.createVerticalBox(); vBox.add(scroll); - txt.addHyperlinkListener(new HyperlinkListener(){ + txt.addHyperlinkListener(e -> { - @Override - public void hyperlinkUpdate(HyperlinkEvent e) { - - if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { - String href = e.getDescription(); - BrowserOpener.showDocument(href); - } - if ( e.getEventType() == HyperlinkEvent.EventType.ENTERED) { - // change the mouse curor - vBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - } - if (e.getEventType() == HyperlinkEvent.EventType.EXITED) { - vBox.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } - } - }); + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + String href = e.getDescription(); + BrowserOpener.showDocument(href); + } + if ( e.getEventType() == HyperlinkEvent.EventType.ENTERED) { + // change the mouse curor + vBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + } + if (e.getEventType() == HyperlinkEvent.EventType.EXITED) { + vBox.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); + } + }); JButton close = new JButton("Close"); - close.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { - Object source = event.getSource(); + close.addActionListener(event -> { + Object source = event.getSource(); - JButton but = (JButton)source; - Container parent = but.getParent().getParent().getParent().getParent().getParent().getParent() ; + JButton but = (JButton)source; + Container parent = but.getParent().getParent().getParent().getParent().getParent().getParent() ; - JDialog dia = (JDialog) parent; - dia.dispose(); - } - }); + JDialog dia = (JDialog) parent; + dia.dispose(); + }); Box hBoxb = Box.createHorizontalBox(); hBoxb.add(Box.createGlue()); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/JPrintPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/JPrintPanel.java index 47ee654f2a..8f9e8322c4 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/JPrintPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/JPrintPanel.java @@ -30,7 +30,6 @@ import java.awt.event.ActionListener; import java.awt.print.PageFormat; import java.awt.print.Printable; -import java.awt.print.PrinterException; import java.awt.print.PrinterJob; public class JPrintPanel extends JPanel implements Printable,ActionListener{ @@ -40,7 +39,7 @@ public class JPrintPanel extends JPanel implements Printable,ActionListener{ private static final long serialVersionUID = -3337337068138131455L; @Override - public int print(Graphics g, PageFormat pf, int pi) throws PrinterException { + public int print(Graphics g, PageFormat pf, int pi) { if (pi >= 1) { return Printable.NO_SUCH_PAGE; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MemoryMonitor.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MemoryMonitor.java index 91ca7571b4..6b6f160441 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MemoryMonitor.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MemoryMonitor.java @@ -55,13 +55,13 @@ */ public class MemoryMonitor extends JPanel { - static JCheckBox dateStampCB = new JCheckBox("Output Date Stamp"); - public Surface surf; - JPanel controls; + static final JCheckBox dateStampCB = new JCheckBox("Output Date Stamp"); + public final Surface surf; + final JPanel controls; boolean doControls; - JTextField tf; + final JTextField tf; - public static final long serialVersionUID = 56289234782130l; + public static final long serialVersionUID = 56289234782130L; public MemoryMonitor() { setLayout(new BorderLayout()); @@ -103,28 +103,28 @@ public void mouseClicked(MouseEvent e) { } - public class Surface extends JPanel implements Runnable { + public static class Surface extends JPanel implements Runnable { - public static final long serialVersionUID = 2387409854370432908l; + public static final long serialVersionUID = 2387409854370432908L; public Thread thread; public long sleepAmount = 1000; private int w, h; private BufferedImage bimg; private Graphics2D big; - private Font font = new Font("Times New Roman", Font.PLAIN, 11); - private Runtime r = Runtime.getRuntime(); + private final Font font = new Font("Times New Roman", Font.PLAIN, 11); + private final Runtime r = Runtime.getRuntime(); private int columnInc; private int[] pts; private int ptNum; private int ascent, descent; //private float freeMemory, totalMemory; - private Rectangle graphOutlineRect = new Rectangle(); - private Rectangle2D mfRect = new Rectangle2D.Float(); - private Rectangle2D muRect = new Rectangle2D.Float(); - private Line2D graphLine = new Line2D.Float(); - private Color graphColor = new Color(46, 139, 87); - private Color mfColor = new Color(0, 100, 0); + private final Rectangle graphOutlineRect = new Rectangle(); + private final Rectangle2D mfRect = new Rectangle2D.Float(); + private final Rectangle2D muRect = new Rectangle2D.Float(); + private final Line2D graphLine = new Line2D.Float(); + private final Color graphColor = new Color(46, 139, 87); + private final Color mfColor = new Color(0, 100, 0); private String usedStr; @@ -169,8 +169,8 @@ public void paint(Graphics g) { // .. Draw allocated and used strings .. big.setColor(Color.green); - big.drawString(String.valueOf((int) totalMemory/1024) + "K allocated", 4.0f, ascent+0.5f); - usedStr = String.valueOf(((int) (totalMemory - freeMemory))/1024) + big.drawString((int) totalMemory / 1024 + "K allocated", 4.0f, ascent+0.5f); + usedStr = ((int) (totalMemory - freeMemory)) / 1024 + "K used"; big.drawString(usedStr, 4, h-descent); @@ -234,7 +234,7 @@ public void paint(Graphics g) { pts = new int[graphW]; ptNum = 0; } else if (pts.length != graphW) { - int[] tmp = null; + int[] tmp; if (ptNum < graphW) { tmp = new int[ptNum]; System.arraycopy(pts, 0, tmp, 0, tmp.length); @@ -259,9 +259,7 @@ public void paint(Graphics g) { } if (ptNum+2 == pts.length) { // throw out oldest point - for (int j = 1;j < ptNum; j++) { - pts[j-1] = pts[j]; - } + if (ptNum - 1 >= 0) System.arraycopy(pts, 1, pts, 0, ptNum - 1); --ptNum; } else { ptNum++; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MenuCreator.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MenuCreator.java index 9484217af9..133bb59b43 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MenuCreator.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MenuCreator.java @@ -29,7 +29,6 @@ import org.biojava.nbio.structure.align.webstart.WebStartMain; import javax.swing.*; - import java.awt.*; import java.awt.event.*; import java.io.File; @@ -209,38 +208,34 @@ public static JMenuBar initJmolMenu(JFrame frame, public static JMenuItem getDBResultMenuItem() { ImageIcon saveicon = createImageIcon("/icons/kpdf.png"); - JMenuItem saveI = null; + JMenuItem saveI; if ( saveicon == null) saveI = new JMenuItem(LOAD_DB_RESULTS); else saveI = new JMenuItem(LOAD_DB_RESULTS, saveicon); - saveI.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - final JFileChooser fc = new JFileChooser(); + saveI.addActionListener(e -> { + final JFileChooser fc = new JFileChooser(); - // In response to a button click: - int returnVal = fc.showOpenDialog(null); - if ( returnVal == JFileChooser.APPROVE_OPTION) { - File file = fc.getSelectedFile(); - - UserConfiguration config = WebStartMain.getWebStartConfig(); - DBResultTable table = new DBResultTable(); - table.show(file,config); - } + // In response to a button click: + int returnVal = fc.showOpenDialog(null); + if ( returnVal == JFileChooser.APPROVE_OPTION) { + File file = fc.getSelectedFile(); + UserConfiguration config = WebStartMain.getWebStartConfig(); + DBResultTable table = new DBResultTable(); + table.show(file,config); } - } ); + + }); return saveI; } public static JMenuItem getShowPDBMenuItem() { ImageIcon loadI = createImageIcon("/icons/background.png"); - JMenuItem openI = null; + JMenuItem openI; if ( loadI == null) openI =new JMenuItem("Show By ID"); @@ -255,7 +250,7 @@ public static JMenuItem getShowPDBMenuItem() { public static JMenuItem getOpenPDBMenuItem() { ImageIcon loadI = createImageIcon("/icons/background.png"); - JMenuItem openI = null; + JMenuItem openI; if ( loadI == null) openI =new JMenuItem("Open PDB file"); @@ -269,7 +264,7 @@ public static JMenuItem getOpenPDBMenuItem() { public static JMenuItem getLoadMenuItem() { - JMenuItem loadF = null; + JMenuItem loadF; ImageIcon loadI = createImageIcon("/icons/revert.png"); if ( loadI == null) loadF = new JMenuItem(LOAD_ALIGNMENT_XML); @@ -305,7 +300,7 @@ public static JMenuBar getAlignmentPanelMenu(JFrame frame, ImageIcon saveicon = createImageIcon("/icons/filesave.png"); - JMenuItem saveF = null; + JMenuItem saveF; if (saveicon != null) saveF = new JMenuItem("Save text display", saveicon); @@ -400,7 +395,7 @@ public static JMenuBar getAlignmentTextMenu(JFrame frame, ImageIcon saveicon = createImageIcon("/icons/filesave.png"); - JMenuItem saveF = null; + JMenuItem saveF; if (saveicon != null ) saveF = new JMenuItem("Save text display", saveicon); @@ -487,7 +482,7 @@ public static JMenuItem getPrintMenuItem() { public static JMenuItem getExportPDBMenuItem(AbstractAlignmentJmol parent) { ImageIcon saveicon = createImageIcon("/icons/compfile.png"); - JMenuItem exportI = null; + JMenuItem exportI; if ( saveicon == null) exportI = new JMenuItem("Export PDB file"); @@ -504,7 +499,7 @@ public static JMenuItem getSaveAlignmentMenuItem(AFPChain afpChain, MultipleAlignment msa){ ImageIcon saveicon = createImageIcon("/icons/filesave.png"); - JMenuItem saveF = null; + JMenuItem saveF; if (saveicon == null) saveF = new JMenuItem(SAVE_ALIGNMENT_XML); @@ -522,7 +517,7 @@ public static JMenuItem getAboutMenuItem() { ImageIcon helpIcon = createImageIcon("/icons/help.png"); - JMenuItem aboutM = null; + JMenuItem aboutM; if ( helpIcon == null) aboutM = new JMenuItem("About this Software"); @@ -530,14 +525,7 @@ public static JMenuItem getAboutMenuItem() { aboutM = new JMenuItem("About this Software", helpIcon); aboutM.setMnemonic(KeyEvent.VK_A); - aboutM.addActionListener(new ActionListener(){ - - @Override - public void actionPerformed(ActionEvent e) { - MenuCreator.showAboutDialog(); - - } - }); + aboutM.addActionListener(e -> MenuCreator.showAboutDialog()); return aboutM; } @@ -547,7 +535,7 @@ private static JMenuItem getSystemInfoItem() ImageIcon helpIcon = createImageIcon("/icons/help.png"); - JMenuItem aboutM = null; + JMenuItem aboutM; if ( helpIcon == null) aboutM = new JMenuItem("System Info"); @@ -555,14 +543,7 @@ private static JMenuItem getSystemInfoItem() aboutM = new JMenuItem("System Info", helpIcon); aboutM.setMnemonic(KeyEvent.VK_S); - aboutM.addActionListener(new ActionListener(){ - - @Override - public void actionPerformed(ActionEvent e) { - MenuCreator.showSystemInfo(); - - } - }); + aboutM.addActionListener(e -> MenuCreator.showSystemInfo()); return aboutM; } @@ -579,15 +560,11 @@ public static JMenuItem getExitMenuItem(){ exitI = new JMenuItem("Quit",exitIcon); exitI.setMnemonic(KeyEvent.VK_Q); exitI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, keyMask)); - exitI.addActionListener(new ActionListener(){ + exitI.addActionListener(e -> { + String cmd = e.getActionCommand(); - @Override - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); - - if ( cmd.equals("Quit")){ - System.exit(0); - } + if ( cmd.equals("Quit")){ + System.exit(0); } }); return exitI; @@ -607,14 +584,10 @@ public static JMenuItem getHelpMenuItem(){ helpM = new JMenuItem("Help", helpIcon); helpM.setMnemonic(KeyEvent.VK_H); - helpM.addActionListener(new ActionListener(){ - - @Override - public void actionPerformed(ActionEvent e) { - HelpDialog d = new HelpDialog(); - d.showDialog(); + helpM.addActionListener(e -> { + HelpDialog d = new HelpDialog(); + d.showDialog(); - } }); return helpM; @@ -635,7 +608,7 @@ public static JMenuItem getCloseMenuItem(JFrame frame){ closeI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, keyMask)); class MyCloseListener implements ActionListener{ - JFrame f; + final JFrame f; MyCloseListener(JFrame frame){ f=frame; } @@ -713,14 +686,11 @@ protected static JMenuItem getPairwiseAlignmentMenuItem() { pairI = new JMenuItem(PAIRWISE_ALIGN, alignIcon); pairI.setMnemonic(KeyEvent.VK_N); pairI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, keyMask)); - pairI.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); + pairI.addActionListener(e -> { + String cmd = e.getActionCommand(); - if ( cmd.equals(PAIRWISE_ALIGN)){ - MenuCreator.showPairDialog(); - } + if ( cmd.equals(PAIRWISE_ALIGN)){ + MenuCreator.showPairDialog(); } }); return pairI; @@ -736,14 +706,11 @@ protected static JMenuItem getMultipleAlignmentMenuItem() { multipleI = new JMenuItem(MULTIPLE_ALIGN, alignIcon); multipleI.setMnemonic(KeyEvent.VK_N); multipleI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, keyMask)); - multipleI.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); + multipleI.addActionListener(e -> { + String cmd = e.getActionCommand(); - if ( cmd.equals(MULTIPLE_ALIGN)){ - MenuCreator.showMultipleDialog(); - } + if ( cmd.equals(MULTIPLE_ALIGN)){ + MenuCreator.showMultipleDialog(); } }); return multipleI; @@ -844,7 +811,7 @@ public static JMenuBar initAlignmentGUIMenu(JFrame frame) { private static JMenuItem getMemoryMonitorItem() { ImageIcon helpIcon = createImageIcon("/icons/help.png"); - JMenuItem aboutM = null; + JMenuItem aboutM; if ( helpIcon == null) aboutM = new JMenuItem("Memory Monitor"); @@ -852,14 +819,7 @@ private static JMenuItem getMemoryMonitorItem() { aboutM = new JMenuItem("Memory Monitor", helpIcon); aboutM.setMnemonic(KeyEvent.VK_M); - aboutM.addActionListener(new ActionListener(){ - - @Override - public void actionPerformed(ActionEvent e) { - MenuCreator.showMemoryMonitor(); - - } - }); + aboutM.addActionListener(e -> MenuCreator.showMemoryMonitor()); return aboutM; } @@ -888,14 +848,7 @@ public void windowClosing(WindowEvent e) {} Box b = Box.createHorizontalBox(); JButton b1 = new JButton("Run Garbage Collector"); - b1.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - System.gc(); - - } - }); + b1.addActionListener(e -> System.gc()); b.add(b1); b.add(Box.createGlue()); @@ -920,15 +873,11 @@ private static JMenuItem getConfigMenuItem() { else configI = new JMenuItem("Settings",configIcon); configI.setMnemonic(KeyEvent.VK_S); - configI.addActionListener(new ActionListener(){ - - @Override - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); + configI.addActionListener(e -> { + String cmd = e.getActionCommand(); - if ( cmd.equals("Settings")){ - ConfigPDBInstallPanel.showDialog(); - } + if ( cmd.equals("Settings")){ + ConfigPDBInstallPanel.showDialog(); } }); return configI; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentCalc.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentCalc.java index e764a5e654..37ffe36517 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentCalc.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentCalc.java @@ -22,19 +22,15 @@ */ package org.biojava.nbio.structure.align.gui; -import java.util.ArrayList; -import java.util.List; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIdentifier; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.MultipleStructureAligner; import org.biojava.nbio.structure.align.multiple.MultipleAlignment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; + /** * A class that obtains structures via DAS and aligns them. * This is done in a separate thread. @@ -78,7 +74,7 @@ public void run() { parent.getMultipleStructureAligner(); try { - List atomArrays = new ArrayList(); + List atomArrays = new ArrayList<>(); for (Structure s:structures){ Atom[] ca = StructureTools.getRepresentativeAtomArray(s); atomArrays.add(ca); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentGUI.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentGUI.java index 95a4ac248e..2cf8e7503f 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentGUI.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentGUI.java @@ -22,22 +22,6 @@ */ package org.biojava.nbio.structure.align.gui; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.util.List; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenuBar; -import javax.swing.JOptionPane; -import javax.swing.JProgressBar; -import javax.swing.JTabbedPane; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIdentifier; @@ -50,6 +34,11 @@ import org.biojava.nbio.structure.align.webstart.AligUIManager; import org.biojava.nbio.structure.gui.util.SelectMultiplePanel; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.util.List; + /** * A JFrame that allows to trigger a multiple structure alignment, * either from files in a directory or after manual upload. @@ -64,14 +53,14 @@ */ public class MultipleAlignmentGUI extends JFrame { - private final static long serialVersionUID =0l; + private final static long serialVersionUID = 0L; private final static String version = "1.0"; private MultipleStructureAligner multiple; private StructureAlignment pairwise; - private SelectMultiplePanel tab; - private JTabbedPane tabPane; + private final SelectMultiplePanel tab; + private final JTabbedPane tabPane; private Thread thread; private AlignmentCalculationRunnable alicalc; @@ -154,7 +143,7 @@ private Box setupPairwiseAlgorithm() { algorithmList.setSelectedIndex(0); Action actionAlgorithm = new AbstractAction("Algorithm") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; @Override public void actionPerformed(ActionEvent evt) { JComboBox cb = (JComboBox)evt.getSource(); @@ -165,7 +154,7 @@ public void actionPerformed(ActionEvent evt) { algorithmList.addActionListener(actionAlgorithm); Action paramAction = new AbstractAction("Parameters") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; @Override public void actionPerformed(ActionEvent evt) { StructureAlignment p = getPairwiseStructureAligner(); @@ -197,7 +186,7 @@ private Box setupMultipleAlgorithm() { multList.setSelectedIndex(0); Action actionMultiple = new AbstractAction("Algorithm") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; @Override public void actionPerformed(ActionEvent evt) { updateMultipleAlgorithm(); @@ -206,7 +195,7 @@ public void actionPerformed(ActionEvent evt) { multList.addActionListener(actionMultiple); Action paramAction = new AbstractAction("Parameters") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; @Override public void actionPerformed(ActionEvent evt) { MultipleStructureAligner m = getMultipleStructureAligner(); @@ -236,7 +225,7 @@ private Box initButtons(){ progress.setVisible(false); Action action1 = new AbstractAction("Align") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -246,7 +235,7 @@ public void actionPerformed(ActionEvent evt) { JButton submitB = new JButton(action1); Action action3 = new AbstractAction("Abort") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -257,7 +246,7 @@ public void actionPerformed(ActionEvent evt) { abortB.setEnabled(false); Action action2 = new AbstractAction("Exit") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -284,7 +273,7 @@ public void cleanUp() { private void calcAlignment() { - try { +// try { List structures = tab.getStructures(); if ( structures.size() < 2) { @@ -309,10 +298,10 @@ private void calcAlignment() { ProgressThreadDrawer drawer = new ProgressThreadDrawer(progress); drawer.start(); - } catch (StructureException e){ - JOptionPane.showMessageDialog(null,"Could not align structures. " - + "Exception: " + e.getMessage()); - } +// } catch (StructureException e){ +// JOptionPane.showMessageDialog(null,"Could not align structures. " +// + "Exception: " + e.getMessage()); +// } } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentJmolDisplay.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentJmolDisplay.java index fac312875f..d746a83aea 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentJmolDisplay.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentJmolDisplay.java @@ -20,15 +20,6 @@ */ package org.biojava.nbio.structure.align.gui; -import java.awt.Dimension; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.Box; -import javax.swing.JFrame; -import javax.swing.JMenuBar; -import javax.swing.JScrollPane; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.gui.aligpanel.MultipleAligPanel; @@ -39,6 +30,11 @@ import org.biojava.nbio.structure.align.multiple.Block; import org.biojava.nbio.structure.align.multiple.MultipleAlignment; import org.biojava.nbio.structure.align.multiple.util.MultipleAlignmentDisplay; + +import javax.swing.*; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; @@ -76,7 +72,7 @@ public class MultipleAlignmentJmolDisplay { public static List getPDBresnum(int structNum, MultipleAlignment multAln, Atom[] ca){ - List lst = new ArrayList(); + List lst = new ArrayList<>(); for(Block block : multAln.getBlocks() ) { @@ -99,11 +95,9 @@ else if (pos < ca.length) { * * @param multAln * @param jmol - - * @throws StructureException */ public static void showMultipleAligmentPanel(MultipleAlignment multAln, - AbstractAlignmentJmol jmol) throws StructureException { + AbstractAlignmentJmol jmol) { MultipleAligPanel me = new MultipleAligPanel(multAln, jmol); JFrame frame = new JFrame(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyAlignmentLoadListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyAlignmentLoadListener.java index 2a85930c27..bd11a5af1b 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyAlignmentLoadListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyAlignmentLoadListener.java @@ -20,6 +20,7 @@ */ package org.biojava.nbio.structure.align.gui; +import org.biojava.nbio.core.util.InputStreamProvider; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; import org.biojava.nbio.structure.align.model.AFPChain; @@ -30,10 +31,8 @@ import org.biojava.nbio.structure.align.webstart.WebStartMain; import org.biojava.nbio.structure.align.xml.AFPChainXMLParser; import org.biojava.nbio.structure.align.xml.MultipleAlignmentXMLParser; -import org.biojava.nbio.core.util.InputStreamProvider; import javax.swing.*; - import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; @@ -76,7 +75,7 @@ public void actionPerformed(ActionEvent evt) { BufferedReader in = new BufferedReader( new InputStreamReader(stream)); - StringBuffer input = new StringBuffer(); + StringBuilder input = new StringBuilder(); String str; while ((str = in.readLine()) != null) { input.append(str); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyDistMaxListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyDistMaxListener.java index 9faf74cfe7..87152b52c7 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyDistMaxListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyDistMaxListener.java @@ -24,7 +24,6 @@ import org.biojava.nbio.structure.jama.Matrix; import javax.swing.*; - import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; @@ -35,7 +34,7 @@ */ public class MyDistMaxListener implements ActionListener{ - AbstractAlignmentJmol parent; + final AbstractAlignmentJmol parent; public MyDistMaxListener(AbstractAlignmentJmol parent){ this.parent = parent; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyExportListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyExportListener.java index 77a550c57c..88d24421d7 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyExportListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyExportListener.java @@ -21,8 +21,8 @@ import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.align.gui.jmol.AbstractAlignmentJmol; -import javax.swing.*; +import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; @@ -32,7 +32,7 @@ public class MyExportListener implements ActionListener{ - AbstractAlignmentJmol parent; + final AbstractAlignmentJmol parent; MyExportListener(AbstractAlignmentJmol parent){ this.parent = parent; } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MySaveFileListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MySaveFileListener.java index f93fba29df..1704f82061 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MySaveFileListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MySaveFileListener.java @@ -30,7 +30,6 @@ import org.biojava.nbio.structure.align.xml.AFPChainXMLConverter; import javax.swing.*; - import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedWriter; @@ -52,8 +51,8 @@ */ public class MySaveFileListener implements ActionListener { - private AFPChain afpChain; - private MultipleAlignment msa; + private final AFPChain afpChain; + private final MultipleAlignment msa; private boolean printText; public MySaveFileListener (AFPChain afpChain){ diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyTableRowSorter.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyTableRowSorter.java index a8f141e76a..5d0745108e 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyTableRowSorter.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyTableRowSorter.java @@ -50,7 +50,7 @@ public Comparator getComparator(int column) class MyComparator implements Comparator, Serializable { private static final long serialVersionUID = 1; - int column; + final int column; public MyComparator(int column){ this.column = column; } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ParameterGUI.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ParameterGUI.java index 836e386ab4..afa9f5500d 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ParameterGUI.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ParameterGUI.java @@ -24,8 +24,6 @@ import javax.swing.*; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; @@ -82,7 +80,7 @@ public ParameterGUI(ConfigStrucAligParams params, String algorithm) { assert(names.size() == types.size()); assert(names.size() == helps.size()); - textFields = new ArrayList(); + textFields = new ArrayList<>(); Box vBox = Box.createVerticalBox(); for (int i = 0 ; i < keys.size(); i++){ @@ -146,32 +144,21 @@ public ParameterGUI(ConfigStrucAligParams params, String algorithm) { JButton abort = new JButton("Cancel"); - abort.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { - destroy(); - dispose(); } - }); + abort.addActionListener(event -> { + destroy(); + dispose(); }); JButton defaultB = new JButton("Default"); - defaultB.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { - setDefault(); - } - }); + defaultB.addActionListener(event -> setDefault()); JButton close = new JButton("Apply"); - close.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { + close.addActionListener(event -> { - storeParameters(); + storeParameters(); - destroy(); - dispose(); } - }); + destroy(); + dispose(); }); Box hBox = Box.createHorizontalBox(); hBox.add(abort); @@ -247,7 +234,7 @@ protected void storeParameters() { Class type = types.get(i); String key = keys.get(i); // String name = keys.get(i); - String value = null; + String value; System.out.println(key); if( type.isEnum() ) { JComboBox field = (JComboBox) textFields.get(i); @@ -256,10 +243,10 @@ protected void storeParameters() { } else if ( type == Boolean.class){ JComboBox field = (JComboBox) textFields.get(i); int sel = field.getSelectedIndex(); - Boolean flag = true; + boolean flag = true; if ( sel == 1 ) flag = false; - value = flag.toString(); + value = Boolean.toString(flag); } else { JTextField field = (JTextField)textFields.get(i); value = field.getText(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/SelectPDBPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/SelectPDBPanel.java index d8eb946e4d..2099eac80f 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/SelectPDBPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/SelectPDBPanel.java @@ -20,26 +20,16 @@ */ package org.biojava.nbio.structure.align.gui; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.io.IOException; - -import javax.swing.Box; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTabbedPane; -import javax.swing.JTextField; - -import org.biojava.nbio.structure.ResidueRange; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIdentifier; -import org.biojava.nbio.structure.SubstructureIdentifier; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.align.util.UserConfiguration; import org.biojava.nbio.structure.align.webstart.WebStartMain; import org.biojava.nbio.structure.gui.util.StructurePairSelector; +import javax.swing.*; +import java.awt.*; +import java.io.IOException; + /** A Panel that allows user to specify PDB & chain ID, as well as sub-ranges * @@ -52,12 +42,12 @@ public class SelectPDBPanel boolean debug = true; - JTextField f1; - JTextField f2; - JTextField c1; - JTextField c2; - JTextField r1; - JTextField r2; + final JTextField f1; + final JTextField f2; + final JTextField c1; + final JTextField c2; + final JTextField r1; + final JTextField r2; UserConfiguration config; JTabbedPane configPane; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/StructureAlignmentDisplay.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/StructureAlignmentDisplay.java index 266abef138..90ec47afca 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/StructureAlignmentDisplay.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/StructureAlignmentDisplay.java @@ -20,8 +20,6 @@ */ package org.biojava.nbio.structure.align.gui; -import java.util.List; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Group; import org.biojava.nbio.structure.StructureException; @@ -30,6 +28,8 @@ import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AlignmentTools; +import java.util.List; + public class StructureAlignmentDisplay { /** Display an AFPChain alignment diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/StructureLoaderThread.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/StructureLoaderThread.java index fa4bba99f2..bb350bbc81 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/StructureLoaderThread.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/StructureLoaderThread.java @@ -34,10 +34,10 @@ public class StructureLoaderThread extends SwingWorker { - String name; - boolean showBiolAssembly; + final String name; + final boolean showBiolAssembly; - UserConfiguration config; + final UserConfiguration config; StructureLoaderThread(UserConfiguration config, String name, boolean showBiolAssembly){ this.name = name; @@ -52,7 +52,7 @@ protected String doInBackground() { System.out.println("loading " + name ); AtomCache cache = new AtomCache(config.getPdbFilePath(),config.getCacheFilePath()); - Structure s = null; + Structure s; try { if ( showBiolAssembly) { s= StructureIO.getBiologicalAssembly(name); @@ -97,29 +97,25 @@ public static void showProgressBar() { if ( progressFrame == null){ - SwingUtilities.invokeLater(new Runnable() { + SwingUtilities.invokeLater(() -> { + // TODO Auto-generated method stub - @Override - public void run() { - // TODO Auto-generated method stub + final JFrame frame = new JFrame("Loading ..."); + final JProgressBar progressBar = new JProgressBar(); - final JFrame frame = new JFrame("Loading ..."); - final JProgressBar progressBar = new JProgressBar(); + progressBar.setIndeterminate(true); - progressBar.setIndeterminate(true); - - final JPanel contentPane = new JPanel(); - contentPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); - contentPane.setLayout(new BorderLayout()); - contentPane.add(new JLabel("Loading ..."), BorderLayout.NORTH); - contentPane.add(progressBar, BorderLayout.CENTER); - frame.setContentPane(contentPane); - frame.pack(); - frame.setLocationRelativeTo(null); - progressFrame = frame; - frame.setVisible(true); - } + final JPanel contentPane = new JPanel(); + contentPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); + contentPane.setLayout(new BorderLayout()); + contentPane.add(new JLabel("Loading ..."), BorderLayout.NORTH); + contentPane.add(progressBar, BorderLayout.CENTER); + frame.setContentPane(contentPane); + frame.pack(); + frame.setLocationRelativeTo(null); + progressFrame = frame; + frame.setVisible(true); }); } @@ -130,14 +126,10 @@ public void run() { static JFrame progressFrame = null; private void hideProgressBar() { - SwingUtilities.invokeLater(new Runnable() { - - @Override - public void run() { - if ( progressFrame != null){ - progressFrame.dispose(); - progressFrame = null; - } + SwingUtilities.invokeLater(() -> { + if ( progressFrame != null){ + progressFrame.dispose(); + progressFrame = null; } }); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/SystemInfo.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/SystemInfo.java index a899f485c8..dacf98c759 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/SystemInfo.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/SystemInfo.java @@ -29,10 +29,7 @@ import javax.swing.*; import javax.swing.border.EtchedBorder; import javax.swing.event.HyperlinkEvent; -import javax.swing.event.HyperlinkListener; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.Enumeration; import java.util.Properties; import java.util.StringTokenizer; @@ -72,7 +69,7 @@ public class SystemInfo + "user.dir " + "user.home " + "user.name "; - EtchedBorder border; + final EtchedBorder border; public SystemInfo() { @@ -212,11 +209,11 @@ public void addOneSystemProperty( } } else if (isURLProperty(name)) { - StringBuffer fixed = new StringBuffer(); + StringBuilder fixed = new StringBuilder(); int start = 0; - int hit = 0; + int hit; while ((hit = propValue.indexOf('%', start)) >= 0) { - fixed.append(propValue.substring(start, hit)); + fixed.append(propValue, start, hit); int value = Integer.parseInt(propValue.substring(hit + 1, hit + 3), 16); fixed.append(((char) value)); @@ -280,22 +277,18 @@ public void showDialog(){ vBox= Box.createVerticalBox(); vBox.add(scroll); - txt.addHyperlinkListener(new HyperlinkListener(){ + txt.addHyperlinkListener(e -> { - @Override - public void hyperlinkUpdate(HyperlinkEvent e) { - - if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { - String href = e.getDescription(); - BrowserOpener.showDocument(href); - } - if ( e.getEventType() == HyperlinkEvent.EventType.ENTERED) { - // change the mouse curor - vBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - } - if (e.getEventType() == HyperlinkEvent.EventType.EXITED) { - vBox.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + String href = e.getDescription(); + BrowserOpener.showDocument(href); + } + if ( e.getEventType() == HyperlinkEvent.EventType.ENTERED) { + // change the mouse curor + vBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + } + if (e.getEventType() == HyperlinkEvent.EventType.EXITED) { + vBox.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } }); @@ -304,17 +297,14 @@ public void hyperlinkUpdate(HyperlinkEvent e) { JButton close = new JButton("Close"); - close.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { - Object source = event.getSource(); + close.addActionListener(event -> { + Object source = event.getSource(); - JButton but = (JButton)source; - Container parent = but.getParent().getParent().getParent().getParent().getParent().getParent() ; + JButton but = (JButton)source; + Container parent = but.getParent().getParent().getParent().getParent().getParent().getParent() ; - JDialog dia = (JDialog) parent; - dia.dispose(); - } + JDialog dia = (JDialog) parent; + dia.dispose(); }); Box hBoxb = Box.createHorizontalBox(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/AligPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/AligPanel.java index 6eadd48dcd..312186cfc2 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/AligPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/AligPanel.java @@ -63,11 +63,11 @@ public class AligPanel extends JPrintPanel implements AlignmentPositionListener private static final long serialVersionUID = -6892229111166263764L; private AFPChain afpChain; - private AFPChainCoordManager coordManager ; - private Font seqFont; - private Font eqFont; + private final AFPChainCoordManager coordManager ; + private final Font seqFont; + private final Font eqFont; private AbstractAlignmentJmol jmol; - private AligPanelMouseMotionListener mouseMoLi; + private final AligPanelMouseMotionListener mouseMoLi; private BitSet selection; @@ -89,7 +89,7 @@ public static void main(String[] args){ try { BufferedReader in = new BufferedReader(new FileReader(file)); - StringBuffer xml = new StringBuffer(); + StringBuilder xml = new StringBuilder(); String str; while ((str = in.readLine()) != null) { xml.append(str); @@ -279,7 +279,7 @@ public void paintComponent(Graphics g){ int colorPos = 0; if (isFATCAT) { - int block = 0; + int block; char s = symb[i]; try { block = Integer.parseInt(String.valueOf(s)) - 1; @@ -430,7 +430,7 @@ private void updateJmolDisplay() { int size = afpChain.getAlnLength(); - StringBuffer cmd = new StringBuffer("select "); + StringBuilder cmd = new StringBuilder("select "); int nrSelected = 0; try { @@ -450,7 +450,7 @@ private void updateJmolDisplay() { select2 = JmolTools.getPdbInfo(a2); // nothing to display - if ( select1.equals("") && select2.equals("")) + if (select1.isEmpty() && select2.isEmpty()) continue; if ( nrSelected > 0) @@ -581,30 +581,42 @@ public void windowOpened(WindowEvent e) { public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); // print is handled by superclass - if ( cmd.equals(MenuCreator.PRINT)) { - super.actionPerformed(e); - } else if (cmd.equals(MenuCreator.TEXT_ONLY)){ - String result = AfpChainWriter.toWebSiteDisplay(afpChain, ca1, ca2); - DisplayAFP.showAlignmentImage(afpChain, result); - } else if ( cmd.equals(MenuCreator.PAIRS_ONLY)) { - String result = AfpChainWriter.toAlignedPairs(afpChain, ca1, ca2) ; - DisplayAFP.showAlignmentImage(afpChain, result); - } else if (cmd.equals(MenuCreator.FATCAT_TEXT)){ - String result = afpChain.toFatcat(ca1, ca2); - result += AFPChain.newline; - result += afpChain.toRotMat(); - DisplayAFP.showAlignmentImage(afpChain, result); - } else if ( cmd.equals(MenuCreator.SELECT_EQR)){ - selectEQR(); - } else if ( cmd.equals(MenuCreator.SIMILARITY_COLOR)){ - colorBySimilarity(true); - } else if ( cmd.equals(MenuCreator.EQR_COLOR)){ - colorBySimilarity(false); - } else if ( cmd.equals(MenuCreator.FATCAT_BLOCK)){ - colorByAlignmentBlock(); - } - else { - System.err.println("Unknown command:" + cmd); + switch (cmd) { + case MenuCreator.PRINT: + super.actionPerformed(e); + break; + case MenuCreator.TEXT_ONLY: { + String result = AfpChainWriter.toWebSiteDisplay(afpChain, ca1, ca2); + DisplayAFP.showAlignmentImage(afpChain, result); + break; + } + case MenuCreator.PAIRS_ONLY: { + String result = AfpChainWriter.toAlignedPairs(afpChain, ca1, ca2); + DisplayAFP.showAlignmentImage(afpChain, result); + break; + } + case MenuCreator.FATCAT_TEXT: { + String result = afpChain.toFatcat(ca1, ca2); + result += AFPChain.newline; + result += afpChain.toRotMat(); + DisplayAFP.showAlignmentImage(afpChain, result); + break; + } + case MenuCreator.SELECT_EQR: + selectEQR(); + break; + case MenuCreator.SIMILARITY_COLOR: + colorBySimilarity(true); + break; + case MenuCreator.EQR_COLOR: + colorBySimilarity(false); + break; + case MenuCreator.FATCAT_BLOCK: + colorByAlignmentBlock(); + break; + default: + System.err.println("Unknown command:" + cmd); + break; } } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/AligPanelMouseMotionListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/AligPanelMouseMotionListener.java index 9914f07d2a..8cbe50f689 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/AligPanelMouseMotionListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/AligPanelMouseMotionListener.java @@ -34,7 +34,7 @@ public class AligPanelMouseMotionListener implements MouseMotionListener, MouseL AligPanel parent; - List aligPosListeners; + final List aligPosListeners; int prevPos; boolean isDragging ; @@ -44,7 +44,7 @@ public class AligPanelMouseMotionListener implements MouseMotionListener, MouseL public AligPanelMouseMotionListener(AligPanel parent){ this.parent = parent; - aligPosListeners = new ArrayList(); + aligPosListeners = new ArrayList<>(); prevPos = -1; isDragging = false; selectionStart = null; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleAligPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleAligPanel.java index 1387bbd417..84ccbe53dd 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleAligPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleAligPanel.java @@ -20,22 +20,7 @@ */ package org.biojava.nbio.structure.align.gui.aligpanel; -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.event.ActionEvent; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.util.ArrayList; -import java.util.BitSet; -import java.util.List; - import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.gui.JPrintPanel; import org.biojava.nbio.structure.align.gui.MenuCreator; import org.biojava.nbio.structure.align.gui.MultipleAlignmentJmolDisplay; @@ -50,6 +35,14 @@ import org.biojava.nbio.structure.gui.events.AlignmentPositionListener; import org.biojava.nbio.structure.gui.util.AlignedPosition; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.util.ArrayList; +import java.util.BitSet; +import java.util.List; + /** * A JPanel that can display the sequence alignment of a * {@link MultipleAlignment} in a nice way and interact with Jmol by @@ -77,11 +70,11 @@ public class MultipleAligPanel extends JPrintPanel int size; //number of structures int length; //number of aligned positions in sequence alignment - private Font seqFont; - private Font eqFont; + private final Font seqFont; + private final Font eqFont; private AbstractAlignmentJmol jmol; - private MultipleAligPanelMouseMotionListener mouseMoLi; + private final MultipleAligPanelMouseMotionListener mouseMoLi; private MultipleAlignmentCoordManager coordManager; private BitSet selection; @@ -120,10 +113,9 @@ public MultipleAligPanel(){ * @param afpChain * @param ca1 * @param ca2 - * @throws StructureException */ public MultipleAligPanel(AFPChain afpChain, Atom[] ca1, Atom[] ca2, - AbstractAlignmentJmol jmol) throws StructureException { + AbstractAlignmentJmol jmol) { this(); @@ -139,7 +131,7 @@ public MultipleAligPanel(AFPChain afpChain, Atom[] ca1, Atom[] ca2, this.multAln = ensemble.getMultipleAlignment(0); //Create the sequence alignment and the structure-sequence mapping. - this.mapSeqToStruct = new ArrayList(); + this.mapSeqToStruct = new ArrayList<>(); this.alnSeq = MultipleAlignmentTools.getSequenceAlignment( this.multAln, this.mapSeqToStruct); @@ -162,7 +154,7 @@ public MultipleAligPanel(MultipleAlignment msa, AbstractAlignmentJmol jm) { this.multAln = msa; //Create the sequence alignment and the structure-sequence mapping. - this.mapSeqToStruct = new ArrayList(); + this.mapSeqToStruct = new ArrayList<>(); this.alnSeq = MultipleAlignmentTools.getSequenceAlignment( this.multAln, this.mapSeqToStruct); @@ -225,7 +217,7 @@ public void paintComponent(Graphics g){ else isGapped = true; //Loop through every structure to get all the points - List points = new ArrayList(); + List points = new ArrayList<>(); for (int str=0; str aligPosListeners; + private final List aligPosListeners; private int prevPos; private boolean isDragging ; @@ -52,7 +52,7 @@ public class MultipleAligPanelMouseMotionListener public MultipleAligPanelMouseMotionListener(MultipleAligPanel parent){ this.parent = parent; - aligPosListeners = new ArrayList(); + aligPosListeners = new ArrayList<>(); prevPos = -1; isDragging = false; selectionStart = null; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleAlignmentCoordManager.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleAlignmentCoordManager.java index 35c65c524c..e7f562487e 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleAlignmentCoordManager.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleAlignmentCoordManager.java @@ -31,8 +31,8 @@ */ public class MultipleAlignmentCoordManager { - private int alignmentLength; //number of aligned residues - private int alignmentSize; //number of strucures aligned + private final int alignmentLength; //number of aligned residues + private final int alignmentSize; //number of strucures aligned /** * Constructor. diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleStatusDisplay.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleStatusDisplay.java index e87ad5817c..4ea5893b8f 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleStatusDisplay.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleStatusDisplay.java @@ -20,19 +20,17 @@ */ package org.biojava.nbio.structure.align.gui.aligpanel; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; - -import javax.swing.JTextField; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.align.gui.jmol.JmolTools; import org.biojava.nbio.structure.align.multiple.util.MultipleAlignmentTools; import org.biojava.nbio.structure.gui.events.AlignmentPositionListener; import org.biojava.nbio.structure.gui.util.AlignedPosition; +import javax.swing.*; +import java.awt.*; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; + /** * This class provides information of the selected positions in the * {@link MultipleAligPanel}. diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/AutoSuggestProvider.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/AutoSuggestProvider.java index 88352df175..64105ca298 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/AutoSuggestProvider.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/AutoSuggestProvider.java @@ -38,31 +38,31 @@ public interface AutoSuggestProvider { * @param userInput * @return list of suggestions */ - public Vector getSuggestion(String userInput); + Vector getSuggestion(String userInput); /** set the maximum number of suggestions to return * * @param maxNrSuggestions */ - public void setMaxNrSuggestions(int maxNrSuggestions); + void setMaxNrSuggestions(int maxNrSuggestions); /** Get the maximun nr of suggestions * * @return maxNrSuggestions */ - public int getMaxNrSuggestions(); + int getMaxNrSuggestions(); /** reset all suggestions * */ - public void clear(); + void clear(); /** Interrupt searching for suggestions * */ - public void stop(); + void stop(); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/DefaultAutoSuggestProvider.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/DefaultAutoSuggestProvider.java index 045ff5ce8d..1a87aa786a 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/DefaultAutoSuggestProvider.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/DefaultAutoSuggestProvider.java @@ -30,7 +30,7 @@ public class DefaultAutoSuggestProvider implements AutoSuggestProvider { @Override public Vector getSuggestion(String userInput) { - Vector data = new Vector(); + Vector data = new Vector<>(); data.add(userInput + " no AutoSuggestProvider registered yet!"); return data; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/JAutoSuggest.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/JAutoSuggest.java index 128ee39149..fae350ef65 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/JAutoSuggest.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/JAutoSuggest.java @@ -135,11 +135,11 @@ public void focusLost(FocusEvent e) { System.out.println("Lost Focus"); dialog.setVisible(false); - if (getText().trim().equals("") && e.getOppositeComponent() != null && e.getOppositeComponent().getName() != null) { + if (getText().trim().isEmpty() && e.getOppositeComponent() != null && e.getOppositeComponent().getName() != null) { if (!e.getOppositeComponent().getName().equals("suggestFieldDropdownButton")) { setText(defaultText); } - } else if (getText().trim().equals("")) { + } else if (getText().trim().isEmpty()) { setText(defaultText); } } @@ -247,7 +247,7 @@ private void init(){ lastWord = ""; regular = getFont(); busy = new Font(getFont().getName(), Font.ITALIC, getFont().getSize()); - suggestions = new Vector(); + suggestions = new Vector<>(); defaultText = DEFAULT_TEXT; @@ -340,7 +340,7 @@ private void updateLocation() { */ private class SuggestionFetcher extends SwingWorker { /** flag used to stop the thread */ - private AtomicBoolean stop = new AtomicBoolean(false); + private final AtomicBoolean stop = new AtomicBoolean(false); String previousWord; /** @@ -352,7 +352,7 @@ public String doInBackground() { try { setFont(busy); String userInput = getText().trim(); - if ( userInput == null || userInput.equals("")) + if ( userInput == null || userInput.isEmpty()) return ""; if ( previousWord != null){ diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/SCOPAutoSuggestProvider.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/SCOPAutoSuggestProvider.java index d90fd0380f..662f9bd3a5 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/SCOPAutoSuggestProvider.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/SCOPAutoSuggestProvider.java @@ -36,18 +36,18 @@ public class SCOPAutoSuggestProvider implements AutoSuggestProvider{ - boolean DEBUG = false; + final boolean DEBUG = false; int maxResults = 20; - AtomicBoolean stop = new AtomicBoolean(false); + final AtomicBoolean stop = new AtomicBoolean(false); @Override public Vector getSuggestion(String userInput) { long timeS = System.currentTimeMillis(); - List domains = new ArrayList(); + List domains; domains = getPossibleScopDomains(userInput); @@ -55,7 +55,7 @@ public Vector getSuggestion(String userInput) { // convert domains to Strings - Vector v=new Vector(); + Vector v= new Vector<>(); int counter = 0; for ( ScopDomain d : domains){ @@ -82,7 +82,7 @@ public Vector getSuggestion(String userInput) { private List getPossibleScopDomains(String userInput) { - List domains = new ArrayList(); + List domains = new ArrayList<>(); ScopDatabase scop = ScopFactory.getSCOP(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AbstractAlignmentJmol.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AbstractAlignmentJmol.java index 4663505797..b6cdf1f0fc 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AbstractAlignmentJmol.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AbstractAlignmentJmol.java @@ -20,23 +20,7 @@ */ package org.biojava.nbio.structure.align.gui.jmol; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.util.List; - -import javax.swing.JFrame; -import javax.swing.JTextField; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ChainImpl; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureImpl; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.ResourceManager; import org.biojava.nbio.structure.jama.Matrix; import org.jcolorbrewer.ColorBrewer; @@ -45,6 +29,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.swing.*; +import java.awt.event.*; +import java.util.List; + /** * An Abstract Class to generalize the visualization of AFP and * MultipleAlignment structure alignments in Jmol. diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AtomInfo.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AtomInfo.java index e90fafcf43..83b93ac1bc 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AtomInfo.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AtomInfo.java @@ -40,7 +40,7 @@ public class AtomInfo { String residueNumber; int modelNumber; - private static Pattern inscodePatter ; + private static final Pattern inscodePatter ; static { inscodePatter = Pattern.compile("([0-9]+)([a-zA-Z]*)?"); } @@ -106,25 +106,25 @@ public void setAtomName(String name) { @Override public String toString() { - String aa3 = ""; + String aa3; boolean printResName = true; - String chain1 =""; - String res1 = ""; + String chain1; + String res1; aa3 = residueName; res1 = residueNumber; chain1 = chainId; - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); if ( printResName) { - if ( !aa3.equals("")){ + if (!aa3.isEmpty()){ buf.append("["); buf.append(aa3); buf.append("]"); } } - if ( ! res1.equals("")) { + if (!res1.isEmpty()) { // let's check if there is an insertion code... Matcher matcher = inscodePatter.matcher(res1); @@ -137,7 +137,7 @@ public String toString() { String residueNumber = matcher.group(1); String insCode = matcher.group(2); buf.append(residueNumber); - if ( insCode != null && ! ( insCode.equals(""))) { + if ( insCode != null && ! (insCode.isEmpty())) { buf.append("^"); buf.append(insCode); } @@ -145,7 +145,7 @@ public String toString() { } - if ( ! chain1.equals("")){ + if (!chain1.isEmpty()){ buf.append(":"); buf.append(chain1); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AtomInfoParser.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AtomInfoParser.java index ac4dd69120..8cef15b12b 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AtomInfoParser.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AtomInfoParser.java @@ -33,11 +33,11 @@ public class AtomInfoParser { private static final Logger logger = LoggerFactory.getLogger(AtomInfoParser.class); - static Pattern pattern; + static final Pattern pattern; static { - String numberPattern = "\\[(.*)\\]([0-9^a-zA-Z]+)(:[a-zA-Z]*)?\\.([a-zA-Z]+)(/[0-9]*)?"; + String numberPattern = "\\[(.*)]([0-9^a-zA-Z]+)(:[a-zA-Z]*)?\\.([a-zA-Z]+)(/[0-9]*)?"; pattern = Pattern.compile(numberPattern); } @@ -94,12 +94,12 @@ public static AtomInfo parse(String jmolAtomInfo){ String ci = " "; if (chainId != null) - ci = chainId.substring(1,chainId.length()); + ci = chainId.substring(1); info.setChainId(ci); int mn = 1; if ( modelNumber != null) - mn = Integer.parseInt(modelNumber.substring(1,modelNumber.length())); + mn = Integer.parseInt(modelNumber.substring(1)); info.setModelNumber(mn); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/JmolPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/JmolPanel.java index b8b37c6251..8ee76173b1 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/JmolPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/JmolPanel.java @@ -24,27 +24,7 @@ package org.biojava.nbio.structure.align.gui.jmol; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.text.DecimalFormat; -import java.util.List; - -import javax.swing.JComboBox; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Calc; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.gui.JPrintPanel; import org.biojava.nbio.structure.domain.LocalProteinDomainParser; import org.biojava.nbio.structure.domain.pdp.Domain; @@ -63,6 +43,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.*; +import java.text.DecimalFormat; +import java.util.List; + +import static org.jmol.util.Logger.LEVEL_FATAL; + public class JmolPanel extends JPrintPanel @@ -74,7 +64,7 @@ public class JmolPanel private JmolViewer viewer; private JmolAdapter adapter; - JmolStatusListener statusListener; + final JmolStatusListener statusListener; final Dimension currentSize = new Dimension(); final Rectangle rectClip = new Rectangle(); @@ -91,6 +81,7 @@ public JmolPanel() { adapter, null,null,null,null, statusListener); + setIgnoreRepaint(true); } @@ -135,9 +126,9 @@ public void setStructure(final Structure s, boolean useMmtf) { try ( PipedOutputStream out = new PipedOutputStream(); // Viewer requires a BufferedInputStream for reflection - InputStream in = new BufferedInputStream(new PipedInputStream(out)); - ) { - new Thread((Runnable)() -> { + InputStream in = new BufferedInputStream(new PipedInputStream(out)) + ) { + new Thread(() -> { try { MmtfActions.writeToOutputStream(s,out); } catch (Exception e) { @@ -171,39 +162,7 @@ public void setStructure(final Structure s) { */ public void jmolColorByChain(){ String script = - "function color_by_chain(objtype, color_list) {"+ String.format("%n") + - ""+ String.format("%n") + - " if (color_list) {"+ String.format("%n") + - " if (color_list.type == \"string\") {"+ String.format("%n") + - " color_list = color_list.split(\",\").trim();"+ String.format("%n") + - " }"+ String.format("%n") + - " } else {"+ String.format("%n") + - " color_list = [\"104BA9\",\"AA00A2\",\"C9F600\",\"FFA200\",\"284A7E\",\"7F207B\",\"9FB82E\",\"BF8B30\",\"052D6E\",\"6E0069\",\"83A000\",\"A66A00\",\"447BD4\",\"D435CD\",\"D8FA3F\",\"FFBA40\",\"6A93D4\",\"D460CF\",\"E1FA71\",\"FFCC73\"];"+ String.format("%n") + - " }"+ String.format("%n") + - - " var cmd2 = \"\";"+ String.format("%n") + - - " if (!objtype) {"+ String.format("%n") + - " var type_list = [ \"backbone\",\"cartoon\",\"dots\",\"halo\",\"label\",\"meshribbon\",\"polyhedra\",\"rocket\",\"star\",\"strand\",\"strut\",\"trace\"];"+ String.format("%n") + - " cmd2 = \"color \" + type_list.join(\" none; color \") + \" none;\";"+ String.format("%n") + - " objtype = \"atoms\";"+ String.format("%n") + - - " }"+ String.format("%n") + - - " var chain_list = script(\"show chain\").trim().lines;"+ String.format("%n") + - " var chain_count = chain_list.length;"+ String.format("%n") + - - " var color_count = color_list.length;"+ String.format("%n") + - " var sel = {selected};"+ String.format("%n") + - " var cmds = \"\";"+ String.format("%n") + - - - " for (var chain_number=1; chain_number<=chain_count; chain_number++) {"+ String.format("%n") + - " // remember, Jmol arrays start with 1, but % can return 0"+ String.format("%n") + - " cmds += \"select sel and :\" + chain_list[chain_number] + \";color \" + objtype + \" [x\" + color_list[(chain_number-1) % color_count + 1] + \"];\" + cmd2;"+ String.format("%n") + - " }"+ String.format("%n") + - " script INLINE @{cmds + \"select sel\"}"+ String.format("%n") + - "}"; + "function color_by_chain(objtype, color_list) {" + String.format("%n") + String.format("%n") + " if (color_list) {" + String.format("%n") + " if (color_list.type == \"string\") {" + String.format("%n") + " color_list = color_list.split(\",\").trim();" + String.format("%n") + " }" + String.format("%n") + " } else {" + String.format("%n") + " color_list = [\"104BA9\",\"AA00A2\",\"C9F600\",\"FFA200\",\"284A7E\",\"7F207B\",\"9FB82E\",\"BF8B30\",\"052D6E\",\"6E0069\",\"83A000\",\"A66A00\",\"447BD4\",\"D435CD\",\"D8FA3F\",\"FFBA40\",\"6A93D4\",\"D460CF\",\"E1FA71\",\"FFCC73\"];" + String.format("%n") + " }" + String.format("%n") + " var cmd2 = \"\";" + String.format("%n") + " if (!objtype) {" + String.format("%n") + " var type_list = [ \"backbone\",\"cartoon\",\"dots\",\"halo\",\"label\",\"meshribbon\",\"polyhedra\",\"rocket\",\"star\",\"strand\",\"strut\",\"trace\"];" + String.format("%n") + " cmd2 = \"color \" + type_list.join(\" none; color \") + \" none;\";" + String.format("%n") + " objtype = \"atoms\";" + String.format("%n") + " }" + String.format("%n") + " var chain_list = script(\"show chain\").trim().lines;" + String.format("%n") + " var chain_count = chain_list.length;" + String.format("%n") + " var color_count = color_list.length;" + String.format("%n") + " var sel = {selected};" + String.format("%n") + " var cmds = \"\";" + String.format("%n") + " for (var chain_number=1; chain_number<=chain_count; chain_number++) {" + String.format("%n") + " // remember, Jmol arrays start with 1, but % can return 0" + String.format("%n") + " cmds += \"select sel and :\" + chain_list[chain_number] + \";color \" + objtype + \" [x\" + color_list[(chain_number-1) % color_count + 1] + \"];\" + cmd2;" + String.format("%n") + " }" + String.format("%n") + " script INLINE @{cmds + \"select sel\"}" + String.format("%n") + "}"; executeCmd(script); } @@ -229,66 +188,86 @@ public void actionPerformed(ActionEvent event) { String selectLigand = "select ligand;wireframe 0.16;spacefill 0.5; color cpk ;"; - if ( value.equals("Cartoon")){ - String script = "hide null; select all; spacefill off; wireframe off; backbone off;" + - " cartoon on; " + - " select ligand; wireframe 0.16;spacefill 0.5; color cpk; " + - " select *.FE; spacefill 0.7; color cpk ; " + - " select *.CU; spacefill 0.7; color cpk ; " + - " select *.ZN; spacefill 0.7; color cpk ; " + - " select all; "; - this.executeCmd(script); - } else if (value.equals("Backbone")){ - String script = "hide null; select all; spacefill off; wireframe off; backbone 0.4;" + - " cartoon off; " + - " select ligand; wireframe 0.16;spacefill 0.5; color cpk; " + - " select *.FE; spacefill 0.7; color cpk ; " + - " select *.CU; spacefill 0.7; color cpk ; " + - " select *.ZN; spacefill 0.7; color cpk ; " + - " select all; "; - this.executeCmd(script); - } else if (value.equals("CPK")){ - String script = "hide null; select all; spacefill off; wireframe off; backbone off;" + - " cartoon off; cpk on;" + - " select ligand; wireframe 0.16;spacefill 0.5; color cpk; " + - " select *.FE; spacefill 0.7; color cpk ; " + - " select *.CU; spacefill 0.7; color cpk ; " + - " select *.ZN; spacefill 0.7; color cpk ; " + - " select all; "; - this.executeCmd(script); - - } else if (value.equals("Ligands")){ - this.executeCmd("restrict ligand; cartoon off; wireframe on; display selected;"); - } else if (value.equals("Ligands and Pocket")){ - this.executeCmd(" select within (6.0,ligand); cartoon off; wireframe on; backbone off; display selected; "); - } else if ( value.equals("Ball and Stick")){ - String script = "hide null; restrict not water; wireframe 0.2; spacefill 25%;" + - " cartoon off; backbone off; " + - " select ligand; wireframe 0.16; spacefill 0.5; color cpk; " + - " select *.FE; spacefill 0.7; color cpk ; " + - " select *.CU; spacefill 0.7; color cpk ; " + - " select *.ZN; spacefill 0.7; color cpk ; " + - " select all; "; - this.executeCmd(script); - } else if ( value.equals("By Chain")){ - jmolColorByChain(); - String script = "hide null; select all;set defaultColors Jmol; color_by_chain(\"cartoon\"); color_by_chain(\"\"); " + selectLigand + "; select all; "; - this.executeCmd(script); - } else if ( value.equals("Rainbow")) { - this.executeCmd("hide null; select all; set defaultColors Jmol; color group; color cartoon group; " + selectLigand + "; select all; " ); - } else if ( value.equals("Secondary Structure")){ - this.executeCmd("hide null; select all; set defaultColors Jmol; color structure; color cartoon structure;" + selectLigand + "; select all; " ); - - } else if ( value.equals("By Element")){ - this.executeCmd("hide null; select all; set defaultColors Jmol; color cpk; color cartoon cpk; " + selectLigand + "; select all; "); - } else if ( value.equals("By Amino Acid")){ - this.executeCmd("hide null; select all; set defaultColors Jmol; color amino; color cartoon amino; " + selectLigand + "; select all; " ); - } else if ( value.equals("Hydrophobicity") ){ - this.executeCmd("hide null; set defaultColors Jmol; select hydrophobic; color red; color cartoon red; select not hydrophobic ; color blue ; color cartoon blue; "+ selectLigand+"; select all; "); - } else if ( value.equals("Suggest Domains")){ - colorByPDP(); - } else if ( value.equals("Show SCOP Domains")){ - colorBySCOP(); + switch (value) { + case "Cartoon": { + String script = "hide null; select all; spacefill off; wireframe off; backbone off;" + + " cartoon on; " + + " select ligand; wireframe 0.16;spacefill 0.5; color cpk; " + + " select *.FE; spacefill 0.7; color cpk ; " + + " select *.CU; spacefill 0.7; color cpk ; " + + " select *.ZN; spacefill 0.7; color cpk ; " + + " select all; "; + this.executeCmd(script); + break; + } + case "Backbone": { + String script = "hide null; select all; spacefill off; wireframe off; backbone 0.4;" + + " cartoon off; " + + " select ligand; wireframe 0.16;spacefill 0.5; color cpk; " + + " select *.FE; spacefill 0.7; color cpk ; " + + " select *.CU; spacefill 0.7; color cpk ; " + + " select *.ZN; spacefill 0.7; color cpk ; " + + " select all; "; + this.executeCmd(script); + break; + } + case "CPK": { + String script = "hide null; select all; spacefill off; wireframe off; backbone off;" + + " cartoon off; cpk on;" + + " select ligand; wireframe 0.16;spacefill 0.5; color cpk; " + + " select *.FE; spacefill 0.7; color cpk ; " + + " select *.CU; spacefill 0.7; color cpk ; " + + " select *.ZN; spacefill 0.7; color cpk ; " + + " select all; "; + this.executeCmd(script); + + break; + } + case "Ligands": + this.executeCmd("restrict ligand; cartoon off; wireframe on; display selected;"); + break; + case "Ligands and Pocket": + this.executeCmd(" select within (6.0,ligand); cartoon off; wireframe on; backbone off; display selected; "); + break; + case "Ball and Stick": { + String script = "hide null; restrict not water; wireframe 0.2; spacefill 25%;" + + " cartoon off; backbone off; " + + " select ligand; wireframe 0.16; spacefill 0.5; color cpk; " + + " select *.FE; spacefill 0.7; color cpk ; " + + " select *.CU; spacefill 0.7; color cpk ; " + + " select *.ZN; spacefill 0.7; color cpk ; " + + " select all; "; + this.executeCmd(script); + break; + } + case "By Chain": { + jmolColorByChain(); + String script = "hide null; select all;set defaultColors Jmol; color_by_chain(\"cartoon\"); color_by_chain(\"\"); " + selectLigand + "; select all; "; + this.executeCmd(script); + break; + } + case "Rainbow": + this.executeCmd("hide null; select all; set defaultColors Jmol; color group; color cartoon group; " + selectLigand + "; select all; "); + break; + case "Secondary Structure": + this.executeCmd("hide null; select all; set defaultColors Jmol; color structure; color cartoon structure;" + selectLigand + "; select all; "); + + break; + case "By Element": + this.executeCmd("hide null; select all; set defaultColors Jmol; color cpk; color cartoon cpk; " + selectLigand + "; select all; "); + break; + case "By Amino Acid": + this.executeCmd("hide null; select all; set defaultColors Jmol; color amino; color cartoon amino; " + selectLigand + "; select all; "); + break; + case "Hydrophobicity": + this.executeCmd("hide null; set defaultColors Jmol; select hydrophobic; color red; color cartoon red; select not hydrophobic ; color blue ; color cartoon blue; " + selectLigand + "; select all; "); + break; + case "Suggest Domains": + colorByPDP(); + break; + case "Show SCOP Domains": + colorBySCOP(); + break; } evalString("restore selection; "); } @@ -361,7 +340,7 @@ private void colorByPDP() { Group startG = ca[start].getGroup(); Group endG = ca[end].getGroup(); logger.debug(" Segment: " +startG.getResidueNumber() +":" + startG.getChainId() + " - " + endG.getResidueNumber()+":"+endG.getChainId() + " " + s); - String j1 = startG.getResidueNumber()+""; + String j1 = String.valueOf(startG.getResidueNumber()); String j2 = endG.getResidueNumber()+":"+endG.getChainId(); String script = " select " +j1 +"-" +j2 +"/1;"; script += " color [" + c1.getRed() + ","+c1.getGreen() + "," +c1.getBlue()+"];"; @@ -407,7 +386,7 @@ public void destroy(){ } public static class JmolLoggerAdapter implements LoggerInterface { - private Logger slf; + private final Logger slf; public JmolLoggerAdapter(Logger slf) { this.slf=slf; } @@ -422,7 +401,9 @@ public int getLogLevel() { return org.jmol.util.Logger.LEVEL_WARN; if( slf.isErrorEnabled() ) return org.jmol.util.Logger.LEVEL_ERROR; - throw new IllegalStateException("Unknown SLF4J error level"); + + return LEVEL_FATAL; + //throw new IllegalStateException("Unknown SLF4J error level"); } @Override public void debug(String txt) { diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/JmolTools.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/JmolTools.java index 5a42f37cad..9d9044015d 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/JmolTools.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/JmolTools.java @@ -34,11 +34,11 @@ public class JmolTools { * * @return a String representation in Jmol style of the PDB information of this atom */ - public static final String getPdbInfo(Atom a){ + public static String getPdbInfo(Atom a){ return getPdbInfo(a,true); } - private static Pattern inscodePatter ; + private static final Pattern inscodePatter ; static { inscodePatter = Pattern.compile("([0-9]+)([a-zA-Z]*)?"); } @@ -63,7 +63,7 @@ public static void main(String[] args){ // TODO: move this to AtomInfo class - public static final String getPdbInfo(Atom a, boolean printResName){ + public static String getPdbInfo(Atom a, boolean printResName){ String aa3 = ""; String chain1 =""; @@ -80,15 +80,15 @@ public static final String getPdbInfo(Atom a, boolean printResName){ } } - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); if ( printResName) { - if ( !aa3.equals("")){ + if (!aa3.isEmpty()){ buf.append("["); buf.append(aa3); buf.append("]"); } } - if ( ! res1.equals("")) { + if (!res1.isEmpty()) { // let's check if there is an insertion code... Matcher matcher = inscodePatter.matcher(res1); @@ -101,7 +101,7 @@ public static final String getPdbInfo(Atom a, boolean printResName){ String residueNumber = matcher.group(1); String insCode = matcher.group(2); buf.append(residueNumber); - if ( insCode != null && ! ( insCode.equals(""))) { + if ( insCode != null && ! (insCode.isEmpty())) { buf.append("^"); buf.append(insCode); } @@ -112,7 +112,7 @@ public static final String getPdbInfo(Atom a, boolean printResName){ - if ( ! chain1.equals("")){ + if (chain1!=null && !chain1.isEmpty()){ buf.append(":"); buf.append(chain1); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/MultipleAlignmentJmol.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/MultipleAlignmentJmol.java index fc7d209312..6d49cd3b18 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/MultipleAlignmentJmol.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/MultipleAlignmentJmol.java @@ -20,33 +20,8 @@ */ package org.biojava.nbio.structure.align.gui.jmol; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenuBar; -import javax.swing.JPanel; -import javax.swing.JTextField; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.gui.MenuCreator; import org.biojava.nbio.structure.align.gui.MultipleAlignmentGUI; import org.biojava.nbio.structure.align.gui.MultipleAlignmentJmolDisplay; @@ -64,6 +39,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ItemEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; + /** * A class that provides a 3D visualization Frame in Jmol for * {@link MultipleAlignment}s. @@ -77,7 +62,7 @@ public class MultipleAlignmentJmol extends AbstractAlignmentJmol { private MultipleAlignment multAln; private List transformedAtoms; private JCheckBox colorByBlocks; - private List selectedStructures; + private final List selectedStructures; private static final String LIGAND_DISPLAY_SCRIPT = "select ligand; wireframe 40; spacefill 120; color CPK;"; @@ -113,7 +98,7 @@ public MultipleAlignmentJmol(MultipleAlignment msa, frame.setJMenuBar(menu); this.multAln = msa; this.transformedAtoms = rotatedAtoms; - this.selectedStructures = new ArrayList(); + this.selectedStructures = new ArrayList<>(); frame.addWindowListener(new WindowAdapter() { @@ -168,23 +153,19 @@ public void windowClosing(WindowEvent e) { vBox.add(modelSelection); JButton show = new JButton("Show Only: "); - show.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - jmolPanel.evalString("save selection;"); - String cmd = getJmolString(multAln, - transformedAtoms, colorPalette, - colorByBlocks.isSelected()); - cmd += "; restrict "; - for (int st = 0; st < multAln.size(); st++) { - if (selectedStructures.get(st).isSelected()) { - cmd += "*/" + (st + 1) + ", "; - } + show.addActionListener(e -> { + jmolPanel.evalString("save selection;"); + String cmd = getJmolString(multAln, + transformedAtoms, colorPalette, + colorByBlocks.isSelected()); + cmd += "; restrict "; + for (int st = 0; st < multAln.size(); st++) { + if (selectedStructures.get(st).isSelected()) { + cmd += "*/" + (st + 1) + ", "; } - cmd += "none;"; - jmolPanel.executeCmd(cmd + " restore selection;"); } + cmd += "none;"; + jmolPanel.executeCmd(cmd + " restore selection;"); }); modelSelection.add(show); @@ -228,29 +209,26 @@ public void actionPerformed(ActionEvent e) { String[] cPalette = { "Spectral", "Set1", "Set2", "Pastel" }; JComboBox palette = new JComboBox<>(cPalette); - palette.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - - @SuppressWarnings("unchecked") - JComboBox source = (JComboBox) e.getSource(); - String value = source.getSelectedItem().toString(); - evalString("save selection; select *; color grey; " - + "select ligand; color CPK;"); - - if (value == "Set1") { - colorPalette = ColorBrewer.Set1; - } else if (value == "Set2") { - colorPalette = ColorBrewer.Set2; - } else if (value == "Spectral") { - colorPalette = ColorBrewer.Spectral; - } else if (value == "Pastel") { - colorPalette = ColorBrewer.Pastel1; - } - String script = getJmolString(multAln, transformedAtoms, - colorPalette, colorByBlocks.isSelected()); - evalString(script + "; restore selection; "); + palette.addActionListener(e -> { + + @SuppressWarnings("unchecked") + JComboBox source = (JComboBox) e.getSource(); + String value = source.getSelectedItem().toString(); + evalString("save selection; select *; color grey; " + + "select ligand; color CPK;"); + + if (value.equals("Set1")) { + colorPalette = ColorBrewer.Set1; + } else if (value.equals("Set2")) { + colorPalette = ColorBrewer.Set2; + } else if (value.equals("Spectral")) { + colorPalette = ColorBrewer.Spectral; + } else if (value.equals("Pastel")) { + colorPalette = ColorBrewer.Pastel1; } + String script = getJmolString(multAln, transformedAtoms, + colorPalette, colorByBlocks.isSelected()); + evalString(script + "; restore selection; "); }); hBox1.add(Box.createGlue()); @@ -262,45 +240,32 @@ public void actionPerformed(ActionEvent e) { hBox2.setMaximumSize(new Dimension(Short.MAX_VALUE, 30)); JButton resetDisplay = new JButton("Reset Display"); - resetDisplay.addActionListener(new ActionListener() { + resetDisplay.addActionListener(e -> { + logger.info("reset!!"); + jmolPanel.executeCmd("restore STATE state_1"); - @Override - public void actionPerformed(ActionEvent e) { - logger.info("reset!!"); - jmolPanel.executeCmd("restore STATE state_1"); - - } }); hBox2.add(resetDisplay); hBox2.add(Box.createGlue()); JCheckBox toggleSelection = new JCheckBox("Show Selection"); - toggleSelection.addItemListener(new ItemListener() { - - @Override - public void itemStateChanged(ItemEvent e) { - boolean showSelection = (e.getStateChange() == ItemEvent.SELECTED); + toggleSelection.addItemListener(e -> { + boolean showSelection = (e.getStateChange() == ItemEvent.SELECTED); - if (showSelection) { - jmolPanel.executeCmd("set display selected"); - } else - jmolPanel.executeCmd("set display off"); - } + if (showSelection) { + jmolPanel.executeCmd("set display selected"); + } else + jmolPanel.executeCmd("set display off"); }); hBox2.add(toggleSelection); hBox2.add(Box.createGlue()); colorByBlocks = new JCheckBox("Color By Block"); - colorByBlocks.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - evalString("save selection; " - + getJmolString(multAln, transformedAtoms, - colorPalette, colorByBlocks.isSelected()) - + "; restore selection;"); - } - }); + colorByBlocks.addItemListener(e -> evalString("save selection; " + + getJmolString(multAln, transformedAtoms, + colorPalette, colorByBlocks.isSelected()) + + "; restore selection;")); hBox2.add(colorByBlocks); hBox2.add(Box.createGlue()); @@ -343,7 +308,7 @@ public void itemStateChanged(ItemEvent e) { @Override protected void initCoords() { - try { +// try { if (multAln == null) { if (structure != null) setStructure(structure); @@ -354,10 +319,11 @@ protected void initCoords() { } Structure artificial = MultipleAlignmentTools.toMultimodelStructure(multAln, transformedAtoms); setStructure(artificial); - logger.info(artificial.getPDBHeader().getTitle()); - } catch (StructureException e) { - e.printStackTrace(); - } + if (logger.isInfoEnabled()) + logger.info(artificial.getPDBHeader().getTitle()); +// } catch (StructureException e) { +// e.printStackTrace(); +// } } @Override @@ -375,37 +341,45 @@ public void actionPerformed(ActionEvent ae) { return; } try { - if (cmd.equals(MenuCreator.TEXT_ONLY)) { - logger.warn("Option not available for MultipleAlignments"); - - } else if (cmd.equals(MenuCreator.PAIRS_ONLY)) { - String result = MultipleAlignmentWriter - .toAlignedResidues(multAln); - MultipleAlignmentJmolDisplay - .showAlignmentImage(multAln, result); - - } else if (cmd.equals(MenuCreator.ALIGNMENT_PANEL)) { - MultipleAlignmentJmolDisplay.showMultipleAligmentPanel(multAln, - this); - - } else if (cmd.equals(MenuCreator.FATCAT_TEXT)) { - String result = MultipleAlignmentWriter.toFatCat(multAln) - + "\n"; - result += MultipleAlignmentWriter.toTransformMatrices(multAln); - MultipleAlignmentJmolDisplay - .showAlignmentImage(multAln, result); - - } else if (cmd.equals(MenuCreator.PHYLOGENETIC_TREE)) { - - // Kimura, Structural and Fractional Dissimilarity Score - Phylogeny kimura = MultipleAlignmentTools - .getKimuraTree(multAln); - Phylogeny sdm = MultipleAlignmentTools.getHSDMTree(multAln); - // Phylogeny structural = MultipleAlignmentTools - // .getStructuralTree(multAln); - - Archaeopteryx - .createApplication(new Phylogeny[] { kimura, sdm }); + switch (cmd) { + case MenuCreator.TEXT_ONLY: + logger.warn("Option not available for MultipleAlignments"); + + break; + case MenuCreator.PAIRS_ONLY: { + String result = MultipleAlignmentWriter + .toAlignedResidues(multAln); + MultipleAlignmentJmolDisplay + .showAlignmentImage(multAln, result); + + break; + } + case MenuCreator.ALIGNMENT_PANEL: + MultipleAlignmentJmolDisplay.showMultipleAligmentPanel(multAln, + this); + + break; + case MenuCreator.FATCAT_TEXT: { + String result = MultipleAlignmentWriter.toFatCat(multAln) + + "\n"; + result += MultipleAlignmentWriter.toTransformMatrices(multAln); + MultipleAlignmentJmolDisplay + .showAlignmentImage(multAln, result); + + break; + } + case MenuCreator.PHYLOGENETIC_TREE: + + // Kimura, Structural and Fractional Dissimilarity Score + Phylogeny kimura = MultipleAlignmentTools + .getKimuraTree(multAln); + Phylogeny sdm = MultipleAlignmentTools.getHSDMTree(multAln); + // Phylogeny structural = MultipleAlignmentTools + // .getStructuralTree(multAln); + + Archaeopteryx + .createApplication(new Phylogeny[]{kimura, sdm}); + break; } } catch (Exception e) { logger.error("Could not complete display option.", e); @@ -426,13 +400,13 @@ public static String getJmolString(MultipleAlignment multAln, colorPalette, colorByBlocks); Color[] colors = colorPalette.getColorPalette(multAln.size()); - StringBuffer j = new StringBuffer(); + StringBuilder j = new StringBuilder(); j.append(DEFAULT_SCRIPT); // Color the equivalent residues of every structure - StringBuffer sel = new StringBuffer(); + StringBuilder sel = new StringBuilder(); sel.append("select *; color lightgrey; backbone 0.1; "); - List> allPDB = new ArrayList>(); + List> allPDB = new ArrayList<>(); // Get the aligned residues of every structure for (int i = 0; i < multAln.size(); i++) { @@ -449,12 +423,11 @@ public static String getJmolString(MultipleAlignment multAln, pos++; sel.append(res); - sel.append("/" + (i + 1)); + sel.append("/").append(i + 1); } if (pos == 0) sel.append("none"); - sel.append("; backbone 0.3 ; color [" + colors[i].getRed() + "," - + colors[i].getGreen() + "," + colors[i].getBlue() + "]; "); + sel.append("; backbone 0.3 ; color [").append(colors[i].getRed()).append(",").append(colors[i].getGreen()).append(",").append(colors[i].getBlue()).append("]; "); } j.append(sel); @@ -482,8 +455,7 @@ public static String getMultiBlockJmolString(MultipleAlignment multAln, // For every structure color all the blocks with the printBlock method for (int str = 0; str < transformedAtoms.size(); str++) { - jmol.append("select */" + (str + 1) + "; color lightgrey; model " - + (str + 1) + "; "); + jmol.append("select */").append(String.valueOf(str + 1)).append("; color lightgrey; model ").append(String.valueOf(str + 1)).append("; "); int index = 0; for (BlockSet bs : multAln.getBlockSets()) { @@ -508,7 +480,7 @@ private static void printJmolScript4Block(Atom[] atoms, int str, int colorPos, int blockNum) { // Obtain the residues aligned in this block of the structure - List pdb = new ArrayList(); + List pdb = new ArrayList<>(); for (int i = 0; i < alignRes.get(str).size(); i++) { // Handle gaps - only color if it is not null @@ -525,12 +497,11 @@ private static void printJmolScript4Block(Atom[] atoms, if (count > 0) buf.append(","); buf.append(res); - buf.append("/" + (str + 1)); + buf.append("/").append(str + 1); count++; } - buf.append("; backbone 0.3 ; color [" + blockColor.getRed() + "," - + blockColor.getGreen() + "," + blockColor.getBlue() + "]; "); + buf.append("; backbone 0.3 ; color [").append(blockColor.getRed()).append(",").append(blockColor.getGreen()).append(",").append(blockColor.getBlue()).append("]; "); jmol.append(buf); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/MyJmolStatusListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/MyJmolStatusListener.java index f0a5a5864d..00243ec366 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/MyJmolStatusListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/MyJmolStatusListener.java @@ -24,15 +24,14 @@ package org.biojava.nbio.structure.align.gui.jmol; -import java.util.Map; - -import javax.swing.JTextField; - import org.jmol.api.JmolStatusListener; import org.jmol.c.CBK; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.swing.*; +import java.util.Map; + public class MyJmolStatusListener implements JmolStatusListener { private static final Logger logger = LoggerFactory.getLogger(MyJmolStatusListener.class); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/RasmolCommandListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/RasmolCommandListener.java index 6c47f80276..e890e90274 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/RasmolCommandListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/RasmolCommandListener.java @@ -41,16 +41,16 @@ public class RasmolCommandListener implements ActionListener, MouseListener { - JTextField textfield; - JmolPanel jmolPanel; + final JTextField textfield; + final JmolPanel jmolPanel; - List history; + final List history; int historyPosition; public RasmolCommandListener(JmolPanel panel, JTextField field){ textfield = field; jmolPanel = panel; - history = new ArrayList(); + history = new ArrayList<>(); historyPosition = -2; // -2 = history = empty; } @@ -69,7 +69,7 @@ public void actionPerformed(ActionEvent event) { // now comes history part: // no need for history: - if ( cmd.equals("")) return; + if (cmd.isEmpty()) return; // check last command in history // if equivalent, don't add, @@ -95,18 +95,20 @@ public void mouseClicked(MouseEvent e){ textfield.setText(""); textfield.repaint(); } - }; + } @Override - public void mouseExited(MouseEvent e){}; + public void mouseExited(MouseEvent e){} + @Override - public void mouseReleased(MouseEvent e){}; + public void mouseReleased(MouseEvent e){} + @Override - public void mousePressed(MouseEvent e){}; + public void mousePressed(MouseEvent e){} @Override - public void mouseEntered(MouseEvent e){}; + public void mouseEntered(MouseEvent e){} /** takes care of the cursor up/down keys. triggers copying of stored * commands into the current textfield diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/StructureAlignmentJmol.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/StructureAlignmentJmol.java index 1b0ee9a6f8..a24d560901 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/StructureAlignmentJmol.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/StructureAlignmentJmol.java @@ -23,7 +23,9 @@ */ package org.biojava.nbio.structure.align.gui.jmol; -import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.Atom; +import org.biojava.nbio.structure.PDBHeader; +import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.align.gui.AlignmentGui; import org.biojava.nbio.structure.align.gui.DisplayAFP; import org.biojava.nbio.structure.align.gui.MenuCreator; @@ -40,9 +42,11 @@ import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; - import java.awt.*; -import java.awt.event.*; +import java.awt.event.ActionEvent; +import java.awt.event.ItemEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; @@ -200,14 +204,10 @@ public void windowClosing(WindowEvent e) { JButton resetDisplay = new JButton("Reset Display"); - resetDisplay.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - System.out.println("reset!!"); - jmolPanel.executeCmd("restore STATE state_1"); + resetDisplay.addActionListener(e -> { + System.out.println("reset!!"); + jmolPanel.executeCmd("restore STATE state_1"); - } }); hBox2.add(resetDisplay); @@ -216,21 +216,17 @@ public void actionPerformed(ActionEvent e) { JCheckBox toggleSelection = new JCheckBox("Show Selection"); toggleSelection.addItemListener( - new ItemListener() { - - @Override - public void itemStateChanged(ItemEvent e) { - boolean showSelection = (e.getStateChange() == ItemEvent.SELECTED); - - if (showSelection){ - jmolPanel.executeCmd("set display selected"); - } else { - jmolPanel.executeCmd("set display off"); - } + e -> { + boolean showSelection = (e.getStateChange() == ItemEvent.SELECTED); + if (showSelection){ + jmolPanel.executeCmd("set display selected"); + } else { + jmolPanel.executeCmd("set display off"); } + } - ); + ); @@ -256,13 +252,13 @@ public void itemStateChanged(ItemEvent e) { zoomSlider.setMajorTickSpacing(100); zoomSlider.setPaintTicks(true); - Hashtable labelTable = new Hashtable(); - labelTable.put(new Integer(0),new JLabel("0%")); - labelTable.put(new Integer(100),new JLabel("100%")); - labelTable.put(new Integer(200),new JLabel("200%")); - labelTable.put(new Integer(300),new JLabel("300%")); - labelTable.put(new Integer(400),new JLabel("400%")); - labelTable.put(new Integer(500),new JLabel("500%")); + Hashtable labelTable = new Hashtable<>(); + labelTable.put(0,new JLabel("0%")); + labelTable.put(100,new JLabel("100%")); + labelTable.put(200,new JLabel("200%")); + labelTable.put(300,new JLabel("300%")); + labelTable.put(400,new JLabel("400%")); + labelTable.put(500,new JLabel("500%")); zoomSlider.setLabelTable(labelTable); zoomSlider.setPaintLabels(true); @@ -273,21 +269,17 @@ public void itemStateChanged(ItemEvent e) { // SPIN CHECKBOX JCheckBox toggleSpin = new JCheckBox("Spin"); toggleSpin.addItemListener( - new ItemListener() { - - @Override - public void itemStateChanged(ItemEvent e) { - boolean spinOn = (e.getStateChange() == ItemEvent.SELECTED); - - if (spinOn){ - jmolPanel.executeCmd("spin ON"); - } else { - jmolPanel.executeCmd("spin OFF"); - } + e -> { + boolean spinOn = (e.getStateChange() == ItemEvent.SELECTED); + if (spinOn){ + jmolPanel.executeCmd("spin ON"); + } else { + jmolPanel.executeCmd("spin OFF"); } + } - ); + ); hBox3.add(toggleSpin); @@ -337,7 +329,7 @@ public void itemStateChanged(ItemEvent e) { @Override protected void initCoords() { - try { +// try { if (ca1 == null || ca2 == null) { if (structure != null) setStructure(structure); @@ -354,9 +346,9 @@ protected void initCoords() { header.setTitle(title); artificial.setPDBHeader(header); setStructure(artificial); - } catch (StructureException e) { - e.printStackTrace(); - } +// } catch (StructureException e) { +// e.printStackTrace(); +// } } @Override @@ -370,47 +362,55 @@ public void destroy() { @Override public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); - if (cmd.equals(MenuCreator.TEXT_ONLY)) { - if (afpChain == null) { - System.err.println("Currently not viewing an alignment!"); - return; - } - // Clone the AFPChain to not override the FatCat numbers in alnsymb - AFPChain textAFP = (AFPChain) afpChain.clone(); - String result = AfpChainWriter.toWebSiteDisplay(textAFP, ca1, ca2); + switch (cmd) { + case MenuCreator.TEXT_ONLY: { + if (afpChain == null) { + System.err.println("Currently not viewing an alignment!"); + return; + } + // Clone the AFPChain to not override the FatCat numbers in alnsymb + AFPChain textAFP = (AFPChain) afpChain.clone(); + String result = AfpChainWriter.toWebSiteDisplay(textAFP, ca1, ca2); - DisplayAFP.showAlignmentImage(afpChain, result); + DisplayAFP.showAlignmentImage(afpChain, result); - } else if (cmd.equals(MenuCreator.PAIRS_ONLY)) { - if (afpChain == null) { - System.err.println("Currently not viewing an alignment!"); - return; + break; } - String result = AfpChainWriter.toAlignedPairs(afpChain, ca1, ca2); + case MenuCreator.PAIRS_ONLY: { + if (afpChain == null) { + System.err.println("Currently not viewing an alignment!"); + return; + } + String result = AfpChainWriter.toAlignedPairs(afpChain, ca1, ca2); - DisplayAFP.showAlignmentImage(afpChain, result); + DisplayAFP.showAlignmentImage(afpChain, result); - } else if (cmd.equals(MenuCreator.ALIGNMENT_PANEL)) { - if (afpChain == null) { - System.err.println("Currently not viewing an alignment!"); - return; - } - try { - DisplayAFP.showAlignmentPanel(afpChain, ca1, ca2, this); - } catch (Exception e1) { - e1.printStackTrace(); - return; + break; } + case MenuCreator.ALIGNMENT_PANEL: + if (afpChain == null) { + System.err.println("Currently not viewing an alignment!"); + return; + } + try { + DisplayAFP.showAlignmentPanel(afpChain, ca1, ca2, this); + } catch (Exception e1) { + e1.printStackTrace(); + return; + } - } else if (cmd.equals(MenuCreator.FATCAT_TEXT)) { - if (afpChain == null) { - System.err.println("Currently not viewing an alignment!"); - return; + break; + case MenuCreator.FATCAT_TEXT: { + if (afpChain == null) { + System.err.println("Currently not viewing an alignment!"); + return; + } + String result = afpChain.toFatcat(ca1, ca2); + result += AFPChain.newline; + result += afpChain.toRotMat(); + DisplayAFP.showAlignmentImage(afpChain, result); + break; } - String result = afpChain.toFatcat(ca1, ca2); - result += AFPChain.newline; - result += afpChain.toRotMat(); - DisplayAFP.showAlignmentImage(afpChain, result); } } @@ -420,11 +420,11 @@ public static String getJmolString(AFPChain afpChain, Atom[] ca1, Atom[] ca2) { return getMultiBlockJmolScript(afpChain, ca1, ca2); } - StringBuffer j = new StringBuffer(); + StringBuilder j = new StringBuilder(); j.append(DEFAULT_SCRIPT); // now color the equivalent residues ... - StringBuffer sel = new StringBuffer(); + StringBuilder sel = new StringBuilder(); List pdb1 = DisplayAFP.getPDBresnum(0, afpChain, ca1); sel.append("select "); int pos = 0; @@ -465,7 +465,7 @@ public static String getJmolString(AFPChain afpChain, Atom[] ca1, Atom[] ca2) { // Rasmol // and now select the aligned residues... - StringBuffer buf = new StringBuffer("select "); + StringBuilder buf = new StringBuilder("select "); int count = 0; for (String res : pdb1) { if (count > 0) @@ -559,8 +559,8 @@ private static void printJmolScript4Block(Atom[] ca1, Atom[] ca2, int blockNum, c1 = ColorUtils.getIntermediate(ColorUtils.orange, end1, blockNum, bk); c2 = ColorUtils.getIntermediate(ColorUtils.cyan, end2, blockNum, bk); - List pdb1 = new ArrayList(); - List pdb2 = new ArrayList(); + List pdb1 = new ArrayList<>(); + List pdb2 = new ArrayList<>(); for (int i = 0; i < optLen[bk]; i++) { /// int pos1 = optAln[bk][0][i]; @@ -580,7 +580,7 @@ private static void printJmolScript4Block(Atom[] ca1, Atom[] ca2, int blockNum, count++; } - buf.append("; backbone 0.6 ; color [" + c1.getRed() + "," + c1.getGreen() + "," + c1.getBlue() + "]; select "); + buf.append("; backbone 0.6 ; color [").append(c1.getRed()).append(",").append(c1.getGreen()).append(",").append(c1.getBlue()).append("]; select "); count = 0; for (String res : pdb2) { @@ -593,7 +593,7 @@ private static void printJmolScript4Block(Atom[] ca1, Atom[] ca2, int blockNum, } // buf.append("; set display selected;"); - buf.append("; backbone 0.6 ; color [" + c2.getRed() + "," + c2.getGreen() + "," + c2.getBlue() + "];"); + buf.append("; backbone 0.6 ; color [").append(c2.getRed()).append(",").append(c2.getGreen()).append(",").append(c2.getBlue()).append("];"); // now color this block: jmol.append(buf); @@ -622,7 +622,7 @@ public List getDistanceMatrices() { public void stateChanged(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); if (!source.getValueIsAdjusting()) { - int zoomValue = (int) source.getValue(); + int zoomValue = source.getValue(); jmolPanel.executeCmd("zoom " + zoomValue); } } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/AligUIManager.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/AligUIManager.java index 7767b948fa..a86fd15062 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/AligUIManager.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/AligUIManager.java @@ -25,7 +25,6 @@ package org.biojava.nbio.structure.align.webstart; import javax.swing.*; -import javax.swing.UIManager.LookAndFeelInfo; public class AligUIManager @@ -43,13 +42,13 @@ public static void setLookAndFeel(){ } //System.out.println("Installed Look And Feels:"); - LookAndFeelInfo[] feels = UIManager.getInstalledLookAndFeels(); + //LookAndFeelInfo[] feels = UIManager.getInstalledLookAndFeels(); - if ( feels != null){ + //if ( feels != null){ //for ( LookAndFeelInfo info: feels){ //System.out.println(info.getName() + " " + info.getClassName()); // } - } + //} //System.out.println("Auxiliary Look And Feels:"); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/ConfigXMLHandler.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/ConfigXMLHandler.java index 78d43fe862..b0659c861c 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/ConfigXMLHandler.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/ConfigXMLHandler.java @@ -35,7 +35,7 @@ */ public class ConfigXMLHandler extends DefaultHandler { - UserConfiguration config ; + final UserConfiguration config ; /** * diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/JNLPProxy.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/JNLPProxy.java index 99e8a6eb3e..8b070a17dd 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/JNLPProxy.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/JNLPProxy.java @@ -78,12 +78,12 @@ public static boolean showDocument ( URL url ) try { Method method = basicServiceClass.getMethod ( - "showDocument", new Class [ ] { URL.class } ); + "showDocument", URL.class); Boolean resultBoolean = ( Boolean ) method.invoke ( basicServiceObject, new Object [ ] { url } ); - boolean success = resultBoolean.booleanValue ( ); + boolean success = resultBoolean; if ( ! success ) System.out.println("invocation of method failed!"); return success; @@ -109,10 +109,10 @@ private static Object getBasicServiceObject ( ) = Class.forName ( "javax.jnlp.ServiceManager" ); Method lookupMethod = serviceManagerClass.getMethod ( "lookup", - new Class [ ] { String.class } ); + String.class); return lookupMethod.invoke ( - null, new Object [ ] { "javax.jnlp.BasicService" } ); + null, "javax.jnlp.BasicService"); } catch ( Exception ex ) { diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/WebStartMain.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/WebStartMain.java index 27c0ceb322..eab0bd83c0 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/WebStartMain.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/WebStartMain.java @@ -41,7 +41,6 @@ import org.biojava.nbio.structure.align.util.UserConfiguration; import javax.swing.*; - import java.io.File; public class WebStartMain @@ -73,13 +72,7 @@ public static void main(String[] args){ // we did not get enough arguments, show the general user interface... - javax.swing.SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - - AlignmentGui.getInstance(); - } - }); + javax.swing.SwingUtilities.invokeLater(AlignmentGui::getInstance); return; @@ -88,12 +81,7 @@ public void run() { else if ( args.length < 3){ //String arg0 = args[0]; - javax.swing.SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - AlignmentGui.getInstance(); - } - }); + javax.swing.SwingUtilities.invokeLater(AlignmentGui::getInstance); return; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/BiojavaJmol.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/BiojavaJmol.java index eeffe5b749..d2542e9240 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/BiojavaJmol.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/BiojavaJmol.java @@ -32,7 +32,9 @@ import javax.swing.*; import java.awt.*; -import java.awt.event.*; +import java.awt.event.ItemEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; /** A class that provides a simple GUI for Jmol @@ -51,8 +53,8 @@ public class BiojavaJmol { Structure structure; - JmolPanel jmolPanel; - JFrame frame ; + final JmolPanel jmolPanel; + final JFrame frame ; public static void main(String[] args){ @@ -149,35 +151,27 @@ public void windowClosing(WindowEvent e) { JButton resetDisplay = new JButton("Reset Display"); - resetDisplay.addActionListener(new ActionListener() { + resetDisplay.addActionListener(e -> { + System.out.println("reset!!"); + jmolPanel.executeCmd("restore STATE state_1"); - @Override - public void actionPerformed(ActionEvent e) { - System.out.println("reset!!"); - jmolPanel.executeCmd("restore STATE state_1"); - - } }); hBox2.add(resetDisplay); hBox2.add(Box.createGlue()); JCheckBox toggleSelection = new JCheckBox("Show Selection"); toggleSelection.addItemListener( - new ItemListener() { - - @Override - public void itemStateChanged(ItemEvent e) { - boolean showSelection = (e.getStateChange() == ItemEvent.SELECTED); + e -> { + boolean showSelection = (e.getStateChange() == ItemEvent.SELECTED); - if (showSelection){ - jmolPanel.executeCmd("set display selected"); - } else { - jmolPanel.executeCmd("set display off"); - } + if (showSelection){ + jmolPanel.executeCmd("set display selected"); + } else { + jmolPanel.executeCmd("set display off"); + } - } } - ); + ); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/JMatrixPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/JMatrixPanel.java index 4f2fbd160b..3f6a889ce5 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/JMatrixPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/JMatrixPanel.java @@ -63,7 +63,7 @@ public class JMatrixPanel extends JPanel{ int selectedAlignmentPos; final static BasicStroke stroke = new BasicStroke(2.0f); - StrucAligParameters params; + final StrucAligParameters params; public JMatrixPanel(){ scale = 1; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/JmolViewerImpl.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/JmolViewerImpl.java index e361a156c1..e7763c3269 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/JmolViewerImpl.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/JmolViewerImpl.java @@ -42,7 +42,7 @@ public class JmolViewerImpl implements StructureViewer { public static final String smartAdapter = "org.jmol.adapter.smarter.SmarterJmolAdapter"; Structure structure; JmolPanel jmolPanel; - JFrame frame; + final JFrame frame; public JmolViewerImpl() { @@ -203,10 +203,10 @@ static class JmolPanel extends JPanel { adapterC = Class.forName(adapter); smartAdapterC = Class.forName(smartAdapter); - Method m = viewerC.getMethod("allocateSimpleViewer", new Class[]{Component.class, adapterC}); + Method m = viewerC.getMethod("allocateSimpleViewer", Component.class, adapterC); - Constructor constructor = smartAdapterC.getConstructor(new Class[]{}); - adapterO = constructor.newInstance(new Object[]{}); + Constructor constructor = smartAdapterC.getConstructor(); + adapterO = constructor.newInstance(); //viewerC = JmolSimpleViewer.allocateSimpleViewer(this, adapter); viewerO = m.invoke(viewerC, this, adapterO); @@ -214,20 +214,12 @@ static class JmolPanel extends JPanel { evalString = viewerC.getMethod("evalString", String.class); renderScreenImage = viewerC.getMethod("renderScreenImage", - new Class[]{Graphics.class, Dimension.class, Rectangle.class}); + Graphics.class, Dimension.class, Rectangle.class); - openStringInline = viewerC.getMethod("openStringInline", new Class[]{String.class}); + openStringInline = viewerC.getMethod("openStringInline", String.class); - } catch (InstantiationException ex) { + } catch (InstantiationException | NoSuchMethodException | InvocationTargetException | IllegalArgumentException | IllegalAccessException ex) { logger.error("Exception caught", ex); - } catch (IllegalAccessException ex) { - logger.error("Exception caught", ex); - } catch (IllegalArgumentException ex) { - logger.error("Exception caught", ex); - } catch (InvocationTargetException ex) { - logger.error("Exception caught", ex); - } catch (NoSuchMethodException e) { - logger.error("Exception caught", e); } evalString("set scriptQueue on;"); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/ScaleableMatrixPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/ScaleableMatrixPanel.java index b2c6917559..cc33a5b106 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/ScaleableMatrixPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/ScaleableMatrixPanel.java @@ -63,12 +63,12 @@ public class ScaleableMatrixPanel */ private static final long serialVersionUID = -8082261434322968652L; - protected JMatrixPanel mPanel; - protected JSlider slider; - protected JScrollPane scroll; - protected JComboBox coloring; + protected final JMatrixPanel mPanel; + protected final JSlider slider; + protected final JScrollPane scroll; + protected final JComboBox coloring; - protected Map gradients; + protected final Map gradients; protected static final int SLIDER_STEPS = 8; // Number of minor ticks per unit scaled @@ -198,7 +198,7 @@ public ScaleableMatrixPanel(){ protected static Map createGradients() { - SortedMap gradients = new TreeMap(); + SortedMap gradients = new TreeMap<>(); int i = 0; //prepend number, since sorted alphabetically ColorSpace hsv = HSVColorSpace.getHSVColorSpace(); @@ -379,9 +379,10 @@ protected class GradientRenderer extends JPanel implements ListCellRenderer { private static final long serialVersionUID = -2000575579184232365L; - private int min,max; - JLabel title; - JPanel gradientContainer; + private final int min; + private final int max; + final JLabel title; + final JPanel gradientContainer; public GradientRenderer() { this.setPreferredSize(new Dimension(100,25)); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/Selection.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/Selection.java index 902b172b2f..9247940df6 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/Selection.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/Selection.java @@ -27,8 +27,8 @@ public interface Selection { - public void clear(); - public List getSelection(); - public void setSelection(List selection); + void clear(); + List getSelection(); + void setSelection(List selection); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/SequenceDisplay.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/SequenceDisplay.java index dd4dc97cc4..22f6781502 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/SequenceDisplay.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/SequenceDisplay.java @@ -57,11 +57,11 @@ public class SequenceDisplay extends JPanel implements ChangeListener { Structure structure2; AlternativeAlignment alig; StructurePairAligner structurePairAligner; - SequenceScalePanel panel1; - SequenceScalePanel panel2; + final SequenceScalePanel panel1; + final SequenceScalePanel panel2; - JSlider residueSizeSlider; - JLabel percentageDisplay; + final JSlider residueSizeSlider; + final JLabel percentageDisplay; int[] idx1; int[] idx2; @@ -73,15 +73,15 @@ public class SequenceDisplay extends JPanel implements ChangeListener { //private static final Logger logger = LoggerFactory.getLogger(SequenceDisplay.class); - List apos; + final List apos; float scale; - SequenceMouseListener mouseListener1; - SequenceMouseListener mouseListener2; + final SequenceMouseListener mouseListener1; + final SequenceMouseListener mouseListener2; - JLabel label1; - JLabel label2; + final JLabel label1; + final JLabel label2; public static void main(String[] args){ @@ -232,7 +232,7 @@ public SequenceDisplay(StructurePairAligner structurePairAligner){ this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS)); - apos = new ArrayList(); + apos = new ArrayList<>(); } public void clearListeners(){ @@ -451,9 +451,7 @@ private void updatePercentageDisplay(){ private int getMaxSequenceLength(){ int l1 = panel1.getChain().getAtomGroups(GroupType.AMINOACID).size(); int l2 = panel2.getChain().getAtomGroups(GroupType.AMINOACID).size(); - if ( l1 > l2) - return l1; - else return l2; + return Math.max(l1, l2); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/StructureViewer.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/StructureViewer.java index 43f608ef32..62d9369236 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/StructureViewer.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/StructureViewer.java @@ -26,35 +26,35 @@ public interface StructureViewer { - public void setStructure(Structure structure); - public void repaint(); - public void setSelection(Selection selection); - public Selection getSelection(); + void setStructure(Structure structure); + void repaint(); + void setSelection(Selection selection); + Selection getSelection(); /** Apply this color to the current Selection * * @param red */ - public void setColor(Color red); - public Color getColor(); + void setColor(Color red); + Color getColor(); /** Apply this style to the current selection * * @param wireframe renderstyle */ - public void setStyle(RenderStyle wireframe); + void setStyle(RenderStyle wireframe); /** Clear the current display * * */ - public void clear(); + void clear(); /** Set the Zoom level * * @param i */ - public void setZoom(int i); + void setZoom(int i); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/WrapLayout.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/WrapLayout.java index 7694632a9b..73ee69513a 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/WrapLayout.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/WrapLayout.java @@ -20,9 +20,8 @@ */ package org.biojava.nbio.structure.gui; +import javax.swing.*; import java.awt.*; -import javax.swing.JScrollPane; -import javax.swing.SwingUtilities; /** * FlowLayout subclass that fully supports wrapping of components. diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/events/AlignmentPositionListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/events/AlignmentPositionListener.java index 61ca8c5fd9..d955b67f3c 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/events/AlignmentPositionListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/events/AlignmentPositionListener.java @@ -25,11 +25,11 @@ public interface AlignmentPositionListener { - public void mouseOverPosition(AlignedPosition p); - public void positionSelected(AlignedPosition p); - public void toggleSelection(AlignedPosition p); - public void rangeSelected(AlignedPosition start , AlignedPosition end); - public void selectionLocked(); - public void selectionUnlocked(); + void mouseOverPosition(AlignedPosition p); + void positionSelected(AlignedPosition p); + void toggleSelection(AlignedPosition p); + void rangeSelected(AlignedPosition start, AlignedPosition end); + void selectionLocked(); + void selectionUnlocked(); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/events/JmolAlignedPositionListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/events/JmolAlignedPositionListener.java index 14937adea2..97f2cc3fc1 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/events/JmolAlignedPositionListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/events/JmolAlignedPositionListener.java @@ -33,10 +33,10 @@ public class JmolAlignedPositionListener implements AlignmentPositionListener{ - BiojavaJmol parent; + final BiojavaJmol parent; Atom[] ca1; Atom[] ca2; - StructurePairAligner structurePairAligner; + final StructurePairAligner structurePairAligner; public JmolAlignedPositionListener(BiojavaJmol parent, StructurePairAligner alig){ this.parent = parent; @@ -71,8 +71,8 @@ public void mouseOverPosition(AlignedPosition p) { return; } - String pdbpos1 =""; - String pdbpos2 = ""; + String pdbpos1; + String pdbpos2; if ( p1 >-1) { Atom a = ca1[p1]; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/AlternativeAlignmentFrame.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/AlternativeAlignmentFrame.java index 8dc672ed36..462c715bcf 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/AlternativeAlignmentFrame.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/AlternativeAlignmentFrame.java @@ -53,18 +53,18 @@ public class AlternativeAlignmentFrame extends JFrame{ - private static final long serialVersionUID=0l; + private static final long serialVersionUID= 0L; private static final Logger logger = LoggerFactory.getLogger(AlternativeAlignmentFrame.class); - private static String[] columnNames = new String[]{"#","eqr","score", "rms", "gaps","cluster", "show distance matrix","show alignment"}; + private static final String[] columnNames = new String[]{"#","eqr","score", "rms", "gaps","cluster", "show distance matrix","show alignment"}; AlternativeAlignment[] aligs; - JPanel panel; + final JPanel panel; - Structure structure1; - Structure structure2; + final Structure structure1; + final Structure structure2; StructurePairAligner structurePairAligner; public AlternativeAlignmentFrame(Structure s1, Structure s2) { @@ -126,12 +126,12 @@ private Object[][] getDataFromAligs(AlternativeAlignment[] aligs){ for ( int i=0;i< aligs.length;i++){ AlternativeAlignment alig = aligs[i]; - data[i][0] = new Integer(i+1); - data[i][1] = new Integer(alig.getEqr()); - data[i][2] = new Double(alig.getScore()); - data[i][3] = new Double(alig.getRmsd()); - data[i][4] = new Integer(alig.getGaps()); - data[i][5] = new Integer(alig.getCluster()); + data[i][0] = i + 1; + data[i][1] = alig.getEqr(); + data[i][2] = (double) alig.getScore(); + data[i][3] = alig.getRmsd(); + data[i][4] = alig.getGaps(); + data[i][5] = alig.getCluster(); JButton maxb = new JButton("Distance Matrix"); maxb.addMouseListener(new MatrixMouseListener(this,i)); @@ -322,8 +322,8 @@ private String[] createRasmolScripts(AlternativeAlignment alig){ } class MyButtonMouseListener implements MouseListener{ - AlternativeAlignmentFrame parent; - int pos; + final AlternativeAlignmentFrame parent; + final int pos; public MyButtonMouseListener(AlternativeAlignmentFrame parent, int position){ this.parent = parent; @@ -362,8 +362,8 @@ public void mouseExited(MouseEvent arg0) { } class MatrixMouseListener implements MouseListener{ - AlternativeAlignmentFrame parent; - int pos; + final AlternativeAlignmentFrame parent; + final int pos; public MatrixMouseListener( AlternativeAlignmentFrame parent, int position){ this.parent = parent; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JButtonTableCellRenderer.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JButtonTableCellRenderer.java index 586220728e..7466e76b89 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JButtonTableCellRenderer.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JButtonTableCellRenderer.java @@ -27,7 +27,7 @@ import java.awt.*; class JButtonTableCellRenderer implements TableCellRenderer { - private TableCellRenderer __defaultRenderer; + private final TableCellRenderer __defaultRenderer; public JButtonTableCellRenderer(TableCellRenderer renderer) { __defaultRenderer = renderer; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JTableDataButtonModel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JTableDataButtonModel.java index 561d130bbf..af19bbaf42 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JTableDataButtonModel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JTableDataButtonModel.java @@ -26,10 +26,10 @@ class JTableDataButtonModel extends AbstractTableModel { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; - Object[][] __rows; - String[] __columns; + final Object[][] __rows; + final String[] __columns; public JTableDataButtonModel(Object[][] rows, String[] columns){ __rows = rows; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JTableMouseButtonListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JTableMouseButtonListener.java index 5b8269a109..bb3bde4a7f 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JTableMouseButtonListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JTableMouseButtonListener.java @@ -30,7 +30,7 @@ class JTableMouseButtonListener implements MouseListener { - private JTable __table; + private final JTable __table; private void __forwardEventToButton(MouseEvent e) { TableColumnModel columnModel = __table.getColumnModel(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/MenuCreator.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/MenuCreator.java index ef945c5263..668dbc7503 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/MenuCreator.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/MenuCreator.java @@ -28,8 +28,6 @@ import javax.swing.*; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; @@ -56,32 +54,29 @@ public static JMenuBar initMenu(){ JMenuItem openI = new JMenuItem("Open"); openI.setMnemonic(KeyEvent.VK_O); - openI.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); - if ( cmd.equals("Open")){ - final JFileChooser fc = new JFileChooser(); + openI.addActionListener(e -> { + String cmd = e.getActionCommand(); + if ( cmd.equals("Open")){ + final JFileChooser fc = new JFileChooser(); // In response to a button click: - int returnVal = fc.showOpenDialog(null); - if ( returnVal == JFileChooser.APPROVE_OPTION) { - File file = fc.getSelectedFile(); - - PDBFileReader reader = new PDBFileReader(); - try { - Structure s = reader.getStructure(file); - BiojavaJmol jmol = new BiojavaJmol(); - jmol.setStructure(s); - jmol.evalString("select * ; color chain;"); - jmol.evalString("select *; spacefill off; wireframe off; backbone 0.4; "); - - } catch (Exception ex){ - ex.printStackTrace(); - } + int returnVal = fc.showOpenDialog(null); + if ( returnVal == JFileChooser.APPROVE_OPTION) { + File file1 = fc.getSelectedFile(); + + PDBFileReader reader = new PDBFileReader(); + try { + Structure s = reader.getStructure(file1); + BiojavaJmol jmol = new BiojavaJmol(); + jmol.setStructure(s); + jmol.evalString("select * ; color chain;"); + jmol.evalString("select *; spacefill off; wireframe off; backbone 0.4; "); + + } catch (Exception ex){ + ex.printStackTrace(); + } - } } } }); @@ -89,15 +84,11 @@ public void actionPerformed(ActionEvent e) { JMenuItem exitI = new JMenuItem("Exit"); exitI.setMnemonic(KeyEvent.VK_X); - exitI.addActionListener(new ActionListener(){ - - @Override - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); + exitI.addActionListener(e -> { + String cmd = e.getActionCommand(); - if ( cmd.equals("Exit")){ - System.exit(0); - } + if ( cmd.equals("Exit")){ + System.exit(0); } }); @@ -106,14 +97,11 @@ public void actionPerformed(ActionEvent e) { JMenu align = new JMenu("Align"); JMenuItem pairI = new JMenuItem("2 protein structures"); - pairI.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); + pairI.addActionListener(e -> { + String cmd = e.getActionCommand(); - if ( cmd.equals("2 protein structures")){ - MenuCreator.showPairDialog(); - } + if ( cmd.equals("2 protein structures")){ + MenuCreator.showPairDialog(); } }); @@ -123,15 +111,11 @@ public void actionPerformed(ActionEvent e) { JMenu about = new JMenu("About"); JMenuItem aboutI = new JMenuItem("PDBview"); - aboutI.addActionListener(new ActionListener(){ - - @Override - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); + aboutI.addActionListener(e -> { + String cmd = e.getActionCommand(); - if ( cmd.equals("PDBview")){ - MenuCreator.showAboutDialog(); - } + if ( cmd.equals("PDBview")){ + MenuCreator.showAboutDialog(); } }); @@ -177,17 +161,14 @@ private static void showAboutDialog(){ JButton close = new JButton("Close"); - close.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { - Object source = event.getSource(); + close.addActionListener(event -> { + Object source = event.getSource(); - JButton but = (JButton)source; - Container parent = but.getParent().getParent().getParent().getParent().getParent().getParent() ; + JButton but = (JButton)source; + Container parent = but.getParent().getParent().getParent().getParent().getParent().getParent() ; - JDialog dia = (JDialog) parent; - dia.dispose(); - } + JDialog dia = (JDialog) parent; + dia.dispose(); }); Box hBoxb = Box.createHorizontalBox(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBDirPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBDirPanel.java index 7db9f67424..67663657ee 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBDirPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBDirPanel.java @@ -52,12 +52,12 @@ public class PDBDirPanel */ private static final long serialVersionUID = -5682120627824627408L; - boolean debug = true; - JTextField pdbDir; - JTextField f1; - JTextField f2; - JTextField c1; - JTextField c2; + final boolean debug = true; + final JTextField pdbDir; + final JTextField f1; + final JTextField f2; + final JTextField c1; + final JTextField c2; private static final Logger logger = LoggerFactory.getLogger(StructurePairSelector.class); @@ -220,12 +220,12 @@ private JPanel getPDBFilePanel(int pos ,JTextField f, JTextField c){ class ChooseDirAction extends AbstractAction{ - JTextField textField; + final JTextField textField; public ChooseDirAction (JTextField textField){ super("Choose"); this.textField = textField; } - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBServerPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBServerPanel.java index 22d0157021..6860f8e5c2 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBServerPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBServerPanel.java @@ -50,12 +50,12 @@ public class PDBServerPanel */ private static final long serialVersionUID = -5682120627824627408L; - boolean debug = true; + final boolean debug = true; JTextField pdbDir; - JTextField f1; - JTextField f2; - JTextField c1; - JTextField c2; + final JTextField f1; + final JTextField f2; + final JTextField c1; + final JTextField c2; private static final Logger logger = LoggerFactory.getLogger(PDBServerPanel.class); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBUploadPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBUploadPanel.java index 2c542f0797..35f12703d3 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBUploadPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBUploadPanel.java @@ -59,12 +59,12 @@ public class PDBUploadPanel - private JComboBox fileType ; + private final JComboBox fileType ; - JTextField filePath1; - JTextField filePath2; - JTextField chain1; - JTextField chain2; + final JTextField filePath1; + final JTextField filePath2; + final JTextField chain1; + final JTextField chain2; public static JComboBox getFileFormatSelect(){ JComboBox fileType = new JComboBox(); @@ -129,7 +129,7 @@ public Structure getStructure2() throws StructureException{ private Structure getStructure(JTextField filePath,JTextField chainId) throws StructureException{ //PDBFileReader reader = new PDBFileReader(); - StructureIOFile reader = null; + StructureIOFile reader; String fileFormat = (String)fileType.getSelectedItem(); if ( fileFormat.equals(UserConfiguration.PDB_FORMAT)){ reader = new PDBFileReader(); @@ -141,7 +141,7 @@ private Structure getStructure(JTextField filePath,JTextField chainId) throws St String path = filePath.getText(); File f = new File(path); - Structure s = null; + Structure s; try { s = reader.getStructure(f); } catch (IOException e){ @@ -157,7 +157,7 @@ private Structure getStructure(JTextField filePath,JTextField chainId) throws St URL u ; - if ( chainId.getText() == null || chainId.getText().equals("")){ + if ( chainId.getText() == null || chainId.getText().isEmpty()){ u = f.toURI().toURL(); } else { @@ -201,12 +201,12 @@ private JPanel getLocalFilePanel(int pos ,JTextField filePath, JTextField chain class ChooseAction extends AbstractAction{ - JTextField textField; + final JTextField textField; public ChooseAction (JTextField textField){ super("Choose"); this.textField = textField; } - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/ScopInstallationInstance.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/ScopInstallationInstance.java index f76fd5ff67..566c0ac33d 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/ScopInstallationInstance.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/ScopInstallationInstance.java @@ -33,8 +33,8 @@ public class ScopInstallationInstance { - static ScopInstallationInstance me = new ScopInstallationInstance(); - ScopDatabase install; + static final ScopInstallationInstance me = new ScopInstallationInstance(); + final ScopDatabase install; private ScopInstallationInstance(){ UserConfiguration config = WebStartMain.getWebStartConfig(); String cacheLocation = config.getPdbFilePath(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/ScopSelectPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/ScopSelectPanel.java index a6571483a6..2ce7594388 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/ScopSelectPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/ScopSelectPanel.java @@ -25,7 +25,6 @@ package org.biojava.nbio.structure.gui.util; import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.gui.autosuggest.AutoSuggestProvider; import org.biojava.nbio.structure.align.gui.autosuggest.JAutoSuggest; import org.biojava.nbio.structure.align.gui.autosuggest.SCOPAutoSuggestProvider; @@ -47,8 +46,8 @@ public class ScopSelectPanel * */ private static final long serialVersionUID = 757947454156959178L; - JAutoSuggest dom1; - JAutoSuggest dom2; + final JAutoSuggest dom1; + final JAutoSuggest dom2; //private static final Logger logger = LoggerFactory.getLogger(ScopSelectPanel.class); @@ -113,22 +112,20 @@ private Box getDomainPanel(int pos ,JTextField f){ } @Override - public Structure getStructure1() throws StructureException - { + public Structure getStructure1() { String scop1 = dom1.getText(); return getStructure(scop1); } @Override - public Structure getStructure2() throws StructureException - { + public Structure getStructure2() { return getStructure(dom2.getText()); } - private Structure getStructure(String domainID) throws StructureException{ + private Structure getStructure(String domainID) { //PDBFileReader reader = new PDBFileReader(); - if ( domainID == null || domainID.equals("")) + if ( domainID == null || domainID.isEmpty()) return null; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SelectMultiplePanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SelectMultiplePanel.java index ae8d859951..254d26369e 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SelectMultiplePanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SelectMultiplePanel.java @@ -23,24 +23,18 @@ */ package org.biojava.nbio.structure.gui.util; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.Box; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; - import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIdentifier; import org.biojava.nbio.structure.align.client.StructureName; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.align.util.UserConfiguration; import org.biojava.nbio.structure.align.webstart.WebStartMain; +import javax.swing.*; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; + /** * A Text Panel that allows the user to specify multiple structure * identifiers, space separated. @@ -53,7 +47,7 @@ public class SelectMultiplePanel extends JPanel { private static final long serialVersionUID = 757947454156959178L; - JTextField input; + final JTextField input; public SelectMultiplePanel(){ this(true); @@ -88,9 +82,9 @@ private Box getDomainPanel(JTextField f){ return hBox; } - public List getStructures() throws StructureException { + public List getStructures() { - List structures = new ArrayList(); + List structures = new ArrayList<>(); for (StructureIdentifier name:getNames()){ structures.add(getStructure(name)); @@ -100,7 +94,7 @@ public List getStructures() throws StructureException { public List getNames() { - List names = new ArrayList(); + List names = new ArrayList<>(); String raw = input.getText().trim(); String[] split = raw.split(" "); @@ -111,7 +105,7 @@ public List getNames() { return names; } - private Structure getStructure(StructureIdentifier name) throws StructureException{ + private Structure getStructure(StructureIdentifier name) { UserConfiguration config = WebStartMain.getWebStartConfig(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceMouseListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceMouseListener.java index e10331b9d5..09b3ed03fd 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceMouseListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceMouseListener.java @@ -50,7 +50,7 @@ public class SequenceMouseListener implements { - boolean selectionLocked; + final boolean selectionLocked; boolean dragging; int selectionStart; @@ -61,13 +61,13 @@ public class SequenceMouseListener implements int chainLength; - CoordManager coordManager; + final CoordManager coordManager; //private static final Logger logger = LoggerFactory.getLogger(SequenceMouseListener.class); - SequenceDisplay parent; + final SequenceDisplay parent; - List alignmentPositionListeners; + final List alignmentPositionListeners; public SequenceMouseListener(SequenceDisplay parent) { super(); @@ -86,7 +86,7 @@ public SequenceMouseListener(SequenceDisplay parent) { coordManager = new CoordManager(); - alignmentPositionListeners = new ArrayList(); + alignmentPositionListeners = new ArrayList<>(); //renderer.getLayeredPane().addMouseListener(popupFrame); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceScalePanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceScalePanel.java index bc29425c07..c969683c1c 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceScalePanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceScalePanel.java @@ -39,7 +39,7 @@ public class SequenceScalePanel extends JPanel{ - static final long serialVersionUID = 7893248902423l; + static final long serialVersionUID = 7893248902423L; //private static final Logger logger = LoggerFactory.getLogger(SequenceScalePanel.class); @@ -105,7 +105,7 @@ public SequenceScalePanel(int position) { setPrefSize(); coordManager = new CoordManager(); - apos = new ArrayList(); + apos = new ArrayList<>(); } @@ -219,7 +219,7 @@ public void paintComponent(Graphics g){ setPaintDefaults(g2D); - int y = 1; + int y; // draw the scale @@ -378,7 +378,7 @@ protected void drawIdx(Graphics2D g2D, int y){ if ( scale <= 3) lineH = 8; - int i = startpos; + int i; // display the actual sequence!; @@ -446,7 +446,7 @@ protected int drawSequence(Graphics2D g2D, int y){ //g2D.setColor(SCALE_COLOR); - int i = startpos; + int i; // display the actual sequence!; for ( int gap = startpos ; gap < apos.size() ;gap++){ diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/StructurePairSelector.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/StructurePairSelector.java index 1ced9fe59f..74a9352861 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/StructurePairSelector.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/StructurePairSelector.java @@ -21,11 +21,11 @@ */ package org.biojava.nbio.structure.gui.util; -import java.io.IOException; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; +import java.io.IOException; + /** To be implemented by JPanels that are part of the GUI to trigger structure aligmnents. * * @@ -35,7 +35,7 @@ */ public interface StructurePairSelector { - public Structure getStructure1() throws StructureException, IOException; - public Structure getStructure2() throws StructureException, IOException; + Structure getStructure1() throws StructureException, IOException; + Structure getStructure2() throws StructureException, IOException; } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ColorInterpolator.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ColorInterpolator.java index 13aedf3b8c..33f04c1240 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ColorInterpolator.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ColorInterpolator.java @@ -36,5 +36,5 @@ public interface ColorInterpolator { * @return The color between a and b * @throws IllegalArgumentException if mixing is not between 0 and 1 */ - public Color interpolate(Color a, Color b, float mixing); + Color interpolate(Color a, Color b, float mixing); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ColorUtils.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ColorUtils.java index 0d253a054d..cfbedfdb17 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ColorUtils.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ColorUtils.java @@ -29,9 +29,9 @@ public class ColorUtils { - public static Color orange = Color.decode("#FFA500"); - public static Color cyan = Color.decode("#00FFFF"); - public static Color gold = Color.decode("#FFD700"); + public static final Color orange = Color.decode("#FFA500"); + public static final Color cyan = Color.decode("#00FFFF"); + public static final Color gold = Color.decode("#FFD700"); static final Color c1 = Color.decode("#228B22"); // green diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ContinuousColorMapper.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ContinuousColorMapper.java index 8ee0c4e2c9..e5442627f0 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ContinuousColorMapper.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ContinuousColorMapper.java @@ -37,5 +37,5 @@ public interface ContinuousColorMapper { * @param value The real to be mapped * @return The color corresponding to value */ - public Color getColor(double value); + Color getColor(double value); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ContinuousColorMapperTransform.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ContinuousColorMapperTransform.java index 5cd010b356..d8a884cc24 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ContinuousColorMapperTransform.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ContinuousColorMapperTransform.java @@ -36,7 +36,7 @@ */ public abstract class ContinuousColorMapperTransform implements ContinuousColorMapper { - protected ContinuousColorMapper mapper; + protected final ContinuousColorMapper mapper; /** * Creates a transform. diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/DefaultMatrixMapper.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/DefaultMatrixMapper.java index 3b9975d0c0..7b246173da 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/DefaultMatrixMapper.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/DefaultMatrixMapper.java @@ -48,7 +48,7 @@ public DefaultMatrixMapper(double scale, float saturation ) { */ @Override public Color getColor(double value) { - float hue = 1.0f; + float hue; hue = (float)(1-(value/scalevalue)); if (hue < 0) hue = 0; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/GradientMapper.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/GradientMapper.java index 4678d68707..f28c74d053 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/GradientMapper.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/GradientMapper.java @@ -51,7 +51,7 @@ public class GradientMapper implements ContinuousColorMapper, Map public static final int RAINBOW_GRADIENT = 4; public static final int RAINBOW_INTENSITY_GRADIENT = 5; - private NavigableMap mapping; + private final NavigableMap mapping; private ColorInterpolator interpolator; public GradientMapper() { @@ -61,7 +61,7 @@ public GradientMapper(Color negInf, Color posInf) { this(negInf,posInf,ColorSpace.getInstance(ColorSpace.CS_sRGB)); } public GradientMapper(Color negInf, Color posInf, ColorSpace cspace) { - mapping = new TreeMap(); + mapping = new TreeMap<>(); mapping.put(Double.NEGATIVE_INFINITY, negInf); mapping.put(Double.POSITIVE_INFINITY, posInf); interpolator = new LinearColorInterpolator(cspace); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/GradientPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/GradientPanel.java index 68690b58cb..7f88f732ca 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/GradientPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/GradientPanel.java @@ -26,8 +26,9 @@ public class GradientPanel extends JPanel { private static final long serialVersionUID = -6387922432121206731L; - private ContinuousColorMapper mapper; - private double min, max; + private final ContinuousColorMapper mapper; + private final double min; + private final double max; public GradientPanel(ContinuousColorMapper mapper, double min, double max) { diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/LinearColorInterpolator.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/LinearColorInterpolator.java index 9522ec7a15..c98b5812e3 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/LinearColorInterpolator.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/LinearColorInterpolator.java @@ -23,6 +23,7 @@ import java.awt.*; import java.awt.color.ColorSpace; +import java.util.Arrays; /** * @author Spencer Bliven @@ -156,8 +157,7 @@ public void setColorSpace(ColorSpace colorSpace, InterpolationDirection[] dir) { public void setColorSpace(ColorSpace colorSpace) { InterpolationDirection[] dir = new InterpolationDirection[colorSpace.getNumComponents()]; - for(int i=0;i> cyclicForm = axes.getRepeatsCyclicForm(a); - List repAtoms = new ArrayList(); + List repAtoms = new ArrayList<>(); for(List cycle : cyclicForm) { for(Integer repeat : cycle) { repAtoms.addAll(Arrays.asList(repeats.get(repeat))); @@ -247,7 +244,7 @@ public static String printSymmetryAxes(CeSymmResult symm,boolean allAxes) } script += rot.getJmolScript( - repAtoms.toArray(new Atom[repAtoms.size()]), id); + repAtoms.toArray(Atom.EmptyAtomArray), id); id++; } @@ -299,7 +296,7 @@ public static String printSymmetryGroup(CeSymmResult symm) */ public static String getSymmTitle(CeSymmResult result) { - StringBuffer buff = new StringBuffer(); + StringBuilder buff = new StringBuilder(); // Add algorithm name and version buff.append(result.getMultipleAlignment().getEnsemble() diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryGui.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryGui.java index 7568141b55..df8b5d4323 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryGui.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryGui.java @@ -20,22 +20,6 @@ */ package org.biojava.nbio.structure.symmetry.gui; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.io.IOException; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenuBar; -import javax.swing.JOptionPane; -import javax.swing.JProgressBar; -import javax.swing.JTabbedPane; - import org.biojava.nbio.structure.PassthroughIdentifier; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; @@ -53,6 +37,11 @@ import org.biojava.nbio.structure.symmetry.internal.CESymmParameters; import org.biojava.nbio.structure.symmetry.internal.CeSymm; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.io.IOException; + /** * A JFrame that allows to trigger a symmetry analysis, either from files * in a directory or after manual upload @@ -65,19 +54,19 @@ */ public class SymmetryGui extends JFrame { - private final static long serialVersionUID = 0l; + private final static long serialVersionUID = 0L; - private CESymmParameters params = new CESymmParameters(); + private final CESymmParameters params = new CESymmParameters(); private JButton abortB; - private SelectPDBPanel tab1 ; - private PDBUploadPanel tab2; - private ScopSelectPanel tab3; + private final SelectPDBPanel tab1 ; + private final PDBUploadPanel tab2; + private final ScopSelectPanel tab3; private Thread thread; private AlignmentCalculationRunnable alicalc; - private JTabbedPane masterPane; - private JTabbedPane tabPane; + private final JTabbedPane masterPane; + private final JTabbedPane tabPane; private JProgressBar progress; public static void main(String[] args){ @@ -159,7 +148,7 @@ private Box setupAlgorithm() { algorithmList.setSelectedIndex(0); Action paramAction = new AbstractAction("Parameters") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -188,7 +177,7 @@ private Box initButtons(){ progress.setVisible(false); Action action1 = new AbstractAction("Analyze") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -206,7 +195,7 @@ public void actionPerformed(ActionEvent evt) { JButton submitB = new JButton(action1); Action action3 = new AbstractAction("Abort") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -220,7 +209,7 @@ public void actionPerformed(ActionEvent evt) { abortB.setEnabled(false); Action action2 = new AbstractAction("Exit") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -302,10 +291,7 @@ private void calcAlignment() { progress.setIndeterminate(true); ProgressThreadDrawer drawer = new ProgressThreadDrawer(progress); drawer.start(); - } catch (StructureException e){ - JOptionPane.showMessageDialog(null, - "Could not align structures. Exception: " + e.getMessage()); - } catch (IOException e) { + } catch (StructureException | IOException e){ JOptionPane.showMessageDialog(null, "Could not align structures. Exception: " + e.getMessage()); } @@ -335,7 +321,7 @@ public CESymmParameters getParameters() { class ProgressThreadDrawer extends Thread { JProgressBar progress; - static int interval = 300; + static final int interval = 300; public ProgressThreadDrawer(JProgressBar progress) { this.progress = progress; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryListener.java index 1fdb882f7c..f14c6c69b1 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryListener.java @@ -20,9 +20,6 @@ */ package org.biojava.nbio.structure.symmetry.gui; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.gui.StructureAlignmentDisplay; @@ -33,6 +30,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + /** * Action Listener for the symmetry menu. Trigger various internal symmetry * specific analysis. @@ -43,8 +43,8 @@ */ public class SymmetryListener implements ActionListener { - private MultipleAlignmentJmol jmol; - private CeSymmResult symm; + private final MultipleAlignmentJmol jmol; + private final CeSymmResult symm; private static final Logger logger = LoggerFactory .getLogger(SymmetryListener.class); @@ -64,34 +64,41 @@ public void actionPerformed(ActionEvent ae) { logger.error("Currently not displaying a symmetry!"); try { - if (cmd.equals("Repeats Superposition")) { - MultipleAlignmentJmol j = SymmetryDisplay.displayRepeats(symm); - String s = SymmetryDisplay.printSymmetryAxes(symm, false); - j.evalString(s); - j.evalString("save STATE state_1"); - + switch (cmd) { + case "Repeats Superposition": { + MultipleAlignmentJmol j = SymmetryDisplay.displayRepeats(symm); + String s = SymmetryDisplay.printSymmetryAxes(symm, false); + j.evalString(s); + j.evalString("save STATE state_1"); - } else if (cmd.equals("Multiple Structure Alignment")) { - MultipleAlignmentJmol j = SymmetryDisplay.displayFull(symm); - String s = SymmetryDisplay.printSymmetryAxes(symm); - j.evalString(s); - j.evalString("save STATE state_1"); - } else if (cmd.equals("Optimal Self Alignment")) { - Atom[] cloned = StructureTools.cloneAtomArray(symm.getAtoms()); - AbstractAlignmentJmol jmol = StructureAlignmentDisplay.display( - symm.getSelfAlignment(), symm.getAtoms(), cloned); - RotationAxis axis = new RotationAxis(symm.getSelfAlignment()); - jmol.evalString(axis.getJmolScript(symm.getAtoms())); - jmol.setTitle(SymmetryDisplay.getSymmTitle(symm)); + break; + } + case "Multiple Structure Alignment": { + MultipleAlignmentJmol j = SymmetryDisplay.displayFull(symm); + String s = SymmetryDisplay.printSymmetryAxes(symm); + j.evalString(s); + j.evalString("save STATE state_1"); - } else if (cmd.equals("Show Symmetry Group")) { - String script = SymmetryDisplay.printSymmetryGroup(symm); - jmol.evalString(script); + break; + } + case "Optimal Self Alignment": { + Atom[] cloned = StructureTools.cloneAtomArray(symm.getAtoms()); + AbstractAlignmentJmol jmol = StructureAlignmentDisplay.display( + symm.getSelfAlignment(), symm.getAtoms(), cloned); + RotationAxis axis = new RotationAxis(symm.getSelfAlignment()); + jmol.evalString(axis.getJmolScript(symm.getAtoms())); + jmol.setTitle(SymmetryDisplay.getSymmTitle(symm)); - } else if (cmd.equals("Show Symmetry Axes")) { - String s = SymmetryDisplay.printSymmetryAxes(symm); - jmol.evalString(s); + break; + } + case "Show Symmetry Group": + jmol.evalString(SymmetryDisplay.printSymmetryGroup(symm)); + break; + case "Show Symmetry Axes": { + jmol.evalString(SymmetryDisplay.printSymmetryAxes(symm)); + break; + } } } catch (Exception e) { diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGenerator.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGenerator.java index dd2401b2c8..1aa07aa747 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGenerator.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGenerator.java @@ -27,7 +27,6 @@ import javax.vecmath.Color4f; import javax.vecmath.Matrix4d; import javax.vecmath.Tuple3d; - import java.util.List; import java.util.Map; import java.util.Map.Entry; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGeneratorH.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGeneratorH.java index 428635c78b..7b45bfe811 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGeneratorH.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGeneratorH.java @@ -28,10 +28,9 @@ import org.jcolorbrewer.ColorBrewer; import javax.vecmath.*; - import java.awt.*; -import java.util.*; import java.util.List; +import java.util.*; /** @@ -39,10 +38,10 @@ * */ public class JmolSymmetryScriptGeneratorH extends JmolSymmetryScriptGenerator { - private static double AXIS_SCALE_FACTOR = 1.2; - private static double SIDE_CHAIN_EXTENSION = 6.0; - private HelixAxisAligner helixAxisAligner = null; - private String name = ""; + private static final double AXIS_SCALE_FACTOR = 1.2; + private static final double SIDE_CHAIN_EXTENSION = 6.0; + private final HelixAxisAligner helixAxisAligner; + private final String name; private String defaultColoring = ""; private boolean onTheFly = false; @@ -416,16 +415,12 @@ public String colorBySubunit() { colors[half+i] = temp; } } - Map> colorMap = new HashMap>(); + Map> colorMap = new HashMap<>(); for (int i = 0; i < orbits.size(); i++) { for (Integer j: orbits.get(i)) { Color4f c = colors[i]; - List ids = colorMap.get(c); - if (ids == null) { - ids = new ArrayList(); - colorMap.put(c, ids); - } + List ids = colorMap.computeIfAbsent(c, k -> new ArrayList<>()); String id = getChainSpecification(modelNumbers, chainIds, j); ids.add(id); } @@ -448,15 +443,11 @@ public String colorBySequenceCluster() { int clusters = Collections.max(seqClusterIds) + 1; Color[] col = ColorBrewer.BrBG.getColorPalette(clusters); Color4f[] colors = ColorConverter.convertColor4f(col); - Map> colorMap = new HashMap>(); + Map> colorMap = new HashMap<>(); for (int i = 0; i < n; i++) { Color4f c = colors[seqClusterIds.get(i)]; - List ids = colorMap.get(c); - if (ids == null) { - ids = new ArrayList(); - colorMap.put(c, ids); - } + List ids = colorMap.computeIfAbsent(c, k -> new ArrayList<>()); String id = getChainSpecification(modelNumbers, chainIds, i); ids.add(id); @@ -481,7 +472,7 @@ public String colorBySymmetry() { List clusterIds = subunits.getClusterIds(); int clusterCount = Collections.max(clusterIds) + 1; - Map> colorMap = new HashMap>(); + Map> colorMap = new HashMap<>(); int maxLen = 0; for (List unit: units) { @@ -502,11 +493,7 @@ public String colorBySymmetry() { Color4f c = new Color4f(colors[count]); count++; c.scale(scale); - List ids = colorMap.get(c); - if (ids == null) { - ids = new ArrayList(); - colorMap.put(c, ids); - } + List ids = colorMap.computeIfAbsent(c, k -> new ArrayList<>()); String id = getChainSpecification(modelNumbers, chainIds, subunit); ids.add(id); } @@ -579,7 +566,7 @@ private List extendUnitCenters(List points) { // System.out.println("XZRadius: " + radius); - List ePoints = new ArrayList(points.size()); + List ePoints = new ArrayList<>(points.size()); for (Point3d p: points) { Point3d q = new Point3d(p); transformation.transform(q); @@ -597,7 +584,7 @@ private List interiorCenters(List points) { Matrix4d transformation = helixAxisAligner.getTransformation(); Matrix4d reversetransformation = helixAxisAligner.getReverseTransformation(); - List ePoints = new ArrayList(points.size()); + List ePoints = new ArrayList<>(points.size()); for (Point3d p: points) { Point3d q = new Point3d(p); transformation.transform(q); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGeneratorPointGroup.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGeneratorPointGroup.java index 1a4f8a7301..80123eab84 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGeneratorPointGroup.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGeneratorPointGroup.java @@ -24,32 +24,31 @@ package org.biojava.nbio.structure.symmetry.jmolScript; import org.biojava.nbio.structure.symmetry.axis.RotationAxisAligner; +import org.biojava.nbio.structure.symmetry.core.QuatSymmetrySubunits; import org.biojava.nbio.structure.symmetry.core.Rotation; import org.biojava.nbio.structure.symmetry.core.RotationGroup; -import org.biojava.nbio.structure.symmetry.core.QuatSymmetrySubunits; import org.biojava.nbio.structure.symmetry.geometry.Polyhedron; import org.jcolorbrewer.ColorBrewer; import javax.vecmath.*; - import java.awt.*; -import java.util.*; import java.util.List; +import java.util.*; /** * @author Peter * */ public abstract class JmolSymmetryScriptGeneratorPointGroup extends JmolSymmetryScriptGenerator { - private static String N_FOLD_AXIS_COLOR = "red"; - private static String TWO_FOLD_AXIS_COLOR = "deepskyblue"; - private static String THREE_FOLD_AXIS_COLOR = "lime"; - private static double AXIS_SCALE_FACTOR = 1.2; + private static final String N_FOLD_AXIS_COLOR = "red"; + private static final String TWO_FOLD_AXIS_COLOR = "deepskyblue"; + private static final String THREE_FOLD_AXIS_COLOR = "lime"; + private static final double AXIS_SCALE_FACTOR = 1.2; - private RotationAxisAligner rotationAxisAligner = null; - private RotationGroup rotationGroup = null; + private RotationAxisAligner rotationAxisAligner; + private RotationGroup rotationGroup; private Polyhedron polyhedron = null; - private String name = ""; + private final String name; private String defaultColoring = ""; private boolean onTheFly = true; @@ -298,15 +297,14 @@ public String colorBySubunit() { List> orbits = rotationAxisAligner.getOrbits(); int fold = rotationGroup.getRotation(0).getFold(); - Color[] col = null; - Color4f[] colors = null; + Color[] col; + Color4f[] colors; if (fold > 1) { col = ColorBrewer.Spectral.getColorPalette(2*fold); - colors = ColorConverter.convertColor4f(col); } else { col = ColorBrewer.Spectral.getColorPalette(orbits.size()); - colors = ColorConverter.convertColor4f(col); } + colors = ColorConverter.convertColor4f(col); int half = colors.length/2; for (int i = 0; i < half; i++) { if (i % 2 != 0) { @@ -315,7 +313,7 @@ public String colorBySubunit() { colors[half+i] = temp; } } - Map> colorMap = new HashMap>(); + Map> colorMap = new HashMap<>(); for (int i = 0; i < orbits.size(); i++) { for (int j = 0; j < fold; j++) { @@ -330,11 +328,7 @@ public String colorBySubunit() { } int subunit = orbits.get(i).get(j); Color4f c = colors[colorIndex]; - List ids = colorMap.get(c); - if (ids == null) { - ids = new ArrayList(); - colorMap.put(c, ids); - } + List ids = colorMap.computeIfAbsent(c, k -> new ArrayList<>()); String id = getChainSpecification(modelNumbers, chainIds, subunit); ids.add(id); } @@ -356,15 +350,11 @@ public String colorBySequenceCluster() { int clusters = Collections.max(seqClusterIds) + 1; Color[] col = ColorBrewer.BrBG.getColorPalette(clusters); Color4f[] colors = ColorConverter.convertColor4f(col); - Map> colorMap = new HashMap>(); + Map> colorMap = new HashMap<>(); for (int i = 0; i < n; i++) { Color4f c = colors[seqClusterIds.get(i)]; - List ids = colorMap.get(c); - if (ids == null) { - ids = new ArrayList(); - colorMap.put(c, ids); - } + List ids = colorMap.computeIfAbsent(c, k -> new ArrayList<>()); String id = getChainSpecification(modelNumbers, chainIds, i); ids.add(id); @@ -388,7 +378,7 @@ public String colorBySymmetry() { int n = subunits.getSubunitCount(); int fold = rotationGroup.getRotation(0).getFold(); - Map> colorMap = new HashMap>(); + Map> colorMap = new HashMap<>(); // Simple Cn symmetry if (pointGroup.startsWith("C") && n == fold) { @@ -396,7 +386,7 @@ public String colorBySymmetry() { // complex cases } else if ((pointGroup.startsWith("D") && orbits.size() > 2) || pointGroup.equals("T")|| pointGroup.equals("O") || pointGroup.equals("I")) { - int nColor = 0; + int nColor; if (orbits.size() % 2 == 0) { nColor = orbits.size()/2; } else { @@ -412,11 +402,7 @@ public String colorBySymmetry() { colorIndex = orbits.size() - 1 - i; } Color4f c = colors[colorIndex]; - List ids = colorMap.get(c); - if (ids == null) { - ids = new ArrayList(); - colorMap.put(c, ids); - } + List ids = colorMap.computeIfAbsent(c, k -> new ArrayList<>()); for (int subunit: orbits.get(i)) { String id = getChainSpecification(modelNumbers, chainIds, subunit); ids.add(id); @@ -429,11 +415,7 @@ public String colorBySymmetry() { for (int i = 0; i < orbits.size(); i++) { Color4f c = new Color4f(colors[i]); - List ids = colorMap.get(c); - if (ids == null) { - ids = new ArrayList(); - colorMap.put(c, ids); - } + List ids = colorMap.computeIfAbsent(c, k -> new ArrayList<>()); List orbit = orbits.get(i); for (int j = 0; j < orbit.size(); j++) { String id = getChainSpecification(modelNumbers, chainIds, orbit.get(j)); @@ -531,20 +513,16 @@ private Map> getCnColorMap() { int fold = rotationGroup.getRotation(0).getFold(); - Map> colorMap = new HashMap>(); + Map> colorMap = new HashMap<>(); Color4f[] colors = getSymmetryColors(fold); for (List orbit: orbits) { for (int i = 0; i < fold; i++) { int subunit = orbit.get(i); - String id = null; + String id; id = getChainSpecification(modelNumbers, chainIds, subunit); Color4f c = colors[i]; - List ids = colorMap.get(c); - if (ids == null) { - ids = new ArrayList(); - colorMap.put(c, ids); - } + List ids = colorMap.computeIfAbsent(c, k -> new ArrayList<>()); ids.add(id); } } @@ -580,8 +558,8 @@ private Color4f getPolyhedronColor() { */ private Color4f[] getSymmetryColors(int nColors) { String pointGroup = rotationGroup.getPointGroup(); - Color[] col = null; - Color4f[] colors = null; + Color[] col; + Color4f[] colors; if (pointGroup.equals("C1")) { col = ColorBrewer.Greys.getColorPalette(nColors); colors = ColorConverter.convertColor4f(col); @@ -638,7 +616,7 @@ private String drawInertiaAxes() { s.append(" off;"); } return s.toString(); - }; + } private String drawSymmetryAxes() { StringBuilder s = new StringBuilder(); @@ -649,8 +627,8 @@ private String drawSymmetryAxes() { } float diameter = 0.5f; - double radius = 0; - String color = ""; + double radius; + String color; List axes = getUniqueAxes(); @@ -933,7 +911,7 @@ private static Vector3d[] getC2PolygonVertices(Vector3d axis, Vector3d reference // in reverse order, draw reflected half of arc (1/6 of full circle) // don't draw first and last element, since the are already part of the previous arc for (int i = k; i < 2*k-2; i++) { - axisAngle.angle = (f/2*k + i + 1.5) * 2 * Math.PI/(f*k); + axisAngle.angle = (f/2.0*k + i + 1.5) * 2 * Math.PI/(f*k); vectors[i] = new Vector3d(ref); m.set(axisAngle); // make sure matrix element m33 is 1.0. It's 0 on Linux. @@ -947,7 +925,7 @@ private static Vector3d[] getC2PolygonVertices(Vector3d axis, Vector3d reference private List getUniqueAxes() { - List uniqueRotations = new ArrayList(); + List uniqueRotations = new ArrayList<>(); for (int i = 0, n = rotationGroup.getOrder(); i < n; i++) { Rotation rotationI = rotationGroup.getRotation(i); diff --git a/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/JmolViewerImplTest.java b/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/JmolViewerImplTest.java index 727cbc137d..7bf2cebab9 100644 --- a/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/JmolViewerImplTest.java +++ b/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/JmolViewerImplTest.java @@ -36,11 +36,11 @@ public class JmolViewerImplTest { @Before - public void setUp() throws Exception { + public void setUp() { } @After - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/RenderStyleTest.java b/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/RenderStyleTest.java index b26b3b6431..1c99583faa 100644 --- a/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/RenderStyleTest.java +++ b/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/RenderStyleTest.java @@ -34,11 +34,11 @@ public class RenderStyleTest { @Before - public void setUp() throws Exception { + public void setUp() { } @After - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/StructureViewerTest.java b/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/StructureViewerTest.java index f954b27b20..0c29bbd0f7 100644 --- a/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/StructureViewerTest.java +++ b/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/StructureViewerTest.java @@ -37,11 +37,11 @@ public class StructureViewerTest { @Before - public void setUp() throws Exception { + public void setUp() { } @After - public void tearDown() throws Exception { + public void tearDown() { } /** @@ -178,7 +178,7 @@ public void testSetZoom() { // fail("The test case is a prototype."); } - public class StructureViewerImpl implements StructureViewer { + public static class StructureViewerImpl implements StructureViewer { @Override public void setStructure(Structure structure) { diff --git a/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/TestAtomInfo.java b/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/TestAtomInfo.java index 9d271a873c..a36c8e0f14 100644 --- a/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/TestAtomInfo.java +++ b/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/TestAtomInfo.java @@ -34,7 +34,7 @@ public void testAtomInfoConversion(){ String s1 = "[MET]508:A.CA/1 #3918"; AtomInfo aa = AtomInfo.fromString(s1); - Assert.assertTrue(aa.getAtomName().equals("CA")); + Assert.assertEquals("CA", aa.getAtomName()); Assert.assertEquals(aa.getChainId(), "A"); Assert.assertEquals(aa.getModelNumber(), 1); Assert.assertEquals(aa.getResidueName(), "MET"); diff --git a/biojava-structure/pom.xml b/biojava-structure/pom.xml index 688984e845..78c0081f24 100644 --- a/biojava-structure/pom.xml +++ b/biojava-structure/pom.xml @@ -63,7 +63,7 @@ org.jgrapht jgrapht-core - 1.1.0 + 1.4.0 UTF-8 - 512M + 1024M 1.0.9 - 1.7.25 - 2.6.2 + 2.0.0-alpha1 + 2.13.1 scm:git:git://github.com/biojava/biojava.git @@ -164,7 +164,7 @@ maven-compiler-plugin - 3.8.0 + 3.8.1 ${jdk.version} ${jdk.version} @@ -180,11 +180,11 @@ maven-scm-plugin - 1.10.0 + 1.11.2 maven-source-plugin - 3.0.1 + 3.2.1 maven-failsafe-plugin @@ -239,7 +239,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.0 + 3.2.2 maven-assembly-plugin @@ -313,7 +313,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.0.0-M3 + 3.0.0-M4 org.apache.maven.plugins @@ -368,8 +368,8 @@ maven-surefire-plugin -Xmx1500M - false - 1 + + @@ -474,7 +474,7 @@ junit junit - 4.12 + 4.13 test @@ -513,17 +513,17 @@ javax.xml.bind jaxb-api - 2.3.0 + 2.4.0-b180830.0359 com.sun.xml.bind jaxb-core - 2.3.0 + 2.3.0.1 com.sun.xml.bind jaxb-impl - 2.3.0 + 2.3.3-b02 javax.activation @@ -549,7 +549,7 @@ maven-project-info-reports-plugin - 2.9 + 3.0.0 @@ -573,12 +573,12 @@ org.apache.maven.plugins maven-checkstyle-plugin - 2.17 + 3.0.0 org.apache.maven.plugins maven-jxr-plugin - 2.5 + 3.0.0 @@ -600,7 +600,7 @@ org.apache.maven.plugins maven-jarsigner-plugin - 1.4 + 3.0.0 sign