Das client files
[jalview.git] / src / org / biojava / dasobert / das / DAS_FeatureRetrieve.java
1 /**
2  *                    BioJava development code
3  *
4  * This code may be freely distributed and modified under the
5  * terms of the GNU Lesser General Public Licence.  This should
6  * be distributed with the code.  If you do not have a copy,
7  * see:
8  *
9  *      http://www.gnu.org/copyleft/lesser.html
10  *
11  * Copyright for this code is held jointly by the individual
12  * authors.  These should be listed in @author doc comments.
13  *
14  * For more information on the BioJava project and its aims,
15  * or to join the biojava-l mailing list, visit the home page
16  * at:
17  *
18  *      http://www.biojava.org/
19  *
20  * Created on 19.03.2004
21  * @author Andreas Prlic
22  *
23  */
24 package org.biojava.dasobert.das;
25
26
27 import java.net.URL                         ;
28 import java.io.InputStream                  ;
29 import org.xml.sax.InputSource              ;
30 import org.xml.sax.XMLReader                ;
31 import javax.xml.parsers.*                  ;
32 import org.xml.sax.*                        ;
33 import java.util.ArrayList                  ;
34 import java.util.List;
35 import java.util.logging.*                  ;
36 import java.net.HttpURLConnection           ;
37 import java.io.IOException;
38 import java.net.ConnectException;
39 import java.lang.reflect.Method;
40
41
42 /**
43  * A class to perform a DAS features request
44  *
45  * @author Andreas Prlic
46  *
47  */
48 public class DAS_FeatureRetrieve {
49
50     List features ;
51     Logger logger     ;
52     int comeBackLater;
53     URL url;
54     /**
55      *
56      */
57     public DAS_FeatureRetrieve(URL url) {
58         super();
59
60         logger = Logger.getLogger("org.biojava.spice");
61         features = new ArrayList() ;
62         comeBackLater = -1;
63         this.url=url;
64         reload();
65     }
66
67
68     /** contact the DAS-feature server again. Usually
69      * it is not necessary to call this again, because the constructor already does, but
70      * if comeBackLater > -1 this should be called again.
71      *
72      */
73     public void reload(){
74
75         try {
76
77             InputStream dasInStream = null;
78             try {
79                 dasInStream     = open(url);
80             } catch (Exception e ){
81                 comeBackLater = -1;
82                 logger.log(Level.FINE,"could not open connection to " + url,e);
83                 return ;
84             }
85
86
87             SAXParserFactory spfactory =
88                 SAXParserFactory.newInstance();
89
90             spfactory.setValidating(false);
91
92             SAXParser saxParser = null ;
93
94             try{
95                 saxParser =
96                     spfactory.newSAXParser();
97             } catch (ParserConfigurationException e) {
98                 e.printStackTrace();
99             }
100
101
102
103             String vali = System.getProperty("XMLVALIDATION");
104
105             boolean validation = false ;
106             if ( vali != null )
107                 if ( vali.equals("true") )
108                     validation = true ;
109
110
111             XMLReader xmlreader = saxParser.getXMLReader();
112
113             //XMLReader xmlreader = XMLReaderFactory.createXMLReader();
114             try {
115                 xmlreader.setFeature("http://xml.org/sax/features/validation", validation);
116             } catch (SAXException e) {
117                 logger.log(Level.FINE,"Cannot set validation " + validation);
118             }
119
120             try {
121                 xmlreader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",validation);
122             } catch (SAXNotRecognizedException e){
123                 e.printStackTrace();
124                 logger.log(Level.FINE,"Cannot set load-external-dtd "+validation);
125
126             }
127
128             DAS_Feature_Handler cont_handle = new DAS_Feature_Handler() ;
129             cont_handle.setDASCommand(url.toString());
130             xmlreader.setContentHandler(cont_handle);
131             xmlreader.setErrorHandler(new org.xml.sax.helpers.DefaultHandler());
132             InputSource insource = new InputSource() ;
133             insource.setByteStream(dasInStream);
134
135             try {
136                 xmlreader.parse(insource);
137                 features = cont_handle.get_features();
138                 comeBackLater = cont_handle.getComBackLater();
139             }
140             catch ( Exception e){
141               System.out.println("ERROR PARSING RESULT FROM "+url+ "\n"+e+"\n");
142                // e.printStackTrace();
143                 logger.log(Level.FINE,"error while parsing response from "+ url);
144                 comeBackLater = -1;
145                 features = new ArrayList();
146             }
147         }
148         catch (Exception ex) {
149             ex.printStackTrace();
150             comeBackLater = -1;
151         }
152     }
153
154     /** open HttpURLConnection. Recommended way to open
155      * HttpURLConnections, since this take care of setting timeouts
156      * properly for java 1.4 and 1.5*/
157     public static HttpURLConnection openHttpURLConnection(URL url)
158     throws IOException, ConnectException {
159     HttpURLConnection huc = null;
160     huc = (HttpURLConnection) url.openConnection();
161
162     String os_name    = java.lang.System.getProperty("os.name");
163     String os_version = java.lang.System.getProperty("os.version");
164     String os_arch    = java.lang.System.getProperty("os.arch");
165     String VERSION = "1.0";
166
167     String userAgent = "Jalview " + VERSION + "("+os_name+"; "+os_arch + " ; "+ os_version+")";
168     //e.g. "Mozilla/5.0 (Windows; U; Win98; en-US; rv:1.7.2) Gecko/20040803"
169      huc.addRequestProperty("User-Agent", userAgent);
170     //logger.finest("opening "+url);
171
172
173     // use reflection to determine if get and set timeout methods for urlconnection are available
174         // seems java 1.5 does not watch the System properties any longer...
175         // and java 1.4 did not provide these...
176     // for 1.4 see setSystemProperties
177     int timeout = 15000;
178     try {
179         // try to use reflection to set timeout property
180         Class urlconnectionClass = Class.forName("java.net.HttpURLConnection");
181
182             Method setconnecttimeout = urlconnectionClass.getMethod (
183                                      "setConnectTimeout", new Class [] {int.class}
184                                      );
185         setconnecttimeout.invoke(huc,new Object[] {new Integer(timeout)});
186
187         Method setreadtimeout = urlconnectionClass.getMethod (
188                                   "setReadTimeout", new Class[] {int.class}
189                                   );
190         setreadtimeout.invoke(huc,new Object[] {new Integer(timeout)});
191         //System.out.println("successfully set java 1.5 timeout");
192     } catch (Exception e) {
193         //e.printStackTrace();
194         // most likely it was a NoSuchMEthodException and we are running java 1.4.
195     }
196     return huc;
197     }
198
199     private InputStream open(URL url)
200     throws java.io.IOException, java.net.ConnectException
201     {
202         InputStream inStream = null;
203
204
205         HttpURLConnection huc = openHttpURLConnection(url);
206
207         inStream = huc.getInputStream();
208
209         return inStream;
210
211     }
212
213     /** returns a List of Features */
214     public List get_features() {
215
216         return features;
217     }
218
219     /** returns the comeBackLater value - if a server returned suchh -
220      *
221      * @return comeBackLater in seconds, or -1 if not provided by server
222      */
223     public int getComeBackLater(){
224
225         return comeBackLater;
226
227     }
228
229
230 }