JAL-2344 groovy script that registers a new file format
[jalview.git] / examples / groovy / fileFormat.groovy
1 import jalview.datamodel.AlignmentI
2 import jalview.datamodel.SequenceI
3 import jalview.datamodel.Sequence
4 import jalview.io.FileFormatI
5 import jalview.io.FileFormats
6 import jalview.io.AlignmentFileI
7 import jalview.io.FileParse
8 import jalview.io.AlignFile
9
10 /*
11  * Example script that registers a new alignment file format 
12  * consisting of lines like
13  * !I=<sequence id>
14  * !S=<sequence string>
15  */
16
17 /*
18  * A parser class to read or write the format
19  */
20 class MyParser extends AlignFile 
21 {
22   /*
23    * Constructor for reading a file; the superclass
24    * constructor will call the parse() method
25    */
26   MyParser(FileParse src) 
27   {
28     super(src)
29   }
30
31   /*
32    * Constructor for writing out an alignment
33    */
34   MyParser(AlignmentI al) 
35   {
36   }
37   
38   /*
39    * Parse a formatted data file (with no error checking!)
40    */
41   void parse() 
42   {
43     String id
44     String line
45     while ((line = nextLine()) != null) 
46     {
47       if (line.startsWith('!I='))
48       {
49         int pos = line.indexOf('/')
50         id = line.substring(3, pos == -1 ? line.length() : pos)
51       } else if (line.startsWith('!S='))
52       {
53         String seq = line.substring(3)
54         addSequence(new Sequence(id, seq))
55       }
56     }
57   }
58   
59   /*
60    * Print the formatted sequences
61    * (addSuffix always defaults to true as no user preference for it)
62    */
63   String print(SequenceI[] seqs, boolean addSuffix) 
64   {
65       StringBuilder sb = new StringBuilder()
66       for (SequenceI seq : seqs) 
67       {
68           sb.append('!I=').append(seq.getDisplayId(addSuffix)).append('\n')
69           sb.append('!S=').append(seq.getSequenceAsString()).append('\n')
70       }
71       sb.toString()
72   }
73 }
74
75 /*
76  * A closure that defines the 'Groovy example' file format,
77  * delegating to MyParser for reading and writing
78  */
79 def myFormat = { ->
80   [
81     getName: { -> 'Groovy example' },
82     
83     toString: { -> getName() },
84     
85     getExtensions: { -> 'grv' },
86     
87     getReader: { FileParse source -> new MyParser(source) },
88     
89     getWriter: { AlignmentI al -> new MyParser(al) },
90     
91     isReadable: { -> true },
92     
93     isWritable: { -> true },
94     
95     isTextFormat: { -> true },
96     
97     isStructureFile: { -> false },
98     
99     isComplexAlignFile: { -> false },
100
101    ] as FileFormatI
102 }
103
104 /*
105  * Register the file format. After running this script in Jalview's
106  * Groovy console, the new format should be shown in open file,
107  * save file, and output to textbox menu options.
108  */
109 FileFormats.instance.registerFileFormat(myFormat())