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