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