JAL-2164 JAL-1919 disabled and removed PDB file parser configuration option, JmolPars...
[jalview.git] / src / jalview / io / AppletFormatAdapter.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.AlignExportSettingI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.AlignmentView;
29 import jalview.datamodel.PDBEntry.Type;
30 import jalview.structure.StructureImportSettings;
31 import jalview.util.MessageManager;
32
33 import java.io.File;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.util.List;
37
38 /**
39  * A low level class for alignment and feature IO with alignment formatting
40  * methods used by both applet and application for generating flat alignment
41  * files. It also holds the lists of magic format names that the applet and
42  * application will allow the user to read or write files with.
43  *
44  * @author $author$
45  * @version $Revision$
46  */
47 public class AppletFormatAdapter
48 {
49   private AlignmentViewPanel viewpanel;
50
51   public static String FILE = "File";
52
53   public static String URL = "URL";
54
55   public static String PASTE = "Paste";
56
57   public static String CLASSLOADER = "ClassLoader";
58
59   /**
60    * add jalview-derived non-secondary structure annotation from PDB structure
61    */
62   boolean annotFromStructure = false;
63
64   /**
65    * add secondary structure from PDB data with built-in algorithms
66    */
67   boolean localSecondaryStruct = false;
68
69   /**
70    * process PDB data with web services
71    */
72   boolean serviceSecondaryStruct = false;
73
74   private AlignFile alignFile = null;
75
76   String inFile;
77
78   /**
79    * character used to write newlines
80    */
81   protected String newline = System.getProperty("line.separator");
82
83   private AlignExportSettingI exportSettings;
84
85   /**
86    * List of valid format strings used in the isValidFormat method
87    */
88   public static final String[] READABLE_FORMATS = new String[] { "BLC",
89       "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH", "PDB",
90       "JnetFile", "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC,
91       IdentifyFile.FeaturesFile, "HTML", "mmCIF" };
92
93   /**
94    * List of readable format file extensions by application in order
95    * corresponding to READABLE_FNAMES
96    */
97   public static final String[] READABLE_EXTENSIONS = new String[] {
98       "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
99       "sto,stk", "xml,rnaml", PhylipFile.FILE_EXT, JSONFile.FILE_EXT,
100       ".gff2,gff3", "jar,jvp", HtmlFile.FILE_EXT, "cif" };
101
102   /**
103    * List of readable formats by application in order corresponding to
104    * READABLE_EXTENSIONS
105    */
106   public static final String[] READABLE_FNAMES = new String[] { "Fasta",
107       "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Stockholm", "RNAML",
108       PhylipFile.FILE_DESC, JSONFile.FILE_DESC, IdentifyFile.FeaturesFile,
109       "Jalview", HtmlFile.FILE_DESC, "mmCIF" };
110
111   /**
112    * List of valid format strings for use by callers of the formatSequences
113    * method
114    */
115   public static final String[] WRITEABLE_FORMATS = new String[] { "BLC",
116       "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA", "STH",
117       PhylipFile.FILE_DESC, JSONFile.FILE_DESC };
118
119   /**
120    * List of extensions corresponding to file format types in WRITABLE_FNAMES
121    * that are writable by the application.
122    */
123   public static final String[] WRITABLE_EXTENSIONS = new String[] {
124       "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
125       "sto,stk", PhylipFile.FILE_EXT, JSONFile.FILE_EXT, "jvp" };
126
127   /**
128    * List of writable formats by the application. Order must correspond with the
129    * WRITABLE_EXTENSIONS list of formats.
130    */
131   public static final String[] WRITABLE_FNAMES = new String[] { "Fasta",
132       "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "STH",
133       PhylipFile.FILE_DESC, JSONFile.FILE_DESC, "Jalview" };
134
135   public static String INVALID_CHARACTERS = "Contains invalid characters";
136
137   // TODO: make these messages dynamic
138   public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
139           + prettyPrint(READABLE_FORMATS);
140
141   public AppletFormatAdapter()
142   {
143   }
144
145   public AppletFormatAdapter(AlignmentViewPanel viewpanel)
146   {
147     this.viewpanel = viewpanel;
148   }
149
150   public AppletFormatAdapter(AlignmentViewPanel alignPanel,
151           AlignExportSettingI settings)
152   {
153     viewpanel = alignPanel;
154     exportSettings = settings;
155   }
156
157   /**
158    *
159    * @param els
160    * @return grammatically correct(ish) list consisting of els elements.
161    */
162   public static String prettyPrint(String[] els)
163   {
164     StringBuffer list = new StringBuffer();
165     for (int i = 0, iSize = els.length - 1; i < iSize; i++)
166     {
167       list.append(els[i]);
168       list.append(", ");
169     }
170     list.append(" and " + els[els.length - 1] + ".");
171     return list.toString();
172   }
173
174   public void setNewlineString(String nl)
175   {
176     newline = nl;
177   }
178
179   public String getNewlineString()
180   {
181     return newline;
182   }
183
184   /**
185    * check that this format is valid for reading
186    *
187    * @param format
188    *          a format string to be compared with READABLE_FORMATS
189    * @return true if format is readable
190    */
191   public static final boolean isValidFormat(String format)
192   {
193     return isValidFormat(format, false);
194   }
195
196   /**
197    * validate format is valid for IO
198    *
199    * @param format
200    *          a format string to be compared with either READABLE_FORMATS or
201    *          WRITEABLE_FORMATS
202    * @param forwriting
203    *          when true, format is checked for containment in WRITEABLE_FORMATS
204    * @return true if format is valid
205    */
206   public static final boolean isValidFormat(String format,
207           boolean forwriting)
208   {
209     if (format == null)
210     {
211       return false;
212     }
213     boolean valid = false;
214     String[] format_list = (forwriting) ? WRITEABLE_FORMATS
215             : READABLE_FORMATS;
216     for (String element : format_list)
217     {
218       if (element.equalsIgnoreCase(format))
219       {
220         return true;
221       }
222     }
223
224     return valid;
225   }
226
227   /**
228    * Constructs the correct filetype parser for a characterised datasource
229    *
230    * @param inFile
231    *          data/data location
232    * @param type
233    *          type of datasource
234    * @param format
235    *          File format of data provided by datasource
236    *
237    * @return DOCUMENT ME!
238    */
239   public AlignmentI readFile(String inFile, String type, String format)
240           throws java.io.IOException
241   {
242     // TODO: generalise mapping between format string and io. class instances
243     // using Constructor.invoke reflection
244     this.inFile = inFile;
245     try
246     {
247       if (format.equals("FASTA"))
248       {
249         alignFile = new FastaFile(inFile, type);
250       }
251       else if (format.equals("MSF"))
252       {
253         alignFile = new MSFfile(inFile, type);
254       }
255       else if (format.equals("PileUp"))
256       {
257         alignFile = new PileUpfile(inFile, type);
258       }
259       else if (format.equals("CLUSTAL"))
260       {
261         alignFile = new ClustalFile(inFile, type);
262       }
263       else if (format.equals("BLC"))
264       {
265         alignFile = new BLCFile(inFile, type);
266       }
267       else if (format.equals("PIR"))
268       {
269         alignFile = new PIRFile(inFile, type);
270       }
271       else if (format.equals("PFAM"))
272       {
273         alignFile = new PfamFile(inFile, type);
274       }
275       else if (format.equals("JnetFile"))
276       {
277         alignFile = new JPredFile(inFile, type);
278         ((JPredFile) alignFile).removeNonSequences();
279       }
280       else if (format.equals("PDB"))
281       {
282
283           StructureImportSettings.addSettings(annotFromStructure,
284                   localSecondaryStruct, serviceSecondaryStruct);
285           alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
286                   localSecondaryStruct, serviceSecondaryStruct, inFile,
287                   type);
288         ((StructureFile) alignFile).setDbRefType(format);
289       }
290       else if (format.equalsIgnoreCase("mmCIF"))
291       {
292         StructureImportSettings.addSettings(annotFromStructure,
293                 localSecondaryStruct, serviceSecondaryStruct);
294         alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
295                 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
296         ((StructureFile) alignFile).setDbRefType(format);
297       }
298       else if (format.equals("STH"))
299       {
300         alignFile = new StockholmFile(inFile, type);
301       }
302       else if (format.equals("SimpleBLAST"))
303       {
304         alignFile = new SimpleBlastFile(inFile, type);
305       }
306       else if (format.equals(PhylipFile.FILE_DESC))
307       {
308         alignFile = new PhylipFile(inFile, type);
309       }
310       else if (format.equals(JSONFile.FILE_DESC))
311       {
312         alignFile = new JSONFile(inFile, type);
313       }
314       else if (format.equals(HtmlFile.FILE_DESC))
315       {
316         alignFile = new HtmlFile(inFile, type);
317       }
318       else if (format.equals("RNAML"))
319       {
320         alignFile = new RnamlFile(inFile, type);
321       }
322       else if (format.equals(IdentifyFile.FeaturesFile))
323       {
324         alignFile = new FeaturesFile(true, inFile, type);
325       }
326       return buildAlignmentFrom(alignFile);
327     } catch (Exception e)
328     {
329       e.printStackTrace();
330       System.err.println("Failed to read alignment using the '" + format
331               + "' reader.\n" + e);
332
333       if (e.getMessage() != null
334               && e.getMessage().startsWith(INVALID_CHARACTERS))
335       {
336         throw new java.io.IOException(e.getMessage());
337       }
338
339       // Finally test if the user has pasted just the sequence, no id
340       if (type.equalsIgnoreCase("Paste"))
341       {
342         try
343         {
344           // Possible sequence is just residues with no label
345           alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
346           return buildAlignmentFrom(alignFile);
347
348         } catch (Exception ex)
349         {
350           if (ex.toString().startsWith(INVALID_CHARACTERS))
351           {
352             throw new java.io.IOException(e.getMessage());
353           }
354
355           ex.printStackTrace();
356         }
357       }
358       if (format.equalsIgnoreCase("HTML"))
359       {
360         throw new IOException(e.getMessage());
361       }
362       // If we get to this stage, the format was not supported
363       throw new java.io.IOException(SUPPORTED_FORMATS);
364     }
365   }
366
367   /**
368    * Constructs the correct filetype parser for an already open datasource
369    *
370    * @param source
371    *          an existing datasource
372    * @param format
373    *          File format of data that will be provided by datasource
374    *
375    * @return DOCUMENT ME!
376    */
377   public AlignmentI readFromFile(FileParse source, String format)
378           throws java.io.IOException
379   {
380     // TODO: generalise mapping between format string and io. class instances
381     // using Constructor.invoke reflection
382     // This is exactly the same as the readFile method except we substitute
383     // 'inFile, type' with 'source'
384     this.inFile = source.getInFile();
385     String type = source.type;
386     try
387     {
388       if (format.equals("FASTA"))
389       {
390         alignFile = new FastaFile(source);
391       }
392       else if (format.equals("MSF"))
393       {
394         alignFile = new MSFfile(source);
395       }
396       else if (format.equals("PileUp"))
397       {
398         alignFile = new PileUpfile(source);
399       }
400       else if (format.equals("CLUSTAL"))
401       {
402         alignFile = new ClustalFile(source);
403       }
404       else if (format.equals("BLC"))
405       {
406         alignFile = new BLCFile(source);
407       }
408       else if (format.equals("PIR"))
409       {
410         alignFile = new PIRFile(source);
411       }
412       else if (format.equals("PFAM"))
413       {
414         alignFile = new PfamFile(source);
415       }
416       else if (format.equals("JnetFile"))
417       {
418         alignFile = new JPredFile(source);
419         ((JPredFile) alignFile).removeNonSequences();
420       }
421       else if (format.equals("PDB"))
422       {
423         // TODO obtain config value from preference settings
424         boolean isParseWithJMOL = false;
425         if (isParseWithJMOL)
426         {
427           StructureImportSettings.addSettings(annotFromStructure,
428                   localSecondaryStruct, serviceSecondaryStruct);
429           alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
430                   localSecondaryStruct, serviceSecondaryStruct, source);
431         }
432         else
433         {
434           StructureImportSettings.setShowSeqFeatures(true);
435           alignFile = new MCview.PDBfile(annotFromStructure,
436                   localSecondaryStruct, serviceSecondaryStruct, source);
437         }
438         ((StructureFile) alignFile).setDbRefType(Type.PDB);
439       }
440       else if (format.equalsIgnoreCase("mmCIF"))
441       {
442         StructureImportSettings.addSettings(annotFromStructure,
443                 localSecondaryStruct, serviceSecondaryStruct);
444         alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
445                 localSecondaryStruct, serviceSecondaryStruct, source);
446         ((StructureFile) alignFile).setDbRefType(Type.MMCIF);
447       }
448       else if (format.equals("STH"))
449       {
450         alignFile = new StockholmFile(source);
451       }
452       else if (format.equals("RNAML"))
453       {
454         alignFile = new RnamlFile(source);
455       }
456       else if (format.equals("SimpleBLAST"))
457       {
458         alignFile = new SimpleBlastFile(source);
459       }
460       else if (format.equals(PhylipFile.FILE_DESC))
461       {
462         alignFile = new PhylipFile(source);
463       }
464       else if (format.equals(IdentifyFile.FeaturesFile))
465       {
466         alignFile = new FeaturesFile(inFile, type);
467       }
468       else if (format.equals(JSONFile.FILE_DESC))
469       {
470         alignFile = new JSONFile(source);
471       }
472       else if (format.equals(HtmlFile.FILE_DESC))
473       {
474         alignFile = new HtmlFile(source);
475       }
476
477       return buildAlignmentFrom(alignFile);
478
479     } catch (Exception e)
480     {
481       e.printStackTrace();
482       System.err.println("Failed to read alignment using the '" + format
483               + "' reader.\n" + e);
484
485       if (e.getMessage() != null
486               && e.getMessage().startsWith(INVALID_CHARACTERS))
487       {
488         throw new java.io.IOException(e.getMessage());
489       }
490
491       // Finally test if the user has pasted just the sequence, no id
492       if (type.equalsIgnoreCase("Paste"))
493       {
494         try
495         {
496           // Possible sequence is just residues with no label
497           alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
498           return buildAlignmentFrom(alignFile);
499
500         } catch (Exception ex)
501         {
502           if (ex.toString().startsWith(INVALID_CHARACTERS))
503           {
504             throw new java.io.IOException(e.getMessage());
505           }
506
507           ex.printStackTrace();
508         }
509       }
510
511       // If we get to this stage, the format was not supported
512       throw new java.io.IOException(SUPPORTED_FORMATS);
513     }
514   }
515
516   /**
517    * boilerplate method to handle data from an AlignFile and construct a new
518    * alignment or import to an existing alignment
519    * 
520    * @param alignFile2
521    * @return AlignmentI instance ready to pass to a UI constructor
522    */
523   private AlignmentI buildAlignmentFrom(AlignFile alignFile2)
524   {
525     // Standard boilerplate for creating alignment from parser
526     // alignFile.configureForView(viewpanel);
527
528     AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
529
530     alignFile.addAnnotations(al);
531
532     alignFile.addGroups(al);
533
534     return al;
535   }
536
537   /**
538    * create an alignment flatfile from a Jalview alignment view
539    * 
540    * @param format
541    * @param jvsuffix
542    * @param av
543    * @param selectedOnly
544    * @return flatfile in a string
545    */
546   public String formatSequences(String format, boolean jvsuffix,
547           AlignmentViewPanel ap, boolean selectedOnly)
548   {
549
550     AlignmentView selvew = ap.getAlignViewport().getAlignmentView(
551             selectedOnly, false);
552     AlignmentI aselview = selvew.getVisibleAlignment(ap.getAlignViewport()
553             .getGapCharacter());
554     List<AlignmentAnnotation> ala = (ap.getAlignViewport()
555             .getVisibleAlignmentAnnotation(selectedOnly));
556     if (ala != null)
557     {
558       for (AlignmentAnnotation aa : ala)
559       {
560         aselview.addAnnotation(aa);
561       }
562     }
563     viewpanel = ap;
564     return formatSequences(format, aselview, jvsuffix);
565   }
566
567   /**
568    * Construct an output class for an alignment in a particular filetype TODO:
569    * allow caller to detect errors and warnings encountered when generating
570    * output
571    *
572    * @param format
573    *          string name of alignment format
574    * @param alignment
575    *          the alignment to be written out
576    * @param jvsuffix
577    *          passed to AlnFile class controls whether /START-END is added to
578    *          sequence names
579    *
580    * @return alignment flat file contents
581    */
582   public String formatSequences(String format, AlignmentI alignment,
583           boolean jvsuffix)
584   {
585     try
586     {
587       AlignFile afile = null;
588       if (format.equalsIgnoreCase("FASTA"))
589       {
590         afile = new FastaFile();
591       }
592       else if (format.equalsIgnoreCase("MSF"))
593       {
594         afile = new MSFfile();
595       }
596       else if (format.equalsIgnoreCase("PileUp"))
597       {
598         afile = new PileUpfile();
599       }
600       else if (format.equalsIgnoreCase("CLUSTAL"))
601       {
602         afile = new ClustalFile();
603       }
604       else if (format.equalsIgnoreCase("BLC"))
605       {
606         afile = new BLCFile();
607       }
608       else if (format.equalsIgnoreCase("PIR"))
609       {
610         afile = new PIRFile();
611       }
612       else if (format.equalsIgnoreCase("PFAM"))
613       {
614         afile = new PfamFile();
615       }
616       else if (format.equalsIgnoreCase("STH"))
617       {
618         afile = new StockholmFile(alignment);
619       }
620       else if (format.equalsIgnoreCase("AMSA"))
621       {
622         afile = new AMSAFile(alignment);
623       }
624       else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
625       {
626         afile = new PhylipFile();
627       }
628       else if (format.equalsIgnoreCase(JSONFile.FILE_DESC))
629       {
630         afile = new JSONFile();
631       }
632       else if (format.equalsIgnoreCase("RNAML"))
633       {
634         afile = new RnamlFile();
635       }
636
637       else
638       {
639         throw new Exception(
640                 MessageManager
641                         .getString("error.implementation_error_unknown_file_format_string"));
642       }
643
644       afile.setNewlineString(newline);
645       afile.addJVSuffix(jvsuffix);
646       afile.setExportSettings(exportSettings);
647       afile.configureForView(viewpanel);
648
649       // check whether we were given a specific alignment to export, rather than
650       // the one in the viewpanel
651       if (viewpanel == null || viewpanel.getAlignment() == null
652               || viewpanel.getAlignment() != alignment)
653       {
654         afile.setSeqs(alignment.getSequencesArray());
655       }
656       else
657       {
658         afile.setSeqs(viewpanel.getAlignment().getSequencesArray());
659       }
660
661       String afileresp = afile.print();
662       if (afile.hasWarningMessage())
663       {
664         System.err.println("Warning raised when writing as " + format
665                 + " : " + afile.getWarningMessage());
666       }
667       return afileresp;
668     } catch (Exception e)
669     {
670       System.err.println("Failed to write alignment as a '" + format
671               + "' file\n");
672       e.printStackTrace();
673     }
674
675     return null;
676   }
677
678   public static String checkProtocol(String file)
679   {
680     String protocol = FILE;
681     String ft = file.toLowerCase().trim();
682     if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
683             || ft.indexOf("file:") == 0)
684     {
685       protocol = URL;
686     }
687     return protocol;
688   }
689
690   public static void main(String[] args)
691   {
692     int i = 0;
693     while (i < args.length)
694     {
695       File f = new File(args[i]);
696       if (f.exists())
697       {
698         try
699         {
700           System.out.println("Reading file: " + f);
701           AppletFormatAdapter afa = new AppletFormatAdapter();
702           Runtime r = Runtime.getRuntime();
703           System.gc();
704           long memf = -r.totalMemory() + r.freeMemory();
705           long t1 = -System.currentTimeMillis();
706           AlignmentI al = afa.readFile(args[i], FILE,
707                   new IdentifyFile().identify(args[i], FILE));
708           t1 += System.currentTimeMillis();
709           System.gc();
710           memf += r.totalMemory() - r.freeMemory();
711           if (al != null)
712           {
713             System.out.println("Alignment contains " + al.getHeight()
714                     + " sequences and " + al.getWidth() + " columns.");
715             try
716             {
717               System.out.println(new AppletFormatAdapter().formatSequences(
718                       "FASTA", al, true));
719             } catch (Exception e)
720             {
721               System.err
722                       .println("Couln't format the alignment for output as a FASTA file.");
723               e.printStackTrace(System.err);
724             }
725           }
726           else
727           {
728             System.out.println("Couldn't read alignment");
729           }
730           System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
731           System.out
732                   .println("Difference between free memory now and before is "
733                           + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
734         } catch (Exception e)
735         {
736           System.err.println("Exception when dealing with " + i
737                   + "'th argument: " + args[i] + "\n" + e);
738         }
739       }
740       else
741       {
742         System.err.println("Ignoring argument '" + args[i] + "' (" + i
743                 + "'th)- not a readable file.");
744       }
745       i++;
746     }
747   }
748
749   /**
750    * try to discover how to access the given file as a valid datasource that
751    * will be identified as the given type.
752    *
753    * @param file
754    * @param format
755    * @return protocol that yields the data parsable as the given type
756    */
757   public static String resolveProtocol(String file, String format)
758   {
759     return resolveProtocol(file, format, false);
760   }
761
762   public static String resolveProtocol(String file, String format,
763           boolean debug)
764   {
765     // TODO: test thoroughly!
766     String protocol = null;
767     if (debug)
768     {
769       System.out.println("resolving datasource started with:\n>>file\n"
770               + file + ">>endfile");
771     }
772
773     // This might throw a security exception in certain browsers
774     // Netscape Communicator for instance.
775     try
776     {
777       boolean rtn = false;
778       InputStream is = System.getSecurityManager().getClass()
779               .getResourceAsStream("/" + file);
780       if (is != null)
781       {
782         rtn = true;
783         is.close();
784       }
785       if (debug)
786       {
787         System.err.println("Resource '" + file + "' was "
788                 + (rtn ? "" : "not") + " located by classloader.");
789       }
790       ;
791       if (rtn)
792       {
793         protocol = AppletFormatAdapter.CLASSLOADER;
794       }
795
796     } catch (Exception ex)
797     {
798       System.err
799               .println("Exception checking resources: " + file + " " + ex);
800     }
801
802     if (file.indexOf("://") > -1)
803     {
804       protocol = AppletFormatAdapter.URL;
805     }
806     else
807     {
808       // skipping codebase prepend check.
809       protocol = AppletFormatAdapter.FILE;
810     }
811     FileParse fp = null;
812     try
813     {
814       if (debug)
815       {
816         System.out.println("Trying to get contents of resource as "
817                 + protocol + ":");
818       }
819       fp = new FileParse(file, protocol);
820       if (!fp.isValid())
821       {
822         fp = null;
823       }
824       else
825       {
826         if (debug)
827         {
828           System.out.println("Successful.");
829         }
830       }
831     } catch (Exception e)
832     {
833       if (debug)
834       {
835         System.err.println("Exception when accessing content: " + e);
836       }
837       fp = null;
838     }
839     if (fp == null)
840     {
841       if (debug)
842       {
843         System.out.println("Accessing as paste.");
844       }
845       protocol = AppletFormatAdapter.PASTE;
846       fp = null;
847       try
848       {
849         fp = new FileParse(file, protocol);
850         if (!fp.isValid())
851         {
852           fp = null;
853         }
854       } catch (Exception e)
855       {
856         System.err.println("Failed to access content as paste!");
857         e.printStackTrace();
858         fp = null;
859       }
860     }
861     if (fp == null)
862     {
863       return null;
864     }
865     if (format == null || format.length() == 0)
866     {
867       return protocol;
868     }
869     else
870     {
871       try
872       {
873         String idformat = new jalview.io.IdentifyFile().identify(file,
874                 protocol);
875         if (idformat == null)
876         {
877           if (debug)
878           {
879             System.out.println("Format not identified. Inaccessible file.");
880           }
881           return null;
882         }
883         if (debug)
884         {
885           System.out.println("Format identified as " + idformat
886                   + "and expected as " + format);
887         }
888         if (idformat.equals(format))
889         {
890           if (debug)
891           {
892             System.out.println("Protocol identified as " + protocol);
893           }
894           return protocol;
895         }
896         else
897         {
898           if (debug)
899           {
900             System.out
901                     .println("File deemed not accessible via " + protocol);
902           }
903           fp.close();
904           return null;
905         }
906       } catch (Exception e)
907       {
908         if (debug)
909         {
910           System.err.println("File deemed not accessible via " + protocol);
911           e.printStackTrace();
912         }
913         ;
914
915       }
916     }
917     return null;
918   }
919
920   public AlignFile getAlignFile()
921   {
922     return alignFile;
923   }
924
925   public void setAlignFile(AlignFile alignFile)
926   {
927     this.alignFile = alignFile;
928   }
929 }