JAL-1807 explicit imports (jalview.io.*)
[jalview.git] / src / jalview / io / WSWUBlastClient.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.io;
22
23 import jalview.analysis.AlignSeq;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.DBRefEntry;
26 import jalview.datamodel.DBRefSource;
27 import jalview.datamodel.Sequence;
28 import jalview.gui.AlignmentPanel;
29 import jalview.gui.CutAndPasteTransfer;
30 import jalview.gui.Desktop;
31 import jalview.util.MessageManager;
32
33 import java.util.ArrayList;
34 import java.util.Enumeration;
35 import java.util.StringTokenizer;
36 import java.util.Vector;
37
38 import javax.swing.ImageIcon;
39 import javax.swing.JOptionPane;
40
41 import uk.ac.ebi.www.Data;
42 import uk.ac.ebi.www.InputParams;
43 import uk.ac.ebi.www.WSFile;
44 import uk.ac.ebi.www.WSWUBlast;
45 import uk.ac.ebi.www.WSWUBlastService;
46 import uk.ac.ebi.www.WSWUBlastServiceLocator;
47
48 /**
49  * DOCUMENT ME!
50  * 
51  * @author $author$
52  * @version $Revision$
53  */
54 public class WSWUBlastClient
55 {
56   AlignmentPanel ap;
57
58   AlignmentI al;
59
60   CutAndPasteTransfer output = new CutAndPasteTransfer();
61
62   int jobsRunning = 0;
63
64   Vector suggestedIds = new Vector();
65
66   /**
67    * Creates a new WSWUBlastClient object.
68    * 
69    * @param al
70    *          DOCUMENT ME!
71    * @param ids
72    *          DOCUMENT ME!
73    */
74   public WSWUBlastClient(AlignmentPanel ap, AlignmentI al, ArrayList ids)
75   {
76     this.ap = ap;
77     this.al = al;
78     output.setText(MessageManager
79             .getString("label.wswublast_client_credits"));
80
81     Desktop.addInternalFrame(output, MessageManager
82             .getString("label.blasting_for_unidentified_sequence"), 800,
83             300);
84
85     for (int i = 0; i < ids.size(); i++)
86     {
87       Sequence sequence = (Sequence) ids.get(i);
88       System.out.println(sequence.getName());
89
90       BlastThread thread = new BlastThread(sequence);
91       thread.start();
92       jobsRunning++;
93     }
94
95     ImageTwirler thread = new ImageTwirler();
96     thread.start();
97   }
98
99   /**
100    * DOCUMENT ME!
101    * 
102    * @param id1
103    *          DOCUMENT ME!
104    * @param res
105    *          DOCUMENT ME!
106    */
107   void parseResult(Sequence seq, String res)
108   {
109     StringTokenizer st = new StringTokenizer(res, "\n");
110     String data;
111     String id2;
112     int maxFound = 90;
113     StringBuffer buffer = new StringBuffer("\n\n" + seq.getName() + " :");
114
115     while (st.hasMoreTokens())
116     {
117       data = st.nextToken();
118
119       if (data.indexOf(">UNIPROT") > -1)
120       {
121         int index = data.indexOf(">UNIPROT") + 9;
122         id2 = data.substring(index, data.indexOf(" ", index));
123
124         boolean identitiesFound = false;
125         while (!identitiesFound)
126         {
127           data = st.nextToken();
128
129           if (data.indexOf("Identities") > -1)
130           {
131             identitiesFound = true;
132
133             int value = Integer.parseInt(data.substring(
134                     data.indexOf("(") + 1, data.indexOf("%")));
135
136             if (value >= maxFound)
137             {
138               maxFound = value;
139               buffer.append(" " + id2 + " " + value + "%; ");
140               suggestedIds.addElement(new Object[]
141               { seq, id2 });
142             }
143           }
144         }
145       }
146     }
147
148     output.appendText(buffer.toString());
149   }
150
151   void updateIds()
152   {
153     // This must be outside the run() body as java 1.5
154     // will not return any value from the OptionPane to the expired thread.
155     int reply = JOptionPane.showConfirmDialog(Desktop.desktop,
156             "Automatically update suggested ids?",
157             "Auto replace sequence ids", JOptionPane.YES_NO_OPTION);
158
159     if (reply == JOptionPane.YES_OPTION)
160     {
161       Enumeration keys = suggestedIds.elements();
162       while (keys.hasMoreElements())
163       {
164         Object[] object = (Object[]) keys.nextElement();
165
166         Sequence oldseq = (Sequence) object[0];
167
168         oldseq.setName(object[1].toString());
169
170         // Oldseq is actually in the dataset, we must find the
171         // Visible seq and change its name also.
172         for (int i = 0; i < al.getHeight(); i++)
173         {
174           if (al.getSequenceAt(i).getDatasetSequence() == oldseq)
175           {
176             al.getSequenceAt(i).setName(oldseq.getName());
177             break;
178           }
179         }
180
181         DBRefEntry[] entries = oldseq.getDBRef();
182         if (entries != null)
183         {
184           oldseq.addDBRef(new DBRefEntry(DBRefSource.UNIPROT, "0",
185                   entries[0].getAccessionId()));
186         }
187       }
188     }
189     ap.paintAlignment(true);
190
191   }
192
193   class ImageTwirler extends Thread
194   {
195     ImageIcon[] imageIcon;
196
197     int imageIndex = 0;
198
199     public ImageTwirler()
200     {
201       imageIcon = new ImageIcon[9];
202
203       for (int i = 0; i < 9; i++)
204       {
205         java.net.URL url = getClass().getResource(
206                 "/images/dna" + (i + 1) + ".gif");
207
208         if (url != null)
209         {
210           imageIcon[i] = new ImageIcon(url);
211         }
212       }
213     }
214
215     public void run()
216     {
217       while (jobsRunning > 0)
218       {
219         try
220         {
221           Thread.sleep(100);
222           imageIndex++;
223           imageIndex %= 9;
224           output.setFrameIcon(imageIcon[imageIndex]);
225           output.setTitle(MessageManager.formatMessage("label.blasting_for_unidentified_sequence_jobs_running", new String[]{Integer.valueOf(jobsRunning).toString()}));
226         } catch (Exception ex)
227         {
228         }
229       }
230
231       if (jobsRunning == 0)
232       {
233         updateIds();
234       }
235     }
236   }
237
238   class BlastThread extends Thread
239   {
240     Sequence sequence;
241
242     String jobid;
243
244     boolean jobComplete = false;
245
246     BlastThread(Sequence sequence)
247     {
248       System.out.println("blasting for: " + sequence.getName());
249       this.sequence = sequence;
250     }
251
252     public void run()
253     {
254       StartJob();
255
256       while (!jobComplete)
257       {
258         try
259         {
260           WSWUBlastService service = new WSWUBlastServiceLocator();
261           WSWUBlast wublast = service.getWSWUBlast();
262           WSFile[] results = wublast.getResults(jobid);
263
264           if (results != null)
265           {
266             String result = new String(wublast.poll(jobid, "tooloutput"));
267             parseResult(sequence, result);
268             jobComplete = true;
269             jobsRunning--;
270           }
271           else
272           {
273             Thread.sleep(10000);
274             System.out.println("WSWuBlastClient: I'm alive "
275                     + sequence.getName() + " " + jobid); // log.debug
276           }
277         } catch (Exception ex)
278         {
279         }
280       }
281     }
282
283     void StartJob()
284     {
285       InputParams params = new InputParams();
286
287       params.setProgram("blastp");
288       params.setDatabase("uniprot");
289       params.setMatrix("pam10");
290
291       params.setNumal(5);
292       params.setSensitivity("low");
293       params.setSort("totalscore");
294       params.setOutformat("txt");
295       params.setAsync(true);
296
297       try
298       {
299         Data inputs[] = new Data[1];
300         Data input = new Data();
301         input.setType("sequence");
302         input.setContent(AlignSeq.extractGaps("-. ",
303                 sequence.getSequenceAsString()));
304         inputs[0] = input;
305
306         WSWUBlastService service = new WSWUBlastServiceLocator();
307         WSWUBlast wublast = service.getWSWUBlast();
308         jobid = wublast.runWUBlast(params, inputs);
309       } catch (Exception exp)
310       {
311         jobComplete = true;
312         jobsRunning--;
313         System.err.println("WSWUBlastClient error:\n" + exp.toString());
314         exp.printStackTrace();
315       }
316     }
317   }
318 }