From: tcofoegbu Date: Tue, 19 Apr 2016 14:37:47 +0000 (+0100) Subject: JAL-2071 architectural improvement for Plugable Free Text Search Services X-Git-Tag: Release_2_10_0~261 X-Git-Url: http://source.jalview.org/gitweb/?a=commitdiff_plain;h=64dd25185d2caf389946bb7e70053183d5aa31a6;p=jalview.git JAL-2071 architectural improvement for Plugable Free Text Search Services --- diff --git a/resources/fts/pdb_data_columns.conf b/resources/fts/pdb_data_columns.conf new file mode 100644 index 0000000..5eebd15 --- /dev/null +++ b/resources/fts/pdb_data_columns.conf @@ -0,0 +1,106 @@ +pdb_data_columns +# +_group.id +_group.name +_group.sort_order +g1;Quality Measures;1 +g2;Cross References;2 +g3;Names & Taxonomy;3 +g4;Procedures & Softwares;4 +g5;Date Of;5 +g6;Miscellenous;6 +# +_data_column.name +_data_column.code +_data_column.group_id +_data_column.min_col_width +_data_column.max_col_width +_data_column.preferred_col_width +_data_column.is_primary_key +_data_column.is_shown_by_default +_data_column.is_searchable +PDB Id;pdb_id;g2;40;60;45;true;true;true +Title;title;g6;300;1500;400;false;true;false +Molecule;molecule_name;g3;50;400;95;false;false;true +Molecule Type;molecule_type;g3;50;400;95;false;false;true +Sequence;molecule_sequence;g6;50;400;95;false;false;false +PFAM Accession;pfam_accession;g2;50;400;95;false;false;true +PFAM Name;pfam_name;g3;50;400;95;false;false;true +InterPro Name;interpro_name;g3;50;400;95;false;false;false +InterPro Accession;interpro_accession;g2;50;400;95;false;false;false +UniProt Id;uniprot_id;g2;50;400;95;false;false;true +UniProt Accession;uniprot_accession;g2;50;400;95;false;false;false +UniProt Coverage;uniprot_coverage;g6;50;400;95;false;false;false +Uniprot Features;uniprot_features;g6;50;400;95;false;false;false +R Factor;r_factor;g1;50;150;85;false;false;false +Resolution;resolution;g1;50;150;85;false;true;false +Data Quality;data_quality;g1;50;150;85;false;false;false +Overall Quality;overall_quality;g1;50;150;85;false;false;false +Number of Polymers;number_of_polymers;g6;50;400;95;false;false;false +Number of Protein Chains;number_of_protein_chains;g6;50;400;95;false;false;false +Number of Bound Molecule;number_of_bound_molecules;g6;50;400;95;false;false;false +Number of Polymer Residue;number_of_polymer_residues;g6;50;400;95;false;false;false +GENUS;genus;g3;50;400;95;false;false;true +Gene Name;gene_name;g3;50;400;95;false;false;true +Experimental Method;experimental_method;g4;50;400;95;false;false;false +GO Id;go_id;g2;50;400;95;false;false;false +Assembly Id;assembly_id;g2;50;400;95;false;false;false +Assembly Form;assembly_form;g6;50;400;95;false;false;false +Assembly Type;assembly_type;g6;50;400;95;false;false;false +Space Group;spacegroup;g6;50;400;95;false;false;false +Cath Code;cath_code;g2;50;400;95;false;false;false +Tax Id;tax_id;g2;50;400;95;false;false;false +Tax Query;tax_query;g2;50;400;95;false;false;false +Interacting Entity Id;interacting_entity_id;g2;50;400;95;false;false;false +Interacting Molecules;interacting_molecules;g6;50;400;95;false;false;false +Pubmed Id;pubmed_id;g2;50;400;95;false;false;false +Status;status;g6;50;400;95;false;false;false +Model Quality;model_quality;g1;50;150;85;false;false;false +Pivot Resolution;pivot_resolution;g1;50;150;85;false;false;false +Data reduction software;data_reduction_software;g4;50;400;95;false;false;false +Max observed residues;max_observed_residues;g6;50;400;95;false;false;false +Organism scientific name;organism_scientific_name;g3;50;400;95;false;false;false +Super kingdom;superkingdom;g3;50;400;95;false;false;false +Rank;rank;g3;50;400;95;false;false;false +Crystallisation Ph;crystallisation_ph;g6;50;400;95;false;false;false +Biological Function;biological_function;g6;50;400;95;false;false;false +Biological Process;biological_process;g6;50;400;95;false;false;false +Biological Cell Component;biological_cell_component;g6;50;400;95;false;false;false +Compound Name;compound_name;g3;50;400;95;false;false;false +Compound Id;compound_id;g2;50;400;95;false;false;false +Compound Weight;compound_weight;g6;50;400;95;false;false;false +Compound Systematic Name;compound_systematic_name;g3;50;400;95;false;false;false +Interacting Ligands;interacting_ligands;g6;50;400;95;false;false;false +Journal;journal;g6;50;400;95;false;false;false +All Authors;all_authors;g6;50;400;95;false;false;false +Experiment Data Available;experiment_data_available;g6;50;400;95;false;false;false +Diffraction Protocol;diffraction_protocol;g4;50;400;95;false;false;false +Refinement Software;refinement_software;g4;50;400;95;false;false;false +Structure Determination Method;structure_determination_method;g4;50;400;95;false;false;false +Synchrotron Site;synchrotron_site;g6;50;400;95;false;false;false +Sample Preparation Method;sample_preparation_method;g4;50;400;95;false;false;false +Entry Authors;entry_authors;g6;50;400;95;false;false;false +Citation Title;citation_title;g6;50;400;95;false;false;false +Structure Solution Software;structure_solution_software;g4;50;400;95;false;false;false +Entry Entity;entry_entity;g6;50;400;95;false;false;false +R Free;r_free;g1;50;150;85;false;false;false +Number of Polymer Entities;number_of_polymer_entities;g6;50;400;95;false;false;false +Number of Bound Entities;number_of_bound_entities;g6;50;400;95;false;false;false +Crystallisation Reservoir;crystallisation_reservoir;g6;50;400;95;false;false;false +Data Scalling Software;data_scaling_software;g4;50;400;95 ;false;false;false +Detector;detector;g6;50;400;95;false;false;false +Detector Type;detector_type;g6;50;400;95;false;false;false +Modified Residue Flag;modified_residue_flag;g6;50;400;95;false;false;false +Number of Copies;number_of_copies;g6;50;400;95;false;false;false +Struc Asym Id;struct_asym_id;g2;50;400;95;false;false;false +Homologus PDB Entity Id;homologus_pdb_entity_id;g2;50;400;95;false;false;false +Molecule Synonym;molecule_synonym;g6;50;400;95;false;false;false +Deposition Site;deposition_site;g6;50;400;95;false;false;false +Synchrotron Beamline;synchrotron_beamline;g6;50;400;95;false;false;false +Entity Id; entity_id;g2;50;400;95;false;false;false +Beam Source Name;beam_source_name;g3;50;400;95;false;false;false +Processing Site;processing_site;g6;50;400;95;false;false;false +Entity Weight;entity_weight;g6;50;400;95;false;false;false +Version;_version_;g6;50;400;95;false;false;false +ALL;text;g6;50;400;95;false;false;true +# diff --git a/resources/fts/uniprot_data_columns.conf b/resources/fts/uniprot_data_columns.conf new file mode 100644 index 0000000..5eebd15 --- /dev/null +++ b/resources/fts/uniprot_data_columns.conf @@ -0,0 +1,106 @@ +pdb_data_columns +# +_group.id +_group.name +_group.sort_order +g1;Quality Measures;1 +g2;Cross References;2 +g3;Names & Taxonomy;3 +g4;Procedures & Softwares;4 +g5;Date Of;5 +g6;Miscellenous;6 +# +_data_column.name +_data_column.code +_data_column.group_id +_data_column.min_col_width +_data_column.max_col_width +_data_column.preferred_col_width +_data_column.is_primary_key +_data_column.is_shown_by_default +_data_column.is_searchable +PDB Id;pdb_id;g2;40;60;45;true;true;true +Title;title;g6;300;1500;400;false;true;false +Molecule;molecule_name;g3;50;400;95;false;false;true +Molecule Type;molecule_type;g3;50;400;95;false;false;true +Sequence;molecule_sequence;g6;50;400;95;false;false;false +PFAM Accession;pfam_accession;g2;50;400;95;false;false;true +PFAM Name;pfam_name;g3;50;400;95;false;false;true +InterPro Name;interpro_name;g3;50;400;95;false;false;false +InterPro Accession;interpro_accession;g2;50;400;95;false;false;false +UniProt Id;uniprot_id;g2;50;400;95;false;false;true +UniProt Accession;uniprot_accession;g2;50;400;95;false;false;false +UniProt Coverage;uniprot_coverage;g6;50;400;95;false;false;false +Uniprot Features;uniprot_features;g6;50;400;95;false;false;false +R Factor;r_factor;g1;50;150;85;false;false;false +Resolution;resolution;g1;50;150;85;false;true;false +Data Quality;data_quality;g1;50;150;85;false;false;false +Overall Quality;overall_quality;g1;50;150;85;false;false;false +Number of Polymers;number_of_polymers;g6;50;400;95;false;false;false +Number of Protein Chains;number_of_protein_chains;g6;50;400;95;false;false;false +Number of Bound Molecule;number_of_bound_molecules;g6;50;400;95;false;false;false +Number of Polymer Residue;number_of_polymer_residues;g6;50;400;95;false;false;false +GENUS;genus;g3;50;400;95;false;false;true +Gene Name;gene_name;g3;50;400;95;false;false;true +Experimental Method;experimental_method;g4;50;400;95;false;false;false +GO Id;go_id;g2;50;400;95;false;false;false +Assembly Id;assembly_id;g2;50;400;95;false;false;false +Assembly Form;assembly_form;g6;50;400;95;false;false;false +Assembly Type;assembly_type;g6;50;400;95;false;false;false +Space Group;spacegroup;g6;50;400;95;false;false;false +Cath Code;cath_code;g2;50;400;95;false;false;false +Tax Id;tax_id;g2;50;400;95;false;false;false +Tax Query;tax_query;g2;50;400;95;false;false;false +Interacting Entity Id;interacting_entity_id;g2;50;400;95;false;false;false +Interacting Molecules;interacting_molecules;g6;50;400;95;false;false;false +Pubmed Id;pubmed_id;g2;50;400;95;false;false;false +Status;status;g6;50;400;95;false;false;false +Model Quality;model_quality;g1;50;150;85;false;false;false +Pivot Resolution;pivot_resolution;g1;50;150;85;false;false;false +Data reduction software;data_reduction_software;g4;50;400;95;false;false;false +Max observed residues;max_observed_residues;g6;50;400;95;false;false;false +Organism scientific name;organism_scientific_name;g3;50;400;95;false;false;false +Super kingdom;superkingdom;g3;50;400;95;false;false;false +Rank;rank;g3;50;400;95;false;false;false +Crystallisation Ph;crystallisation_ph;g6;50;400;95;false;false;false +Biological Function;biological_function;g6;50;400;95;false;false;false +Biological Process;biological_process;g6;50;400;95;false;false;false +Biological Cell Component;biological_cell_component;g6;50;400;95;false;false;false +Compound Name;compound_name;g3;50;400;95;false;false;false +Compound Id;compound_id;g2;50;400;95;false;false;false +Compound Weight;compound_weight;g6;50;400;95;false;false;false +Compound Systematic Name;compound_systematic_name;g3;50;400;95;false;false;false +Interacting Ligands;interacting_ligands;g6;50;400;95;false;false;false +Journal;journal;g6;50;400;95;false;false;false +All Authors;all_authors;g6;50;400;95;false;false;false +Experiment Data Available;experiment_data_available;g6;50;400;95;false;false;false +Diffraction Protocol;diffraction_protocol;g4;50;400;95;false;false;false +Refinement Software;refinement_software;g4;50;400;95;false;false;false +Structure Determination Method;structure_determination_method;g4;50;400;95;false;false;false +Synchrotron Site;synchrotron_site;g6;50;400;95;false;false;false +Sample Preparation Method;sample_preparation_method;g4;50;400;95;false;false;false +Entry Authors;entry_authors;g6;50;400;95;false;false;false +Citation Title;citation_title;g6;50;400;95;false;false;false +Structure Solution Software;structure_solution_software;g4;50;400;95;false;false;false +Entry Entity;entry_entity;g6;50;400;95;false;false;false +R Free;r_free;g1;50;150;85;false;false;false +Number of Polymer Entities;number_of_polymer_entities;g6;50;400;95;false;false;false +Number of Bound Entities;number_of_bound_entities;g6;50;400;95;false;false;false +Crystallisation Reservoir;crystallisation_reservoir;g6;50;400;95;false;false;false +Data Scalling Software;data_scaling_software;g4;50;400;95 ;false;false;false +Detector;detector;g6;50;400;95;false;false;false +Detector Type;detector_type;g6;50;400;95;false;false;false +Modified Residue Flag;modified_residue_flag;g6;50;400;95;false;false;false +Number of Copies;number_of_copies;g6;50;400;95;false;false;false +Struc Asym Id;struct_asym_id;g2;50;400;95;false;false;false +Homologus PDB Entity Id;homologus_pdb_entity_id;g2;50;400;95;false;false;false +Molecule Synonym;molecule_synonym;g6;50;400;95;false;false;false +Deposition Site;deposition_site;g6;50;400;95;false;false;false +Synchrotron Beamline;synchrotron_beamline;g6;50;400;95;false;false;false +Entity Id; entity_id;g2;50;400;95;false;false;false +Beam Source Name;beam_source_name;g3;50;400;95;false;false;false +Processing Site;processing_site;g6;50;400;95;false;false;false +Entity Weight;entity_weight;g6;50;400;95;false;false;false +Version;_version_;g6;50;400;95;false;false;false +ALL;text;g6;50;400;95;false;false;true +# diff --git a/resources/lang/Messages.properties b/resources/lang/Messages.properties index 05505a4..d1bd66a 100644 --- a/resources/lang/Messages.properties +++ b/resources/lang/Messages.properties @@ -1241,7 +1241,7 @@ label.hide_insertions = Hide Insertions label.mark_as_representative = Mark as representative 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.pdb_sequence_fetcher = PDB Sequence Fetcher label.result = result label.results = results label.structure_chooser = Structure Chooser @@ -1292,3 +1292,4 @@ status.cancelled_image_export_operation = Cancelled {0} export operation. info.error_creating_file = Error creating {0} file. exception.outofmemory_loading_mmcif_file = Out of memory loading mmCIF File info.error_creating_file = Error creating {0} file. +label.uniprot_sequence_fetcher = UniProt Sequence Fetcher \ No newline at end of file diff --git a/src/jalview/fts/api/FTSData.java b/src/jalview/fts/api/FTSData.java new file mode 100644 index 0000000..83a704a --- /dev/null +++ b/src/jalview/fts/api/FTSData.java @@ -0,0 +1,8 @@ +package jalview.fts.api; + +public interface FTSData +{ + public Object[] getSummaryData(); + + public Object getPrimaryKey(); +} diff --git a/src/jalview/fts/api/FTSDataColumnGroupI.java b/src/jalview/fts/api/FTSDataColumnGroupI.java new file mode 100644 index 0000000..1f23976 --- /dev/null +++ b/src/jalview/fts/api/FTSDataColumnGroupI.java @@ -0,0 +1,10 @@ +package jalview.fts.api; + +public interface FTSDataColumnGroupI +{ + public String getID(); + + public String getName(); + + public int getSortOrder(); +} diff --git a/src/jalview/fts/api/FTSDataColumnI.java b/src/jalview/fts/api/FTSDataColumnI.java new file mode 100644 index 0000000..f6fc5da --- /dev/null +++ b/src/jalview/fts/api/FTSDataColumnI.java @@ -0,0 +1,22 @@ +package jalview.fts.api; + +public interface FTSDataColumnI +{ + public String getName(); + + public String getCode(); + + public int getMinWidth(); + + public int getMaxWidth(); + + public int getPreferredWidth(); + + public boolean isPrimaryKeyColumn(); + + public boolean isSearchable(); + + public boolean isVisibleByDefault(); + + public FTSDataColumnGroupI getGroup(); +} diff --git a/src/jalview/fts/api/FTSRestClientI.java b/src/jalview/fts/api/FTSRestClientI.java new file mode 100644 index 0000000..b7ce5df --- /dev/null +++ b/src/jalview/fts/api/FTSRestClientI.java @@ -0,0 +1,34 @@ +package jalview.fts.api; + +import jalview.fts.core.FTSRestRequest; +import jalview.fts.core.FTSRestResponse; + +import java.util.Collection; + +public interface FTSRestClientI +{ + + public FTSRestResponse executeRequest(FTSRestRequest pdbRestRequest) + throws Exception; + + public String getColumnDataConfigFile(); + + public FTSDataColumnGroupI getDataColumnGroupById(String id) + throws Exception; + + public FTSDataColumnI getDataColumnByNameOrCode(String nameOrCode) + throws Exception; + + public int getPrimaryKeyColumIndex( + Collection wantedFields, boolean hasRefSeq) + throws Exception; + + public FTSDataColumnI getPrimaryKeyColumn(); + + public Collection getAllDefaulDisplayedDataColumns(); + + public Collection getSearchableDataColumns(); + + public Collection getAllFTSDataColumns(); +} + diff --git a/src/jalview/jbgui/PDBDocFieldPreferences.java b/src/jalview/fts/core/FTSDataColumnPreferences.java similarity index 61% rename from src/jalview/jbgui/PDBDocFieldPreferences.java rename to src/jalview/fts/core/FTSDataColumnPreferences.java index e33cf01..1828610 100644 --- a/src/jalview/jbgui/PDBDocFieldPreferences.java +++ b/src/jalview/fts/core/FTSDataColumnPreferences.java @@ -18,10 +18,11 @@ * along with Jalview. If not, see . * The Jalview Authors are detailed in the 'AUTHORS' file. */ -package jalview.jbgui; +package jalview.fts.core; -import jalview.ws.dbsources.PDBRestClient.PDBDocField; -import jalview.ws.dbsources.PDBRestClient.PDBDocField.Group; +import jalview.fts.api.FTSDataColumnGroupI; +import jalview.fts.api.FTSDataColumnI; +import jalview.fts.api.FTSRestClientI; import java.util.ArrayList; import java.util.Collection; @@ -40,18 +41,18 @@ import javax.swing.table.TableRowSorter; @SuppressWarnings("serial") -public class PDBDocFieldPreferences extends JScrollPane +public class FTSDataColumnPreferences extends JScrollPane { - protected JTable tbl_pdbDocFieldConfig = new JTable(); + protected JTable tbl_FTSDataColumnPrefs = new JTable(); protected JScrollPane scrl_pdbDocFieldConfig = new JScrollPane( - tbl_pdbDocFieldConfig); + tbl_FTSDataColumnPrefs); - private HashMap map = new HashMap(); + private HashMap map = new HashMap(); - private static Collection searchSummaryFields = new LinkedHashSet(); + private static Collection structSummaryColumns = new LinkedHashSet(); - private static Collection structureSummaryFields = new LinkedHashSet(); + private Collection allFTSDataColumns = new LinkedHashSet(); public enum PreferenceSource { @@ -60,24 +61,21 @@ public class PDBDocFieldPreferences extends JScrollPane private PreferenceSource currentSource; - static - { - searchSummaryFields.add(PDBDocField.PDB_ID); - searchSummaryFields.add(PDBDocField.TITLE); - searchSummaryFields.add(PDBDocField.RESOLUTION); - - structureSummaryFields.add(PDBDocField.PDB_ID); - structureSummaryFields.add(PDBDocField.TITLE); - structureSummaryFields.add(PDBDocField.RESOLUTION); - } + private FTSRestClientI ftsRestClient; - public PDBDocFieldPreferences(PreferenceSource source) + public FTSDataColumnPreferences(PreferenceSource source, + FTSRestClientI ftsRestClient) { - tbl_pdbDocFieldConfig.setAutoCreateRowSorter(true); + this.ftsRestClient = ftsRestClient; + Collection defaultCols = ftsRestClient + .getAllDefaulDisplayedDataColumns(); + structSummaryColumns.addAll(defaultCols); + allFTSDataColumns.addAll(ftsRestClient.getAllFTSDataColumns()); - this.getViewport().add(tbl_pdbDocFieldConfig); + tbl_FTSDataColumnPrefs.setAutoCreateRowSorter(true); + this.getViewport().add(tbl_FTSDataColumnPrefs); this.currentSource = source; String[] columnNames = null; @@ -97,9 +95,10 @@ public class PDBDocFieldPreferences extends JScrollPane break; } - Object[][] data = new Object[PDBDocField.values().length - 1][3]; + Object[][] data = new Object[allFTSDataColumns.size() - 1][3]; + int x = 0; - for (PDBDocField field : PDBDocField.values()) + for (FTSDataColumnI field : allFTSDataColumns) { if (field.getName().equalsIgnoreCase("all")) { @@ -109,17 +108,20 @@ public class PDBDocFieldPreferences extends JScrollPane switch (source) { case SEARCH_SUMMARY: - data[x++] = new Object[] { searchSummaryFields.contains(field), + data[x++] = new Object[] { + ftsRestClient.getAllDefaulDisplayedDataColumns() + .contains(field), field.getName(), field.getGroup() }; break; case STRUCTURE_CHOOSER: - data[x++] = new Object[] { structureSummaryFields.contains(field), + data[x++] = new Object[] { structSummaryColumns.contains(field), field.getName(), field.getGroup() }; break; case PREFERENCES: data[x++] = new Object[] { field.getName(), - searchSummaryFields.contains(field), - structureSummaryFields.contains(field) }; + ftsRestClient.getAllDefaulDisplayedDataColumns() + .contains(field), + structSummaryColumns.contains(field) }; break; default: break; @@ -127,28 +129,28 @@ public class PDBDocFieldPreferences extends JScrollPane map.put(field.getName(), field); } - PDBFieldTableModel model = new PDBFieldTableModel(columnNames, data); - tbl_pdbDocFieldConfig.setModel(model); + FTSDataColumnPrefsTableModel model = new FTSDataColumnPrefsTableModel(columnNames, data); + tbl_FTSDataColumnPrefs.setModel(model); switch (source) { case SEARCH_SUMMARY: case STRUCTURE_CHOOSER: - tbl_pdbDocFieldConfig.getColumnModel().getColumn(0) + tbl_FTSDataColumnPrefs.getColumnModel().getColumn(0) .setPreferredWidth(30); - tbl_pdbDocFieldConfig.getColumnModel().getColumn(0).setMinWidth(20); - tbl_pdbDocFieldConfig.getColumnModel().getColumn(0).setMaxWidth(40); - tbl_pdbDocFieldConfig.getColumnModel().getColumn(1) + tbl_FTSDataColumnPrefs.getColumnModel().getColumn(0).setMinWidth(20); + tbl_FTSDataColumnPrefs.getColumnModel().getColumn(0).setMaxWidth(40); + tbl_FTSDataColumnPrefs.getColumnModel().getColumn(1) .setPreferredWidth(150); - tbl_pdbDocFieldConfig.getColumnModel().getColumn(1).setMinWidth(150); - tbl_pdbDocFieldConfig.getColumnModel().getColumn(2) + tbl_FTSDataColumnPrefs.getColumnModel().getColumn(1).setMinWidth(150); + tbl_FTSDataColumnPrefs.getColumnModel().getColumn(2) .setPreferredWidth(150); - tbl_pdbDocFieldConfig.getColumnModel().getColumn(2) + tbl_FTSDataColumnPrefs.getColumnModel().getColumn(2) .setMinWidth(150); TableRowSorter sorter = new TableRowSorter<>( - tbl_pdbDocFieldConfig.getModel()); - tbl_pdbDocFieldConfig.setRowSorter(sorter); + tbl_FTSDataColumnPrefs.getModel()); + tbl_FTSDataColumnPrefs.setRowSorter(sorter); List sortKeys = new ArrayList<>(); int columnIndexToSort = 2; sortKeys.add(new RowSorter.SortKey(columnIndexToSort, @@ -156,17 +158,18 @@ public class PDBDocFieldPreferences extends JScrollPane sorter.setSortKeys(sortKeys); sorter.setComparator( columnIndexToSort, - new Comparator() + new Comparator() { @Override - public int compare(Group o1, Group o2) + public int compare(FTSDataColumnGroupI o1, + FTSDataColumnGroupI o2) { return o1.getSortOrder() - o2.getSortOrder(); } }); sorter.sort(); - tbl_pdbDocFieldConfig + tbl_FTSDataColumnPrefs .setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN); break; case PREFERENCES: @@ -176,32 +179,21 @@ public class PDBDocFieldPreferences extends JScrollPane } - public static Collection getSearchSummaryFields() - { - return searchSummaryFields; - } - - public static void setSearchSummaryFields( - Collection searchSummaryFields) - { - PDBDocFieldPreferences.searchSummaryFields = searchSummaryFields; - } - - public static Collection getStructureSummaryFields() + public static Collection getStructureSummaryFields() { - return structureSummaryFields; + return structSummaryColumns; } public static void setStructureSummaryFields( - Collection structureSummaryFields) + Collection structureSummaryFields) { - PDBDocFieldPreferences.structureSummaryFields = structureSummaryFields; + FTSDataColumnPreferences.structSummaryColumns = structureSummaryFields; } - class PDBFieldTableModel extends AbstractTableModel + class FTSDataColumnPrefsTableModel extends AbstractTableModel { - public PDBFieldTableModel(String[] columnNames, Object[][] data) + public FTSDataColumnPrefsTableModel(String[] columnNames, Object[][] data) { this.data = data; this.columnNames = columnNames; @@ -261,9 +253,9 @@ public class PDBDocFieldPreferences extends JScrollPane { case SEARCH_SUMMARY: case STRUCTURE_CHOOSER: - return (col == 0) && !isPDBID(row, 1); + return (col == 0) && !isPrimaryKeyCell(row, 1); case PREFERENCES: - return (col == 1 || col == 2) && !isPDBID(row, 0); + return (col == 1 || col == 2) && !isPrimaryKeyCell(row, 0); default: return false; } @@ -278,16 +270,11 @@ public class PDBDocFieldPreferences extends JScrollPane * @return */ - public boolean isPDBID(int row, int col) + public boolean isPrimaryKeyCell(int row, int col) { - boolean matched = false; String name = getValueAt(row, col).toString(); - PDBDocField pdbField = map.get(name); - if (pdbField == PDBDocField.PDB_ID) - { - matched = true; - } - return matched; + FTSDataColumnI pdbField = map.get(name); + return pdbField.isPrimaryKeyColumn(); } /* @@ -314,40 +301,45 @@ public class PDBDocFieldPreferences extends JScrollPane } boolean selected = ((Boolean) value).booleanValue(); - PDBDocField pdbField = map.get(name); + FTSDataColumnI ftsDataColumn = map.get(name); if (currentSource == PreferenceSource.SEARCH_SUMMARY) { - updatePrefs(searchSummaryFields, pdbField, selected); + updatePrefs(ftsRestClient + .getAllDefaulDisplayedDataColumns(), ftsDataColumn, + selected); } else if (currentSource == PreferenceSource.STRUCTURE_CHOOSER) { - updatePrefs(structureSummaryFields, pdbField, selected); + updatePrefs(structSummaryColumns, ftsDataColumn, selected); } else if (currentSource == PreferenceSource.PREFERENCES) { if (col == 1) { - updatePrefs(searchSummaryFields, pdbField, selected); + updatePrefs(ftsRestClient + .getAllDefaulDisplayedDataColumns(), ftsDataColumn, + selected); } else if (col == 2) { - updatePrefs(structureSummaryFields, pdbField, selected); + updatePrefs(structSummaryColumns, ftsDataColumn, selected); } } } - private void updatePrefs(Collection prefConfig, - PDBDocField pdbField, boolean selected) + private void updatePrefs( + Collection prefConfig, + FTSDataColumnI dataColumn, boolean selected) { - if (prefConfig.contains(pdbField) && !selected) + if (prefConfig.contains(dataColumn) && !selected) { - prefConfig.remove(pdbField); + prefConfig.remove(dataColumn); } - if (!prefConfig.contains(pdbField) && selected) + if (!prefConfig.contains(dataColumn) && selected) { - prefConfig.add(pdbField); + prefConfig.add(dataColumn); } } diff --git a/src/jalview/fts/core/FTSRestClient.java b/src/jalview/fts/core/FTSRestClient.java new file mode 100644 index 0000000..77b94c4 --- /dev/null +++ b/src/jalview/fts/core/FTSRestClient.java @@ -0,0 +1,337 @@ +package jalview.fts.core; + +import jalview.fts.api.FTSDataColumnGroupI; +import jalview.fts.api.FTSDataColumnI; +import jalview.fts.api.FTSRestClientI; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Objects; + +public abstract class FTSRestClient implements FTSRestClientI +{ + protected Collection dataColumns = new ArrayList(); + + protected Collection dataColumnGroups = new ArrayList(); + + protected Collection searchableDataColumns = new ArrayList(); + + protected Collection defaulDisplayedDataColumns = new ArrayList(); + + protected FTSDataColumnI primaryKeyColumn; + + protected FTSRestClient() + { + + } + + public void parseDataColumnsFile() + { + String fileName = getColumnDataConfigFile(); + try (BufferedReader br = new BufferedReader(new FileReader(fileName))) + { + String line; + while ((line = br.readLine()) != null) + { + final String[] lineData = line.split(";"); + if (lineData.length == 3) + { + dataColumnGroups.add(new FTSDataColumnGroupI() + { + @Override + public String getID() + { + return lineData[0]; + } + + @Override + public String getName() + { + return lineData[1]; + } + + @Override + public int getSortOrder() + { + return Integer.valueOf(lineData[2]); + } + + @Override + public String toString() + { + return lineData[1]; + } + + @Override + public int hashCode() + { + return Objects.hash(this.getID(), this.getName(), + this.getSortOrder()); + } + + @Override + public boolean equals(Object otherObject) + { + FTSDataColumnGroupI that = (FTSDataColumnGroupI) otherObject; + return this.getID().equals(that.getID()) + && this.getName().equals(that.getName()) + && this.getSortOrder() == that.getSortOrder(); + } + }); + } + else if (lineData.length > 6) + { + FTSDataColumnI dataCol = new FTSDataColumnI() + { + @Override + public String toString() + { + return lineData[0]; + } + + @Override + public String getName() + { + return lineData[0]; + } + + @Override + public String getCode() + { + return lineData[1]; + } + + @Override + public FTSDataColumnGroupI getGroup() + { + FTSDataColumnGroupI group = null; + try + { + group = getDataColumnGroupById(lineData[2]); + } catch (Exception e) + { + e.printStackTrace(); + } + return group; + } + + @Override + public int getMinWidth() + { + return Integer.valueOf(lineData[3]); + } + + @Override + public int getMaxWidth() + { + return Integer.valueOf(lineData[4]); + } + + @Override + public int getPreferredWidth() + { + return Integer.valueOf(lineData[5]); + } + + + @Override + public boolean isPrimaryKeyColumn() + { + return Boolean.valueOf(lineData[6]); + } + + @Override + public boolean isVisibleByDefault() + { + return Boolean.valueOf(lineData[7]); + } + + @Override + public boolean isSearchable() + { + return Boolean.valueOf(lineData[8]); + } + + @Override + public int hashCode() + { + return Objects.hash(this.getName(), this.getCode(), + this.getGroup()); + } + + @Override + public boolean equals(Object otherObject) + { + FTSDataColumnI that = (FTSDataColumnI) otherObject; + return this.getCode().equals(that.getCode()) + && this.getName().equals(that.getName()) + && this.getGroup().equals(that.getGroup()); + } + }; + dataColumns.add(dataCol); + + if (dataCol.isSearchable()) + { + searchableDataColumns.add(dataCol); + } + + if (dataCol.isVisibleByDefault()) + { + defaulDisplayedDataColumns.add(dataCol); + } + + } + else + { + continue; + } + } + } catch (IOException e) + { + e.printStackTrace(); + } + } + + /** + * Determines the column index for 'Primary key' Fields in the dynamic summary + * table. + * + * @param wantedFields + * the available table columns in no particular order + * @return the primary key column index + * @throws Exception + */ + @Override + public int getPrimaryKeyColumIndex( + Collection wantedFields, + boolean hasRefSeq) throws Exception + { + + // If a reference sequence is attached then start counting from 1 else + // start from zero + int pdbFieldIndexCounter = hasRefSeq ? 1 : 0; + + for (FTSDataColumnI field : wantedFields) + { + if (field.isPrimaryKeyColumn()) + { + break; // Once PDB Id index is determined exit iteration + } + ++pdbFieldIndexCounter; + } + return pdbFieldIndexCounter; + } + + /** + * Takes a collection of FTSDataColumnI and converts its 'code' values into a + * comma delimited string. + * + * @param dataColumnFields + * the collection of FTSDataColumnI to process + * @return the generated comma delimited string from the supplied + * FTSDataColumnI collection + */ + public static String getDataColumnsFieldsAsCommaDelimitedString( + Collection dataColumnFields) + { + String result = ""; + if (dataColumnFields != null && !dataColumnFields.isEmpty()) + { + StringBuilder returnedFields = new StringBuilder(); + for (FTSDataColumnI field : dataColumnFields) + { + returnedFields.append(",").append(field.getCode()); + } + returnedFields.deleteCharAt(0); + result = returnedFields.toString(); + } + return result; + } + + @Override + public Collection getAllFTSDataColumns() + { + if (dataColumns == null || dataColumns.isEmpty()) + { + parseDataColumnsFile(); + } + return dataColumns; + } + + @Override + public Collection getSearchableDataColumns() + { + if (searchableDataColumns == null || searchableDataColumns.isEmpty()) + { + parseDataColumnsFile(); + } + return searchableDataColumns; + } + + @Override + public Collection getAllDefaulDisplayedDataColumns() + { + if (defaulDisplayedDataColumns == null + || defaulDisplayedDataColumns.isEmpty()) + { + parseDataColumnsFile(); + } + return defaulDisplayedDataColumns; + } + + @Override + public FTSDataColumnI getPrimaryKeyColumn() + { + return primaryKeyColumn; + } + + @Override + public FTSDataColumnI getDataColumnByNameOrCode( + String nameOrCode) throws Exception + { + for (FTSDataColumnI column : dataColumns) + { + if (column.getName().equalsIgnoreCase(nameOrCode) + || column.getCode().equalsIgnoreCase(nameOrCode)) + { + return column; + } + } + throw new Exception("Couldn't find data column with name : " + + nameOrCode); + } + + @Override + public FTSDataColumnGroupI getDataColumnGroupById(String id) + throws Exception + { + for (FTSDataColumnGroupI columnGroup : dataColumnGroups) + { + if (columnGroup.getID().equalsIgnoreCase(id)) + { + return columnGroup; + } + } + throw new Exception("Couldn't find data column group with id : " + id); + } + + protected String getFile(String fileName) + { + ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource(fileName).getFile()); + String result = ""; + try + { + result = classLoader.getResource(fileName).getFile(); + } catch (Exception e) + { + e.printStackTrace(); + } + return result; + + } + +} diff --git a/src/jalview/ws/uimodel/PDBRestRequest.java b/src/jalview/fts/core/FTSRestRequest.java similarity index 83% rename from src/jalview/ws/uimodel/PDBRestRequest.java rename to src/jalview/fts/core/FTSRestRequest.java index 7bfc226..94f9bfb 100644 --- a/src/jalview/ws/uimodel/PDBRestRequest.java +++ b/src/jalview/fts/core/FTSRestRequest.java @@ -19,11 +19,11 @@ * The Jalview Authors are detailed in the 'AUTHORS' file. */ -package jalview.ws.uimodel; +package jalview.fts.core; import jalview.bin.Cache; import jalview.datamodel.SequenceI; -import jalview.ws.dbsources.PDBRestClient.PDBDocField; +import jalview.fts.api.FTSDataColumnI; import java.util.Collection; @@ -33,7 +33,7 @@ import java.util.Collection; * @author tcnofoegbu * */ -public class PDBRestRequest +public class FTSRestRequest { private String fieldToSearchBy; @@ -58,7 +58,7 @@ public class PDBRestRequest private boolean isSortAscending; - private Collection wantedFields; + private Collection wantedFields; public String getFieldToSearchBy() { @@ -100,12 +100,13 @@ public class PDBRestRequest this.responseSize = responseSize; } - public Collection getWantedFields() + public Collection getWantedFields() { return wantedFields; } - public void setWantedFields(Collection wantedFields) + public void setWantedFields( + Collection wantedFields) { this.wantedFields = wantedFields; } @@ -136,21 +137,6 @@ public class PDBRestRequest this.associatedSequence = associatedSequence; } - public String getQuery() - { - return fieldToSearchBy + searchTerm - + (isAllowEmptySeq() ? "" : " AND molecule_sequence:['' TO *]") - + (isAllowUnpublishedEntries() ? "" : " AND status:REL"); - } - - @Override - public String toString() - { - return "Query : " + getQuery() + " sort field: " + fieldToSortBy - + " isAsc: " + isAscending() + " Associated Seq : " - + associatedSequence; - } - public boolean isAllowUnpublishedEntries() { return allowUnpublishedEntries; diff --git a/src/jalview/fts/core/FTSRestResponse.java b/src/jalview/fts/core/FTSRestResponse.java new file mode 100644 index 0000000..17204d7 --- /dev/null +++ b/src/jalview/fts/core/FTSRestResponse.java @@ -0,0 +1,169 @@ +/* + * 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.fts.core; + +import jalview.fts.api.FTSData; +import jalview.fts.api.FTSDataColumnI; + +import java.util.Collection; + +import javax.swing.JTable; +import javax.swing.table.DefaultTableModel; + +/** + * Represents the response model produced by the PDBRestClient upon successful + * execution of a given request + * + * @author tcnofoegbu + * + */ +public class FTSRestResponse +{ + private int numberOfItemsFound; + + private String responseTime; + + private Collection searchSummary; + + public int getNumberOfItemsFound() + { + return numberOfItemsFound; + } + + public void setNumberOfItemsFound(int itemFound) + { + this.numberOfItemsFound = itemFound; + } + + public String getResponseTime() + { + return responseTime; + } + + public void setResponseTime(String responseTime) + { + this.responseTime = responseTime; + } + + public Collection getSearchSummary() + { + return searchSummary; + } + + public void setSearchSummary(Collection searchSummary) + { + this.searchSummary = searchSummary; + } + + /** + * Convenience method to obtain a Table model for a given summary List based + * on the request parameters + * + * @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(FTSRestRequest request, + Collection summariesList) + { + final FTSDataColumnI[] cols = request.getWantedFields() + .toArray(new FTSDataColumnI[0]); + final int colOffset = request.getAssociatedSequence() == null ? 0 : 1; + DefaultTableModel tableModel = new DefaultTableModel() + { + @Override + public boolean isCellEditable(int row, int column) + { + return false; + } + + @Override + public Class getColumnClass(int columnIndex) + { + if (colOffset == 1 && columnIndex == 0) + { + return String.class; + } + if (cols[columnIndex - colOffset].getGroup().getName() + .equalsIgnoreCase("Quality Measures")) + { + return Double.class; + } + return String.class; + } + + }; + if (request.getAssociatedSequence() != null) + { + tableModel.addColumn("Ref Sequence"); // Create sequence column header if + // exists in the request + } + for (FTSDataColumnI field : request + .getWantedFields()) + { + tableModel.addColumn(field.getName()); // Create sequence column header if + // exists in the request + } + + for (FTSData res : summariesList) + { + tableModel.addRow(res.getSummaryData()); // Populate table rows with + // summary list + } + + return tableModel; + } + + public static void configureTableColumn(JTable tbl_summary, + Collection wantedFields) + { + try + { + // wait for table model initialisation to complete + Thread.sleep(1200); + } catch (InterruptedException e1) + { + e1.printStackTrace(); + } + for (FTSDataColumnI wantedField : wantedFields) + { + try + { + tbl_summary.getColumn(wantedField.getName()).setMinWidth( + wantedField.getMinWidth()); + tbl_summary.getColumn(wantedField.getName()).setMaxWidth( + wantedField.getMaxWidth()); + tbl_summary.getColumn(wantedField.getName()).setPreferredWidth( + wantedField.getPreferredWidth()); + } catch (Exception e) + { + e.printStackTrace(); + } + } + } + + +} diff --git a/src/jalview/jbgui/GPDBSearchPanel.java b/src/jalview/fts/core/GFTSPanel.java similarity index 77% rename from src/jalview/jbgui/GPDBSearchPanel.java rename to src/jalview/fts/core/GFTSPanel.java index d640df8..2e50386 100644 --- a/src/jalview/jbgui/GPDBSearchPanel.java +++ b/src/jalview/fts/core/GFTSPanel.java @@ -19,13 +19,17 @@ * The Jalview Authors are detailed in the 'AUTHORS' file. */ -package jalview.jbgui; +package jalview.fts.core; +import jalview.fts.api.FTSDataColumnI; +import jalview.fts.api.FTSRestClientI; +import jalview.fts.core.FTSDataColumnPreferences.PreferenceSource; +import jalview.fts.service.pdb.PDBFTSRestClient; import jalview.gui.Desktop; +import jalview.gui.IProgressIndicator; import jalview.gui.JvSwingUtils; -import jalview.jbgui.PDBDocFieldPreferences.PreferenceSource; +import jalview.gui.SequenceFetcher; import jalview.util.MessageManager; -import jalview.ws.dbsources.PDBRestClient.PDBDocField; import java.awt.BorderLayout; import java.awt.CardLayout; @@ -36,7 +40,12 @@ import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; import javax.swing.ImageIcon; import javax.swing.JButton; @@ -60,15 +69,16 @@ import javax.swing.event.DocumentListener; * @author tcnofoegbu * */ + @SuppressWarnings("serial") -public abstract class GPDBSearchPanel extends JPanel +public abstract class GFTSPanel extends JPanel { - protected String frameTitle = MessageManager - .getString("label.pdb_sequence_getcher"); + protected JInternalFrame mainFrame = new JInternalFrame( + getFTSFrameTitle()); - protected JInternalFrame mainFrame = new JInternalFrame(frameTitle); + protected IProgressIndicator progressIdicator; - protected JComboBox cmb_searchTarget = new JComboBox(); + protected JComboBox cmb_searchTarget = new JComboBox(); protected JButton btn_ok = new JButton(); @@ -78,6 +88,10 @@ public abstract class GPDBSearchPanel extends JPanel protected JTextField txt_search = new JTextField(20); + protected SequenceFetcher seqFetcher; + + protected Collection wantedFields; + protected JTable tbl_summary = new JTable() { @Override @@ -125,9 +139,6 @@ public abstract class GPDBSearchPanel extends JPanel private JTabbedPane tabbedPane = new JTabbedPane(); - private PDBDocFieldPreferences pdbDocFieldPrefs = new PDBDocFieldPreferences( - PreferenceSource.SEARCH_SUMMARY); - private JPanel pnl_actions = new JPanel(); private JPanel pnl_results = new JPanel(new CardLayout()); @@ -136,9 +147,9 @@ public abstract class GPDBSearchPanel extends JPanel private BorderLayout mainLayout = new BorderLayout(); - protected PDBDocField[] previousWantedFields; + protected Object[] previousWantedFields; - public GPDBSearchPanel() + public GFTSPanel() { try { @@ -387,8 +398,9 @@ public abstract class GPDBSearchPanel extends JPanel btn_back.setEnabled(false); btn_cancel.setEnabled(false); btn_ok.setEnabled(false); - previousWantedFields = PDBDocFieldPreferences - .getSearchSummaryFields().toArray(new PDBDocField[0]); + previousWantedFields = PDBFTSRestClient.getInstance() + .getAllDefaulDisplayedDataColumns() + .toArray(new Object[0]); } if (sourceTabbedPane.getTitleAt(index).equals(searchTabTitle)) { @@ -408,7 +420,8 @@ public abstract class GPDBSearchPanel extends JPanel tabbedPane.addChangeListener(changeListener); tabbedPane.setPreferredSize(new Dimension(500, 300)); tabbedPane.add(searchTabTitle, scrl_searchResult); - tabbedPane.add(configureCols, pdbDocFieldPrefs); + tabbedPane.add(configureCols, new FTSDataColumnPreferences( + PreferenceSource.SEARCH_SUMMARY, getFTSRestClient())); pnl_actions.add(btn_back); pnl_actions.add(btn_ok); @@ -427,7 +440,7 @@ public abstract class GPDBSearchPanel extends JPanel mainFrame.setVisible(true); mainFrame.setContentPane(this); mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - Desktop.addInternalFrame(mainFrame, frameTitle, 800, 400); + Desktop.addInternalFrame(mainFrame, getFTSFrameTitle(), 800, 400); } public boolean wantedFieldsUpdated() @@ -437,8 +450,9 @@ public abstract class GPDBSearchPanel extends JPanel return true; } - return Arrays.equals(PDBDocFieldPreferences.getSearchSummaryFields() - .toArray(new PDBDocField[0]), previousWantedFields) ? false + return Arrays.equals(PDBFTSRestClient.getInstance() + .getAllDefaulDisplayedDataColumns() + .toArray(new Object[0]), previousWantedFields) ? false : true; } @@ -455,7 +469,7 @@ public abstract class GPDBSearchPanel extends JPanel } } - public JComboBox getCmbSearchTarget() + public JComboBox getCmbSearchTarget() { return cmb_searchTarget; } @@ -470,16 +484,103 @@ public abstract class GPDBSearchPanel extends JPanel return mainFrame; } - public abstract void transferToSequenceFetcher(String ids); + protected void delayAndEnableActionButtons() + { + new Thread() + { + @Override + public void run() + { + try + { + Thread.sleep(1500); + } catch (InterruptedException e) + { + e.printStackTrace(); + } + btn_ok.setEnabled(true); + btn_back.setEnabled(true); + btn_cancel.setEnabled(true); + } + }.start(); + } - public abstract void txt_search_ActionPerformed(); + protected void checkForErrors() + { + lbl_warning.setVisible(false); + if (errorWarning.length() > 0) + { + lbl_loading.setVisible(false); + lbl_warning.setToolTipText(JvSwingUtils.wrapTooltip(true, + errorWarning.toString())); + lbl_warning.setVisible(true); + } + } - public abstract void btn_ok_ActionPerformed(); + protected void btn_back_ActionPerformed() + { + mainFrame.dispose(); + new SequenceFetcher(progressIdicator); + } + + protected void disableActionButtons() + { + btn_ok.setEnabled(false); + btn_back.setEnabled(false); + btn_cancel.setEnabled(false); + } + + protected void btn_cancel_ActionPerformed() + { + mainFrame.dispose(); + } + + /** + * Populates search target combo-box options + */ + public void populateCmbSearchTargetOptions() + { + List searchableTargets = new ArrayList(); + try + { + Collection foundFTSTargets = getFTSRestClient() + .getSearchableDataColumns(); + searchableTargets.addAll(foundFTSTargets); + } catch (Exception e) + { + e.printStackTrace(); + } + + Collections.sort(searchableTargets, new Comparator() + { + @Override + public int compare(FTSDataColumnI o1, FTSDataColumnI o2) + { + return o1.getName().compareTo(o2.getName()); + } + }); + + for (FTSDataColumnI searchTarget : searchableTargets) + { + cmb_searchTarget.addItem(searchTarget); + } + } - public abstract void btn_back_ActionPerformed(); - public abstract void btn_cancel_ActionPerformed(); + public void transferToSequenceFetcher(String ids) + { + // mainFrame.dispose(); + seqFetcher.getTextArea().setText(ids); + Thread worker = new Thread(seqFetcher); + worker.start(); + } + + public abstract String getFTSFrameTitle(); + + public abstract FTSRestClientI getFTSRestClient(); - public abstract void populateCmbSearchTargetOptions(); + public abstract void txt_search_ActionPerformed(); + + public abstract void btn_ok_ActionPerformed(); } diff --git a/src/jalview/gui/PDBSearchPanel.java b/src/jalview/fts/service/pdb/PDBFTSPanel.java similarity index 59% rename from src/jalview/gui/PDBSearchPanel.java rename to src/jalview/fts/service/pdb/PDBFTSPanel.java index 9b94c27..0b8917d 100644 --- a/src/jalview/gui/PDBSearchPanel.java +++ b/src/jalview/fts/service/pdb/PDBFTSPanel.java @@ -19,41 +19,32 @@ * The Jalview Authors are detailed in the 'AUTHORS' file. */ -package jalview.gui; - -import jalview.jbgui.GPDBSearchPanel; -import jalview.jbgui.PDBDocFieldPreferences; +package jalview.fts.service.pdb; + +import jalview.fts.api.FTSDataColumnI; +import jalview.fts.api.FTSRestClientI; +import jalview.fts.core.FTSRestRequest; +import jalview.fts.core.FTSRestResponse; +import jalview.fts.core.GFTSPanel; +import jalview.gui.SequenceFetcher; 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 java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; import java.util.HashSet; -import java.util.List; import javax.swing.table.DefaultTableModel; @SuppressWarnings("serial") -public class PDBSearchPanel extends GPDBSearchPanel +public class PDBFTSPanel extends GFTSPanel { - private SequenceFetcher seqFetcher; - - private IProgressIndicator progressIdicator; - private Collection wantedFields; - - public PDBSearchPanel(SequenceFetcher seqFetcher) + public PDBFTSPanel(SequenceFetcher seqFetcher) { this.seqFetcher = seqFetcher; this.progressIdicator = (seqFetcher == null) ? null : seqFetcher .getProgressIndicator(); } + /** * Action performed when an input is detected on txt_search field. */ @@ -70,31 +61,32 @@ public class PDBSearchPanel extends GPDBSearchPanel lbl_warning.setVisible(false); btn_ok.setEnabled(false); boolean allowEmptySequence = false; - mainFrame.setTitle(MessageManager - .getString("label.pdb_sequence_getcher")); + mainFrame.setTitle(getFTSFrameTitle()); tbl_summary.setModel(new DefaultTableModel()); + tbl_summary.setVisible(false); if (txt_search.getText().trim().length() > 0) { lbl_loading.setVisible(true); long startTime = System.currentTimeMillis(); - String searchTarget = ((PDBDocField) cmb_searchTarget + String searchTarget = ((FTSDataColumnI) cmb_searchTarget .getSelectedItem()).getCode(); - wantedFields = PDBDocFieldPreferences.getSearchSummaryFields(); - + // wantedFields = FTSDataColumnPreferences.getSearchSummaryFields(); + wantedFields = PDBFTSRestClient.getInstance() + .getAllDefaulDisplayedDataColumns(); String searchTerm = decodeSearchTerm(txt_search.getText(), searchTarget); - PDBRestRequest request = new PDBRestRequest(); + FTSRestRequest request = new FTSRestRequest(); request.setAllowEmptySeq(allowEmptySequence); request.setResponseSize(100); request.setFieldToSearchBy("(" + searchTarget + ":"); request.setSearchTerm(searchTerm + ")"); request.setWantedFields(wantedFields); // System.out.println(">>>>>>>>>>>>>> " + request.getQuery()); - PDBRestClient pdbRestCleint = new PDBRestClient(); - PDBRestResponse resultList; + FTSRestClientI pdbRestCleint = PDBFTSRestClient.getInstance(); + FTSRestResponse resultList; try { resultList = pdbRestCleint.executeRequest(request); @@ -108,18 +100,20 @@ public class PDBSearchPanel extends GPDBSearchPanel if (resultList.getSearchSummary() != null) { - tbl_summary.setModel(PDBRestResponse.getTableModel(request, + tbl_summary.setModel(FTSRestResponse.getTableModel(request, resultList.getSearchSummary())); + FTSRestResponse.configureTableColumn(tbl_summary, wantedFields); + tbl_summary.setVisible(true); } - PDBRestResponse.configureTableColumn(tbl_summary, wantedFields); long endTime = System.currentTimeMillis(); int resultSetCount = resultList.getNumberOfItemsFound(); String result = (resultSetCount > 1) ? MessageManager .getString("label.results") : MessageManager .getString("label.result"); - mainFrame.setTitle(frameTitle + " - " + resultSetCount + " " + mainFrame.setTitle(getFTSFrameTitle() + " - " + resultSetCount + + " " + result + " (" + (endTime - startTime) + " milli secs)"); lbl_loading.setVisible(false); } @@ -166,48 +160,27 @@ public class PDBSearchPanel extends GPDBSearchPanel @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(); - } - - @Override - public void transferToSequenceFetcher(String ids) - { - // mainFrame.dispose(); - seqFetcher.textArea.setText(ids); - Thread worker = new Thread(seqFetcher); - worker.start(); - } - - /** - * Add the discovered/selected sequences to a target alignment window - */ - public void loadSelectedPDBSequencesToAlignment() - { // mainFrame.dispose(); disableActionButtons(); StringBuilder selectedIds = new StringBuilder(); HashSet selectedIdsSet = new HashSet(); - int pdbIdCol = PDBRestClient.getPDBIdColumIndex(wantedFields, false); + int pdbIdCol = 0; + try + { + pdbIdCol = getFTSRestClient().getPrimaryKeyColumIndex(wantedFields, + false); + } catch (Exception e) + { + // TODO Auto-generated catch block + e.printStackTrace(); + } int[] selectedRows = tbl_summary.getSelectedRows(); for (int summaryRow : selectedRows) { - String pdbIdStr = tbl_summary.getValueAt(summaryRow, pdbIdCol) + String idStr = tbl_summary.getValueAt(summaryRow, pdbIdCol) .toString(); String searchTerm = txt_search.getText(); - selectedIdsSet.add(getPDBIdwithSpecifiedChain(pdbIdStr, searchTerm)); + selectedIdsSet.add(getPDBIdwithSpecifiedChain(idStr, searchTerm)); } for (String selectedId : selectedIdsSet) @@ -217,40 +190,12 @@ public class PDBSearchPanel extends GPDBSearchPanel String ids = selectedIds.toString(); // System.out.println(">>>>>>>>>>>>>>>> selected Ids: " + ids); - seqFetcher.textArea.setText(ids); + seqFetcher.getTextArea().setText(ids); Thread worker = new Thread(seqFetcher); worker.start(); delayAndEnableActionButtons(); - - } - - private void disableActionButtons() - { - btn_ok.setEnabled(false); - btn_back.setEnabled(false); - btn_cancel.setEnabled(false); } - private void delayAndEnableActionButtons() - { - new Thread() - { - @Override - public void run() - { - try - { - Thread.sleep(1500); - } catch (InterruptedException e) - { - e.printStackTrace(); - } - btn_ok.setEnabled(true); - btn_back.setEnabled(true); - btn_cancel.setEnabled(true); - } - }.start(); - } public static String getPDBIdwithSpecifiedChain(String pdbId, String searchTerm) @@ -278,46 +223,18 @@ public class PDBSearchPanel extends GPDBSearchPanel return pdbIdWithChainCode; } - /** - * Populates search target combo-box options - */ - @Override - 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); - } + @Override + public FTSRestClientI getFTSRestClient() + { + return PDBFTSRestClient.getInstance(); } - public void checkForErrors() + @Override + public String getFTSFrameTitle() { - lbl_warning.setVisible(false); - if (errorWarning.length() > 0) - { - lbl_loading.setVisible(false); - lbl_warning.setToolTipText(JvSwingUtils.wrapTooltip(true, - errorWarning.toString())); - lbl_warning.setVisible(true); - } + return MessageManager.getString("label.pdb_sequence_fetcher"); } + } diff --git a/src/jalview/fts/service/pdb/PDBFTSRestClient.java b/src/jalview/fts/service/pdb/PDBFTSRestClient.java new file mode 100644 index 0000000..be1c9ee --- /dev/null +++ b/src/jalview/fts/service/pdb/PDBFTSRestClient.java @@ -0,0 +1,439 @@ +/* + * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$) + * Copyright (C) $$Year-Rel$$ 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.fts.service.pdb; + +import jalview.datamodel.SequenceI; +import jalview.fts.api.FTSData; +import jalview.fts.api.FTSDataColumnI; +import jalview.fts.api.FTSRestClientI; +import jalview.fts.core.FTSRestClient; +import jalview.fts.core.FTSRestRequest; +import jalview.fts.core.FTSRestResponse; +import jalview.util.MessageManager; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; + +import javax.ws.rs.core.MediaType; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.client.config.DefaultClientConfig; + +/** + * A rest client for querying the Search endpoint of the PDB REST API + * + * @author tcnofoegbu + * + */ +public class PDBFTSRestClient extends FTSRestClient +{ + + private static FTSRestClientI instance = null; + + public static final String PDB_SEARCH_ENDPOINT = "http://www.ebi.ac.uk/pdbe/search/pdb/select?"; + + private static int DEFAULT_RESPONSE_SIZE = 200; + + protected PDBFTSRestClient() + { + } + + /** + * Takes a PDBRestRequest object and returns a response upon execution + * + * @param pdbRestRequest + * the PDBRestRequest instance to be processed + * @return the pdbResponse object for the given request + * @throws Exception + */ + @Override + public FTSRestResponse executeRequest(FTSRestRequest pdbRestRequest) + throws Exception + { + try + { + ClientConfig clientConfig = new DefaultClientConfig(); + Client client = Client.create(clientConfig); + + String wantedFields = getDataColumnsFieldsAsCommaDelimitedString(pdbRestRequest + .getWantedFields()); + int responseSize = (pdbRestRequest.getResponseSize() == 0) ? DEFAULT_RESPONSE_SIZE + : pdbRestRequest.getResponseSize(); + String sortParam = null; + if (pdbRestRequest.getFieldToSortBy() == null + || pdbRestRequest.getFieldToSortBy().trim().isEmpty()) + { + sortParam = ""; + } + else + { + if (pdbRestRequest.getFieldToSortBy() + .equalsIgnoreCase("Resolution")) + { + sortParam = pdbRestRequest.getFieldToSortBy() + + (pdbRestRequest.isAscending() ? " asc" : " desc"); + } + else + { + sortParam = pdbRestRequest.getFieldToSortBy() + + (pdbRestRequest.isAscending() ? " desc" : " asc"); + } + } + + String facetPivot = (pdbRestRequest.getFacetPivot() == null || pdbRestRequest + .getFacetPivot().isEmpty()) ? "" : pdbRestRequest + .getFacetPivot(); + String facetPivotMinCount = String.valueOf(pdbRestRequest + .getFacetPivotMinCount()); + + String query = pdbRestRequest.getFieldToSearchBy() + + pdbRestRequest.getSearchTerm() + + (pdbRestRequest.isAllowEmptySeq() ? "" + : " AND molecule_sequence:['' TO *]") + + (pdbRestRequest.isAllowUnpublishedEntries() ? "" + : " AND status:REL"); + + // Build request parameters for the REST Request + WebResource webResource = null; + if (pdbRestRequest.isFacet()) + { + webResource = client.resource(PDB_SEARCH_ENDPOINT) + .queryParam("wt", "json").queryParam("fl", wantedFields) + .queryParam("rows", String.valueOf(responseSize)) + .queryParam("q", query) + .queryParam("sort", sortParam).queryParam("facet", "true") + .queryParam("facet.pivot", facetPivot) + .queryParam("facet.pivot.mincount", facetPivotMinCount); + } + else + { + webResource = client.resource(PDB_SEARCH_ENDPOINT) + .queryParam("wt", "json").queryParam("fl", wantedFields) + .queryParam("rows", String.valueOf(responseSize)) + .queryParam("q", query) + .queryParam("sort", sortParam); + } + // Execute the REST request + ClientResponse clientResponse = webResource.accept( + MediaType.APPLICATION_JSON).get(ClientResponse.class); + + // Get the JSON string from the response object + String responseString = clientResponse.getEntity(String.class); + // System.out.println("query >>>>>>> " + pdbRestRequest.toString()); + + // Check the response status and report exception if one occurs + if (clientResponse.getStatus() != 200) + { + String errorMessage = ""; + if (clientResponse.getStatus() == 400) + { + errorMessage = parseJsonExceptionString(responseString); + throw new Exception(errorMessage); + } + else + { + errorMessage = getMessageByHTTPStatusCode(clientResponse + .getStatus()); + throw new Exception(errorMessage); + } + } + + // Make redundant objects eligible for garbage collection to conserve + // memory + clientResponse = null; + client = null; + + // Process the response and return the result to the caller. + return parsePDBJsonResponse(responseString, pdbRestRequest); + } catch (Exception e) + { + String exceptionMsg = e.getMessage(); + if (exceptionMsg.contains("SocketException")) + { + // No internet connection + throw new Exception( + MessageManager + .getString("exception.unable_to_detect_internet_connection")); + } + else if (exceptionMsg.contains("UnknownHostException")) + { + // The server 'www.ebi.ac.uk' is unreachable + throw new Exception( + MessageManager + .getString("exception.pdb_server_unreachable")); + } + else + { + throw e; + } + } + } + + public String getMessageByHTTPStatusCode(int code) + { + String message = ""; + switch (code) + { + case 410: + message = MessageManager + .getString("exception.pdb_rest_service_no_longer_available"); + break; + case 403: + case 404: + message = MessageManager.getString("exception.resource_not_be_found"); + break; + case 408: + case 409: + case 500: + case 501: + case 502: + case 503: + case 504: + case 505: + message = MessageManager.getString("exception.pdb_server_error"); + break; + + default: + break; + } + return message; + } + + /** + * 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) + { + StringBuilder errorMessage = new StringBuilder( + "\n============= PDB Rest Client RunTime error =============\n"); + + try + { + JSONParser jsonParser = new JSONParser(); + JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonErrorResponse); + JSONObject errorResponse = (JSONObject) jsonObj.get("error"); + + JSONObject responseHeader = (JSONObject) jsonObj + .get("responseHeader"); + JSONObject paramsObj = (JSONObject) responseHeader.get("params"); + String status = responseHeader.get("status").toString(); + String message = errorResponse.get("msg").toString(); + String query = paramsObj.get("q").toString(); + String fl = paramsObj.get("fl").toString(); + + errorMessage.append("Status: ").append(status).append("\n"); + errorMessage.append("Message: ").append(message).append("\n"); + errorMessage.append("query: ").append(query).append("\n"); + errorMessage.append("fl: ").append(fl).append("\n"); + + } catch (ParseException e) + { + e.printStackTrace(); + } + return errorMessage.toString(); + } + + /** + * Parses the JSON response string from PDB REST API. The response is dynamic + * hence, only fields specifically requested for in the 'wantedFields' + * parameter is fetched/processed + * + * @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") + public static FTSRestResponse parsePDBJsonResponse( + String pdbJsonResponseString, FTSRestRequest pdbRestRequest) + { + FTSRestResponse searchResult = new FTSRestResponse(); + List result = null; + try + { + JSONParser jsonParser = new JSONParser(); + JSONObject jsonObj = (JSONObject) jsonParser + .parse(pdbJsonResponseString); + + JSONObject pdbResponse = (JSONObject) jsonObj.get("response"); + String queryTime = ((JSONObject) jsonObj.get("responseHeader")).get( + "QTime").toString(); + int numFound = Integer + .valueOf(pdbResponse.get("numFound").toString()); + if (numFound > 0) + { + result = new ArrayList(); + JSONArray docs = (JSONArray) pdbResponse.get("docs"); + for (Iterator docIter = docs.iterator(); docIter + .hasNext();) + { + JSONObject doc = docIter.next(); + result.add(getFTSData(doc, pdbRestRequest)); + } + searchResult.setNumberOfItemsFound(numFound); + searchResult.setResponseTime(queryTime); + searchResult.setSearchSummary(result); + } + } catch (ParseException e) + { + e.printStackTrace(); + } + return searchResult; + } + + public static FTSData getFTSData(JSONObject pdbJsonDoc, + FTSRestRequest request) + { + + String primaryKey = null; + + Object[] summaryRowData; + + SequenceI associatedSequence; + + Collection diplayFields = request.getWantedFields(); + SequenceI associatedSeq = request.getAssociatedSequence(); + int colCounter = 0; + summaryRowData = new Object[(associatedSeq != null) ? diplayFields + .size() + 1 : diplayFields.size()]; + if (associatedSeq != null) + { + associatedSequence = associatedSeq; + summaryRowData[0] = associatedSequence; + colCounter = 1; + } + + for (FTSDataColumnI field : diplayFields) + { + String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? "" + : pdbJsonDoc.get(field.getCode()).toString(); + if (field.isPrimaryKeyColumn()) + { + primaryKey = fieldData; + summaryRowData[colCounter++] = primaryKey; + } + else + { + if (field.getGroup().getName().equals("Quality Measures")) + { + try + { + if (fieldData == null || fieldData.isEmpty()) + { + summaryRowData[colCounter++] = null; + } + else + { + Double value = Double.valueOf(fieldData); + summaryRowData[colCounter++] = value; + } + } catch (Exception e) + { + e.printStackTrace(); + System.out.println("offending value:" + fieldData); + summaryRowData[colCounter++] = 0.0; + } + } + else + { + summaryRowData[colCounter++] = (fieldData == null || fieldData + .isEmpty()) ? null : fieldData; + } + } + } + + final String primaryKey1 = primaryKey; + + final Object[] summaryRowData1 = summaryRowData; + return new FTSData() + { + @Override + public Object[] getSummaryData() + { + return summaryRowData1; + } + + @Override + public Object getPrimaryKey() + { + return primaryKey1; + } + + /** + * Returns a string representation of this object; + */ + @Override + public String toString() + { + StringBuilder summaryFieldValues = new StringBuilder(); + for (Object summaryField : summaryRowData1) + { + summaryFieldValues.append( + summaryField == null ? " " : summaryField.toString()) + .append("\t"); + } + return summaryFieldValues.toString(); + } + + /** + * Returns hash code value for this object + */ + @Override + public int hashCode() + { + return Objects.hash(primaryKey1, this.toString()); + } + }; + } + + @Override + public String getColumnDataConfigFile() + { + return getFile("fts/pdb_data_columns.conf"); + } + + + public static FTSRestClientI getInstance() + { + if (instance == null) + { + instance = new PDBFTSRestClient(); + } + return instance; + } +} diff --git a/src/jalview/gui/SequenceFetcher.java b/src/jalview/gui/SequenceFetcher.java index eb33ce7..da88b12 100755 --- a/src/jalview/gui/SequenceFetcher.java +++ b/src/jalview/gui/SequenceFetcher.java @@ -26,6 +26,7 @@ import jalview.datamodel.AlignmentI; import jalview.datamodel.DBRefEntry; import jalview.datamodel.SequenceFeature; import jalview.datamodel.SequenceI; +import jalview.fts.service.pdb.PDBFTSPanel; import jalview.io.gff.SequenceOntologyI; import jalview.util.DBRefUtils; import jalview.util.MessageManager; @@ -114,6 +115,11 @@ public class SequenceFetcher extends JPanel implements Runnable int debounceTrap = 0; + public JTextArea getTextArea() + { + return textArea; + } + /** * Blocking method that initialises and returns the shared instance of the * SequenceFetcher client @@ -399,7 +405,7 @@ public class SequenceFetcher extends JPanel implements Runnable private void pdbSourceAction() { databaseButt.setText(database.getSelectedItem()); - new PDBSearchPanel(this); + new PDBFTSPanel(this); frame.dispose(); } diff --git a/src/jalview/gui/StructureChooser.java b/src/jalview/gui/StructureChooser.java index 5709ac9..2d9028a 100644 --- a/src/jalview/gui/StructureChooser.java +++ b/src/jalview/gui/StructureChooser.java @@ -26,16 +26,17 @@ import jalview.datamodel.DBRefEntry; import jalview.datamodel.DBRefSource; import jalview.datamodel.PDBEntry; import jalview.datamodel.SequenceI; +import jalview.fts.api.FTSData; +import jalview.fts.api.FTSDataColumnI; +import jalview.fts.api.FTSRestClientI; +import jalview.fts.core.FTSDataColumnPreferences; +import jalview.fts.core.FTSRestRequest; +import jalview.fts.core.FTSRestResponse; +import jalview.fts.service.pdb.PDBFTSRestClient; import jalview.jbgui.GStructureChooser; -import jalview.jbgui.PDBDocFieldPreferences; import jalview.structure.StructureSelectionManager; import jalview.util.MessageManager; -import jalview.ws.dbsources.PDBRestClient; -import jalview.ws.dbsources.PDBRestClient.PDBDocField; import jalview.ws.sifts.SiftsSettings; -import jalview.ws.uimodel.PDBRestRequest; -import jalview.ws.uimodel.PDBRestResponse; -import jalview.ws.uimodel.PDBRestResponse.PDBResponseSummary; import java.awt.event.ItemEvent; import java.util.ArrayList; @@ -70,11 +71,11 @@ public class StructureChooser extends GStructureChooser implements private IProgressIndicator progressIndicator; - private Collection discoveredStructuresSet; + private Collection discoveredStructuresSet; - private PDBRestRequest lastPdbRequest; + private FTSRestRequest lastPdbRequest; - private PDBRestClient pdbRestCleint; + private FTSRestClientI pdbRestCleint; private String selectedPdbFileName; @@ -146,22 +147,22 @@ public class StructureChooser extends GStructureChooser implements public void fetchStructuresMetaData() { long startTime = System.currentTimeMillis(); - Collection wantedFields = PDBDocFieldPreferences + Collection wantedFields = FTSDataColumnPreferences .getStructureSummaryFields(); - discoveredStructuresSet = new LinkedHashSet(); + discoveredStructuresSet = new LinkedHashSet(); HashSet errors = new HashSet(); for (SequenceI seq : selectedSequences) { - PDBRestRequest pdbRequest = new PDBRestRequest(); + FTSRestRequest pdbRequest = new FTSRestRequest(); pdbRequest.setAllowEmptySeq(false); pdbRequest.setResponseSize(500); pdbRequest.setFieldToSearchBy("("); pdbRequest.setWantedFields(wantedFields); pdbRequest.setSearchTerm(buildQuery(seq) + ")"); pdbRequest.setAssociatedSequence(seq); - pdbRestCleint = new PDBRestClient(); - PDBRestResponse resultList; + pdbRestCleint = PDBFTSRestClient.getInstance(); + FTSRestResponse resultList; try { resultList = pdbRestCleint.executeRequest(pdbRequest); @@ -185,7 +186,7 @@ public class StructureChooser extends GStructureChooser implements if (discoveredStructuresSet != null && !discoveredStructuresSet.isEmpty()) { - tbl_summary.setModel(PDBRestResponse.getTableModel(lastPdbRequest, + tbl_summary.setModel(FTSRestResponse.getTableModel(lastPdbRequest, discoveredStructuresSet)); structuresDiscovered = true; noOfStructuresFound = discoveredStructuresSet.size(); @@ -255,7 +256,7 @@ public class StructureChooser extends GStructureChooser implements { if (isValidSeqName(entry.getId())) { - queryBuilder.append(PDBRestClient.PDBDocField.PDB_ID.getCode()) + queryBuilder.append("pdb_id") .append(":") .append(entry.getId().toLowerCase()) .append(" OR "); @@ -274,12 +275,11 @@ public class StructureChooser extends GStructureChooser implements if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT)) { queryBuilder - .append(PDBRestClient.PDBDocField.UNIPROT_ACCESSION - .getCode()).append(":") +.append("uniprot_accession").append(":") .append(getDBRefId(dbRef)) .append(" OR "); queryBuilder - .append(PDBRestClient.PDBDocField.UNIPROT_ID.getCode()) +.append("uniprot_id") .append(":") .append(getDBRefId(dbRef)).append(" OR "); isUniProtRefsFound = true; @@ -287,7 +287,7 @@ public class StructureChooser extends GStructureChooser implements else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB)) { - queryBuilder.append(PDBRestClient.PDBDocField.PDB_ID.getCode()) + queryBuilder.append("pdb_id") .append(":").append(getDBRefId(dbRef).toLowerCase()) .append(" OR "); isPDBRefsFound = true; @@ -396,14 +396,14 @@ public class StructureChooser extends GStructureChooser implements { long startTime = System.currentTimeMillis(); lbl_loading.setVisible(true); - Collection wantedFields = PDBDocFieldPreferences + Collection wantedFields = FTSDataColumnPreferences .getStructureSummaryFields(); - Collection filteredResponse = new HashSet(); + Collection filteredResponse = new HashSet(); HashSet errors = new HashSet(); for (SequenceI seq : selectedSequences) { - PDBRestRequest pdbRequest = new PDBRestRequest(); + FTSRestRequest pdbRequest = new FTSRestRequest(); if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage")) { System.out.println(">>>>>> Filtering with uniprot coverate"); @@ -428,8 +428,8 @@ public class StructureChooser extends GStructureChooser implements pdbRequest.setWantedFields(wantedFields); pdbRequest.setAssociatedSequence(seq); } - pdbRestCleint = new PDBRestClient(); - PDBRestResponse resultList; + pdbRestCleint = PDBFTSRestClient.getInstance(); + FTSRestResponse resultList; try { resultList = pdbRestCleint.executeRequest(pdbRequest); @@ -452,13 +452,13 @@ public class StructureChooser extends GStructureChooser implements if (!filteredResponse.isEmpty()) { final int filterResponseCount = filteredResponse.size(); - Collection reorderedStructuresSet = new LinkedHashSet(); + Collection reorderedStructuresSet = new LinkedHashSet(); reorderedStructuresSet.addAll(filteredResponse); reorderedStructuresSet.addAll(discoveredStructuresSet); - tbl_summary.setModel(PDBRestResponse.getTableModel( + tbl_summary.setModel(FTSRestResponse.getTableModel( lastPdbRequest, reorderedStructuresSet)); - PDBRestResponse.configureTableColumn(tbl_summary, wantedFields); + FTSRestResponse.configureTableColumn(tbl_summary, wantedFields); tbl_summary.getColumn("Ref Sequence").setPreferredWidth(120); tbl_summary.getColumn("Ref Sequence").setMinWidth(100); tbl_summary.getColumn("Ref Sequence").setMaxWidth(200); @@ -529,17 +529,17 @@ public class StructureChooser extends GStructureChooser implements if (isStructuresDiscovered()) { cmb_filterOption.addItem(new FilterOption("Best Quality", - PDBDocField.OVERALL_QUALITY.getCode(), VIEWS_FILTER)); + "overall_quality", VIEWS_FILTER)); cmb_filterOption.addItem(new FilterOption("Most UniProt Coverage", - PDBDocField.UNIPROT_COVERAGE.getCode(), VIEWS_FILTER)); + "uniprot_coverage", VIEWS_FILTER)); cmb_filterOption.addItem(new FilterOption("Best Resolution", - PDBDocField.RESOLUTION.getCode(), VIEWS_FILTER)); + "resolution", VIEWS_FILTER)); cmb_filterOption.addItem(new FilterOption("Most Protein Chain", - PDBDocField.PROTEIN_CHAIN_COUNT.getCode(), VIEWS_FILTER)); + "number_of_protein_chains", VIEWS_FILTER)); cmb_filterOption.addItem(new FilterOption("Most Bound Molecules", - PDBDocField.BOUND_MOLECULE_COUNT.getCode(), VIEWS_FILTER)); + "number_of_bound_molecules", VIEWS_FILTER)); cmb_filterOption.addItem(new FilterOption("Most Polymer Residues", - PDBDocField.POLYMER_RESIDUE_COUNT.getCode(), VIEWS_FILTER)); + "number_of_polymer_residues", VIEWS_FILTER)); } cmb_filterOption.addItem(new FilterOption("Enter PDB Id", "-", VIEWS_ENTER_ID)); @@ -730,8 +730,8 @@ public class StructureChooser extends GStructureChooser implements String currentView = selectedFilterOpt.getView(); if (currentView == VIEWS_FILTER) { - int pdbIdColIndex = tbl_summary.getColumn( - PDBRestClient.PDBDocField.PDB_ID.getName()).getModelIndex(); + int pdbIdColIndex = tbl_summary.getColumn("PDB Id") + .getModelIndex(); int refSeqColIndex = tbl_summary.getColumn("Ref Sequence") .getModelIndex(); int[] selectedRows = tbl_summary.getSelectedRows(); @@ -769,8 +769,8 @@ public class StructureChooser extends GStructureChooser implements int[] selectedRows = tbl_local_pdb.getSelectedRows(); PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length]; int count = 0; - int pdbIdColIndex = tbl_local_pdb.getColumn( - PDBRestClient.PDBDocField.PDB_ID.getName()).getModelIndex(); + int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id") + .getModelIndex(); int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence") .getModelIndex(); ArrayList selectedSeqsToView = new ArrayList(); @@ -927,7 +927,7 @@ public class StructureChooser extends GStructureChooser implements this.structuresDiscovered = structuresDiscovered; } - public Collection getDiscoveredStructuresSet() + public Collection getDiscoveredStructuresSet() { return discoveredStructuresSet; } @@ -944,9 +944,8 @@ public class StructureChooser extends GStructureChooser implements isValidPBDEntry = false; if (txt_search.getText().length() > 0) { - List wantedFields = new ArrayList(); - wantedFields.add(PDBDocField.PDB_ID); - PDBRestRequest pdbRequest = new PDBRestRequest(); + List wantedFields = new ArrayList(); + FTSRestRequest pdbRequest = new FTSRestRequest(); pdbRequest.setAllowEmptySeq(false); pdbRequest.setResponseSize(1); pdbRequest.setFieldToSearchBy("(pdb_id:"); @@ -954,8 +953,9 @@ public class StructureChooser extends GStructureChooser implements pdbRequest .setSearchTerm(txt_search.getText().toLowerCase() + ")"); pdbRequest.setAssociatedSequence(selectedSequence); - pdbRestCleint = new PDBRestClient(); - PDBRestResponse resultList; + pdbRestCleint = PDBFTSRestClient.getInstance(); + wantedFields.add(pdbRestCleint.getPrimaryKeyColumn()); + FTSRestResponse resultList; try { resultList = pdbRestCleint.executeRequest(pdbRequest); diff --git a/src/jalview/jbgui/GPreferences.java b/src/jalview/jbgui/GPreferences.java index b5c1804..c4c737c 100755 --- a/src/jalview/jbgui/GPreferences.java +++ b/src/jalview/jbgui/GPreferences.java @@ -20,9 +20,11 @@ */ package jalview.jbgui; +import jalview.fts.core.FTSDataColumnPreferences; +import jalview.fts.core.FTSDataColumnPreferences.PreferenceSource; +import jalview.fts.service.pdb.PDBFTSRestClient; import jalview.gui.JvSwingUtils; import jalview.gui.StructureViewer.ViewerType; -import jalview.jbgui.PDBDocFieldPreferences.PreferenceSource; import jalview.util.MessageManager; import java.awt.BorderLayout; @@ -899,8 +901,8 @@ public class GPreferences extends JPanel ypos += lineSpacing; ypos += lineSpacing; - PDBDocFieldPreferences docFieldPref = new PDBDocFieldPreferences( - PreferenceSource.PREFERENCES); + FTSDataColumnPreferences docFieldPref = new FTSDataColumnPreferences( + PreferenceSource.PREFERENCES, PDBFTSRestClient.getInstance()); docFieldPref.setBounds(new Rectangle(10, ypos, 450, 120)); structureTab.add(docFieldPref); diff --git a/src/jalview/jbgui/GStructureChooser.java b/src/jalview/jbgui/GStructureChooser.java index 8430557..ed94172 100644 --- a/src/jalview/jbgui/GStructureChooser.java +++ b/src/jalview/jbgui/GStructureChooser.java @@ -22,13 +22,14 @@ package jalview.jbgui; import jalview.datamodel.SequenceI; +import jalview.fts.api.FTSDataColumnI; +import jalview.fts.core.FTSDataColumnPreferences; +import jalview.fts.core.FTSDataColumnPreferences.PreferenceSource; +import jalview.fts.service.pdb.PDBFTSRestClient; import jalview.gui.AlignmentPanel; import jalview.gui.Desktop; import jalview.gui.JvSwingUtils; -import jalview.jbgui.PDBDocFieldPreferences.PreferenceSource; import jalview.util.MessageManager; -import jalview.ws.dbsources.PDBRestClient; -import jalview.ws.dbsources.PDBRestClient.PDBDocField; import java.awt.BorderLayout; import java.awt.CardLayout; @@ -195,10 +196,10 @@ public abstract class GStructureChooser extends JPanel implements private JTabbedPane pnl_filter = new JTabbedPane(); - private PDBDocFieldPreferences pdbDocFieldPrefs = new PDBDocFieldPreferences( - PreferenceSource.STRUCTURE_CHOOSER); + private FTSDataColumnPreferences pdbDocFieldPrefs = new FTSDataColumnPreferences( + PreferenceSource.STRUCTURE_CHOOSER, PDBFTSRestClient.getInstance()); - protected PDBDocField[] previousWantedFields; + protected FTSDataColumnI[] previousWantedFields; public GStructureChooser() { @@ -473,9 +474,9 @@ public abstract class GStructureChooser extends JPanel implements btn_cancel.setEnabled(false); btn_view.setVisible(false); btn_cancel.setVisible(false); - previousWantedFields = PDBDocFieldPreferences + previousWantedFields = FTSDataColumnPreferences .getStructureSummaryFields().toArray( - new PDBRestClient.PDBDocField[0]); + new FTSDataColumnI[0]); } if (sourceTabbedPane.getTitleAt(index) .equals(foundStructureSummary)) @@ -527,8 +528,8 @@ public abstract class GStructureChooser extends JPanel implements return true; } - return Arrays.equals(PDBDocFieldPreferences.getStructureSummaryFields() - .toArray(new PDBRestClient.PDBDocField[0]), + return Arrays.equals(FTSDataColumnPreferences.getStructureSummaryFields() + .toArray(new FTSDataColumnI[0]), previousWantedFields) ? false : true; } diff --git a/src/jalview/ws/dbsources/PDBRestClient.java b/src/jalview/ws/dbsources/PDBRestClient.java deleted file mode 100644 index dbdb01d..0000000 --- a/src/jalview/ws/dbsources/PDBRestClient.java +++ /dev/null @@ -1,563 +0,0 @@ -/* - * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$) - * Copyright (C) $$Year-Rel$$ 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.dbsources; - -import jalview.util.MessageManager; -import jalview.ws.uimodel.PDBRestRequest; -import jalview.ws.uimodel.PDBRestResponse; -import jalview.ws.uimodel.PDBRestResponse.PDBResponseSummary; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import javax.ws.rs.core.MediaType; - -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.config.DefaultClientConfig; - -/** - * A rest client for querying the Search endpoing of the PDB REST API - * - * @author tcnofoegbu - * - */ -public class PDBRestClient -{ - public static final String PDB_SEARCH_ENDPOINT = "http://www.ebi.ac.uk/pdbe/search/pdb/select?"; - - private static int DEFAULT_RESPONSE_SIZE = 200; - - /** - * Takes a PDBRestRequest object and returns a response upon execution - * - * @param pdbRestRequest - * the PDBRestRequest instance to be processed - * @return the pdbResponse object for the given request - * @throws Exception - */ - public PDBRestResponse executeRequest(PDBRestRequest pdbRestRequest) - throws Exception - { - try - { - ClientConfig clientConfig = new DefaultClientConfig(); - Client client = Client.create(clientConfig); - - String wantedFields = getPDBDocFieldsAsCommaDelimitedString(pdbRestRequest - .getWantedFields()); - int responseSize = (pdbRestRequest.getResponseSize() == 0) ? DEFAULT_RESPONSE_SIZE - : pdbRestRequest.getResponseSize(); - String sortParam = null; - if (pdbRestRequest.getFieldToSortBy() == null - || pdbRestRequest.getFieldToSortBy().trim().isEmpty()) - { - sortParam = ""; - } - else - { - if (pdbRestRequest.getFieldToSortBy() - .equalsIgnoreCase("Resolution")) - { - sortParam = pdbRestRequest.getFieldToSortBy() - + (pdbRestRequest.isAscending() ? " asc" : " desc"); - } - else - { - sortParam = pdbRestRequest.getFieldToSortBy() - + (pdbRestRequest.isAscending() ? " desc" : " asc"); - } - } - - String facetPivot = (pdbRestRequest.getFacetPivot() == null || pdbRestRequest - .getFacetPivot().isEmpty()) ? "" : pdbRestRequest - .getFacetPivot(); - String facetPivotMinCount = String.valueOf(pdbRestRequest - .getFacetPivotMinCount()); - - // Build request parameters for the REST Request - WebResource webResource = null; - if (pdbRestRequest.isFacet()) - { - webResource = client.resource(PDB_SEARCH_ENDPOINT) - .queryParam("wt", "json").queryParam("fl", wantedFields) - .queryParam("rows", String.valueOf(responseSize)) - .queryParam("q", pdbRestRequest.getQuery()) - .queryParam("sort", sortParam).queryParam("facet", "true") - .queryParam("facet.pivot", facetPivot) - .queryParam("facet.pivot.mincount", facetPivotMinCount); - } - else - { - webResource = client.resource(PDB_SEARCH_ENDPOINT) - .queryParam("wt", "json").queryParam("fl", wantedFields) - .queryParam("rows", String.valueOf(responseSize)) - .queryParam("q", pdbRestRequest.getQuery()) - .queryParam("sort", sortParam); - } - // Execute the REST request - ClientResponse clientResponse = webResource.accept( - MediaType.APPLICATION_JSON).get(ClientResponse.class); - - // Get the JSON string from the response object - String responseString = clientResponse.getEntity(String.class); - // System.out.println("query >>>>>>> " + pdbRestRequest.toString()); - - // Check the response status and report exception if one occurs - if (clientResponse.getStatus() != 200) - { - String errorMessage = ""; - if (clientResponse.getStatus() == 400) - { - errorMessage = parseJsonExceptionString(responseString); - throw new Exception(errorMessage); - } - else - { - errorMessage = getMessageByHTTPStatusCode(clientResponse - .getStatus()); - throw new Exception(errorMessage); - } - } - - // Make redundant objects eligible for garbage collection to conserve - // memory - clientResponse = null; - client = null; - - // Process the response and return the result to the caller. - return parsePDBJsonResponse(responseString, pdbRestRequest); - } catch (Exception e) - { - String exceptionMsg = e.getMessage(); - if (exceptionMsg.contains("SocketException")) - { - // No internet connection - throw new Exception( - MessageManager - .getString("exception.unable_to_detect_internet_connection")); - } - else if (exceptionMsg.contains("UnknownHostException")) - { - // The server 'www.ebi.ac.uk' is unreachable - throw new Exception( - MessageManager - .getString("exception.pdb_server_unreachable")); - } - else - { - throw e; - } - } - } - - public String getMessageByHTTPStatusCode(int code) - { - String message = ""; - switch (code) - { - case 410: - message = MessageManager - .getString("exception.pdb_rest_service_no_longer_available"); - break; - case 403: - case 404: - message = MessageManager.getString("exception.resource_not_be_found"); - break; - case 408: - case 409: - case 500: - case 501: - case 502: - case 503: - case 504: - case 505: - message = MessageManager.getString("exception.pdb_server_error"); - break; - - default: - break; - } - return message; - } - - /** - * 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) - { - StringBuilder errorMessage = new StringBuilder( - "\n============= PDB Rest Client RunTime error =============\n"); - - try - { - JSONParser jsonParser = new JSONParser(); - JSONObject jsonObj = (JSONObject) jsonParser.parse(jsonErrorResponse); - JSONObject errorResponse = (JSONObject) jsonObj.get("error"); - - JSONObject responseHeader = (JSONObject) jsonObj - .get("responseHeader"); - JSONObject paramsObj = (JSONObject) responseHeader.get("params"); - String status = responseHeader.get("status").toString(); - String message = errorResponse.get("msg").toString(); - String query = paramsObj.get("q").toString(); - String fl = paramsObj.get("fl").toString(); - - errorMessage.append("Status: ").append(status).append("\n"); - errorMessage.append("Message: ").append(message).append("\n"); - errorMessage.append("query: ").append(query).append("\n"); - errorMessage.append("fl: ").append(fl).append("\n"); - - } catch (ParseException e) - { - e.printStackTrace(); - } - return errorMessage.toString(); - } - - /** - * Parses the JSON response string from PDB REST API. The response is dynamic - * hence, only fields specifically requested for in the 'wantedFields' - * parameter is fetched/processed - * - * @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") - public static PDBRestResponse parsePDBJsonResponse( - String pdbJsonResponseString, PDBRestRequest pdbRestRequest) - { - PDBRestResponse searchResult = new PDBRestResponse(); - List result = null; - try - { - JSONParser jsonParser = new JSONParser(); - JSONObject jsonObj = (JSONObject) jsonParser - .parse(pdbJsonResponseString); - - JSONObject pdbResponse = (JSONObject) jsonObj.get("response"); - String queryTime = ((JSONObject) jsonObj.get("responseHeader")).get( - "QTime").toString(); - int numFound = Integer - .valueOf(pdbResponse.get("numFound").toString()); - if (numFound > 0) - { - result = new ArrayList(); - JSONArray docs = (JSONArray) pdbResponse.get("docs"); - for (Iterator docIter = docs.iterator(); docIter - .hasNext();) - { - JSONObject doc = docIter.next(); - result.add(searchResult.new PDBResponseSummary(doc, - pdbRestRequest)); - } - searchResult.setNumberOfItemsFound(numFound); - searchResult.setResponseTime(queryTime); - searchResult.setSearchSummary(result); - } - } catch (ParseException e) - { - e.printStackTrace(); - } - return searchResult; - } - - /** - * Takes a collection of PDBDocField and converts its 'code' Field values into - * a comma delimited string. - * - * @param pdbDocfields - * the collection of PDBDocField to process - * @return the comma delimited string from the pdbDocFields collection - */ - public static String getPDBDocFieldsAsCommaDelimitedString( - Collection pdbDocfields) - { - String result = ""; - if (pdbDocfields != null && !pdbDocfields.isEmpty()) - { - StringBuilder returnedFields = new StringBuilder(); - for (PDBDocField field : pdbDocfields) - { - returnedFields.append(",").append(field.getCode()); - } - returnedFields.deleteCharAt(0); - result = returnedFields.toString(); - } - return result; - } - - /** - * Determines the column index for 'PDB Id' Fields in the dynamic summary - * table. The PDB Id serves as a unique identifier for a given row in the - * summary table - * - * @param wantedFields - * the available table columns in no particular order - * @return the pdb id field column index - */ - public static int getPDBIdColumIndex( - Collection wantedFields, boolean hasRefSeq) - { - - // If a reference sequence is attached then start counting from 1 else - // start from zero - int pdbFieldIndexCounter = hasRefSeq ? 1 : 0; - - for (PDBDocField field : wantedFields) - { - if (field.equals(PDBDocField.PDB_ID)) - { - break; // Once PDB Id index is determined exit iteration - } - ++pdbFieldIndexCounter; - } - return pdbFieldIndexCounter; - } - - public static PDBDocField getPDBDocFieldByCode(String fieldCode) - throws Exception - { - for (PDBDocField curPDBDocField : PDBDocField.values()) - { - if (curPDBDocField.getCode().equalsIgnoreCase(fieldCode)) - { - return curPDBDocField; - } - } - throw new Exception("PDB doc Field not found!"); - } - - /** - * This enum represents the fields available in the PDB JSON response - * - */ - public enum PDBDocField - { - PDB_ID("PDB Id", "pdb_id", Group.CROSS_REFS), TITLE( - "Title", - "title", Group.MISCELLENOUS), - MOLECULE_NAME("Molecule", - "molecule_name", - Group.NAMES_AND_TAXONOMY), MOLECULE_TYPE( - "Molecule Type", "molecule_type", Group.NAMES_AND_TAXONOMY), MOLECULE_SEQUENCE( - "Sequence", "molecule_sequence", Group.MISCELLENOUS), PFAM_ACCESSION( - "PFAM Accession", "pfam_accession", - Group.CROSS_REFS), PFAM_NAME( - "PFAM Name", "pfam_name", Group.NAMES_AND_TAXONOMY), INTERPRO_NAME( - "InterPro Name", "interpro_name", Group.NAMES_AND_TAXONOMY), INTERPRO_ACCESSION( - "InterPro Accession", "interpro_accession", - Group.CROSS_REFS), UNIPROT_ID("UniProt Id", - "uniprot_id", Group.CROSS_REFS), UNIPROT_ACCESSION( - "UniProt Accession", "uniprot_accession", - Group.CROSS_REFS), - - UNIPROT_COVERAGE( - "UniProt Coverage", "uniprot_coverage", Group.MISCELLENOUS), UNIPROT_FEATURES( - "Uniprot Features", "uniprot_features", Group.MISCELLENOUS), R_FACTOR( -"R Factor", - "r_factor", Group.QUALITY_MEASURES), RESOLUTION("Resolution", - "resolution", Group.QUALITY_MEASURES), DATA_QUALITY( - "Data Quality", "data_quality", Group.QUALITY_MEASURES), OVERALL_QUALITY( - "Overall Quality", "overall_quality", Group.QUALITY_MEASURES), POLYMER_COUNT( - "Number of Polymers", "number_of_polymers", Group.MISCELLENOUS), PROTEIN_CHAIN_COUNT( - "Number of Protein Chains", "number_of_protein_chains", - Group.MISCELLENOUS), BOUND_MOLECULE_COUNT( - "Number of Bound Molecule", "number_of_bound_molecules", - Group.MISCELLENOUS), POLYMER_RESIDUE_COUNT( - "Number of Polymer Residue", "number_of_polymer_residues", - Group.MISCELLENOUS), GENUS("GENUS", "genus", - Group.NAMES_AND_TAXONOMY), GENE_NAME("Gene Name", "gene_name", - Group.NAMES_AND_TAXONOMY), EXPERIMENTAL_METHOD( - "Experimental Method", "experimental_method", - Group.PROCEDURE_AND_SOFTWARE), GO_ID("GO Id", "go_id", - Group.CROSS_REFS), ASSEMBLY_ID("Assembly Id", - "assembly_id", Group.CROSS_REFS), ASSEMBLY_FORM( - "Assembly Form", "assembly_form", Group.MISCELLENOUS), ASSEMBLY_TYPE( - "Assembly Type", "assembly_type", Group.MISCELLENOUS), SPACE_GROUP( - "Space Group", "spacegroup", Group.MISCELLENOUS), CATH_CODE( - "Cath Code", "cath_code", Group.CROSS_REFS), TAX_ID( - "Tax Id", "tax_id", Group.CROSS_REFS), TAX_QUERY( - "Tax Query", "tax_query", Group.CROSS_REFS), INTERACTING_ENTITY_ID( - "Interacting Entity Id", "interacting_entity_id", - Group.CROSS_REFS), INTERACTING_MOLECULES( - "Interacting Molecules", "interacting_molecules", - Group.MISCELLENOUS), PUBMED_ID("Pubmed Id", "pubmed_id", - Group.CROSS_REFS), STATUS("Status", "status", - Group.MISCELLENOUS), MODEL_QUALITY("Model Quality", - "model_quality", Group.QUALITY_MEASURES), PIVOT_RESOLUTION( - "Pivot Resolution", "pivot_resolution", Group.QUALITY_MEASURES), DATA_REDUCTION_SOFTWARE( - "Data reduction software", "data_reduction_software", - Group.PROCEDURE_AND_SOFTWARE), MAX_OBSERVED_RES( - "Max observed residues", - "max_observed_residues", Group.MISCELLENOUS), ORG_SCI_NAME( - "Organism scientific name", "organism_scientific_name", - Group.NAMES_AND_TAXONOMY), SUPER_KINGDOM("Super kingdom", - "superkingdom", Group.NAMES_AND_TAXONOMY), RANK("Rank", "rank", - Group.NAMES_AND_TAXONOMY), CRYSTALLISATION_PH( - "Crystallisation Ph", - "crystallisation_ph", Group.MISCELLENOUS), BIOLOGICAL_FUNCTION( - "Biological Function", "biological_function", - Group.MISCELLENOUS), BIOLOGICAL_PROCESS("Biological Process", - "biological_process", Group.MISCELLENOUS), BIOLOGICAL_CELL_COMPONENT( - "Biological Cell Component", "biological_cell_component", - Group.MISCELLENOUS), COMPOUND_NAME("Compound Name", - "compound_name", Group.NAMES_AND_TAXONOMY), COMPOUND_ID( - "Compound Id", "compound_id", Group.CROSS_REFS), COMPOUND_WEIGHT( - "Compound Weight", "compound_weight", Group.MISCELLENOUS), COMPOUND_SYSTEMATIC_NAME( - "Compound Systematic Name", "compound_systematic_name", - Group.NAMES_AND_TAXONOMY), INTERACTING_LIG( - "Interacting Ligands", - "interacting_ligands", Group.MISCELLENOUS), JOURNAL("Journal", - "journal", Group.MISCELLENOUS), ALL_AUTHORS("All Authors", - "all_authors", Group.MISCELLENOUS), EXPERIMENTAL_DATA_AVAILABLE( - "Experiment Data Available", "experiment_data_available", - Group.MISCELLENOUS), DIFFRACTION_PROTOCOL( - "Diffraction Protocol", "diffraction_protocol", - Group.PROCEDURE_AND_SOFTWARE), REFINEMENT_SOFTWARE( - "Refinement Software", "refinement_software", - Group.PROCEDURE_AND_SOFTWARE), STRUCTURE_DETERMINATION_METHOD( - "Structure Determination Method", - "structure_determination_method", Group.PROCEDURE_AND_SOFTWARE), SYNCHROTON_SITE( - "Synchrotron Site", "synchrotron_site", Group.MISCELLENOUS), SAMPLE_PREP_METHOD( - "Sample Preparation Method", "sample_preparation_method", - Group.PROCEDURE_AND_SOFTWARE), ENTRY_AUTHORS("Entry Authors", - "entry_authors", Group.MISCELLENOUS), CITATION_TITLE( - "Citation Title", "citation_title", Group.MISCELLENOUS), STRUCTURE_SOLUTION_SOFTWARE( - "Structure Solution Software", "structure_solution_software", - Group.PROCEDURE_AND_SOFTWARE), ENTRY_ENTITY("Entry Entity", - "entry_entity", Group.MISCELLENOUS), R_FREE("R Free", "r_free", - Group.QUALITY_MEASURES), NO_OF_POLYMER_ENTITIES( - "Number of Polymer Entities", "number_of_polymer_entities", - Group.MISCELLENOUS), NO_OF_BOUND_ENTITIES( - "Number of Bound Entities", "number_of_bound_entities", - Group.MISCELLENOUS), CRYSTALLISATION_RESERVOIR( - "Crystallisation Reservoir", "crystallisation_reservoir", - Group.MISCELLENOUS), DATA_SCALING_SW("Data Scalling Software", - "data_scaling_software", Group.PROCEDURE_AND_SOFTWARE), DETECTOR( - "Detector", "detector", Group.MISCELLENOUS), DETECTOR_TYPE( - "Detector Type", "detector_type", Group.MISCELLENOUS), MODIFIED_RESIDUE_FLAG( - "Modified Residue Flag", "modified_residue_flag", - Group.MISCELLENOUS), NUMBER_OF_COPIES("Number of Copies", - "number_of_copies", Group.MISCELLENOUS), STRUCT_ASYM_ID( - "Struc Asym Id", "struct_asym_id", - Group.CROSS_REFS), HOMOLOGUS_PDB_ENTITY_ID( - "Homologus PDB Entity Id", "homologus_pdb_entity_id", - Group.CROSS_REFS), MOLECULE_SYNONYM( - "Molecule Synonym", - "molecule_synonym", Group.MISCELLENOUS), DEPOSITION_SITE( - "Deposition Site", "deposition_site", Group.MISCELLENOUS), SYNCHROTRON_BEAMLINE( - "Synchrotron Beamline", "synchrotron_beamline", - Group.MISCELLENOUS), ENTITY_ID("Entity Id", "entity_id", - Group.CROSS_REFS), BEAM_SOURCE_NAME( - "Beam Source Name", - "beam_source_name", - Group.NAMES_AND_TAXONOMY), PROCESSING_SITE( - "Processing Site", "processing_site", Group.MISCELLENOUS), ENTITY_WEIGHT( - "Entity Weight", "entity_weight", Group.MISCELLENOUS), VERSION( - "Version", "_version_", Group.MISCELLENOUS), ALL("ALL", "text", - Group.MISCELLENOUS); - - public enum Group - { - DATE_OF("Date Of", 5), NAMES_AND_TAXONOMY("Names & Taxonomy", 3), - MISCELLENOUS("Miscellenous", 6), QUALITY_MEASURES("Quality Measures", - 1), CROSS_REFS("Cross References", 2), - PROCEDURE_AND_SOFTWARE("Procedures & Softwares", 4); - - Group(String name, int sortOrder) - { - this.name = name; - this.sortOrder = sortOrder; - } - - private String name; - - private int sortOrder; - - public String getName() - { - return this.name; - } - - public int getSortOrder() - { - return sortOrder; - } - - @Override - public String toString() - { - return this.name; - } - }; - private String name; - - private String code; - - private Group group; - - PDBDocField(String name, String code, Group group) - { - this.name = name; - this.code = code; - this.group = group; - } - - public String getName() - { - return name; - } - - public String getCode() - { - return code; - } - - public Group getGroup() - { - return group; - } - - @Override - public String toString() - { - return name; - } - } -} diff --git a/src/jalview/ws/uimodel/PDBRestResponse.java b/src/jalview/ws/uimodel/PDBRestResponse.java deleted file mode 100644 index 3471fab..0000000 --- a/src/jalview/ws/uimodel/PDBRestResponse.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * 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.datamodel.SequenceI; -import jalview.ws.dbsources.PDBRestClient.PDBDocField; -import jalview.ws.dbsources.PDBRestClient.PDBDocField.Group; - -import java.util.Collection; -import java.util.Objects; - -import javax.swing.JTable; -import javax.swing.table.DefaultTableModel; - -import org.json.simple.JSONObject; - -/** - * Represents the response model produced by the PDBRestClient upon successful - * execution of a given request - * - * @author tcnofoegbu - * - */ -public class PDBRestResponse -{ - private int numberOfItemsFound; - - private String responseTime; - - private Collection searchSummary; - - public int getNumberOfItemsFound() - { - return numberOfItemsFound; - } - - public void setNumberOfItemsFound(int itemFound) - { - this.numberOfItemsFound = itemFound; - } - - public String getResponseTime() - { - return responseTime; - } - - public void setResponseTime(String responseTime) - { - this.responseTime = responseTime; - } - - public Collection getSearchSummary() - { - return searchSummary; - } - - public void setSearchSummary(Collection searchSummary) - { - this.searchSummary = searchSummary; - } - - /** - * Convenience method to obtain a Table model for a given summary List based - * on the request parameters - * - * @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) - { - final PDBDocField[] cols = request.getWantedFields().toArray( - new PDBDocField[0]); - final int colOffset = request.getAssociatedSequence() == null ? 0 : 1; - DefaultTableModel tableModel = new DefaultTableModel() - { - @Override - public boolean isCellEditable(int row, int column) - { - return false; - } - - @Override - public Class getColumnClass(int columnIndex) - { - if (colOffset == 1 && columnIndex == 0) - { - return String.class; - } - if (cols[columnIndex - colOffset].getGroup().getName() - .equalsIgnoreCase(Group.QUALITY_MEASURES.getName())) - { - return Double.class; - } - return String.class; - } - - }; - if (request.getAssociatedSequence() != null) - { - tableModel.addColumn("Ref Sequence"); // Create sequence column header if - // exists in the request - } - for (PDBDocField field : request.getWantedFields()) - { - tableModel.addColumn(field.getName()); // Create sequence column header if - // exists in the request - } - - for (PDBResponseSummary res : summariesList) - { - tableModel.addRow(res.getSummaryData()); // Populate table rows with - // summary list - } - - return tableModel; - } - - /** - * Model for a unique response summary - * - */ - public class PDBResponseSummary - { - private String pdbId; - - private Object[] summaryRowData; - - private SequenceI associatedSequence; - - public PDBResponseSummary(JSONObject pdbJsonDoc, PDBRestRequest request) - { - Collection diplayFields = request.getWantedFields(); - SequenceI associatedSeq = request.getAssociatedSequence(); - int colCounter = 0; - summaryRowData = new Object[(associatedSeq != null) ? diplayFields - .size() + 1 : diplayFields.size()]; - if (associatedSeq != null) - { - this.associatedSequence = associatedSeq; - summaryRowData[0] = associatedSequence; - colCounter = 1; - } - - for (PDBDocField field : diplayFields) - { - String fieldData = (pdbJsonDoc.get(field.getCode()) == null) ? "" - : pdbJsonDoc.get(field.getCode()).toString(); - if (field.equals(PDBDocField.PDB_ID)) - { - this.pdbId = fieldData; - summaryRowData[colCounter++] = this.pdbId; - } - else - { - if (field.getGroup().getName() - .equals(Group.QUALITY_MEASURES.getName())) - { - try - { - if (fieldData == null || fieldData.isEmpty()) - { - summaryRowData[colCounter++] = null; - } - else - { - Double value = Double.valueOf(fieldData); - summaryRowData[colCounter++] = value; - } - } catch (Exception e) - { - e.printStackTrace(); - System.out.println("offending value:" + fieldData); - summaryRowData[colCounter++] = 0.0; - } - }else{ - summaryRowData[colCounter++] = (fieldData == null || fieldData - .isEmpty()) ? null : fieldData; - } - } - } - } - - public Object getPdbId() - { - return pdbId; - } - - public void setPdbId(String pdbId) - { - this.pdbId = pdbId; - } - - public Object[] getSummaryData() - { - return summaryRowData; - } - - public void setSummaryData(Object[] summaryData) - { - this.summaryRowData = summaryData; - } - - /** - * Returns a string representation of this object; - */ - @Override - public String toString() - { - StringBuilder summaryFieldValues = new StringBuilder(); - for (Object summaryField : summaryRowData) - { - summaryFieldValues.append( - summaryField == null ? " " : summaryField.toString()) - .append("\t"); - } - return summaryFieldValues.toString(); - } - - /** - * Returns hash code value for this object - */ - @Override - public int hashCode() - { - return Objects.hash(this.pdbId, this.toString()); - } - - /** - * Indicates whether some object is equal to this one - */ - @Override - public boolean equals(Object that) - { - if (!(that instanceof PDBResponseSummary)) - { - return false; - } - PDBResponseSummary another = (PDBResponseSummary) that; - return this.toString().equals(another.toString()); - } - - } - - public static void configureTableColumn(JTable tbl_summary, - Collection wantedFields) - { - try - { - // wait for table model initialisation to complete - Thread.sleep(1200); - } catch (InterruptedException e1) - { - e1.printStackTrace(); - } - for (PDBDocField wantedField : wantedFields) - { - try - { - if (wantedField.equals(PDBDocField.PDB_ID)) - { - tbl_summary.getColumn(wantedField.getName()).setMinWidth(40); - tbl_summary.getColumn(wantedField.getName()).setMaxWidth(60); - tbl_summary.getColumn(wantedField.getName()).setPreferredWidth(45); - } - else if (wantedField.equals(PDBDocField.TITLE)) - { - tbl_summary.getColumn(wantedField.getName()).setMinWidth(300); - tbl_summary.getColumn(wantedField.getName()).setMaxWidth(1000); - tbl_summary.getColumn(wantedField.getName()).setPreferredWidth(400); - } - else if (wantedField.getGroup() == Group.QUALITY_MEASURES) - { - tbl_summary.getColumn(wantedField.getName()).setMinWidth(50); - tbl_summary.getColumn(wantedField.getName()).setMaxWidth(150); - tbl_summary.getColumn(wantedField.getName()).setPreferredWidth(85); - } - else - { - tbl_summary.getColumn(wantedField.getName()).setMinWidth(50); - tbl_summary.getColumn(wantedField.getName()).setMaxWidth(400); - tbl_summary.getColumn(wantedField.getName()).setPreferredWidth(95); - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - } -} diff --git a/test/jalview/gui/PDBSearchPanelTest.java b/test/jalview/fts/service/pdb/PDBFTSPanelTest.java similarity index 85% rename from test/jalview/gui/PDBSearchPanelTest.java rename to test/jalview/fts/service/pdb/PDBFTSPanelTest.java index 2310373..6837847 100644 --- a/test/jalview/gui/PDBSearchPanelTest.java +++ b/test/jalview/fts/service/pdb/PDBFTSPanelTest.java @@ -18,11 +18,13 @@ * along with Jalview. If not, see . * The Jalview Authors are detailed in the 'AUTHORS' file. */ -package jalview.gui; +package jalview.fts.service.pdb; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; +import jalview.fts.service.pdb.PDBFTSPanel; + import javax.swing.JInternalFrame; import javax.swing.JTextField; @@ -30,7 +32,7 @@ import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -public class PDBSearchPanelTest +public class PDBFTSPanelTest { @BeforeMethod(alwaysRun = true) @@ -46,7 +48,7 @@ public class PDBSearchPanelTest @Test(groups = { "Functional" }) public void populateCmbSearchTargetOptionsTest() { - PDBSearchPanel searchPanel = new PDBSearchPanel(null); + PDBFTSPanel searchPanel = new PDBFTSPanel(null); assertTrue(searchPanel.getCmbSearchTarget().getItemCount() > 0); searchPanel.populateCmbSearchTargetOptions(); } @@ -55,13 +57,13 @@ public class PDBSearchPanelTest public void testDecodeSearchTerm() { String expectedString = "1xyz OR text:2xyz OR text:3xyz"; - String outcome = PDBSearchPanel.decodeSearchTerm("1xyz:A;2xyz;3xyz", + String outcome = PDBFTSPanel.decodeSearchTerm("1xyz:A;2xyz;3xyz", "text"); // System.out.println("1 >>>>>>>>>>> " + outcome); assertEquals(expectedString, outcome); expectedString = "1xyz"; - outcome = PDBSearchPanel.decodeSearchTerm("1xyz", "text"); + outcome = PDBFTSPanel.decodeSearchTerm("1xyz", "text"); // System.out.println("2 >>>>>>>>>>> " + outcome); assertEquals(expectedString, outcome); } @@ -71,19 +73,19 @@ public class PDBSearchPanelTest { String expectedString = "1xyz:A"; - String outcome = PDBSearchPanel.getPDBIdwithSpecifiedChain("1xyz", + String outcome = PDBFTSPanel.getPDBIdwithSpecifiedChain("1xyz", "2xyz;3xyz;1xyz:A"); System.out.println("1 >>>>>>>>>>> " + outcome); assertEquals(expectedString, outcome); expectedString = "2xyz"; - outcome = PDBSearchPanel.getPDBIdwithSpecifiedChain("2xyz", + outcome = PDBFTSPanel.getPDBIdwithSpecifiedChain("2xyz", "1xyz:A;2xyz;3xyz"); System.out.println("2 >>>>>>>>>>> " + outcome); assertEquals(expectedString, outcome); expectedString = "2xyz:A"; - outcome = PDBSearchPanel.getPDBIdwithSpecifiedChain("2xyz", "2xyz:A"); + outcome = PDBFTSPanel.getPDBIdwithSpecifiedChain("2xyz", "2xyz:A"); System.out.println("3 >>>>>>>>>>> " + outcome); assertEquals(expectedString, outcome); } @@ -91,7 +93,7 @@ public class PDBSearchPanelTest @Test(groups = { "Network", "External" }, timeOut = 7000) public void txt_search_ActionPerformedTest() { - PDBSearchPanel searchPanel = new PDBSearchPanel(null); + PDBFTSPanel searchPanel = new PDBFTSPanel(null); JInternalFrame mainFrame = searchPanel.getMainFrame(); JTextField txt_search = searchPanel.getTxtSearch(); diff --git a/test/jalview/ws/dbsources/PDBRestClientTest.java b/test/jalview/fts/service/pdb/PDBFTSRestClientTest.java similarity index 59% rename from test/jalview/ws/dbsources/PDBRestClientTest.java rename to test/jalview/fts/service/pdb/PDBFTSRestClientTest.java index 401f4c9..39d9aa5 100644 --- a/test/jalview/ws/dbsources/PDBRestClientTest.java +++ b/test/jalview/fts/service/pdb/PDBFTSRestClientTest.java @@ -18,14 +18,15 @@ * along with Jalview. If not, see . * The Jalview Authors are detailed in the 'AUTHORS' file. */ -package jalview.ws.dbsources; +package jalview.fts.service.pdb; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; -import jalview.ws.dbsources.PDBRestClient.PDBDocField; -import jalview.ws.uimodel.PDBRestRequest; -import jalview.ws.uimodel.PDBRestResponse; +import jalview.fts.api.FTSDataColumnI; +import jalview.fts.core.FTSRestRequest; +import jalview.fts.core.FTSRestResponse; +import jalview.fts.service.pdb.PDBFTSRestClient; import java.io.BufferedReader; import java.io.FileReader; @@ -51,7 +52,7 @@ import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; -public class PDBRestClientTest +public class PDBFTSRestClientTest { @BeforeMethod(alwaysRun = true) @@ -67,24 +68,37 @@ public class PDBRestClientTest @Test(groups = { "External", "Network" }) 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(); + List wantedFields = new ArrayList(); + try + { + wantedFields.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("molecule_type")); + wantedFields +.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("pdb_id")); + wantedFields.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("genus")); + wantedFields +.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("gene_name")); + wantedFields.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("title")); + } catch (Exception e1) + { + e1.printStackTrace(); + } + + FTSRestRequest request = new FTSRestRequest(); request.setAllowEmptySeq(false); request.setResponseSize(100); request.setFieldToSearchBy("text:"); request.setSearchTerm("abc"); request.setWantedFields(wantedFields); - PDBRestResponse response; + FTSRestResponse response; try { - response = new PDBRestClient().executeRequest(request); + response = PDBFTSRestClient.getInstance().executeRequest(request); } catch (Exception e) { e.printStackTrace(); @@ -99,16 +113,29 @@ public class PDBRestClientTest @Test(groups = { "Functional" }) 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); + List wantedFields = new ArrayList(); + try + { + wantedFields.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("molecule_type")); + wantedFields +.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("pdb_id")); + wantedFields.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("genus")); + wantedFields +.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("gene_name")); + wantedFields.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("title")); + } catch (Exception e) + { + e.printStackTrace(); + } String expectedResult = "molecule_type,pdb_id,genus,gene_name,title"; - String actualResult = PDBRestClient - .getPDBDocFieldsAsCommaDelimitedString(wantedFields); + String actualResult = PDBFTSRestClient + .getDataColumnsFieldsAsCommaDelimitedString(wantedFields); assertEquals("", expectedResult, actualResult); } @@ -116,14 +143,27 @@ public class PDBRestClientTest @Test(groups = { "External, Network" }) 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(); + List wantedFields = new ArrayList(); + try + { + wantedFields.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("molecule_type")); + wantedFields +.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("pdb_id")); + wantedFields.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("genus")); + wantedFields +.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("gene_name")); + wantedFields.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("title")); + } catch (Exception e1) + { + e1.printStackTrace(); + } + + FTSRestRequest request = new FTSRestRequest(); request.setAllowEmptySeq(false); request.setResponseSize(100); request.setFieldToSearchBy("text:"); @@ -139,7 +179,7 @@ public class PDBRestClientTest e.printStackTrace(); } - String parsedErrorResponse = PDBRestClient + String parsedErrorResponse = PDBFTSRestClient .parseJsonExceptionString(jsonErrorResponse); String expectedErrorMsg = "\n============= PDB Rest Client RunTime error =============\n" @@ -156,27 +196,41 @@ public class PDBRestClientTest expectedExceptions = Exception.class) public void testForExpectedRuntimeException() throws Exception { - List wantedFields = new ArrayList(); - wantedFields.add(PDBDocField.PDB_ID); + List wantedFields = new ArrayList(); + wantedFields.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("pdb_id")); - PDBRestRequest request = new PDBRestRequest(); + FTSRestRequest request = new FTSRestRequest(); request.setFieldToSearchBy("text:"); request.setSearchTerm("abc OR text:go:abc"); request.setWantedFields(wantedFields); - new PDBRestClient().executeRequest(request); + PDBFTSRestClient.getInstance().executeRequest(request); } @Test(groups = { "External" }) 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(); + List wantedFields = new ArrayList(); + try + { + wantedFields.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("molecule_type")); + wantedFields +.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("pdb_id")); + wantedFields.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("genus")); + wantedFields +.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("gene_name")); + wantedFields.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("title")); + } catch (Exception e1) + { + e1.printStackTrace(); + } + + FTSRestRequest request = new FTSRestRequest(); request.setAllowEmptySeq(false); request.setWantedFields(wantedFields); @@ -188,7 +242,7 @@ public class PDBRestClientTest { e.printStackTrace(); } - PDBRestResponse response = PDBRestClient.parsePDBJsonResponse( + FTSRestResponse response = PDBFTSRestClient.parsePDBJsonResponse( jsonString, request); assertTrue(response.getSearchSummary() != null); assertTrue(response.getNumberOfItemsFound() == 931); @@ -198,14 +252,38 @@ public class PDBRestClientTest @Test(groups = { "Functional" }) 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, PDBRestClient.getPDBIdColumIndex(wantedFields, true)); - assertEquals(4, PDBRestClient.getPDBIdColumIndex(wantedFields, false)); + List wantedFields = new ArrayList(); + try + { + wantedFields.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("molecule_type")); + wantedFields.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("genus")); + wantedFields +.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("gene_name")); + wantedFields.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("title")); + wantedFields +.add(PDBFTSRestClient.getInstance() + .getDataColumnByNameOrCode("pdb_id")); + } catch (Exception e) + { + e.printStackTrace(); + } + try + { + assertEquals(5, + PDBFTSRestClient.getInstance() + .getPrimaryKeyColumIndex(wantedFields, true)); + assertEquals(4, + PDBFTSRestClient.getInstance() + .getPrimaryKeyColumIndex(wantedFields, false)); + } catch (Exception e) + { + // TODO Auto-generated catch block + e.printStackTrace(); + } } @Test(groups = { "External" }) @@ -216,7 +294,7 @@ public class PDBRestClientTest // Build request parameters for the REST Request WebResource webResource = client - .resource(PDBRestClient.PDB_SEARCH_ENDPOINT) + .resource(PDBFTSRestClient.PDB_SEARCH_ENDPOINT) .queryParam("wt", "json").queryParam("rows", String.valueOf(1)) .queryParam("q", "text:abc AND molecule_sequence:['' TO *]"); @@ -255,9 +333,10 @@ public class PDBRestClientTest JSONObject pdbJsonDoc = docIter.next(); - for (PDBDocField field : PDBDocField.values()) + for (FTSDataColumnI field : PDBFTSRestClient.getInstance() + .getAllFTSDataColumns()) { - if (field == PDBDocField.ALL) + if (field.getName().equalsIgnoreCase("ALL")) { continue; } diff --git a/test/jalview/gui/StructureChooserTest.java b/test/jalview/gui/StructureChooserTest.java index 6b726de..c2209d6 100644 --- a/test/jalview/gui/StructureChooserTest.java +++ b/test/jalview/gui/StructureChooserTest.java @@ -96,7 +96,7 @@ public class StructureChooserTest sc.populateFilterComboBox(); try { - Thread.sleep(1000); + Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace();