001
002/*
003 * This file is originally coming from the Dasobert library.
004 * Author: Andreas Prlic
005 *
006 *                  BioJava development code
007 *
008 * This code may be freely distributed and modified under the
009 * terms of the GNU Lesser General Public Licence.  This should
010 * be distributed with the code.  If you do not have a copy,
011 * see:
012 *
013 *      http://www.gnu.org/copyleft/lesser.html
014 *
015 * Copyright for this code is held jointly by the individual
016 * authors.  These should be listed in @author doc comments.
017 *
018 * For more information on the BioJava project and its aims,
019 * or to join the biojava-l mailing list, visit the home page
020 * at:
021 *
022 *      http://www.biojava.org/
023 *
024 * Created on Jul 25, 2006
025 *
026 */
027
028package org.biojava.nbio.structure.align.util;
029
030import java.io.IOException;
031import java.io.InputStream;
032import java.io.OutputStreamWriter;
033import java.lang.reflect.Method;
034import java.net.ConnectException;
035import java.net.HttpURLConnection;
036import java.net.URL;
037import java.util.zip.GZIPInputStream;
038
039
040
041/** a class that takes care about opening HttpURLConnections and sets the proper timeouts
042 *
043 * @author Andreas Prlic
044 * @since 9:58:25 AM
045 * @version %I% %G%
046 */
047public class HTTPConnectionTools {
048
049        public static final String USERAGENT = "JFatCat Java client";
050
051        public static final int    DEFAULT_CONNECTION_TIMEOUT = 15000; // timeout for http connection = 15. sec
052
053
054        public HTTPConnectionTools() {
055                super();
056
057        }
058
059        /**open HttpURLConnection. Recommended way to open
060         * HttpURLConnections, since this take care of setting timeouts
061         * properly for java 1.4 and 1.5
062         *
063         * @param url URL to oopen
064         * @param timeout timeout in milli seconds
065         * @return a HttpURLConnection
066         * @throws IOException
067         * @throws ConnectException
068         *
069         *
070         */
071        @SuppressWarnings({ "rawtypes", "unchecked" })
072public static HttpURLConnection openHttpURLConnection(URL url, int timeout)
073        throws IOException, ConnectException{
074
075                HttpURLConnection huc = null;
076
077                huc = (HttpURLConnection) url.openConnection();
078                huc.addRequestProperty("User-Agent", USERAGENT);
079
080                // this sets the timeouts for Java 1.4
081                System.setProperty("sun.net.client.defaultConnectTimeout", ""+timeout);
082                System.setProperty("sun.net.client.defaultReadTimeout", ""+timeout);
083
084                // for Java 1.5 we need to do this:
085                // use reflection to determine if get and set timeout methods for urlconnection are available
086                // seems java 1.5 does not watch the System properties any longer...
087                // and java 1.4 did not provide the new classes...
088
089                try {
090                        // try to use reflection to set timeout property
091                        Class urlconnectionClass = Class.forName("java.net.HttpURLConnection");
092
093                        Method setconnecttimeout = urlconnectionClass.getMethod (
094                                        "setConnectTimeout", new Class [] {int.class}
095                        );
096                        setconnecttimeout.invoke(huc,new Object[] {new Integer(timeout)});
097
098                        Method setreadtimeout = urlconnectionClass.getMethod (
099                                        "setReadTimeout", new Class[] {int.class}
100                        );
101                        setreadtimeout.invoke(huc,new Object[] {new Integer(timeout)});
102                        //System.out.println("successfully set java 1.5 timeout");
103                } catch (Exception e) {
104                        e.printStackTrace(); // TODO dmyersturnbull: should we rethrow this?
105                        // most likely it was a NoSuchMEthodException and we are running java 1.4.
106                }
107                return huc;
108        }
109
110
111        /** open HttpURLConnection. Recommended way to open
112         * HttpURLConnections, since this take care of setting timeouts
113         * properly for java 1.4 and 1.5
114         * uses the DEFAULT_CONNECTION_TIMEOUT (= 15 seconds)
115         *
116         * @param url a URL to open a http connection to
117         * @return HttpURLConnect the opened connection
118         * @throws IOException
119         * @throws ConnectException
120         *
121         * */
122        public static HttpURLConnection openHttpURLConnection(URL url)
123        throws IOException, ConnectException {
124
125                return openHttpURLConnection(url,DEFAULT_CONNECTION_TIMEOUT);
126
127        }
128
129        /** connect to DAS server and return result as an InputStream.
130         * always asks for response to be in GZIP encoded
131         *
132         * @param url the URL to connect to
133         * @param timeout the timeout for the connection
134         * @return an InputStream
135         * @throws IOException
136         * @throws DASException if DAS server returns error response code
137         *
138         */
139        public static InputStream getInputStream(URL url, int timeout)
140        throws IOException
141        {
142                return getInputStream(url,true, timeout);
143        }
144
145
146        /** connect to DAS server and return result as an InputStream.
147         * always asks for response to be in GZIP encoded
148         *
149         * @param url the URL to connect to
150         * @return an InputStream
151         * @throws IOException
152         * @throws DASException if DAS server returns error response code
153         *
154         */
155        public static InputStream getInputStream(URL url)
156        throws IOException
157        {
158                return getInputStream(url,true, DEFAULT_CONNECTION_TIMEOUT);
159        }
160
161        /** open a URL and return an InputStream to it
162         *  if acceptGzipEncoding == true, use GZIPEncoding to
163         *  compress communication
164         *
165         * @param url
166         * @param acceptGzipEncoding
167         * @return an InputStream to the URL
168         * @throws IOException
169         * @throws DASException if DAS server returns error response code
170         */
171        @SuppressWarnings("unused")
172public static InputStream getInputStream(URL url, boolean acceptGzipEncoding, int timeout)
173        throws IOException {
174                InputStream inStream = null ;
175
176                //System.out.println("opening connection to "+url);
177                HttpURLConnection huc = HTTPConnectionTools.openHttpURLConnection(url,timeout);
178
179                if ( acceptGzipEncoding) {
180                        // should make communication faster
181                        huc.setRequestProperty("Accept-Encoding", "gzip");
182                }
183
184
185                // check the HTTP response code
186                int httpCode = huc.getResponseCode();
187
188                String contentEncoding = huc.getContentEncoding();
189
190                inStream = huc.getInputStream();
191
192                if (contentEncoding != null) {
193                        if (contentEncoding.contains("gzip")) {
194                                // we have gzip encoding
195                                inStream = new GZIPInputStream(inStream);
196                        }
197                }
198
199                return inStream;
200
201        }
202
203        /** do a POST to a URL and return the response stream for further processing elsewhere.
204         *
205         *
206         * @param url
207         * @return InputStream of response
208         * @throws IOException
209         */
210        public static InputStream doPOST(URL url, String data)
211        throws IOException
212        {
213                return doPOST(url,data,DEFAULT_CONNECTION_TIMEOUT);
214        }
215
216        /** do a POST to a URL and return the response stream for further processing elsewhere.
217         *
218         *
219         * @param url
220         * @return InputStream of response
221         * @throws IOException
222         */
223        public static InputStream doPOST(URL url, String data, int timeout)
224        throws IOException
225        {
226
227        // Send data
228
229          HttpURLConnection conn = openHttpURLConnection(url, timeout);
230
231                //URLConnection conn = url.openConnection();
232                conn.setDoOutput(true);
233
234                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
235                wr.write(data);
236                wr.flush();
237
238                // Get the response
239                return conn.getInputStream();
240
241
242        }
243
244
245}