You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

HttpClientConnection.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /*
  2. * Copyright (C) 2013 Christian Halstrick <christian.halstrick@sap.com>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.transport.http.apache;
  44. import java.io.IOException;
  45. import java.io.InputStream;
  46. import java.io.OutputStream;
  47. import java.net.InetSocketAddress;
  48. import java.net.MalformedURLException;
  49. import java.net.ProtocolException;
  50. import java.net.Proxy;
  51. import java.net.URL;
  52. import java.security.KeyManagementException;
  53. import java.security.NoSuchAlgorithmException;
  54. import java.security.SecureRandom;
  55. import java.security.cert.X509Certificate;
  56. import java.util.HashMap;
  57. import java.util.LinkedList;
  58. import java.util.List;
  59. import java.util.Map;
  60. import javax.net.ssl.HostnameVerifier;
  61. import javax.net.ssl.KeyManager;
  62. import javax.net.ssl.SSLContext;
  63. import javax.net.ssl.SSLException;
  64. import javax.net.ssl.SSLSession;
  65. import javax.net.ssl.SSLSocket;
  66. import javax.net.ssl.TrustManager;
  67. import org.apache.http.Header;
  68. import org.apache.http.HeaderElement;
  69. import org.apache.http.HttpEntity;
  70. import org.apache.http.HttpEntityEnclosingRequest;
  71. import org.apache.http.HttpHost;
  72. import org.apache.http.HttpResponse;
  73. import org.apache.http.client.ClientProtocolException;
  74. import org.apache.http.client.HttpClient;
  75. import org.apache.http.client.methods.HttpGet;
  76. import org.apache.http.client.methods.HttpPost;
  77. import org.apache.http.client.methods.HttpPut;
  78. import org.apache.http.client.methods.HttpUriRequest;
  79. import org.apache.http.client.params.ClientPNames;
  80. import org.apache.http.conn.params.ConnRoutePNames;
  81. import org.apache.http.conn.scheme.Scheme;
  82. import org.apache.http.conn.ssl.SSLSocketFactory;
  83. import org.apache.http.conn.ssl.X509HostnameVerifier;
  84. import org.apache.http.impl.client.DefaultHttpClient;
  85. import org.apache.http.params.CoreConnectionPNames;
  86. import org.apache.http.params.HttpParams;
  87. import org.eclipse.jgit.transport.http.HttpConnection;
  88. import org.eclipse.jgit.transport.http.apache.internal.HttpApacheText;
  89. import org.eclipse.jgit.util.TemporaryBuffer;
  90. import org.eclipse.jgit.util.TemporaryBuffer.LocalFile;
  91. /**
  92. * A {@link HttpConnection} which uses {@link HttpClient}
  93. *
  94. * @since 3.3
  95. */
  96. public class HttpClientConnection implements HttpConnection {
  97. HttpClient client;
  98. String urlStr;
  99. HttpUriRequest req;
  100. HttpResponse resp = null;
  101. String method = "GET"; //$NON-NLS-1$
  102. private TemporaryBufferEntity entity;
  103. private boolean isUsingProxy = false;
  104. private Proxy proxy;
  105. private Integer timeout = null;
  106. private Integer readTimeout;
  107. private Boolean followRedirects;
  108. private X509HostnameVerifier hostnameverifier;
  109. SSLContext ctx;
  110. private HttpClient getClient() {
  111. if (client == null)
  112. client = new DefaultHttpClient();
  113. HttpParams params = client.getParams();
  114. if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
  115. isUsingProxy = true;
  116. InetSocketAddress adr = (InetSocketAddress) proxy.address();
  117. params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
  118. new HttpHost(adr.getHostName(), adr.getPort()));
  119. }
  120. if (timeout != null)
  121. params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
  122. timeout.intValue());
  123. if (readTimeout != null)
  124. params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
  125. readTimeout.intValue());
  126. if (followRedirects != null)
  127. params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS,
  128. followRedirects.booleanValue());
  129. if (hostnameverifier != null) {
  130. SSLSocketFactory sf;
  131. sf = new SSLSocketFactory(getSSLContext(), hostnameverifier);
  132. Scheme https = new Scheme("https", 443, sf); //$NON-NLS-1$
  133. client.getConnectionManager().getSchemeRegistry().register(https);
  134. }
  135. return client;
  136. }
  137. private SSLContext getSSLContext() {
  138. if (ctx == null) {
  139. try {
  140. ctx = SSLContext.getInstance("TLS"); //$NON-NLS-1$
  141. } catch (NoSuchAlgorithmException e) {
  142. throw new IllegalStateException(
  143. HttpApacheText.get().unexpectedSSLContextException, e);
  144. }
  145. }
  146. return ctx;
  147. }
  148. /**
  149. * Sets the buffer from which to take the request body
  150. *
  151. * @param buffer
  152. */
  153. public void setBuffer(TemporaryBuffer buffer) {
  154. this.entity = new TemporaryBufferEntity(buffer);
  155. }
  156. /**
  157. * @param urlStr
  158. */
  159. public HttpClientConnection(String urlStr) {
  160. this(urlStr, null);
  161. }
  162. /**
  163. * @param urlStr
  164. * @param proxy
  165. */
  166. public HttpClientConnection(String urlStr, Proxy proxy) {
  167. this(urlStr, proxy, null);
  168. }
  169. /**
  170. * @param urlStr
  171. * @param proxy
  172. * @param cl
  173. */
  174. public HttpClientConnection(String urlStr, Proxy proxy, HttpClient cl) {
  175. this.client = cl;
  176. this.urlStr = urlStr;
  177. this.proxy = proxy;
  178. }
  179. public int getResponseCode() throws IOException {
  180. execute();
  181. return resp.getStatusLine().getStatusCode();
  182. }
  183. public URL getURL() {
  184. try {
  185. return new URL(urlStr);
  186. } catch (MalformedURLException e) {
  187. return null;
  188. }
  189. }
  190. public String getResponseMessage() throws IOException {
  191. execute();
  192. return resp.getStatusLine().getReasonPhrase();
  193. }
  194. private void execute() throws IOException, ClientProtocolException {
  195. if (resp == null)
  196. if (entity != null) {
  197. if (req instanceof HttpEntityEnclosingRequest) {
  198. HttpEntityEnclosingRequest eReq = (HttpEntityEnclosingRequest) req;
  199. eReq.setEntity(entity);
  200. }
  201. resp = getClient().execute(req);
  202. entity.getBuffer().close();
  203. entity = null;
  204. } else
  205. resp = getClient().execute(req);
  206. }
  207. public Map<String, List<String>> getHeaderFields() {
  208. Map<String, List<String>> ret = new HashMap<String, List<String>>();
  209. for (Header hdr : resp.getAllHeaders()) {
  210. List<String> list = new LinkedList<String>();
  211. for (HeaderElement hdrElem : hdr.getElements())
  212. list.add(hdrElem.toString());
  213. ret.put(hdr.getName(), list);
  214. }
  215. return ret;
  216. }
  217. public void setRequestProperty(String name, String value) {
  218. req.addHeader(name, value);
  219. }
  220. public void setRequestMethod(String method) throws ProtocolException {
  221. this.method = method;
  222. if ("GET".equalsIgnoreCase(method)) //$NON-NLS-1$
  223. req = new HttpGet(urlStr);
  224. else if ("PUT".equalsIgnoreCase(method)) //$NON-NLS-1$
  225. req = new HttpPut(urlStr);
  226. else if ("POST".equalsIgnoreCase(method)) //$NON-NLS-1$
  227. req = new HttpPost(urlStr);
  228. else {
  229. this.method = null;
  230. throw new UnsupportedOperationException();
  231. }
  232. }
  233. public void setUseCaches(boolean usecaches) {
  234. // not needed
  235. }
  236. public void setConnectTimeout(int timeout) {
  237. this.timeout = new Integer(timeout);
  238. }
  239. public void setReadTimeout(int readTimeout) {
  240. this.readTimeout = new Integer(readTimeout);
  241. }
  242. public String getContentType() {
  243. HttpEntity responseEntity = resp.getEntity();
  244. if (responseEntity != null) {
  245. Header contentType = responseEntity.getContentType();
  246. if (contentType != null)
  247. return contentType.getValue();
  248. }
  249. return null;
  250. }
  251. public InputStream getInputStream() throws IOException {
  252. return resp.getEntity().getContent();
  253. }
  254. // will return only the first field
  255. public String getHeaderField(String name) {
  256. Header header = resp.getFirstHeader(name);
  257. return (header == null) ? null : header.getValue();
  258. }
  259. public int getContentLength() {
  260. return Integer.parseInt(resp.getFirstHeader("content-length") //$NON-NLS-1$
  261. .getValue());
  262. }
  263. public void setInstanceFollowRedirects(boolean followRedirects) {
  264. this.followRedirects = new Boolean(followRedirects);
  265. }
  266. public void setDoOutput(boolean dooutput) {
  267. // TODO: check whether we can really ignore this.
  268. }
  269. public void setFixedLengthStreamingMode(int contentLength) {
  270. if (entity != null)
  271. throw new IllegalArgumentException();
  272. entity = new TemporaryBufferEntity(new LocalFile());
  273. entity.setContentLength(contentLength);
  274. }
  275. public OutputStream getOutputStream() throws IOException {
  276. if (entity == null)
  277. entity = new TemporaryBufferEntity(new LocalFile());
  278. return entity.getBuffer();
  279. }
  280. public void setChunkedStreamingMode(int chunklen) {
  281. if (entity == null)
  282. entity = new TemporaryBufferEntity(new LocalFile());
  283. entity.setChunked(true);
  284. }
  285. public String getRequestMethod() {
  286. return method;
  287. }
  288. public boolean usingProxy() {
  289. return isUsingProxy;
  290. }
  291. public void connect() throws IOException {
  292. execute();
  293. }
  294. public void setHostnameVerifier(final HostnameVerifier hostnameverifier) {
  295. this.hostnameverifier = new X509HostnameVerifier() {
  296. public boolean verify(String hostname, SSLSession session) {
  297. return hostnameverifier.verify(hostname, session);
  298. }
  299. public void verify(String host, String[] cns, String[] subjectAlts)
  300. throws SSLException {
  301. throw new UnsupportedOperationException(); // TODO message
  302. }
  303. public void verify(String host, X509Certificate cert)
  304. throws SSLException {
  305. throw new UnsupportedOperationException(); // TODO message
  306. }
  307. public void verify(String host, SSLSocket ssl) throws IOException {
  308. hostnameverifier.verify(host, ssl.getSession());
  309. }
  310. };
  311. }
  312. public void configure(KeyManager[] km, TrustManager[] tm,
  313. SecureRandom random) throws KeyManagementException {
  314. getSSLContext().init(km, tm, random);
  315. }
  316. }