JAL-1432 updated copyright notices
[jalview.git] / src / jalview / ws / rest / HttpResultSet.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
3  * Copyright (C) 2014 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 of the License, or (at your option) any later version.
10  *  
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  * The Jalview Authors are detailed in the 'AUTHORS' file.
18  */
19 package jalview.ws.rest;
20
21 import jalview.bin.Cache;
22 import jalview.io.FileParse;
23 import jalview.io.packed.DataProvider;
24 import jalview.io.packed.ParsePackedSet;
25 import jalview.io.packed.SimpleDataProvider;
26 import jalview.io.packed.DataProvider.JvDataType;
27 import jalview.ws.io.mime.JalviewMimeContentHandler;
28
29 import java.io.BufferedReader;
30 import java.io.IOException;
31 import java.io.InputStreamReader;
32 import java.io.UnsupportedEncodingException;
33 import java.util.ArrayList;
34 import java.util.List;
35
36 import org.apache.http.HttpEntity;
37 import org.apache.http.HttpResponse;
38 import org.apache.http.client.methods.HttpRequestBase;
39 import org.apache.http.entity.mime.MultipartEntity;
40 import org.apache.james.mime4j.MimeException;
41 import org.apache.james.mime4j.parser.MimeStreamParser;
42
43 /**
44  * data source instantiated from the response of an httpclient request.
45  * 
46  * @author JimP
47  * 
48  */
49
50 public class HttpResultSet extends FileParse
51 {
52
53   private HttpRequestBase cachedRequest;
54
55   /**
56    * when set, indicates that en can be recreated by repeating the HttpRequest
57    * in cachedRequest
58    */
59   boolean repeatable = false;
60
61   /**
62    * response that is to be parsed as jalview input data
63    */
64   private HttpEntity en = null;
65
66   /**
67    * (sub)job that produced this result set.
68    */
69   private RestJob restJob;
70
71   public HttpResultSet(RestJob rj, HttpResponse con, HttpRequestBase req)
72           throws IOException
73   {
74     super();
75     setDataName(rj.getJobId() + " Part " + rj.getJobnum());
76     restJob = rj;
77     cachedRequest = req;
78     initDataSource(con);
79   }
80
81   /**
82    * construct a set of dataproviders to parse a result set from this service
83    * 
84    * @param resSet
85    * @return
86    */
87   public List<DataProvider> createResultDataProviders()
88   {
89     List<DataProvider> dp = new ArrayList<DataProvider>();
90     for (JvDataType type : restJob.rsd.getResultDataTypes())
91     {
92       dp.add(new SimpleDataProvider(type, this, null));
93     }
94     return dp;
95   }
96
97   /**
98    * parses the results of the service output.
99    * 
100    * @return the result of ParsePackedSet.getAlignment()
101    * @throws Exception
102    * @throws Error
103    */
104   public Object[] parseResultSet() throws Exception, Error
105   {
106     List<DataProvider> dp = new ArrayList<DataProvider>();
107     Object[] results = null;
108
109     if (en == null)
110     {
111       throw new Error(
112               "Implementation Error: need to have an HttpResponse to process.");
113     }
114     jalview.io.packed.JalviewDataset ds = restJob.newJalviewDataset();
115     // Decide how we deal with content.
116     if (en instanceof MultipartEntity)
117     {
118       // Multipart messages should be properly typed, so we parse them as we go.
119       MultipartEntity mpe = (MultipartEntity) en;
120       // multipart
121       JalviewMimeContentHandler handler = new JalviewMimeContentHandler(ds);
122       MimeStreamParser parser = new MimeStreamParser();
123       parser.setContentHandler(handler);
124       try
125       {
126         parser.parse(mpe.getContent());
127       } catch (MimeException me)
128       {
129         error = true;
130         errormessage = "Couldn't parse message from web service.";
131         Cache.log.warn("Failed to parse MIME multipart content", me);
132         en.consumeContent();
133       }
134       return new ParsePackedSet().getAlignment(ds,
135               handler.getJalviewDataProviders());
136     }
137     else
138     {
139       // Need to use hints from rest service description.
140       dp = createResultDataProviders();
141       ParsePackedSet pps = new ParsePackedSet();
142       return pps.getAlignment(ds, dp);
143     }
144   }
145
146   private void initDataSource(HttpResponse con) throws IOException
147   {
148     en = con.getEntity();
149     repeatable = en.isRepeatable();
150
151     if (!(en instanceof MultipartEntity))
152     {
153       // assume content is simple text stream that can be read from
154       String enc = (en.getContentEncoding() == null) ? null : en
155               .getContentEncoding().getValue();
156       if (en.getContentType() != null)
157       {
158         Cache.log.debug("Result Type: " + en.getContentType().toString());
159       }
160       else
161       {
162         Cache.log.debug("No Result Type Specified.");
163       }
164       if (enc == null || enc.length() < 1)
165       {
166         Cache.log.debug("Assuming 'Default' Result Encoding.");
167       }
168       else
169       {
170         Cache.log.debug("Result Encoded as : " + enc);
171       }
172       // attempt to identify file and construct an appropriate DataSource
173       // identifier for it.
174       // try to parse
175       // Mime-Multipart or single content type will be expected.
176       // if (enc.equals(org.apache.http.client.utils.)))
177       InputStreamReader br = null;
178       try
179       {
180         br = (enc != null) ? new InputStreamReader(en.getContent(), enc)
181                 : new InputStreamReader(en.getContent());
182       } catch (UnsupportedEncodingException e)
183       {
184         Cache.log.error("Can't handle encoding '" + enc
185                 + "' for response from webservice.", e);
186         en.consumeContent();
187         error = true;
188         errormessage = "Can't handle encoding for response from webservice";
189         return;
190       }
191       if (br != null)
192       {
193         dataIn = new BufferedReader(br);
194         error = false;
195       }
196     }
197   }
198
199   @Override
200   protected void finalize() throws Throwable
201   {
202     dataIn = null;
203     cachedRequest = null;
204     try
205     {
206       if (en != null)
207       {
208         en.consumeContent();
209       }
210     } catch (Exception e)
211     {
212     } catch (Error ex)
213     {
214     }
215     super.finalize();
216   }
217
218   /**
219    * 
220    * @return the URL that this result set read data from.
221    */
222   public String getUrl()
223   {
224     try
225     {
226       return cachedRequest.getURI().toURL().toString();
227     } catch (Exception x)
228     {
229       x.printStackTrace();
230       return null;
231     }
232   }
233
234 }