JAL-2520 improvement to use URL leaf name for creating temp file for URL file download
[jalview.git] / src / jalview / io / FileLoader.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.api.ComplexAlignFile;
24 import jalview.api.FeatureSettingsModelI;
25 import jalview.api.FeaturesDisplayedI;
26 import jalview.api.FeaturesSourceI;
27 import jalview.bin.Cache;
28 import jalview.bin.Jalview;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.ColumnSelection;
31 import jalview.datamodel.PDBEntry;
32 import jalview.datamodel.SequenceI;
33 import jalview.gui.AlignFrame;
34 import jalview.gui.AlignViewport;
35 import jalview.gui.Desktop;
36 import jalview.gui.Jalview2XML;
37 import jalview.gui.JvOptionPane;
38 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
39 import jalview.schemes.ColourSchemeI;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.util.MessageManager;
42 import jalview.ws.utils.UrlDownloadClient;
43
44 import java.io.File;
45 import java.io.IOException;
46 import java.util.StringTokenizer;
47 import java.util.Vector;
48
49 import javax.swing.SwingUtilities;
50
51 public class FileLoader implements Runnable
52 {
53   String file;
54
55   DataSourceType protocol;
56
57   FileFormatI format;
58
59   AlignmentFileReaderI source = null; // alternative specification of where data
60                                       // comes
61
62   // from
63
64   AlignViewport viewport;
65
66   AlignFrame alignFrame;
67
68   long loadtime;
69
70   long memused;
71
72   boolean raiseGUI = true;
73
74   /**
75    * default constructor always raised errors in GUI dialog boxes
76    */
77   public FileLoader()
78   {
79     this(true);
80   }
81
82   /**
83    * construct a Fileloader that may raise errors non-interactively
84    * 
85    * @param raiseGUI
86    *          true if errors are to be raised as GUI dialog boxes
87    */
88   public FileLoader(boolean raiseGUI)
89   {
90     this.raiseGUI = raiseGUI;
91   }
92
93   public void LoadFile(AlignViewport viewport, String file,
94           DataSourceType protocol, FileFormatI format)
95   {
96     this.viewport = viewport;
97     LoadFile(file, protocol, format);
98   }
99
100   public void LoadFile(String file, DataSourceType protocol,
101           FileFormatI format)
102   {
103     this.file = file;
104     this.protocol = protocol;
105     this.format = format;
106
107     final Thread loader = new Thread(this);
108
109     SwingUtilities.invokeLater(new Runnable()
110     {
111       @Override
112       public void run()
113       {
114         loader.start();
115       }
116     });
117   }
118
119   /**
120    * Load a (file, protocol) source of unknown type
121    * 
122    * @param file
123    * @param protocol
124    */
125   public void LoadFile(String file, DataSourceType protocol)
126   {
127     LoadFile(file, protocol, null);
128   }
129
130   /**
131    * Load alignment from (file, protocol) and wait till loaded
132    * 
133    * @param file
134    * @param sourceType
135    * @return alignFrame constructed from file contents
136    */
137   public AlignFrame LoadFileWaitTillLoaded(String file,
138           DataSourceType sourceType)
139   {
140     return LoadFileWaitTillLoaded(file, sourceType, null);
141   }
142
143   /**
144    * Load alignment from (file, protocol) of type format and wait till loaded
145    * 
146    * @param file
147    * @param sourceType
148    * @param format
149    * @return alignFrame constructed from file contents
150    */
151   public AlignFrame LoadFileWaitTillLoaded(String file,
152           DataSourceType sourceType, FileFormatI format)
153   {
154     this.file = file;
155     this.protocol = sourceType;
156     this.format = format;
157     return _LoadFileWaitTillLoaded();
158   }
159
160   /**
161    * Load alignment from FileParse source of type format and wait till loaded
162    * 
163    * @param source
164    * @param format
165    * @return alignFrame constructed from file contents
166    */
167   public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
168           FileFormatI format)
169   {
170     this.source = source;
171
172     file = source.getInFile();
173     protocol = source.getDataSourceType();
174     this.format = format;
175     return _LoadFileWaitTillLoaded();
176   }
177
178   /**
179    * start thread and wait until finished, then return the alignFrame that's
180    * (hopefully) been read.
181    * 
182    * @return
183    */
184   protected AlignFrame _LoadFileWaitTillLoaded()
185   {
186     Thread loader = new Thread(this);
187     loader.start();
188
189     while (loader.isAlive())
190     {
191       try
192       {
193         Thread.sleep(500);
194       } catch (Exception ex)
195       {
196       }
197     }
198
199     return alignFrame;
200   }
201
202   public void updateRecentlyOpened()
203   {
204     Vector recent = new Vector();
205     if (protocol == DataSourceType.PASTE)
206     {
207       // do nothing if the file was pasted in as text... there is no filename to
208       // refer to it as.
209       return;
210     }
211     String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
212             : "RECENT_URL";
213
214     String historyItems = jalview.bin.Cache.getProperty(type);
215
216     StringTokenizer st;
217
218     if (historyItems != null)
219     {
220       st = new StringTokenizer(historyItems, "\t");
221
222       while (st.hasMoreTokens())
223       {
224         recent.addElement(st.nextElement().toString().trim());
225       }
226     }
227
228     if (recent.contains(file))
229     {
230       recent.remove(file);
231     }
232
233     StringBuffer newHistory = new StringBuffer(file);
234     for (int i = 0; i < recent.size() && i < 10; i++)
235     {
236       newHistory.append("\t");
237       newHistory.append(recent.elementAt(i));
238     }
239
240     Cache.setProperty(type, newHistory.toString());
241
242     if (protocol == DataSourceType.FILE)
243     {
244       Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
245     }
246   }
247
248   @Override
249   public void run()
250   {
251     String title = protocol == DataSourceType.PASTE ? "Copied From Clipboard"
252             : file;
253     Runtime rt = Runtime.getRuntime();
254     try
255     {
256       if (Desktop.instance != null)
257       {
258         Desktop.instance.startLoading(file);
259       }
260       if (format == null)
261       {
262         // just in case the caller didn't identify the file for us
263         if (source != null)
264         {
265           format = new IdentifyFile().identify(source, false);
266           // identify stream and rewind rather than close
267         }
268         else
269         {
270           format = new IdentifyFile().identify(file, protocol);
271         }
272
273       }
274
275       if (format == null)
276       {
277         Desktop.instance.stopLoading();
278         System.err.println("The input file \"" + file
279                 + "\" has null or unidentifiable data content!");
280         if (!Jalview.isHeadlessMode())
281         {
282           JvOptionPane.showInternalMessageDialog(
283                   Desktop.desktop,
284                   MessageManager.getString("label.couldnt_read_data")
285                           + " in " + file + "\n"
286                           + AppletFormatAdapter.getSupportedFormats(),
287                   MessageManager.getString("label.couldnt_read_data"),
288                   JvOptionPane.WARNING_MESSAGE);
289         }
290         return;
291       }
292       // TODO: cache any stream datasources as a temporary file (eg. PDBs
293       // retrieved via URL)
294       if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
295       {
296         System.gc();
297         memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
298         // memory
299         // before
300         // load
301       }
302       loadtime = -System.currentTimeMillis();
303       AlignmentI al = null;
304
305       if (FileFormat.Jalview.equals(format))
306       {
307         if (source != null)
308         {
309           // Tell the user (developer?) that this is going to cause a problem
310           System.err
311                   .println("IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
312           // We read the data anyway - it might make sense.
313         }
314         alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
315       }
316       else
317       {
318         String error = AppletFormatAdapter.getSupportedFormats();
319         try
320         {
321           if (source != null)
322           {
323             // read from the provided source
324             al = new FormatAdapter().readFromFile(source, format);
325           }
326           else
327           {
328
329             // open a new source and read from it
330             FormatAdapter fa = new FormatAdapter();
331             boolean downloadStructureFile = format.isStructureFile()
332                     && protocol.equals(DataSourceType.URL);
333             if (downloadStructureFile)
334             {
335               String structExt = format.getExtensions().split(",")[0];
336               String urlLeafName = file.substring(file.lastIndexOf(System
337                       .getProperty("file.separator")), file
338                       .lastIndexOf("."));
339               String tempStructureFileStr = createNamedJvTempFile(
340                       urlLeafName, structExt);
341               UrlDownloadClient.download(file, tempStructureFileStr);
342               file = tempStructureFileStr;
343               protocol = DataSourceType.FILE;
344             }
345             al = fa.readFile(file, protocol, format);
346             source = fa.getAlignFile(); // keep reference for later if
347                                         // necessary.
348           }
349         } catch (java.io.IOException ex)
350         {
351           error = ex.getMessage();
352         }
353
354         if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
355         {
356           // construct and register dataset sequences
357           for (SequenceI sq : al.getSequences())
358           {
359             while (sq.getDatasetSequence() != null)
360             {
361               sq = sq.getDatasetSequence();
362             }
363             if (sq.getAllPDBEntries() != null)
364             {
365               for (PDBEntry pdbe : sq.getAllPDBEntries())
366               {
367                 // register PDB entries with desktop's structure selection
368                 // manager
369                 StructureSelectionManager.getStructureSelectionManager(
370                         Desktop.instance).registerPDBEntry(pdbe);
371               }
372             }
373           }
374
375           FeatureSettingsModelI proxyColourScheme = source
376                   .getFeatureColourScheme();
377           if (viewport != null)
378           {
379             if (proxyColourScheme != null)
380             {
381               viewport.applyFeaturesStyle(proxyColourScheme);
382             }
383             // append to existing alignment
384             viewport.addAlignment(al, title);
385           }
386           else
387           {
388             // otherwise construct the alignFrame
389
390             if (source instanceof ComplexAlignFile)
391             {
392               ColumnSelection colSel = ((ComplexAlignFile) source)
393                       .getColumnSelection();
394               SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
395                       .getHiddenSequences();
396               String colourSchemeName = ((ComplexAlignFile) source)
397                       .getGlobalColourScheme();
398               FeaturesDisplayedI fd = ((ComplexAlignFile) source)
399                       .getDisplayedFeatures();
400               alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
401                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
402               alignFrame.getViewport().setFeaturesDisplayed(fd);
403               alignFrame.getViewport().setShowSequenceFeatures(
404                       ((ComplexAlignFile) source).isShowSeqFeatures());
405               ColourSchemeI cs = ColourSchemeMapper.getJalviewColourScheme(
406                       colourSchemeName, al);
407               if (cs != null)
408               {
409                 alignFrame.changeColour(cs);
410               }
411             }
412             else
413             {
414               alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
415                       AlignFrame.DEFAULT_HEIGHT);
416               if (source instanceof FeaturesSourceI)
417               {
418                 alignFrame.getViewport().setShowSequenceFeatures(true);
419               }
420             }
421             // add metadata and update ui
422             if (!(protocol == DataSourceType.PASTE))
423             {
424               alignFrame.setFileName(file, format);
425             }
426             if (proxyColourScheme != null)
427             {
428               alignFrame.getViewport()
429                       .applyFeaturesStyle(proxyColourScheme);
430             }
431             alignFrame.statusBar.setText(MessageManager.formatMessage(
432                     "label.successfully_loaded_file",
433                     new String[] { title }));
434
435             if (raiseGUI)
436             {
437               // add the window to the GUI
438               // note - this actually should happen regardless of raiseGUI
439               // status in Jalview 3
440               // TODO: define 'virtual desktop' for benefit of headless scripts
441               // that perform queries to find the 'current working alignment'
442               Desktop.addInternalFrame(alignFrame, title,
443                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
444             }
445
446             try
447             {
448               alignFrame.setMaximum(jalview.bin.Cache.getDefault(
449                       "SHOW_FULLSCREEN", false));
450             } catch (java.beans.PropertyVetoException ex)
451             {
452             }
453           }
454         }
455         else
456         {
457           if (Desktop.instance != null)
458           {
459             Desktop.instance.stopLoading();
460           }
461
462           final String errorMessage = MessageManager
463                   .getString("label.couldnt_load_file")
464                   + " "
465                   + title
466                   + "\n" + error;
467           // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
468           // bits ?
469           if (raiseGUI && Desktop.desktop != null)
470           {
471             javax.swing.SwingUtilities.invokeLater(new Runnable()
472             {
473               @Override
474               public void run()
475               {
476                 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
477                         errorMessage, MessageManager
478                                 .getString("label.error_loading_file"),
479                         JvOptionPane.WARNING_MESSAGE);
480               }
481             });
482           }
483           else
484           {
485             System.err.println(errorMessage);
486           }
487         }
488       }
489
490       updateRecentlyOpened();
491
492     } catch (Exception er)
493     {
494       System.err.println("Exception whilst opening file '" + file);
495       er.printStackTrace();
496       if (raiseGUI)
497       {
498         javax.swing.SwingUtilities.invokeLater(new Runnable()
499         {
500           @Override
501           public void run()
502           {
503             JvOptionPane.showInternalMessageDialog(
504                     Desktop.desktop, MessageManager.formatMessage(
505                             "label.problems_opening_file",
506                             new String[] { file }), MessageManager
507                             .getString("label.file_open_error"),
508                     JvOptionPane.WARNING_MESSAGE);
509           }
510         });
511       }
512       alignFrame = null;
513     } catch (OutOfMemoryError er)
514     {
515
516       er.printStackTrace();
517       alignFrame = null;
518       if (raiseGUI)
519       {
520         javax.swing.SwingUtilities.invokeLater(new Runnable()
521         {
522           @Override
523           public void run()
524           {
525             JvOptionPane.showInternalMessageDialog(
526                     Desktop.desktop, MessageManager.formatMessage(
527                             "warn.out_of_memory_loading_file", new String[]
528                             { file }), MessageManager
529                             .getString("label.out_of_memory"),
530                     JvOptionPane.WARNING_MESSAGE);
531           }
532         });
533       }
534       System.err.println("Out of memory loading file " + file + "!!");
535
536     }
537     loadtime += System.currentTimeMillis();
538     // TODO: Estimate percentage of memory used by a newly loaded alignment -
539     // warn if more memory will be needed to work with it
540     // System.gc();
541     memused = memused
542             - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
543     // in free
544     // memory
545     // after
546     // load
547     if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
548     {
549       if (alignFrame != null)
550       {
551         AlignmentI al = alignFrame.getViewport().getAlignment();
552
553         System.out.println("Loaded '" + title + "' in "
554                 + (loadtime / 1000.0) + "s, took an additional "
555                 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
556                 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
557       }
558       else
559       {
560         // report that we didn't load anything probably due to an out of memory
561         // error
562         System.out.println("Failed to load '" + title + "' in "
563                 + (loadtime / 1000.0) + "s, took an additional "
564                 + (1.0 * memused / (1024.0 * 1024.0))
565                 + " MB (alignment is null)");
566       }
567     }
568     // remove the visual delay indicator
569     if (Desktop.instance != null)
570     {
571       Desktop.instance.stopLoading();
572     }
573
574   }
575
576   /**
577    * This method creates the file -
578    * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
579    * file name and extension
580    * 
581    * @param fileName
582    *          the name of the temp file to be created
583    * @param extension
584    *          the extension of the temp file to be created
585    * @return
586    */
587   private static String createNamedJvTempFile(String fileName,
588           String extension) throws IOException
589   {
590     String seprator = System.getProperty("file.separator");
591     String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
592             + seprator + System.currentTimeMillis();
593     File tempStructFile = new File(jvTempDir + seprator + fileName + "."
594             + extension);
595     tempStructFile.mkdirs();
596     return tempStructFile.toString();
597   }
598
599   /*
600    * (non-Javadoc)
601    * 
602    * @see java.lang.Object#finalize()
603    */
604   @Override
605   protected void finalize() throws Throwable
606   {
607     source = null;
608     alignFrame = null;
609     viewport = null;
610     super.finalize();
611   }
612
613 }