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