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