Jalview-JS/JAL-3253-applet also comments relating to JAL-3268
[jalview.git] / src / jalview / io / RnamlFile.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.analysis.Rna;
24 import jalview.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.Annotation;
26 import jalview.datamodel.Sequence;
27 import jalview.datamodel.SequenceI;
28 import jalview.util.MessageManager;
29 import jalview.util.Platform;
30
31 import java.io.BufferedReader;
32 import java.io.FileNotFoundException;
33 import java.io.FileReader;
34 import java.io.IOException;
35 import java.util.ArrayList;
36 import java.util.List;
37
38 import com.stevesoft.pat.Regex;
39
40 import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
41 import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
42 import fr.orsay.lri.varna.exceptions.ExceptionPermissionDenied;
43 import fr.orsay.lri.varna.factories.RNAFactory;
44 import fr.orsay.lri.varna.models.rna.RNA;
45
46 public class RnamlFile extends AlignFile
47 {
48   public String id;
49
50   protected ArrayList<RNA> result;
51
52   public RnamlFile()
53   {
54     super();
55
56   }
57
58   public RnamlFile(String inFile, DataSourceType type) throws IOException
59   {
60     super(inFile, type);
61
62   }
63
64   public RnamlFile(FileParse source) throws IOException
65   {
66     super(source);
67
68   }
69
70   public BufferedReader CreateReader() throws FileNotFoundException
71   {
72     FileReader fr = null;
73     fr = new FileReader(inFile);
74
75     BufferedReader r = new BufferedReader(fr);
76     return r;
77   }
78
79   /*
80    * (non-Javadoc)
81    * 
82    * @see jalview.io.AlignFile#parse()
83    */
84   @Override
85   public void parse() throws IOException
86   {
87     if (System.getProperty("java.version").indexOf("1.6") > -1
88             || System.getProperty("java.version").indexOf("1.5") > -1)
89     {
90       // patch for 'This parser does not support specification "null" version
91       // "null"' error
92       // this hack ensures we get a properly updated SAXParserFactory on older
93       // JVMs
94       // thanks to Stefan Birkner over at https://coderwall.com/p/kqsrrw
95       System.setProperty("javax.xml.parsers.SAXParserFactory",
96               "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
97     }
98     // rather than lose exception semantics whilst parsing RNAML with VARNA we
99     // wrap the routine and catch all exceptions before passing them up the
100     // chain as an IOException
101     try
102     {
103       _parse();
104     } catch (ExceptionPermissionDenied pdx)
105     {
106       errormessage = MessageManager.formatMessage(
107               "exception.rnaml_couldnt_access_datasource", new String[]
108               { pdx.getMessage() });
109       throw new IOException(pdx);
110     } catch (ExceptionLoadingFailed lf)
111     {
112       errormessage = MessageManager.formatMessage(
113               "exception.ranml_couldnt_process_data", new String[]
114               { lf.getMessage() });
115       throw new IOException(lf);
116     } catch (ExceptionFileFormatOrSyntax iff)
117     {
118       errormessage = MessageManager
119               .formatMessage("exception.ranml_invalid_file", new String[]
120               { iff.getMessage() });
121       throw new IOException(iff);
122     } catch (Exception x)
123     {
124       error = true;
125       errormessage = MessageManager.formatMessage(
126               "exception.ranml_problem_parsing_data", new String[]
127               { x.getMessage() });
128       throw new IOException(errormessage, x);
129     }
130   }
131
132   @SuppressWarnings("unchecked")
133   public void _parse()
134           throws FileNotFoundException, ExceptionPermissionDenied,
135           ExceptionLoadingFailed, ExceptionFileFormatOrSyntax
136   {
137
138     result = RNAFactory.loadSecStrRNAML(getReader());
139
140     // ArrayList<ArrayList> allarray = new ArrayList();
141     // ArrayList<ArrayList<SimpleBP>> BP = new ArrayList();
142     // ArrayList strucinarray = new ArrayList();
143     SequenceI[] sqs = new SequenceI[result.size()];
144
145     for (int i = 0; i < result.size(); i++)
146     {
147
148       RNA current = result.get(i);
149       String rna = current.getStructDBN(true);
150       String seq = current.getSeq();
151       int begin = 1;
152       int end = seq.length();
153
154       id = current.getName();
155       if (id == null || id.trim().length() == 0)
156       {
157         id = safeName(getDataName());
158         if (result.size() > 1)
159         {
160           id += "." + i;
161         }
162       }
163       sqs[i] = new Sequence(id, seq, begin, end);
164
165       sqs[i].setEnd(sqs[i].findPosition(sqs[i].getLength()));
166       String[] annot = new String[rna.length()];
167       Annotation[] ann = new Annotation[rna.length()];
168
169       for (int j = 0; j < rna.length(); j++)
170       {
171         annot[j] = "" + rna.charAt(j);
172
173       }
174       for (int k = 0; k < rna.length(); k++)
175       {
176         ann[k] = new Annotation(annot[k], "",
177                 Rna.getRNASecStrucState(annot[k]).charAt(0), 0f);
178       }
179
180       AlignmentAnnotation align = new AlignmentAnnotation(
181               "Secondary Structure",
182               current.getID().trim().length() > 0
183                       ? "Secondary Structure for " + current.getID()
184                       : "",
185               ann);
186
187       sqs[i].addAlignmentAnnotation(align);
188       sqs[i].setRNA(result.get(i));
189
190       // allarray.add(strucinarray);
191
192       annotations.addElement(align);
193       // BP.add(align.bps);
194
195     }
196
197     setSeqs(sqs);
198   }
199
200   @Override
201   public String print(SequenceI[] s, boolean jvSuffix)
202   {
203     return "not yet implemented";
204   }
205
206   public List<RNA> getRNA()
207   {
208     return result;
209   }
210
211   // public static void main(String[] args) {
212   // Pattern p= Pattern.compile("(.+)[.][^.]+");
213   // Matcher m = p.matcher("toto.xml.zip");
214   // System.out.println(m.matches());
215   // System.out.println(m.group(1));
216   // }
217   /**
218    * make a friendly ID string.
219    * 
220    * @param dataName
221    * @return truncated dataName to after last '/'
222    */
223   private String safeName(String dataName)
224   {
225     int b = 0;
226     if ((b = dataName.lastIndexOf(".")) > 0)
227     {
228       dataName = dataName.substring(0, b - 1);
229     }
230     b = 0;
231     Regex m = getSafeRegex();
232     String mm = dataName;
233     while (m.searchFrom(dataName, b))
234     {
235       mm = m.stringMatched();
236       b = m.matchedTo();
237     }
238     return mm;
239   }
240
241   private static Regex SAFE_REGEX;
242
243   private static Regex getSafeRegex()
244   {
245     return (SAFE_REGEX == null
246             ? SAFE_REGEX = Platform.newRegex("[\\/]?([-A-Za-z0-9]+)\\.?", null)
247             : SAFE_REGEX);
248   }
249 }