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