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