From: gmungoc Date: Wed, 11 Jan 2017 16:06:01 +0000 (+0000) Subject: JAL-2344 groovy script that registers a new file format X-Git-Tag: Release_2_10_3b1~378 X-Git-Url: http://source.jalview.org/gitweb/?a=commitdiff_plain;h=88895ebd5fe3f92e288261dfee9eb8f59aedfefd;hp=95ebbef7b78bf266a8252bd479510be3c80cd234;p=jalview.git JAL-2344 groovy script that registers a new file format --- diff --git a/examples/groovy/fileFormat.groovy b/examples/groovy/fileFormat.groovy new file mode 100644 index 0000000..137fec6 --- /dev/null +++ b/examples/groovy/fileFormat.groovy @@ -0,0 +1,109 @@ +import jalview.datamodel.AlignmentI +import jalview.datamodel.SequenceI +import jalview.datamodel.Sequence +import jalview.io.FileFormatI +import jalview.io.FileFormats +import jalview.io.AlignmentFileI +import jalview.io.FileParse +import jalview.io.AlignFile + +/* + * Example script that registers a new alignment file format + * consisting of lines like + * !I= + * !S= + */ + +/* + * A parser class to read or write the format + */ +class MyParser extends AlignFile +{ + /* + * Constructor for reading a file; the superclass + * constructor will call the parse() method + */ + MyParser(FileParse src) + { + super(src) + } + + /* + * Constructor for writing out an alignment + */ + MyParser(AlignmentI al) + { + } + + /* + * Parse a formatted data file (with no error checking!) + */ + void parse() + { + String id + String line + while ((line = nextLine()) != null) + { + if (line.startsWith('!I=')) + { + int pos = line.indexOf('/') + id = line.substring(3, pos == -1 ? line.length() : pos) + } else if (line.startsWith('!S=')) + { + String seq = line.substring(3) + addSequence(new Sequence(id, seq)) + } + } + } + + /* + * Print the formatted sequences + * (addSuffix always defaults to true as no user preference for it) + */ + String print(SequenceI[] seqs, boolean addSuffix) + { + StringBuilder sb = new StringBuilder() + for (SequenceI seq : seqs) + { + sb.append('!I=').append(seq.getDisplayId(addSuffix)).append('\n') + sb.append('!S=').append(seq.getSequenceAsString()).append('\n') + } + sb.toString() + } +} + +/* + * A closure that defines the 'Groovy example' file format, + * delegating to MyParser for reading and writing + */ +def myFormat = { -> + [ + getName: { -> 'Groovy example' }, + + toString: { -> getName() }, + + getExtensions: { -> 'grv' }, + + getReader: { FileParse source -> new MyParser(source) }, + + getWriter: { AlignmentI al -> new MyParser(al) }, + + isReadable: { -> true }, + + isWritable: { -> true }, + + isTextFormat: { -> true }, + + isStructureFile: { -> false }, + + isComplexAlignFile: { -> false }, + + ] as FileFormatI +} + +/* + * Register the file format. After running this script in Jalview's + * Groovy console, the new format should be shown in open file, + * save file, and output to textbox menu options. + */ +FileFormats.instance.registerFileFormat(myFormat())