From d9cedb863c0d5b665b8cdde3f8791d8a96030c6b Mon Sep 17 00:00:00 2001 From: Charles Ofoegbu Date: Sun, 15 Mar 2015 15:10:40 +0000 Subject: [PATCH] JAL-1667 updated test and internationalization messages --- resources/lang/Messages.properties | 11 +- src/jalview/gui/PDBFetchPanel.java | 146 ------ src/jalview/gui/PDBSearchPanel.java | 171 +++++++ src/jalview/gui/PopupMenu.java | 8 +- src/jalview/gui/SequenceFetcher.java | 19 +- src/jalview/gui/StructureChooser.java | 498 ++++++++++++-------- src/jalview/jbgui/GPDBFetchPanel.java | 167 ------- src/jalview/jbgui/GPDBSearchPanel.java | 200 ++++++++ src/jalview/jbgui/GStructureChooser.java | 203 ++++---- src/jalview/ws/dbsources/PDBRestClient.java | 120 +++-- .../{PDBSearchRequest.java => PDBRestRequest.java} | 45 +- ...PDBSearchResponse.java => PDBRestResponse.java} | 117 +++-- test/jalview/gui/PDBSearchPanelTest.java | 28 ++ test/jalview/gui/StructureChooserTest.java | 100 ++++ test/jalview/io/pdb_request_json_error.txt | 17 + test/jalview/io/pdb_response_json.txt | 176 +++++++ test/jalview/ws/dbsources/PDBRestClientTest.java | 168 +++++++ 17 files changed, 1501 insertions(+), 693 deletions(-) delete mode 100644 src/jalview/gui/PDBFetchPanel.java create mode 100644 src/jalview/gui/PDBSearchPanel.java delete mode 100644 src/jalview/jbgui/GPDBFetchPanel.java create mode 100644 src/jalview/jbgui/GPDBSearchPanel.java rename src/jalview/ws/uimodel/{PDBSearchRequest.java => PDBRestRequest.java} (54%) rename src/jalview/ws/uimodel/{PDBSearchResponse.java => PDBRestResponse.java} (58%) create mode 100644 test/jalview/gui/PDBSearchPanelTest.java create mode 100644 test/jalview/gui/StructureChooserTest.java create mode 100644 test/jalview/io/pdb_request_json_error.txt create mode 100644 test/jalview/io/pdb_response_json.txt create mode 100644 test/jalview/ws/dbsources/PDBRestClientTest.java diff --git a/resources/lang/Messages.properties b/resources/lang/Messages.properties index 2e37ee4..decf87b 100644 --- a/resources/lang/Messages.properties +++ b/resources/lang/Messages.properties @@ -775,7 +775,6 @@ label.use_sequence_id_1 = Use $SEQUENCE_ID$ or $SEQUENCE_ID=//=$ label.use_sequence_id_2 = \nto embed sequence id in URL label.ws_parameters_for = Parameters for {0} label.switch_server = Switch server -label.open_jabaws_web_page = Opens the JABAWS server's homepage in web browser label.choose_jabaws_server = Choose a server for running this service label.services_at = Services at {0} label.rest_client_submit = {0} using {1} @@ -1195,4 +1194,12 @@ label.include_description= Include Description action.back = Back label.hide_insertions = Hide Insertions label.mark_as_representative = Mark as representative -label.open_jabaws_web_page = Open JABAWS web page \ No newline at end of file +label.open_jabaws_web_page = Open JABAWS web page +label.opens_the_jabaws_server_homepage = Opens the JABAWS server's homepage in web browser +label.pdb_sequence_getcher = PDB Sequence Fetcher +label.result = result +label.results = results +label.structure_chooser = Structure Chooser +label.select = Select : +label.invert = Invert +label.select_pdb_file = Select PDB File \ No newline at end of file diff --git a/src/jalview/gui/PDBFetchPanel.java b/src/jalview/gui/PDBFetchPanel.java deleted file mode 100644 index 85231f7..0000000 --- a/src/jalview/gui/PDBFetchPanel.java +++ /dev/null @@ -1,146 +0,0 @@ -package jalview.gui; - -import jalview.jbgui.GPDBFetchPanel; -import jalview.ws.dbsources.PDBRestClient; -import jalview.ws.dbsources.PDBRestClient.PDBDocField; -import jalview.ws.uimodel.PDBSearchRequest; -import jalview.ws.uimodel.PDBSearchResponse; -import jalview.ws.uimodel.PDBSearchResponse.PDBResponseSummary; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import javax.swing.DefaultListModel; -import javax.swing.SwingUtilities; - -@SuppressWarnings("serial") -public class PDBFetchPanel extends GPDBFetchPanel -{ - private SequenceFetcher seqFetcher; - - public PDBFetchPanel() - { - } - - public PDBFetchPanel(SequenceFetcher seqFetcher) - { - this(); - this.seqFetcher = seqFetcher; - } - - public static void main(String[] args) - { - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { - new PDBFetchPanel(); - } - }); - } - - @Override - public void searchStringAction() - { - boolean allowEmptySequence = false; - jListSearchResult.setModel(new DefaultListModel()); - mainFrame.setTitle("PDB Sequence Fetcher"); - if (search.getText().trim().length() > 0) - { - long startTime = System.currentTimeMillis(); - PDBRestClient pdbRestCleint = new PDBRestClient(); - String searchTarget = ((PDBDocField) searchTargetOptions - .getSelectedItem()).getCode(); - - PDBSearchRequest request = new PDBSearchRequest(); - request.setAllowEmptySeq(allowEmptySequence); - request.setResponseSize(100); - request.setFieldToSearchBy(searchTarget + ":"); - request.setSearchTerm(search.getText()); - List wantedFields = new ArrayList(); - wantedFields.add(PDBDocField.MOLECULE_TYPE); - wantedFields.add(PDBDocField.PDB_ID); - wantedFields.add(PDBDocField.GENUS); - wantedFields.add(PDBDocField.GENE_NAME); - wantedFields.add(PDBDocField.TITLE); - request.setWantedFields(wantedFields); - - PDBSearchResponse resultList = pdbRestCleint.executeRequest(request); - - if (resultList.getSearchSummary() != null) - { - jListSearchResult.setModel(PDBSearchResponse - .getListModel(resultList.getSearchSummary())); - } - long endTime = System.currentTimeMillis(); - mainFrame.setTitle("PDB Sequence Fetcher - " - + resultList.getItemsFound() + " results (" - + (endTime - startTime) + " milli secs)"); - } - - } - - @Override - public void okActionPerformed() - { - importSelectedPDBSequencesToAlignment(); - } - - - @Override - public void backActionPerformed() - { - System.out.println("back! pressed!"); - } - - @Override - public void cancelActionPerformed() - { - mainFrame.dispose(); - } - - private void importSelectedPDBSequencesToAlignment() - { - mainFrame.dispose(); - StringBuilder selectedIds = new StringBuilder(); - for (PDBResponseSummary dataSelected : jListSearchResult - .getSelectedValuesList()) - { - selectedIds.append(";").append(dataSelected.getPdbId()); - } - String ids = selectedIds.deleteCharAt(0).toString(); - seqFetcher.textArea.setText(ids); - Thread worker = new Thread(seqFetcher); - worker.start(); - } - - public void populateSearchOptionComboBox() - { - List searchableTargets = new ArrayList(); - searchableTargets.add(PDBDocField.PDB_ID); - searchableTargets.add(PDBDocField.PFAM_ACCESSION); - searchableTargets.add(PDBDocField.MOLECULE_TYPE); - searchableTargets.add(PDBDocField.MOLECULE_NAME); - searchableTargets.add(PDBDocField.UNIPROT_ACCESSION); - searchableTargets.add(PDBDocField.GENE_NAME); - searchableTargets.add(PDBDocField.GENUS); - searchableTargets.add(PDBDocField.ALL); - - Collections.sort(searchableTargets, new Comparator() - { - @Override - public int compare(PDBDocField o1, PDBDocField o2) - { - return o1.getName().compareTo(o2.getName()); - } - }); - - for (PDBDocField searchTarget : searchableTargets) - { - searchTargetOptions.addItem(searchTarget); - } - } - -} diff --git a/src/jalview/gui/PDBSearchPanel.java b/src/jalview/gui/PDBSearchPanel.java new file mode 100644 index 0000000..1441e08 --- /dev/null +++ b/src/jalview/gui/PDBSearchPanel.java @@ -0,0 +1,171 @@ +/* + * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2) + * Copyright (C) 2014 The Jalview Authors + * + * This file is part of Jalview. + * + * Jalview is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation, either version 3 + * of the License, or (at your option) any later version. + * + * Jalview is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty + * of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Jalview. If not, see . + * The Jalview Authors are detailed in the 'AUTHORS' file. + */ + +package jalview.gui; + +import jalview.jbgui.GPDBSearchPanel; +import jalview.util.MessageManager; +import jalview.ws.dbsources.PDBRestClient; +import jalview.ws.dbsources.PDBRestClient.PDBDocField; +import jalview.ws.uimodel.PDBRestRequest; +import jalview.ws.uimodel.PDBRestResponse; +import jalview.ws.uimodel.PDBRestResponse.PDBResponseSummary; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import javax.swing.DefaultListModel; +import javax.swing.SwingUtilities; + +@SuppressWarnings("serial") +public class PDBSearchPanel extends GPDBSearchPanel +{ + private SequenceFetcher seqFetcher; + + private IProgressIndicator progressIdicator; + + public PDBSearchPanel(SequenceFetcher seqFetcher) + { + this.seqFetcher = seqFetcher; + this.progressIdicator = (seqFetcher == null) ? null : seqFetcher + .getProgressIndicator(); + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater(new Runnable() + { + public void run() + { + new PDBSearchPanel(null); + } + }); + } + + @Override + public void txt_search_ActionPerformed() + { + boolean allowEmptySequence = false; + lst_searchResult.setModel(new DefaultListModel()); + mainFrame.setTitle(MessageManager + .getString("label.pdb_sequence_getcher")); + if (txt_search.getText().trim().length() > 0) + { + long startTime = System.currentTimeMillis(); + PDBRestClient pdbRestCleint = new PDBRestClient(); + String searchTarget = ((PDBDocField) cmb_searchTarget + .getSelectedItem()).getCode(); + + PDBRestRequest request = new PDBRestRequest(); + request.setAllowEmptySeq(allowEmptySequence); + request.setResponseSize(100); + request.setFieldToSearchBy(searchTarget + ":"); + request.setSearchTerm(txt_search.getText()); + List wantedFields = new ArrayList(); + wantedFields.add(PDBDocField.MOLECULE_TYPE); + wantedFields.add(PDBDocField.PDB_ID); + // wantedFields.add(PDBDocField.GENUS); + wantedFields.add(PDBDocField.GENE_NAME); + wantedFields.add(PDBDocField.TITLE); + // wantedFields.add(PDBDocField.RESOLUTION); + // wantedFields.add(PDBDocField.EXPERIMENTAL_METHOD); + request.setWantedFields(wantedFields); + PDBRestResponse resultList = pdbRestCleint.executeRequest(request); + if (resultList.getSearchSummary() != null) + { + lst_searchResult.setModel(PDBRestResponse + .getListModel(resultList.getSearchSummary())); + } + + long endTime = System.currentTimeMillis(); + int resultSetCount = resultList.getNumberOfItemsFound(); + String result = (resultSetCount > 1) ? MessageManager + .getString("label.results") : MessageManager + .getString("label.result"); + mainFrame.setTitle(frameTitle + " - " + resultSetCount + " " + result + + " (" + (endTime - startTime) + " milli secs)"); + } + } + + @Override + public void btn_ok_ActionPerformed() + { + loadSelectedPDBSequencesToAlignment(); + } + + @Override + public void btn_back_ActionPerformed() + { + mainFrame.dispose(); + new SequenceFetcher(progressIdicator); + } + + @Override + public void btn_cancel_ActionPerformed() + { + mainFrame.dispose(); + } + + public void loadSelectedPDBSequencesToAlignment() + { + mainFrame.dispose(); + StringBuilder selectedIds = new StringBuilder(); + for (PDBResponseSummary dataSelected : lst_searchResult + .getSelectedValuesList()) + { + selectedIds.append(";").append(dataSelected.getPdbId()); + } + String ids = selectedIds.deleteCharAt(0).toString(); + seqFetcher.textArea.setText(ids); + Thread worker = new Thread(seqFetcher); + worker.start(); + } + + public void populateCmbSearchTargetOptions() + { + List searchableTargets = new ArrayList(); + searchableTargets.add(PDBDocField.PDB_ID); + searchableTargets.add(PDBDocField.PFAM_ACCESSION); + searchableTargets.add(PDBDocField.MOLECULE_TYPE); + searchableTargets.add(PDBDocField.MOLECULE_NAME); + searchableTargets.add(PDBDocField.UNIPROT_ACCESSION); + searchableTargets.add(PDBDocField.GENE_NAME); + searchableTargets.add(PDBDocField.GENUS); + searchableTargets.add(PDBDocField.ALL); + + Collections.sort(searchableTargets, new Comparator() + { + @Override + public int compare(PDBDocField o1, PDBDocField o2) + { + return o1.getName().compareTo(o2.getName()); + } + }); + + for (PDBDocField searchTarget : searchableTargets) + { + cmb_searchTarget.addItem(searchTarget); + } + } + +} diff --git a/src/jalview/gui/PopupMenu.java b/src/jalview/gui/PopupMenu.java index 72313be..0a40af7 100644 --- a/src/jalview/gui/PopupMenu.java +++ b/src/jalview/gui/PopupMenu.java @@ -1509,7 +1509,13 @@ public class PopupMenu extends JPopupMenu @Override public void actionPerformed(ActionEvent actionEvent) { - new StructureChooser(ap, sequence); + SequenceI[] selectedSeqs = new SequenceI[] + { sequence }; + if (ap.av.getSelectionGroup() != null) + { + selectedSeqs = ap.av.getSequenceSelection(); + } + new StructureChooser(selectedSeqs, sequence, ap); } }); diff --git a/src/jalview/gui/SequenceFetcher.java b/src/jalview/gui/SequenceFetcher.java index 56b4b87..d83f034 100755 --- a/src/jalview/gui/SequenceFetcher.java +++ b/src/jalview/gui/SequenceFetcher.java @@ -190,9 +190,10 @@ public class SequenceFetcher extends JPanel implements Runnable return sfetch; } + private IProgressIndicator progressIndicator; public SequenceFetcher(IProgressIndicator guiIndic) { - final IProgressIndicator guiWindow = guiIndic; + this.progressIndicator = guiIndic; final SequenceFetcher us = this; // launch initialiser thread Thread sf = new Thread(new Runnable() @@ -201,9 +202,9 @@ public class SequenceFetcher extends JPanel implements Runnable @Override public void run() { - if (getSequenceFetcherSingleton(guiWindow) != null) + if (getSequenceFetcherSingleton(progressIndicator) != null) { - us.initGui(guiWindow); + us.initGui(progressIndicator); } else { @@ -390,7 +391,7 @@ public class SequenceFetcher extends JPanel implements Runnable private void pdbSourceAction() { databaseButt.setText(database.getSelectedItem()); - new PDBFetchPanel(this); + new PDBSearchPanel(this); frame.dispose(); } @@ -899,4 +900,14 @@ public class SequenceFetcher extends JPanel implements Runnable } }); } + + public IProgressIndicator getProgressIndicator() + { + return progressIndicator; + } + + public void setProgressIndicator(IProgressIndicator progressIndicator) + { + this.progressIndicator = progressIndicator; + } } diff --git a/src/jalview/gui/StructureChooser.java b/src/jalview/gui/StructureChooser.java index 9abf22f..4b3f5de 100644 --- a/src/jalview/gui/StructureChooser.java +++ b/src/jalview/gui/StructureChooser.java @@ -1,3 +1,24 @@ +/* + * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2) + * Copyright (C) 2014 The Jalview Authors + * + * This file is part of Jalview. + * + * Jalview is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation, either version 3 + * of the License, or (at your option) any later version. + * + * Jalview is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty + * of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Jalview. If not, see . + * The Jalview Authors are detailed in the 'AUTHORS' file. + */ + package jalview.gui; import jalview.datamodel.DBRefEntry; @@ -7,72 +28,99 @@ import jalview.jbgui.GStructureChooser; import jalview.util.MessageManager; import jalview.ws.dbsources.PDBRestClient; import jalview.ws.dbsources.PDBRestClient.PDBDocField; -import jalview.ws.uimodel.PDBSearchRequest; -import jalview.ws.uimodel.PDBSearchResponse; -import jalview.ws.uimodel.PDBSearchResponse.PDBResponseSummary; +import jalview.ws.uimodel.PDBRestRequest; +import jalview.ws.uimodel.PDBRestResponse; +import jalview.ws.uimodel.PDBRestResponse.PDBResponseSummary; -import java.awt.Component; import java.awt.event.ItemEvent; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; +import java.util.Vector; import javax.swing.JCheckBox; import javax.swing.JOptionPane; -import javax.swing.JTable; import javax.swing.ListSelectionModel; -import javax.swing.table.TableCellRenderer; -import javax.swing.table.TableColumnModel; +/** + * Provides the behaviors for the Structure chooser Panel + * + * @author tcnofoegbu + * + */ @SuppressWarnings("serial") public class StructureChooser extends GStructureChooser { - - private boolean structuresWereFound = false; + private boolean structuresDiscovered = false; private SequenceI selectedSequence; private SequenceI[] selectedSequences; - IProgressIndicator af; + private IProgressIndicator progressIndicator; + + private Collection discoveredStructuresSet = new HashSet(); + + private PDBRestRequest pdbRequest; - Collection discoveredStructuresSet = new HashSet(); + private PDBRestClient pdbRestCleint; - public StructureChooser(AlignmentPanel ap, final SequenceI sequence) + + public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq, + AlignmentPanel ap) { this.ap = ap; - this.af = ap.alignFrame; - this.selectedSequence = sequence; - this.selectedSequences = ((ap.av.getSelectionGroup() == null) ? new SequenceI[] - { sequence } - : ap.av.getSequenceSelection()); + this.selectedSequence = selectedSeq; + this.selectedSequences = selectedSeqs; + this.progressIndicator = (ap == null) ? null : ap.alignFrame; init(); } - private void init() + /** + * Initializes parameters used by the Structure Chooser Panel + */ + public void init() { - Thread discPDBThread = new Thread(new Runnable() + Thread discoverPDBStructuresThread = new Thread(new Runnable() { @Override public void run() { long startTime = System.currentTimeMillis(); - af.setProgressBar( - MessageManager.getString("status.fetching_db_refs"), - startTime); - - fetchStructures(); - populateFilterOptions(); - af.setProgressBar(null, startTime); + String msg = MessageManager.getString("status.fetching_db_refs"); + updateProgressIndicator(msg, startTime); + fetchStructuresMetaData(); + populateFilterComboBox(); + updateProgressIndicator(null, startTime); mainFrame.setVisible(true); updateCurrentView(); } }); - discPDBThread.start(); + discoverPDBStructuresThread.start(); + } + + /** + * Updates the progress indicator with the specified message + * + * @param message + * displayed message for the operation + * @param id + * unique handle for this indicator + */ + public void updateProgressIndicator(String message, long id) + { + if (progressIndicator != null) + { + progressIndicator.setProgressBar(message, id); + } } - private void fetchStructures() + /** + * Retrieve meta-data for all the structure(s) for a given sequence(s) in a + * selection group + */ + public void fetchStructuresMetaData() { long startTime = System.currentTimeMillis(); List wantedFields = new ArrayList(); @@ -81,35 +129,35 @@ public class StructureChooser extends GStructureChooser // wantedFields.add(PDBDocField.GENUS); // wantedFields.add(PDBDocField.GENE_NAME); wantedFields.add(PDBDocField.TITLE); - - PDBSearchRequest request = new PDBSearchRequest(); - request.setAllowEmptySeq(false); - request.setResponseSize(500); - request.setFieldToSearchBy("(text:"); - request.setWantedFields(wantedFields); - + pdbRequest = new PDBRestRequest(); + pdbRequest.setAllowEmptySeq(false); + pdbRequest.setResponseSize(500); + pdbRequest.setFieldToSearchBy("(text:"); + pdbRequest.setWantedFields(wantedFields); for (SequenceI seq : selectedSequences) { - request.setSearchTerm(buildQuery(seq) + ")"); - request.setAssociatedSequence(seq.getName()); - PDBRestClient pdbRestCleint = new PDBRestClient(); - PDBSearchResponse resultList = pdbRestCleint.executeRequest(request); + pdbRequest.setSearchTerm(buildQuery(seq) + ")"); + pdbRequest.setAssociatedSequence(seq.getName()); + pdbRestCleint = new PDBRestClient(); + PDBRestResponse resultList = pdbRestCleint.executeRequest(pdbRequest); if (resultList.getSearchSummary() != null && !resultList.getSearchSummary().isEmpty()) { discoveredStructuresSet.addAll(resultList.getSearchSummary()); + updateSequenceDbRef(seq, resultList.getSearchSummary()); } } int noOfStructuresFound = 0; - if (discoveredStructuresSet != null) + if (discoveredStructuresSet != null + && !discoveredStructuresSet.isEmpty()) { - jListFoundStructures.setModel(PDBSearchResponse + jList_FoundStructures.setModel(PDBRestResponse .getListModel(discoveredStructuresSet)); - summaryTable.setModel(PDBSearchResponse.getTableModel(request, + tbl_summary.setModel(PDBRestResponse.getTableModel(pdbRequest, discoveredStructuresSet)); // resizeColumnWidth(summaryTable); - structuresWereFound = true; + structuresDiscovered = true; noOfStructuresFound = discoveredStructuresSet.size(); } String totalTime = (System.currentTimeMillis() - startTime) @@ -118,60 +166,55 @@ public class StructureChooser extends GStructureChooser + " Found (" + totalTime + ")"); } - public void resizeColumnWidth(JTable table) - { - // table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); - final TableColumnModel columnModel = table.getColumnModel(); - for (int column = 0; column < table.getColumnCount(); column++) - { - int width = 50; // Min width - for (int row = 0; row < table.getRowCount(); row++) - { - TableCellRenderer renderer = table.getCellRenderer(row, column); - Component comp = table.prepareRenderer(renderer, row, column); - width = Math.max(comp.getPreferredSize().width, width); - } - columnModel.getColumn(column).setPreferredWidth(width); - } - } - - protected void populateFilterOptions() + /** + * Update the DBRef entry for a given sequence with values retrieved from + * PDBResponseSummary + * + * @param seq + * the Sequence to update its DBRef entry + * @param responseSummaries + * a collection of PDBResponseSummary + */ + public void updateSequenceDbRef(SequenceI seq, + Collection responseSummaries) { - if (structuresWereFound) + for (PDBResponseSummary response : responseSummaries) { - filterOptionsComboBox.addItem(new FilterOptions("Best Quality", - PDBDocField.OVERALL_QUALITY.getCode(), VIEWS_FILTER)); - filterOptionsComboBox.addItem(new FilterOptions( - "Best UniProt Coverage", PDBDocField.UNIPROT_COVERAGE - .getCode(), VIEWS_FILTER)); - filterOptionsComboBox.addItem(new FilterOptions("Highest Resolution", - PDBDocField.RESOLUTION.getCode(), VIEWS_FILTER)); - filterOptionsComboBox.addItem(new FilterOptions( - "Highest Protein Chain", PDBDocField.PROTEIN_CHAIN_COUNT - .getCode(), VIEWS_FILTER)); - filterOptionsComboBox.addItem(new FilterOptions( - "Highest Bound Molecules", PDBDocField.BOUND_MOLECULE_COUNT - .getCode(), VIEWS_FILTER)); - filterOptionsComboBox.addItem(new FilterOptions( - "Highest Polymer Residues", PDBDocField.POLYMER_RESIDUE_COUNT - .getCode(), VIEWS_FILTER)); + PDBEntry newEntry = new PDBEntry(); + newEntry.setId(response.getPdbId()); + newEntry.setType("PDB"); + seq.getDatasetSequence().addPDBId(newEntry); } - filterOptionsComboBox.addItem(new FilterOptions("Enter PDB Id", "-", - VIEWS_ENTER_ID)); - filterOptionsComboBox.addItem(new FilterOptions("From File", "-", - VIEWS_FROM_FILE)); } - private String buildQuery(SequenceI seq) + /** + * Builds a query string for a given sequences using its DBRef entries + * + * @param seq + * the sequences to build a query for + * @return the built query string + */ + @SuppressWarnings("unchecked") + public static String buildQuery(SequenceI seq) { String query = seq.getName(); StringBuilder queryBuilder = new StringBuilder(); int count = 0; + + if (seq.getPDBId() != null) + { + for (PDBEntry entry : (Vector) seq.getPDBId()) + { + queryBuilder.append("text:").append(entry.getId()).append(" OR "); + } + } + if (seq.getDBRef() != null && seq.getDBRef().length != 0) { for (DBRefEntry dbRef : seq.getDBRef()) { - queryBuilder.append("text:").append(dbRef.getAccessionId()) + queryBuilder.append("text:") + .append(dbRef.getAccessionId().replaceAll("GO:", "")) .append(" OR "); ++count; if (count > 10) @@ -182,23 +225,16 @@ public class StructureChooser extends GStructureChooser int endIndex = queryBuilder.lastIndexOf(" OR "); query = queryBuilder.toString().substring(5, endIndex); } + // System.out.println("Query -----> " + query); return query; } - protected void updateCurrentView() - { - FilterOptions currentOption = ((FilterOptions) filterOptionsComboBox - .getSelectedItem()); - switchableViewsLayout.show(switchableViewsPanel, - currentOption.getView()); - invertFilter.setEnabled(false); - if (currentOption.getView() == VIEWS_FILTER) - { - invertFilter.setEnabled(true); - filterResultSet(currentOption.getValue()); - } - } - + /** + * Filters a given list of discovered structures based on supplied argument + * + * @param fieldToFilterBy + * the field to filter by + */ public void filterResultSet(final String fieldToFilterBy) { Thread filterThread = new Thread(new Runnable() @@ -208,77 +244,61 @@ public class StructureChooser extends GStructureChooser { try { - loadingImageLabel.setVisible(true); - List wantedFields = new ArrayList(); - // wantedFields.add(PDBDocField.MOLECULE_TYPE); - wantedFields.add(PDBDocField.PDB_ID); - // wantedFields.add(PDBDocField.GENUS); - // wantedFields.add(PDBDocField.GENE_NAME); - wantedFields.add(PDBDocField.TITLE); - - PDBSearchRequest request = new PDBSearchRequest(); - request.setAllowEmptySeq(false); - request.setResponseSize(1); - request.setFieldToSearchBy("(text:"); - request.setFieldToSortBy(fieldToFilterBy, - !invertFilter.isSelected()); - - request.setWantedFields(wantedFields); - - Collection filteredResponse = new HashSet(); - for (SequenceI seq : selectedSequences) - { - request.setSearchTerm(buildQuery(seq) + ")"); - request.setAssociatedSequence(seq.getName()); - PDBRestClient pdbRestCleint = new PDBRestClient(); - PDBSearchResponse resultList = pdbRestCleint - .executeRequest(request); - if (resultList.getSearchSummary() != null - && !resultList.getSearchSummary().isEmpty()) + lbl_loading.setVisible(true); + pdbRequest.setResponseSize(1); + pdbRequest.setFieldToSearchBy("(text:"); + pdbRequest.setFieldToSortBy(fieldToFilterBy, + !chk_invertFilter.isSelected()); + + Collection filteredResponse = new HashSet(); + for (SequenceI seq : selectedSequences) { - filteredResponse.addAll(resultList.getSearchSummary()); + pdbRequest.setSearchTerm(buildQuery(seq) + ")"); + pdbRequest.setAssociatedSequence(seq.getName()); + pdbRestCleint = new PDBRestClient(); + PDBRestResponse resultList = pdbRestCleint + .executeRequest(pdbRequest); + if (resultList.getSearchSummary() != null + && !resultList.getSearchSummary().isEmpty()) + { + filteredResponse.addAll(resultList.getSearchSummary()); + } } - } - - if (filteredResponse != null) - { - // - // for (PDBResponseSummary s : filteredResponse) - // { - // System.out.println("-----------> " + s.getPdbId()); - // } - - int filterResponseCount = filteredResponse.size(); - List list = new ArrayList( - discoveredStructuresSet); - list.removeAll(filteredResponse); - - Collection newSet = new ArrayList(); - newSet.addAll(filteredResponse); - newSet.addAll(list); - - jListFoundStructures.setModel(PDBSearchResponse - .getListModel(newSet)); - summaryTable.setModel(PDBSearchResponse.getTableModel(request, - newSet)); - // resizeColumnWidth(summaryTable); - list = null; - newSet = null; - - int[] filterIndice = new int[filterResponseCount]; - ListSelectionModel model = summaryTable.getSelectionModel(); - model.clearSelection(); - // int x = 0; - for (int x = 0; x < filterResponseCount; x++) + if (filteredResponse != null) { - filterIndice[x] = x; - model.addSelectionInterval(x, x); + int filterResponseCount = filteredResponse.size(); + List originalDiscoveredStructuresList = new ArrayList( + discoveredStructuresSet); + originalDiscoveredStructuresList.removeAll(filteredResponse); + + Collection reorderedStructuresSet = new ArrayList(); + reorderedStructuresSet.addAll(filteredResponse); + reorderedStructuresSet.addAll(originalDiscoveredStructuresList); + + jList_FoundStructures.setModel(PDBRestResponse + .getListModel(reorderedStructuresSet)); + tbl_summary.setModel(PDBRestResponse.getTableModel(pdbRequest, + reorderedStructuresSet)); + + // int[] filterIndice = new int[filterResponseCount]; + ListSelectionModel model = tbl_summary.getSelectionModel(); + model.clearSelection(); + for (int x = 0; x < filterResponseCount; x++) + { + // filterIndice[x] = x; + model.addSelectionInterval(x, x); + } + + // Discard unwanted objects to make them eligible for garbage + // collection + originalDiscoveredStructuresList = null; + reorderedStructuresSet = null; + + // jListFoundStructures.setSelectedIndices(filterIndice); } - jListFoundStructures.setSelectedIndices(filterIndice); - } - loadingImageLabel.setVisible(false); + lbl_loading.setVisible(false); } catch (Exception e) { e.printStackTrace(); @@ -286,32 +306,33 @@ public class StructureChooser extends GStructureChooser } }); filterThread.start(); - } - @Override - protected void stateChanged(ItemEvent e) + /** + * Determines the column index for the pdb id in the summary table. The pdb id + * serves as a unique identifier for a given row in the summary table + * + * @param wantedFeilds + * the available table columns in no particular order + * @return the pdb id field column index + */ + public static int getPDBIdColumIndex(Collection wantedFeilds) { - if (e.getSource() instanceof JCheckBox) + int pdbFeildIndex = 1; + for (PDBDocField feild : wantedFeilds) { - updateCurrentView(); - } - else - { - if (e.getStateChange() == ItemEvent.SELECTED) + if (feild.equals(PDBDocField.PDB_ID)) { - updateCurrentView(); + break; } + ++pdbFeildIndex; } - - } - - @Override - public void ok_ActionPerformed() - { - // TODO code to load selected structures to jmol or chimera + return pdbFeildIndex; } + /** + * Handles action event for btn_pdbFromFile + */ public void pdbFromFile_actionPerformed() { jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser( @@ -325,7 +346,6 @@ public class StructureChooser extends GStructureChooser { selectedSequence.getDisplayId(false) })); int value = chooser.showOpenDialog(null); - if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION) { String choice = chooser.getSelectedFile().getPath(); @@ -334,20 +354,34 @@ public class StructureChooser extends GStructureChooser jalview.io.AppletFormatAdapter.FILE, selectedSequence, true, Desktop.instance); } - } - // rpdbview.addActionListener(new ActionListener() - // { - // - // @Override - // public void actionPerformed(ActionEvent e) - // { - // new StructureViewer(ap.getStructureSelectionManager()) - // .viewStructures(ap, pr, ap.av.collateForPDB(pr)); - // } - // }); + /** + * Handles action event for btn_ok + */ + @Override + public void ok_ActionPerformed() + { + int pdbIdCol = getPDBIdColumIndex(pdbRequest.getWantedFields()); + int[] selectedRows = tbl_summary.getSelectedRows(); + PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length]; + int count = 0; + for (int summaryRow : selectedRows) + { + String pdbIdStr = tbl_summary.getValueAt(summaryRow, pdbIdCol) + .toString(); + PDBEntry pdbEntry = new PDBEntry(); + pdbEntry.setId(pdbIdStr); + pdbEntry.setType("PDB"); + pdbEntriesToView[count++] = pdbEntry; + } + new StructureViewer(ap.getStructureSelectionManager()).viewStructures( + ap, pdbEntriesToView, ap.av.collateForPDB(pdbEntriesToView)); + } + /** + * Handles action event for manual entry of pdb ids + */ public void enterPDB_actionPerformed() { String id = JOptionPane.showInternalInputDialog(Desktop.desktop, @@ -362,4 +396,84 @@ public class StructureChooser extends GStructureChooser } } + /** + * Populates the filter combo-box options dynamically depending on discovered + * structures + */ + protected void populateFilterComboBox() + { + if (isStructuresDiscovered()) + { + cmb_filterOption.addItem(new FilterOption("Best Quality", + PDBDocField.OVERALL_QUALITY.getCode(), VIEWS_FILTER)); + cmb_filterOption.addItem(new FilterOption("Best UniProt Coverage", + PDBDocField.UNIPROT_COVERAGE.getCode(), VIEWS_FILTER)); + cmb_filterOption.addItem(new FilterOption("Highest Resolution", + PDBDocField.RESOLUTION.getCode(), VIEWS_FILTER)); + cmb_filterOption.addItem(new FilterOption("Highest Protein Chain", + PDBDocField.PROTEIN_CHAIN_COUNT.getCode(), VIEWS_FILTER)); + cmb_filterOption.addItem(new FilterOption("Highest Bound Molecules", + PDBDocField.BOUND_MOLECULE_COUNT.getCode(), VIEWS_FILTER)); + cmb_filterOption.addItem(new FilterOption("Highest Polymer Residues", + PDBDocField.POLYMER_RESIDUE_COUNT.getCode(), VIEWS_FILTER)); + } + cmb_filterOption.addItem(new FilterOption("Enter PDB Id", "-", + VIEWS_ENTER_ID)); + cmb_filterOption.addItem(new FilterOption("From File", "-", + VIEWS_FROM_FILE)); + } + + /** + * Updates the displayed view based on the selected filter option + */ + protected void updateCurrentView() + { + FilterOption selectedOption = ((FilterOption) cmb_filterOption + .getSelectedItem()); + layout_switchableViews.show(pnl_switchableViews, + selectedOption.getView()); + chk_invertFilter.setEnabled(false); + if (selectedOption.getView() == VIEWS_FILTER) + { + chk_invertFilter.setEnabled(true); + filterResultSet(selectedOption.getValue()); + } + } + + /** + * Handles the state change event for the 'filter' combo-box and 'invert' + * check-box + */ + @Override + protected void stateChanged(ItemEvent e) + { + if (e.getSource() instanceof JCheckBox) + { + updateCurrentView(); + } + else + { + if (e.getStateChange() == ItemEvent.SELECTED) + { + updateCurrentView(); + } + } + + } + + + public boolean isStructuresDiscovered() + { + return structuresDiscovered; + } + + public void setStructuresDiscovered(boolean structuresDiscovered) + { + this.structuresDiscovered = structuresDiscovered; + } + + public Collection getDiscoveredStructuresSet() + { + return discoveredStructuresSet; + } } diff --git a/src/jalview/jbgui/GPDBFetchPanel.java b/src/jalview/jbgui/GPDBFetchPanel.java deleted file mode 100644 index c7fa057..0000000 --- a/src/jalview/jbgui/GPDBFetchPanel.java +++ /dev/null @@ -1,167 +0,0 @@ -package jalview.jbgui; - -import jalview.gui.Desktop; -import jalview.util.MessageManager; -import jalview.ws.dbsources.PDBRestClient.PDBDocField; -import jalview.ws.uimodel.PDBSearchResponse.PDBResponseSummary; - -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JInternalFrame; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; - -@SuppressWarnings("serial") -public abstract class GPDBFetchPanel extends JPanel -{ - protected String frameTitle = "PDB Sequence Fetcher"; - - protected JInternalFrame mainFrame = new JInternalFrame(frameTitle); - - protected JComboBox searchTargetOptions = new JComboBox(); - - protected JButton ok = new JButton(); - - protected JButton back = new JButton(); - - protected JButton cancel = new JButton(); - - protected JTextField search = new JTextField(20); - - protected JList jListSearchResult = new JList(); - - protected JScrollPane searchResultScroller = new JScrollPane( - jListSearchResult); - - private JPanel actionPanel = new JPanel(); - - private JPanel resultPanel = new JPanel(); - - private JPanel inputPanel = new JPanel(); - - private BorderLayout mainLayout = new BorderLayout(); - - public GPDBFetchPanel() - { - try - { - jbInit(); - mainFrame.invalidate(); - mainFrame.pack(); - } catch (Exception e) - { - e.printStackTrace(); - } - } - - private void jbInit() throws Exception - { - back.setFont(new java.awt.Font("Verdana", 0, 12)); - back.setText(MessageManager.getString("action.back")); - back.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(ActionEvent e) - { - backActionPerformed(); - } - }); - ok.setFont(new java.awt.Font("Verdana", 0, 12)); - ok.setText(MessageManager.getString("action.ok")); - ok.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(ActionEvent e) - { - okActionPerformed(); - } - }); - cancel.setFont(new java.awt.Font("Verdana", 0, 12)); - cancel.setText(MessageManager.getString("action.cancel")); - cancel.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(ActionEvent e) - { - cancelActionPerformed(); - } - }); - actionPanel.add(back); - actionPanel.add(ok); - actionPanel.add(cancel); - - jListSearchResult - .setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - jListSearchResult.setLayoutOrientation(JList.VERTICAL); - jListSearchResult.setVisibleRowCount(-1); - searchResultScroller.setPreferredSize(new Dimension(500, 300)); - searchResultScroller - .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - resultPanel.add(searchResultScroller); - - searchTargetOptions.setFont(new java.awt.Font("Verdana", 0, 12)); - searchTargetOptions.addActionListener(new ActionListener() - { - @Override - public void actionPerformed(ActionEvent e) - { - searchStringAction(); - } - }); - - populateSearchOptionComboBox(); - - search.setFont(new java.awt.Font("Verdana", 0, 12)); - search.getDocument().addDocumentListener(new DocumentListener() - { - @Override - public void insertUpdate(DocumentEvent e) - { - searchStringAction(); - } - - @Override - public void removeUpdate(DocumentEvent e) - { - searchStringAction(); - } - - @Override - public void changedUpdate(DocumentEvent e) - { - searchStringAction(); - } - }); - - inputPanel.add(searchTargetOptions); - inputPanel.add(search); - - this.setLayout(mainLayout); - this.add(inputPanel, java.awt.BorderLayout.NORTH); - this.add(resultPanel, java.awt.BorderLayout.CENTER); - this.add(actionPanel, java.awt.BorderLayout.SOUTH); - mainFrame.setVisible(true); - mainFrame.setContentPane(this); - mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - Desktop.addInternalFrame(mainFrame, frameTitle, 800, 400); - } - - public abstract void searchStringAction(); - - public abstract void okActionPerformed(); - - public abstract void backActionPerformed(); - - public abstract void cancelActionPerformed(); - - protected abstract void populateSearchOptionComboBox(); - -} diff --git a/src/jalview/jbgui/GPDBSearchPanel.java b/src/jalview/jbgui/GPDBSearchPanel.java new file mode 100644 index 0000000..5593d5c --- /dev/null +++ b/src/jalview/jbgui/GPDBSearchPanel.java @@ -0,0 +1,200 @@ +/* + * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2) + * Copyright (C) 2014 The Jalview Authors + * + * This file is part of Jalview. + * + * Jalview is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation, either version 3 + * of the License, or (at your option) any later version. + * + * Jalview is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty + * of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Jalview. If not, see . + * The Jalview Authors are detailed in the 'AUTHORS' file. + */ + +package jalview.jbgui; + +import jalview.gui.Desktop; +import jalview.util.MessageManager; +import jalview.ws.dbsources.PDBRestClient.PDBDocField; +import jalview.ws.uimodel.PDBRestResponse.PDBResponseSummary; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.ListSelectionModel; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; + +/** + * GUI layout for PDB Fetch Panel + * + * @author tcnofoegbu + * + */ +@SuppressWarnings("serial") +public abstract class GPDBSearchPanel extends JPanel +{ + protected String frameTitle = MessageManager + .getString("label.pdb_sequence_getcher"); + + protected JInternalFrame mainFrame = new JInternalFrame(frameTitle); + + protected JComboBox cmb_searchTarget = new JComboBox(); + + protected JButton btn_ok = new JButton(); + + protected JButton btn_back = new JButton(); + + protected JButton btn_cancel = new JButton(); + + protected JTextField txt_search = new JTextField(20); + + protected JList lst_searchResult = new JList(); + + protected JScrollPane scrl_searchResult = new JScrollPane( + lst_searchResult); + + private JPanel pnl_actions = new JPanel(); + + private JPanel pnl_results = new JPanel(); + + private JPanel pnl_inputs = new JPanel(); + + private BorderLayout mainLayout = new BorderLayout(); + + public GPDBSearchPanel() + { + try + { + jbInit(); + mainFrame.invalidate(); + mainFrame.pack(); + } catch (Exception e) + { + e.printStackTrace(); + } + } + + /** + * Initializes the GUI default properties + * + * @throws Exception + */ + private void jbInit() throws Exception + { + btn_back.setFont(new java.awt.Font("Verdana", 0, 12)); + btn_back.setText(MessageManager.getString("action.back")); + btn_back.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + btn_back_ActionPerformed(); + } + }); + btn_ok.setFont(new java.awt.Font("Verdana", 0, 12)); + btn_ok.setText(MessageManager.getString("action.ok")); + btn_ok.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + btn_ok_ActionPerformed(); + } + }); + btn_cancel.setFont(new java.awt.Font("Verdana", 0, 12)); + btn_cancel.setText(MessageManager.getString("action.cancel")); + btn_cancel.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(ActionEvent e) + { + btn_cancel_ActionPerformed(); + } + }); + pnl_actions.add(btn_back); + pnl_actions.add(btn_ok); + pnl_actions.add(btn_cancel); + + lst_searchResult + .setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + lst_searchResult.setLayoutOrientation(JList.VERTICAL); + lst_searchResult.setVisibleRowCount(-1); + scrl_searchResult.setPreferredSize(new Dimension(500, 300)); + scrl_searchResult + .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + pnl_results.add(scrl_searchResult); + + cmb_searchTarget.setFont(new java.awt.Font("Verdana", 0, 12)); + cmb_searchTarget.addActionListener(new ActionListener() + { + @Override + public void actionPerformed(ActionEvent e) + { + txt_search_ActionPerformed(); + } + }); + + populateCmbSearchTargetOptions(); + + txt_search.setFont(new java.awt.Font("Verdana", 0, 12)); + txt_search.getDocument().addDocumentListener(new DocumentListener() + { + @Override + public void insertUpdate(DocumentEvent e) + { + txt_search_ActionPerformed(); + } + + @Override + public void removeUpdate(DocumentEvent e) + { + txt_search_ActionPerformed(); + } + + @Override + public void changedUpdate(DocumentEvent e) + { + txt_search_ActionPerformed(); + } + }); + + pnl_inputs.add(cmb_searchTarget); + pnl_inputs.add(txt_search); + + this.setLayout(mainLayout); + this.add(pnl_inputs, java.awt.BorderLayout.NORTH); + this.add(pnl_results, java.awt.BorderLayout.CENTER); + this.add(pnl_actions, java.awt.BorderLayout.SOUTH); + mainFrame.setVisible(true); + mainFrame.setContentPane(this); + mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + Desktop.addInternalFrame(mainFrame, frameTitle, 800, 400); + } + + public abstract void txt_search_ActionPerformed(); + + public abstract void btn_ok_ActionPerformed(); + + public abstract void btn_back_ActionPerformed(); + + public abstract void btn_cancel_ActionPerformed(); + + protected abstract void populateCmbSearchTargetOptions(); + +} diff --git a/src/jalview/jbgui/GStructureChooser.java b/src/jalview/jbgui/GStructureChooser.java index 7224b78..cbd6f1a 100644 --- a/src/jalview/jbgui/GStructureChooser.java +++ b/src/jalview/jbgui/GStructureChooser.java @@ -1,15 +1,35 @@ +/* + * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2) + * Copyright (C) 2014 The Jalview Authors + * + * This file is part of Jalview. + * + * Jalview is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation, either version 3 + * of the License, or (at your option) any later version. + * + * Jalview is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty + * of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Jalview. If not, see . + * The Jalview Authors are detailed in the 'AUTHORS' file. + */ + package jalview.jbgui; import jalview.gui.AlignmentPanel; import jalview.gui.Desktop; import jalview.util.MessageManager; -import jalview.ws.uimodel.PDBSearchResponse.PDBResponseSummary; +import jalview.ws.uimodel.PDBRestResponse.PDBResponseSummary; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Dimension; import java.awt.FlowLayout; -import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; @@ -29,56 +49,59 @@ import javax.swing.JTextField; import javax.swing.ListSelectionModel; @SuppressWarnings("serial") +/** + * GUI layout for structure chooser + * @author tcnofoegbu + * + */ public abstract class GStructureChooser extends JPanel implements ItemListener { - protected String frameTitle = "Structure Chooser"; + protected String frameTitle = MessageManager + .getString("label.structure_chooser"); protected JInternalFrame mainFrame = new JInternalFrame(frameTitle); - - - protected JComboBox filterOptionsComboBox = new JComboBox(); + protected JComboBox cmb_filterOption = new JComboBox(); protected AlignmentPanel ap; - protected JLabel resultLabel = new JLabel("Select : "); + protected JLabel lbl_result = new JLabel( + MessageManager.getString("label.select") /* "Select : " */); - protected JButton ok = new JButton(); + protected JButton btn_ok = new JButton(); - protected JButton cancel = new JButton(); + protected JButton btn_cancel = new JButton(); - protected JButton pdbFromFile = new JButton(); + protected JButton btn_pdbFromFile = new JButton(); - protected JTextField search = new JTextField(16); + protected JTextField txt_search = new JTextField(18); - protected JPanel actionPanel = new JPanel(); + private JPanel pnl_actions = new JPanel(); - protected JPanel filterPanel = new JPanel(); + private JPanel pnl_filter = new JPanel(); - protected JPanel idInputPanel = new JPanel(); + private JPanel pnl_idInput = new JPanel(); - protected JPanel fileChooserPanel = new JPanel(); + private JPanel pnl_fileChooser = new JPanel(); - protected JPanel switchableViewsPanel = new JPanel(new CardLayout()); + protected JPanel pnl_switchableViews = new JPanel(new CardLayout()); - protected CardLayout switchableViewsLayout = (CardLayout) (switchableViewsPanel + protected CardLayout layout_switchableViews = (CardLayout) (pnl_switchableViews .getLayout()); - protected BorderLayout mainLayout = new BorderLayout(); - - protected BorderLayout idInputPanelLayout = new BorderLayout(); - - protected BorderLayout fileChooserPanelLayout = new BorderLayout(); + private BorderLayout mainLayout = new BorderLayout(); - protected JCheckBox rememberSettings = new JCheckBox("Don't ask me again"); + protected JCheckBox chk_rememberSettings = new JCheckBox( + MessageManager.getString("label.dont_ask_me_again")); - protected JCheckBox invertFilter = new JCheckBox("Invert"); + protected JCheckBox chk_invertFilter = new JCheckBox( + MessageManager.getString("label.invert")); protected ImageIcon loadingImage = new ImageIcon(getClass().getResource( "/images/loading.gif")); - protected JLabel loadingImageLabel = new JLabel(loadingImage); + protected JLabel lbl_loading = new JLabel(loadingImage); protected static final String VIEWS_FILTER = "VIEWS_FILTER"; @@ -86,14 +109,12 @@ public abstract class GStructureChooser extends JPanel implements protected static final String VIEWS_ENTER_ID = "VIEWS_ENTER_ID"; - protected JList jListFoundStructures = new JList(); + protected JList jList_FoundStructures = new JList(); - // protected JScrollPane foundStructuresScroller = new JScrollPane( - // jListFoundStructures); + protected JTable tbl_summary = new JTable(); - protected JTable summaryTable = new JTable(); - protected JScrollPane foundStructuresScroller = new JScrollPane( - summaryTable); + protected JScrollPane scrl_foundStructures = new JScrollPane( + tbl_summary); public GStructureChooser() { @@ -109,20 +130,25 @@ public abstract class GStructureChooser extends JPanel implements } } + /** + * Initializes the GUI default properties + * + * @throws Exception + */ private void jbInit() throws Exception { - ok.setFont(new java.awt.Font("Verdana", 0, 12)); - ok.setText(MessageManager.getString("action.view")); - ok.addActionListener(new java.awt.event.ActionListener() + btn_ok.setFont(new java.awt.Font("Verdana", 0, 12)); + btn_ok.setText(MessageManager.getString("action.view")); + btn_ok.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { ok_ActionPerformed(); } }); - cancel.setFont(new java.awt.Font("Verdana", 0, 12)); - cancel.setText(MessageManager.getString("action.cancel")); - cancel.addActionListener(new java.awt.event.ActionListener() + btn_cancel.setFont(new java.awt.Font("Verdana", 0, 12)); + btn_cancel.setText(MessageManager.getString("action.cancel")); + btn_cancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { @@ -130,9 +156,10 @@ public abstract class GStructureChooser extends JPanel implements } }); - pdbFromFile.setFont(new java.awt.Font("Verdana", 0, 12)); - pdbFromFile.setText(" Select PDB File "); - pdbFromFile.addActionListener(new java.awt.event.ActionListener() + btn_pdbFromFile.setFont(new java.awt.Font("Verdana", 0, 12)); + String btn_title = MessageManager.getString("label.select_pdb_file"); + btn_pdbFromFile.setText(" " + btn_title + " "); + btn_pdbFromFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { @@ -140,50 +167,47 @@ public abstract class GStructureChooser extends JPanel implements } }); - jListFoundStructures + jList_FoundStructures .setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - jListFoundStructures.setLayoutOrientation(JList.VERTICAL); - jListFoundStructures.setVisibleRowCount(-1); - foundStructuresScroller.setPreferredSize(new Dimension(500, 300)); - foundStructuresScroller + jList_FoundStructures.setLayoutOrientation(JList.VERTICAL); + jList_FoundStructures.setVisibleRowCount(-1); + scrl_foundStructures.setPreferredSize(new Dimension(500, 300)); + scrl_foundStructures .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - filterOptionsComboBox.setFont(new java.awt.Font("Verdana", 0, 12)); - invertFilter.setFont(new java.awt.Font("Verdana", 0, 12)); - rememberSettings.setFont(new java.awt.Font("Verdana", 0, 12)); + cmb_filterOption.setFont(new java.awt.Font("Verdana", 0, 12)); + chk_invertFilter.setFont(new java.awt.Font("Verdana", 0, 12)); + chk_rememberSettings.setFont(new java.awt.Font("Verdana", 0, 12)); - filterOptionsComboBox.addItemListener(this); - invertFilter.addItemListener(this); + cmb_filterOption.addItemListener(this); + chk_invertFilter.addItemListener(this); - actionPanel.add(rememberSettings); - actionPanel.add(ok); - actionPanel.add(cancel); + pnl_actions.add(chk_rememberSettings); + pnl_actions.add(btn_ok); + pnl_actions.add(btn_cancel); + pnl_filter.add(lbl_result); + pnl_filter.add(cmb_filterOption); + lbl_loading.setVisible(false); - filterPanel.add(resultLabel); - filterPanel.add(filterOptionsComboBox); - loadingImageLabel.setVisible(false); + pnl_filter.add(lbl_loading); - filterPanel.add(loadingImageLabel); + pnl_filter.add(chk_invertFilter); - filterPanel.add(invertFilter); + pnl_idInput.setLayout(new FlowLayout()); + pnl_idInput.add(txt_search); - idInputPanel.setLayout(new FlowLayout()); - idInputPanel.add(search); - - - fileChooserPanel.setLayout(new FlowLayout()); - fileChooserPanel.add(pdbFromFile); - - switchableViewsPanel.add(fileChooserPanel, VIEWS_FROM_FILE); - switchableViewsPanel.add(idInputPanel, VIEWS_ENTER_ID); - switchableViewsPanel.add(foundStructuresScroller, VIEWS_FILTER); + pnl_fileChooser.setLayout(new FlowLayout()); + pnl_fileChooser.add(btn_pdbFromFile); + pnl_switchableViews.add(pnl_fileChooser, VIEWS_FROM_FILE); + pnl_switchableViews.add(pnl_idInput, VIEWS_ENTER_ID); + pnl_switchableViews.add(scrl_foundStructures, VIEWS_FILTER); this.setLayout(mainLayout); - this.add(filterPanel, java.awt.BorderLayout.NORTH); - this.add(switchableViewsPanel, java.awt.BorderLayout.CENTER); - this.add(actionPanel, java.awt.BorderLayout.SOUTH); + this.add(pnl_filter, java.awt.BorderLayout.NORTH); + this.add(pnl_switchableViews, java.awt.BorderLayout.CENTER); + this.add(pnl_actions, java.awt.BorderLayout.SOUTH); mainFrame.setVisible(true); mainFrame.setContentPane(this); @@ -192,23 +216,22 @@ public abstract class GStructureChooser extends JPanel implements } - private ImageIcon scaleImageIcone(ImageIcon imageIcon, int width, int height) - { - Image image = imageIcon.getImage(); // transform it - - Image newimg = image.getScaledInstance(width, height, - java.awt.Image.SCALE_SMOOTH); // scale it the smooth way - - return new ImageIcon(newimg); - } - @Override + /** + * Event listener for the 'filter' combo-box and 'invert' check-box + */ public void itemStateChanged(ItemEvent e) { stateChanged(e); } - public class FilterOptions + /** + * This inner class provides the data model for the structure filter combo-box + * + * @author tcnofoegbu + * + */ + public class FilterOption { private String name; @@ -216,20 +239,13 @@ public abstract class GStructureChooser extends JPanel implements private String view; - public FilterOptions(String name, String value, String view) + public FilterOption(String name, String value, String view) { this.name = name; this.value = value; this.view = view; } - // public FilterOptions(PDBDocField field, String view) - // { - // this.name = "Best " + field.getName(); - // this.value = field.getCode(); - // this.view = view; - // } - public String getName() { return name; @@ -266,13 +282,18 @@ public abstract class GStructureChooser extends JPanel implements } } + public JComboBox getCmbFilterOption() + { + return cmb_filterOption; + } + protected abstract void stateChanged(ItemEvent e); protected abstract void updateCurrentView(); protected abstract void ok_ActionPerformed(); - protected abstract void populateFilterOptions(); + protected abstract void populateFilterComboBox(); protected abstract void pdbFromFile_actionPerformed(); } diff --git a/src/jalview/ws/dbsources/PDBRestClient.java b/src/jalview/ws/dbsources/PDBRestClient.java index e00d9ac..85701b2 100644 --- a/src/jalview/ws/dbsources/PDBRestClient.java +++ b/src/jalview/ws/dbsources/PDBRestClient.java @@ -1,8 +1,8 @@ package jalview.ws.dbsources; -import jalview.ws.uimodel.PDBSearchRequest; -import jalview.ws.uimodel.PDBSearchResponse; -import jalview.ws.uimodel.PDBSearchResponse.PDBResponseSummary; +import jalview.ws.uimodel.PDBRestRequest; +import jalview.ws.uimodel.PDBRestResponse; +import jalview.ws.uimodel.PDBRestResponse.PDBResponseSummary; import java.util.ArrayList; import java.util.Iterator; @@ -26,44 +26,35 @@ public class PDBRestClient { private String pdbSearchEndpoint = "http://wwwdev.ebi.ac.uk/pdbe/search/pdb/select?"; - public static void main(String[] args) - { - PDBSearchRequest request = new PDBSearchRequest(); - request.setAllowEmptySeq(false); - request.setResponseSize(100); - request.setFieldToSearchBy("pfam_name"); - request.setSearchTerm("Lipoc*"); - List wantedFields = new ArrayList(); - wantedFields.add(PDBDocField.MOLECULE_TYPE); - wantedFields.add(PDBDocField.PDB_ID); - wantedFields.add(PDBDocField.GENUS); - wantedFields.add(PDBDocField.GENE_NAME); - wantedFields.add(PDBDocField.TITLE); - request.setWantedFields(wantedFields); - new PDBRestClient().executeRequest(request); - } - - public PDBSearchResponse executeRequest(PDBSearchRequest request) + /** + * Takes a PDBRestRequest object and returns a response upon execution + * + * @param pdbRestRequest + * the pdbRequest to be sent + * @return the pdbResponse object for the given pdbRequest + */ + public PDBRestResponse executeRequest(PDBRestRequest pdbRestRequest) { ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client client = Client.create(clientConfig); - String query = request.getFieldToSearchBy() - + request.getSearchTerm() - + ((request.isAllowEmptySeq()) ? "" + String query = pdbRestRequest.getFieldToSearchBy() + + pdbRestRequest.getSearchTerm() + + ((pdbRestRequest.isAllowEmptySeq()) ? "" : " AND molecule_sequence:['' TO *]"); - String wantedFields = getFieldsAsCommaDelimitedString(request + String wantedFields = getPDBDocFieldsAsCommaDelimitedString(pdbRestRequest .getWantedFields()); - String responseSize = (request.getResponseSize() == 0) ? "200" : String - .valueOf(request.getResponseSize()); - String sortParam = (request.getFieldToSortBy() == null || request + String responseSize = (pdbRestRequest.getResponseSize() == 0) ? "200" + : String.valueOf(pdbRestRequest.getResponseSize()); + String sortParam = (pdbRestRequest.getFieldToSortBy() == null || pdbRestRequest .getFieldToSortBy().trim().isEmpty()) ? "" - : (request - .getFieldToSortBy() + (request.isAscending() ? " asc" : " desc")); + : (pdbRestRequest + .getFieldToSortBy() + (pdbRestRequest.isAscending() ? " asc" + : " desc")); WebResource webResource = client.resource(pdbSearchEndpoint) .queryParam("wt", "json").queryParam("fl", wantedFields) @@ -78,7 +69,7 @@ public class PDBRestClient { if (clientResponse.getStatus() == 400) { - throw new RuntimeException(parseException(responseString)); + throw new RuntimeException(parseJsonExceptionString(responseString)); } else { @@ -86,18 +77,25 @@ public class PDBRestClient + clientResponse.getStatus()); } } - // System.out.println("--------------> " + responseString); - return parseResponse(responseString, request.getWantedFields(), - request.getAssociatedSequence()); + clientResponse = null; + client = null; + return parsePDBJsonResponse(responseString, pdbRestRequest); } - private String parseException(String jsonResponse) + /** + * Process error response from PDB server if/when one occurs. + * + * @param jsonResponse + * the json string containing error message from the server + * @return the processed error message from the json string + */ + public static String parseJsonExceptionString(String jsonErrorResponse) { String errorMessage = "RunTime error"; try { JSONParser jsonParser = new JSONParser(); - JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonResponse); + JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonErrorResponse); JSONObject errorResponse = (JSONObject) jsonObj.get("error"); errorMessage = errorResponse.get("msg").toString(); @@ -111,17 +109,30 @@ public class PDBRestClient return errorMessage; } + /** + * Parses json response string from PDB REST API to a PDBRestResponse + * instance. The parsed response is dynamic and based upon some of the request + * parameters. + * + * @param pdbJsonResponseString + * the json string to be parsed + * @param pdbRestRequest + * the request object which contains parameters used to process the + * json string + * @return + */ @SuppressWarnings("unchecked") - private PDBSearchResponse parseResponse(String jsonResponse, - List wantedFields, String associatedSequence) + public static PDBRestResponse parsePDBJsonResponse( + String pdbJsonResponseString, + PDBRestRequest pdbRestRequest) { - PDBSearchResponse searchResult = new PDBSearchResponse(); + PDBRestResponse searchResult = new PDBRestResponse(); List result = null; try { JSONParser jsonParser = new JSONParser(); JSONObject jsonObj = (JSONObject) jsonParser -.parse(jsonResponse); + .parse(pdbJsonResponseString); JSONObject pdbResponse = (JSONObject) jsonObj.get("response"); String queryTime = ((JSONObject) jsonObj.get("responseHeader")).get( @@ -138,11 +149,10 @@ public class PDBRestClient JSONObject doc = docIter.next(); // if (doc.get("molecule_sequence") != null) // { - result.add(searchResult.new PDBResponseSummary(doc, wantedFields, - associatedSequence)); + result.add(searchResult.new PDBResponseSummary(doc, pdbRestRequest)); // } } - searchResult.setItemsFound(numFound); + searchResult.setNumberOfItemsFound(numFound); searchResult.setResponseTime(queryTime); searchResult.setSearchSummary(result); } @@ -154,23 +164,35 @@ public class PDBRestClient return searchResult; } - private String getFieldsAsCommaDelimitedString(List fields) + /** + * Takes a collection of PDBDocField and converts it into a comma delimited + * string. + * + * @param pdbDocfields + * @return + */ + public static String getPDBDocFieldsAsCommaDelimitedString( + List pdbDocfields) { String result = ""; - if (fields != null && !fields.isEmpty()) + if (pdbDocfields != null && !pdbDocfields.isEmpty()) { StringBuilder returnedFields = new StringBuilder(); - for (PDBDocField field : fields) + for (PDBDocField field : pdbDocfields) { returnedFields.append(",").append(field.getCode()); } - returnedFields.deleteCharAt(0); + returnedFields.deleteCharAt(0); result = returnedFields.toString(); } return result; } + /** + * Represents the fields retrievable from a PDB Document response + * + */ public enum PDBDocField { PDB_ID("PDB Id", "pdb_id"), TITLE("Title", "title"), MOLECULE_NAME( @@ -189,7 +211,9 @@ public class PDBRestClient "Bound Molecule Count", "number_of_bound_molecules"), POLYMER_RESIDUE_COUNT( "Polymer Residue Count", "number_of_polymer_residues"), UNIPROT_COVERAGE( "UniProt Coverage", "uniprot_coverage"), GENUS("GENUS", "genus"), GENE_NAME( - "Gene Name", "gene_name"), ALL("ALL", "text"); + "Gene Name", "gene_name"), EXPERIMENTAL_METHOD( + "Experimental Method", "experimental_method"), ALL("ALL", + "text"); private String name; diff --git a/src/jalview/ws/uimodel/PDBSearchRequest.java b/src/jalview/ws/uimodel/PDBRestRequest.java similarity index 54% rename from src/jalview/ws/uimodel/PDBSearchRequest.java rename to src/jalview/ws/uimodel/PDBRestRequest.java index 3c5f45a..168811f 100644 --- a/src/jalview/ws/uimodel/PDBSearchRequest.java +++ b/src/jalview/ws/uimodel/PDBRestRequest.java @@ -1,3 +1,24 @@ +/* + * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2) + * Copyright (C) 2014 The Jalview Authors + * + * This file is part of Jalview. + * + * Jalview is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation, either version 3 + * of the License, or (at your option) any later version. + * + * Jalview is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty + * of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Jalview. If not, see . + * The Jalview Authors are detailed in the 'AUTHORS' file. + */ + package jalview.ws.uimodel; @@ -6,7 +27,13 @@ import jalview.ws.dbsources.PDBRestClient.PDBDocField; import java.util.ArrayList; import java.util.List; -public class PDBSearchRequest +/** + * Represents the PDB request to be consumed by the PDBRestClient + * + * @author tcnofoegbu + * + */ +public class PDBRestRequest { private String fieldToSearchBy; @@ -16,11 +43,11 @@ public class PDBSearchRequest private String associatedSequence; - private boolean allowEmptySeq; + private boolean allowEmptySequence; private int responseSize; - private boolean isAscending; + private boolean isSortAscending; private List wantedFields = new ArrayList(); @@ -46,12 +73,12 @@ public class PDBSearchRequest public boolean isAllowEmptySeq() { - return allowEmptySeq; + return allowEmptySequence; } public void setAllowEmptySeq(boolean allowEmptySeq) { - this.allowEmptySeq = allowEmptySeq; + this.allowEmptySequence = allowEmptySeq; } public int getResponseSize() @@ -79,15 +106,15 @@ public class PDBSearchRequest return fieldToSortBy; } - public void setFieldToSortBy(String fieldToSortBy, boolean isAscending) + public void setFieldToSortBy(String fieldToSortBy, boolean isSortAscending) { this.fieldToSortBy = fieldToSortBy; - this.isAscending = isAscending; + this.isSortAscending = isSortAscending; } public boolean isAscending() { - return isAscending; + return isSortAscending; } public String getAssociatedSequence() @@ -100,6 +127,4 @@ public class PDBSearchRequest this.associatedSequence = associatedSequence; } - - } diff --git a/src/jalview/ws/uimodel/PDBSearchResponse.java b/src/jalview/ws/uimodel/PDBRestResponse.java similarity index 58% rename from src/jalview/ws/uimodel/PDBSearchResponse.java rename to src/jalview/ws/uimodel/PDBRestResponse.java index 7b172de..5a1f53d 100644 --- a/src/jalview/ws/uimodel/PDBSearchResponse.java +++ b/src/jalview/ws/uimodel/PDBRestResponse.java @@ -1,3 +1,24 @@ +/* + * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2) + * Copyright (C) 2014 The Jalview Authors + * + * This file is part of Jalview. + * + * Jalview is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation, either version 3 + * of the License, or (at your option) any later version. + * + * Jalview is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty + * of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Jalview. If not, see . + * The Jalview Authors are detailed in the 'AUTHORS' file. + */ + package jalview.ws.uimodel; import jalview.ws.dbsources.PDBRestClient.PDBDocField; @@ -11,22 +32,29 @@ import javax.swing.table.DefaultTableModel; import org.json.simple.JSONObject; -public class PDBSearchResponse +/** + * Represents the response model produced by the PDBRestClient upon successful + * execution of a given request + * + * @author tcnofoegbu + * + */ +public class PDBRestResponse { - private int itemsFound; + private int numberOfItemsFound; private String responseTime; private Collection searchSummary; - public int getItemsFound() + public int getNumberOfItemsFound() { - return itemsFound; + return numberOfItemsFound; } - public void setItemsFound(int itemFound) + public void setNumberOfItemsFound(int itemFound) { - this.itemsFound = itemFound; + this.numberOfItemsFound = itemFound; } public String getResponseTime() @@ -49,6 +77,14 @@ public class PDBSearchResponse this.searchSummary = searchSummary; } + /** + * Convenience method to obtain a List model for a given summary list + * + * @param summariesList + * the summary list which contains the data for generating the lists + * data + * @return the list model generated for the search summary + */ public static DefaultListModel getListModel( Collection summariesList) { @@ -60,7 +96,19 @@ public class PDBSearchResponse return defaultListModel; } - public static DefaultTableModel getTableModel(PDBSearchRequest request, + /** + * Convenience method to obtain a Table model for a given summary List and + * request + * + * @param request + * the PDBRestRequest object which holds useful information for + * creating a table model + * @param summariesList + * the summary list which contains the data for populating the + * table's rows + * @return the table model which was dynamically generated + */ + public static DefaultTableModel getTableModel(PDBRestRequest request, Collection summariesList) { DefaultTableModel model = new DefaultTableModel(); @@ -76,38 +124,42 @@ public class PDBSearchResponse for (PDBResponseSummary res : summariesList) { - model.addRow(res.getSummaryColums()); + model.addRow(res.getSummaryData()); } return model; } - - + /** + * Model for a unique response summary + * + * @author tcnofoegbu + * + */ public class PDBResponseSummary { private String pdbId; - private String summaryRow; + private String concatenatedSummaryData; - private String[] summaryColums; + private String[] summaryData; private String associatedSequence; private int width = 480; - public PDBResponseSummary(JSONObject doc, - List diplayFields, String associatedSeq) + public PDBResponseSummary(JSONObject doc, PDBRestRequest request) { StringBuilder summaryBuilder = new StringBuilder(); - + List diplayFields = request.getWantedFields(); + String associatedSeq = request.getAssociatedSequence(); int colCounter = 0; - summaryColums = new String[(associatedSeq != null) ? diplayFields + summaryData = new String[(associatedSeq != null) ? diplayFields .size() + 1 : diplayFields.size()]; if (associatedSeq != null) { this.associatedSequence = (associatedSeq.length() > 18) ? associatedSeq .substring(0, 18) : associatedSeq; - summaryColums[0] = associatedSequence; + summaryData[0] = associatedSequence; colCounter = 1; } @@ -142,25 +194,25 @@ public class PDBSearchResponse + getClass().getResource("/images/sugar.png") .toString() + "\">"); } - summaryColums[colCounter++] = moleculeType; + summaryData[colCounter++] = moleculeType; } else if (field.equals(PDBDocField.PDB_ID) && doc.get(PDBDocField.PDB_ID.getCode()) != null) { this.pdbId = doc.get(PDBDocField.PDB_ID.getCode()).toString(); summaryBuilder.append(this.pdbId).append(" | "); - summaryColums[colCounter++] = this.pdbId; + summaryData[colCounter++] = this.pdbId; } else if (doc.get(field.getCode()) != null) { summaryBuilder.append(field.getName()).append(": ") .append(doc.get(field.getCode())).append(" | "); - summaryColums[colCounter++] = doc.get(field.getCode()).toString(); + summaryData[colCounter++] = doc.get(field.getCode()).toString(); } } int endIndex = summaryBuilder.lastIndexOf(" | "); String fSummary = summaryBuilder.toString().substring(0, endIndex); - this.summaryRow = fSummary.trim(); + this.concatenatedSummaryData = fSummary.trim(); summaryBuilder = null; } @@ -174,24 +226,24 @@ public class PDBSearchResponse this.pdbId = pdbId; } - public String getSummaryRow() + public String getConcatenatedSummaryData() { - return summaryRow; + return concatenatedSummaryData; } - public void setSummaryRow(String summary) + public void setConcatenatedSummaryData(String concatenatedSummaryData) { - this.summaryRow = summary; + this.concatenatedSummaryData = concatenatedSummaryData; } - public String[] getSummaryColums() + public String[] getSummaryData() { - return summaryColums; + return summaryData; } - public void setSummaryColums(String[] summaryColums) + public void setSummaryData(String[] summaryData) { - this.summaryColums = summaryColums; + this.summaryData = summaryData; } public String toString() @@ -199,7 +251,7 @@ public class PDBSearchResponse StringBuilder html = new StringBuilder(); html.append("
"); - html.append(summaryRow); + html.append(concatenatedSummaryData); html.append("
"); return html.toString(); } @@ -207,7 +259,7 @@ public class PDBSearchResponse @Override public int hashCode() { - return Objects.hash(this.pdbId, this.summaryRow); + return Objects.hash(this.pdbId, this.concatenatedSummaryData); } @Override @@ -222,7 +274,8 @@ public class PDBSearchResponse // Custom equality check here. return this.pdbId.equals(that.pdbId) - && this.summaryRow.equals(that.summaryRow); + && this.concatenatedSummaryData + .equals(that.concatenatedSummaryData); } } diff --git a/test/jalview/gui/PDBSearchPanelTest.java b/test/jalview/gui/PDBSearchPanelTest.java new file mode 100644 index 0000000..356e664 --- /dev/null +++ b/test/jalview/gui/PDBSearchPanelTest.java @@ -0,0 +1,28 @@ +package jalview.gui; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class PDBSearchPanelTest +{ + + @Before + public void setUp() throws Exception + { + } + + @After + public void tearDown() throws Exception + { + } + + @Test + public void test() + { + fail("Not yet implemented"); + } + +} diff --git a/test/jalview/gui/StructureChooserTest.java b/test/jalview/gui/StructureChooserTest.java new file mode 100644 index 0000000..078174f --- /dev/null +++ b/test/jalview/gui/StructureChooserTest.java @@ -0,0 +1,100 @@ +package jalview.gui; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import jalview.datamodel.DBRefEntry; +import jalview.datamodel.PDBEntry; +import jalview.datamodel.Sequence; +import jalview.datamodel.SequenceI; +import jalview.ws.dbsources.PDBRestClient.PDBDocField; + +import java.util.ArrayList; +import java.util.List; +import java.util.Vector; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class StructureChooserTest +{ + Sequence seq; + + @Before + public void setUp() throws Exception + { + seq = new Sequence("Test_Seq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1, 26); + seq.setDatasetSequence(seq); + for (int x = 1; x < 5; x++) + { + DBRefEntry dbRef = new DBRefEntry(); + dbRef.setAccessionId("XYZ_" + x); + seq.addDBRef(dbRef); + } + + PDBEntry dbRef = new PDBEntry(); + dbRef.setId("1tim"); + + Vector pdbIds = new Vector(); + pdbIds.add(dbRef); + + seq.setPDBId(pdbIds); + } + + @After + public void tearDown() throws Exception + { + seq = null; + } + + @Test + public void getPDBIdColumIndexTest() + { + List wantedFields = new ArrayList(); + wantedFields.add(PDBDocField.MOLECULE_TYPE); + wantedFields.add(PDBDocField.GENUS); + wantedFields.add(PDBDocField.GENE_NAME); + wantedFields.add(PDBDocField.TITLE); + wantedFields.add(PDBDocField.PDB_ID); + assertEquals(5, StructureChooser.getPDBIdColumIndex(wantedFields)); + } + + @Test + public void buildQueryTest() + { + assertEquals( + "1tim OR text:XYZ_1 OR text:XYZ_2 OR text:XYZ_3 OR text:XYZ_4", + StructureChooser.buildQuery(seq)); + } + + @Test + public void populateFilterComboBoxTest() + { + SequenceI[] selectedSeqs = new SequenceI[] + { seq }; + StructureChooser sc = new StructureChooser(selectedSeqs, seq, + null); + sc.populateFilterComboBox(); + int optionsSize = sc.getCmbFilterOption().getItemCount(); + assertEquals(2, optionsSize); // if structures are not discovered then don't + // populate filter options + + sc.setStructuresDiscovered(true); + sc.populateFilterComboBox(); + optionsSize = sc.getCmbFilterOption().getItemCount(); + assertTrue(optionsSize > 2); // if structures are found, filter options + // should be populated + } + + @Test + public void fetchStructuresInfoTest() + { + SequenceI[] selectedSeqs = new SequenceI[] + { seq }; + StructureChooser sc = new StructureChooser(selectedSeqs, seq, null); + sc.fetchStructuresMetaData(); + assertTrue(sc.getDiscoveredStructuresSet() != null); + assertTrue(sc.getDiscoveredStructuresSet().size() > 0); + + } +} diff --git a/test/jalview/io/pdb_request_json_error.txt b/test/jalview/io/pdb_request_json_error.txt new file mode 100644 index 0000000..de14bf1 --- /dev/null +++ b/test/jalview/io/pdb_request_json_error.txt @@ -0,0 +1,17 @@ +{ + "responseHeader": { + "status": 400, + "QTime": 0, + "params": { + "sort": "", + "fl": "pdb_id", + "q": "text:abc OR text:go:abc AND molecule_sequence:['' TO *]", + "wt": "json", + "rows": "100" + } + }, + "error": { + "msg": "org.apache.solr.search.SyntaxError: Cannot parse 'text:abc OR text:go:abc AND molecule_sequence:['' TO *]': Encountered \" \":\" \": \"\" at line 1, column 19.", + "code": 400 + } +} \ No newline at end of file diff --git a/test/jalview/io/pdb_response_json.txt b/test/jalview/io/pdb_response_json.txt new file mode 100644 index 0000000..e3f3583 --- /dev/null +++ b/test/jalview/io/pdb_response_json.txt @@ -0,0 +1,176 @@ +{ + "responseHeader": { + "status": 0, + "QTime": 0, + "params": { + "sort": "", + "fl": "molecule_type,pdb_id,genus,gene_name,title", + "q": "text:abc AND molecule_sequence:['' TO *]", + "wt": "json", + "rows": "100" + } + }, + "response": { + "numFound": 931, + "start": 0, + "docs": [ + { + "pdb_id": "3qf4", + "title": "Crystal structure of a heterodimeric ABC transporter in its inward-facing conformation", + "genus": [ + "Thermotoga" + ], + "molecule_type": "Protein", + "gene_name": [ + "THEMA_03290", + "Tmari_0285", + "TM_0287" + ] + }, + { + "pdb_id": "4wbs", + "title": "Crystal structure of an ABC transporter related protein from Burkholderia phymatum", + "genus": [ + "Burkholderia" + ], + "molecule_type": "Protein", + "gene_name": [ + "Bphy_0327" + ] + }, + { + "pdb_id": "1hn0", + "title": "CRYSTAL STRUCTURE OF CHONDROITIN ABC LYASE I FROM PROTEUS VULGARIS AT 1.9 ANGSTROMS RESOLUTION", + "genus": [ + "Proteus" + ], + "molecule_type": "Protein" + }, + { + "pdb_id": "4a82", + "title": "Fitted model of staphylococcus aureus sav1866 model ABC transporter in the human cystic fibrosis transmembrane conductance regulator volume map EMD-1966.", + "genus": [ + "Homo" + ], + "molecule_type": "Protein", + "gene_name": [ + "SAV1866" + ] + }, + { + "pdb_id": "3nh6", + "title": "Nucleotide Binding Domain of human ABCB6 (apo structure)", + "genus": [ + "Homo" + ], + "molecule_type": "Protein", + "gene_name": [ + "ABCB6", + "UMAT", + "MTABC3", + "PRP" + ] + }, + { + "pdb_id": "2nq2", + "title": "An inward-facing conformation of a putative metal-chelate type ABC transporter.", + "genus": [ + "Haemophilus" + ], + "molecule_type": "Protein", + "gene_name": [ + "HI_1471" + ] + }, + { + "pdb_id": "3s4u", + "title": "Crystal structure of open, unliganded E. coli PhnD H157A", + "genus": [ + "Escherichia" + ], + "molecule_type": "Protein", + "gene_name": [ + "phnD", + "UTI89_C4699" + ] + }, + { + "pdb_id": "4q4a", + "title": "Improved model of AMP-PNP bound TM287/288", + "genus": [ + "Thermotoga" + ], + "molecule_type": "Protein", + "gene_name": [ + "TM_0288" + ] + }, + { + "pdb_id": "1oxs", + "title": "Crystal structure of GlcV, the ABC-ATPase of the glucose ABC transporter from Sulfolobus solfataricus", + "genus": [ + "Sulfolobus" + ], + "molecule_type": "Protein", + "gene_name": [ + "SSO2850" + ] + }, + { + "pdb_id": "4q4j", + "title": "Structure of crosslinked TM287/288_S498C_S520C mutant", + "genus": [ + "Thermotoga" + ], + "molecule_type": "Protein", + "gene_name": [ + "TM_0288" + ] + }, + { + "pdb_id": "1oxt", + "title": "Crystal structure of GlcV, the ABC-ATPase of the glucose ABC transporter from Sulfolobus solfataricus", + "genus": [ + "Sulfolobus" + ], + "molecule_type": "Protein", + "gene_name": [ + "SSO2850" + ] + }, + { + "pdb_id": "4q4h", + "title": "TM287/288 in its apo state", + "genus": [ + "Thermotoga" + ], + "molecule_type": "Protein", + "gene_name": [ + "TM_0288" + ] + }, + { + "pdb_id": "3qf4", + "title": "Crystal structure of a heterodimeric ABC transporter in its inward-facing conformation", + "genus": [ + "Thermotoga" + ], + "molecule_type": "Protein", + "gene_name": [ + "TM_0288" + ] + }, + { + "pdb_id": "2fgk", + "title": "Crystal structure of the ABC-cassette E631Q mutant of HlyB with bound ATP", + "genus": [ + "Escherichia" + ], + "molecule_type": "Protein", + "gene_name": [ + "hlyB" + ] + } + ] + } +} \ No newline at end of file diff --git a/test/jalview/ws/dbsources/PDBRestClientTest.java b/test/jalview/ws/dbsources/PDBRestClientTest.java new file mode 100644 index 0000000..3f33ffe --- /dev/null +++ b/test/jalview/ws/dbsources/PDBRestClientTest.java @@ -0,0 +1,168 @@ +package jalview.ws.dbsources; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import jalview.ws.dbsources.PDBRestClient.PDBDocField; +import jalview.ws.uimodel.PDBRestRequest; +import jalview.ws.uimodel.PDBRestResponse; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class PDBRestClientTest +{ + + @Before + public void setUp() throws Exception + { + } + + @After + public void tearDown() throws Exception + { + } + + @Test + public void executeRequestTest() + { + List wantedFields = new ArrayList(); + wantedFields.add(PDBDocField.MOLECULE_TYPE); + wantedFields.add(PDBDocField.PDB_ID); + wantedFields.add(PDBDocField.GENUS); + wantedFields.add(PDBDocField.GENE_NAME); + wantedFields.add(PDBDocField.TITLE); + + PDBRestRequest request = new PDBRestRequest(); + request.setAllowEmptySeq(false); + request.setResponseSize(100); + request.setFieldToSearchBy("text:"); + request.setSearchTerm("abc"); + request.setWantedFields(wantedFields); + + PDBRestResponse response = new PDBRestClient().executeRequest(request); + assertTrue(response.getNumberOfItemsFound() > 99); + assertTrue(response.getSearchSummary() != null); + assertTrue(response.getSearchSummary().size() > 99); + } + + @Test + public void getPDBDocFieldsAsCommaDelimitedStringTest() + { + List wantedFields = new ArrayList(); + wantedFields.add(PDBDocField.MOLECULE_TYPE); + wantedFields.add(PDBDocField.PDB_ID); + wantedFields.add(PDBDocField.GENUS); + wantedFields.add(PDBDocField.GENE_NAME); + wantedFields.add(PDBDocField.TITLE); + assertEquals("molecule_type,pdb_id,genus,gene_name,title", + PDBRestClient + .getPDBDocFieldsAsCommaDelimitedString(wantedFields)); + } + + @Test + public void parsePDBJsonExceptionStringTest() + { + List wantedFields = new ArrayList(); + wantedFields.add(PDBDocField.MOLECULE_TYPE); + wantedFields.add(PDBDocField.PDB_ID); + wantedFields.add(PDBDocField.GENUS); + wantedFields.add(PDBDocField.GENE_NAME); + wantedFields.add(PDBDocField.TITLE); + + PDBRestRequest request = new PDBRestRequest(); + request.setAllowEmptySeq(false); + request.setResponseSize(100); + request.setFieldToSearchBy("text:"); + request.setSearchTerm("abc"); + request.setWantedFields(wantedFields); + + String jsonErrorResponse = ""; + try + { + jsonErrorResponse = readJsonStringFromFile("test/jalview/io/pdb_request_json_error.txt"); + } catch (IOException e) + { + e.printStackTrace(); + } + + String parsedErrorResponse = PDBRestClient + .parseJsonExceptionString(jsonErrorResponse); + String expectedErrorMsg = "org.apache.solr.search.SyntaxError: Cannot parse 'text:abc OR text:go:abc AND molecule_sequence:['' TO *]': Encountered \" \":\" \": \"\" at line 1, column 19.{\"q\":\"text:abc OR text:go:abc AND molecule_sequence:['' TO *]\",\"fl\":\"pdb_id\",\"sort\":\"\",\"rows\":\"100\",\"wt\":\"json\"}"; + + assertEquals(expectedErrorMsg, parsedErrorResponse); + } + + @Test(expected = RuntimeException.class) + public void testForExpectedRuntimeException() + { + List wantedFields = new ArrayList(); + wantedFields.add(PDBDocField.PDB_ID); + + PDBRestRequest request = new PDBRestRequest(); + request.setFieldToSearchBy("text:"); + request.setSearchTerm("abc OR text:go:abc"); + request.setWantedFields(wantedFields); + new PDBRestClient().executeRequest(request); + } + + @Test + public void parsePDBJsonResponseTest() + { + List wantedFields = new ArrayList(); + wantedFields.add(PDBDocField.MOLECULE_TYPE); + wantedFields.add(PDBDocField.PDB_ID); + wantedFields.add(PDBDocField.GENUS); + wantedFields.add(PDBDocField.GENE_NAME); + wantedFields.add(PDBDocField.TITLE); + + PDBRestRequest request = new PDBRestRequest(); + request.setAllowEmptySeq(false); + request.setWantedFields(wantedFields); + + String jsonString = ""; + try + { + jsonString = readJsonStringFromFile("test/jalview/io/pdb_response_json.txt"); + } catch (IOException e) + { + e.printStackTrace(); + } + PDBRestResponse response = PDBRestClient.parsePDBJsonResponse( + jsonString, request); + assertTrue(response.getSearchSummary() != null); + assertTrue(response.getNumberOfItemsFound() == 931); + assertTrue(response.getSearchSummary().size() == 14); + } + + public String readJsonStringFromFile(String filePath) throws IOException + { + String fileContent; + BufferedReader br = new BufferedReader(new FileReader(filePath)); + try + { + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); + + while (line != null) + { + sb.append(line); + sb.append(System.lineSeparator()); + line = br.readLine(); + } + fileContent = sb.toString(); + } finally + { + br.close(); + } + return fileContent; + } + + +} -- 1.7.10.2