]> git.argeo.org Git - gpl/argeo-slc.git/blob - org.argeo.slc.core/src/org/argeo/slc/core/execution/http/WebServiceTask.java
Make HttpContext configurable
[gpl/argeo-slc.git] / org.argeo.slc.core / src / org / argeo / slc / core / execution / http / WebServiceTask.java
1 package org.argeo.slc.core.execution.http;
2
3 import java.io.InputStream;
4 import java.nio.ByteBuffer;
5 import java.nio.channels.AsynchronousByteChannel;
6 import java.nio.channels.Channels;
7 import java.nio.channels.ReadableByteChannel;
8 import java.util.concurrent.Callable;
9 import java.util.concurrent.Future;
10
11 import org.apache.commons.httpclient.HttpClient;
12 import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
13 import org.apache.commons.httpclient.methods.PostMethod;
14 import org.apache.commons.httpclient.methods.RequestEntity;
15
16 public class WebServiceTask implements Callable<Integer> {
17 private String url;
18 private String requContentType;
19 private String respContentType;
20
21 private AsynchronousByteChannel channel;
22
23 public WebServiceTask(AsynchronousByteChannel channel, String url) {
24 this(url, "application/json", "application/json", channel);
25 }
26
27 public WebServiceTask(String url, String requContentType, String respContentType, AsynchronousByteChannel channel) {
28 this.url = url;
29 this.requContentType = requContentType;
30 this.respContentType = respContentType;
31 this.channel = channel;
32 }
33
34 @Override
35 public Integer call() throws Exception {
36 // Webservice
37 HttpClient httpClient = new HttpClient();
38 PostMethod postMethod = new PostMethod(url);
39 InputStream in = Channels.newInputStream(channel);
40 RequestEntity requestEntity = new InputStreamRequestEntity(in, requContentType);
41 // StringRequestEntity requestEntity = new
42 // StringRequestEntity(payloadStr, "application/json", "UTF-8");
43 postMethod.setRequestEntity(requestEntity);
44 httpClient.executeMethod(postMethod);
45 InputStream answerIn = postMethod.getResponseBodyAsStream();
46 ReadableByteChannel answer = Channels.newChannel(answerIn);
47 ByteBuffer buffer = ByteBuffer.allocate(8 * 1024);
48 int read = 0;
49 Integer writeRes = 0;
50 while (read != -1) {
51 read = answer.read(buffer);
52 if (read <= 0)
53 break;
54 buffer.flip();
55 Future<Integer> f = channel.write(buffer);
56 writeRes = writeRes + f.get();
57 buffer.clear();
58 }
59 return writeRes;
60 }
61
62 public String getUrl() {
63 return url;
64 }
65
66 public String getRequContentType() {
67 return requContentType;
68 }
69
70 public String getRespContentType() {
71 return respContentType;
72 }
73
74 }