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