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