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 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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 static org.eclipse.jgit.util.HttpSupport.METHOD_GET;
  45. import static org.eclipse.jgit.util.HttpSupport.METHOD_HEAD;
  46. import static org.eclipse.jgit.util.HttpSupport.METHOD_POST;
  47. import static org.eclipse.jgit.util.HttpSupport.METHOD_PUT;
  48. import java.io.IOException;
  49. import java.io.InputStream;
  50. import java.io.OutputStream;
  51. import java.net.InetSocketAddress;
  52. import java.net.MalformedURLException;
  53. import java.net.ProtocolException;
  54. import java.net.Proxy;
  55. import java.net.URL;
  56. import java.security.KeyManagementException;
  57. import java.security.NoSuchAlgorithmException;
  58. import java.security.SecureRandom;
  59. import java.util.HashMap;
  60. import java.util.LinkedList;
  61. import java.util.List;
  62. import java.util.Map;
  63. import javax.net.ssl.HostnameVerifier;
  64. import javax.net.ssl.KeyManager;
  65. import javax.net.ssl.SSLContext;
  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.config.RequestConfig;
  76. import org.apache.http.client.methods.HttpGet;
  77. import org.apache.http.client.methods.HttpHead;
  78. import org.apache.http.client.methods.HttpPost;
  79. import org.apache.http.client.methods.HttpPut;
  80. import org.apache.http.client.methods.HttpUriRequest;
  81. import org.apache.http.config.Registry;
  82. import org.apache.http.config.RegistryBuilder;
  83. import org.apache.http.conn.socket.ConnectionSocketFactory;
  84. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  85. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  86. import org.apache.http.impl.client.HttpClientBuilder;
  87. import org.apache.http.impl.client.HttpClients;
  88. import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
  89. import org.eclipse.jgit.transport.http.HttpConnection;
  90. import org.eclipse.jgit.transport.http.apache.internal.HttpApacheText;
  91. import org.eclipse.jgit.util.TemporaryBuffer;
  92. import org.eclipse.jgit.util.TemporaryBuffer.LocalFile;
  93. /**
  94. * A {@link org.eclipse.jgit.transport.http.HttpConnection} which uses
  95. * {@link org.apache.http.client.HttpClient}
  96. *
  97. * @since 3.3
  98. */
  99. public class HttpClientConnection implements HttpConnection {
  100. HttpClient client;
  101. URL url;
  102. HttpUriRequest req;
  103. HttpResponse resp = null;
  104. String method = "GET"; //$NON-NLS-1$
  105. private TemporaryBufferEntity entity;
  106. private boolean isUsingProxy = false;
  107. private Proxy proxy;
  108. private Integer timeout = null;
  109. private Integer readTimeout;
  110. private Boolean followRedirects;
  111. private HostnameVerifier hostnameverifier;
  112. SSLContext ctx;
  113. private HttpClient getClient() {
  114. if (client == null) {
  115. HttpClientBuilder clientBuilder = HttpClients.custom();
  116. RequestConfig.Builder configBuilder = RequestConfig.custom();
  117. if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
  118. isUsingProxy = true;
  119. InetSocketAddress adr = (InetSocketAddress) proxy.address();
  120. clientBuilder.setProxy(
  121. new HttpHost(adr.getHostName(), adr.getPort()));
  122. }
  123. if (timeout != null) {
  124. configBuilder.setConnectTimeout(timeout.intValue());
  125. }
  126. if (readTimeout != null) {
  127. configBuilder.setSocketTimeout(readTimeout.intValue());
  128. }
  129. if (followRedirects != null) {
  130. configBuilder
  131. .setRedirectsEnabled(followRedirects.booleanValue());
  132. }
  133. if (hostnameverifier != null) {
  134. SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(
  135. getSSLContext(), hostnameverifier);
  136. clientBuilder.setSSLSocketFactory(sslConnectionFactory);
  137. Registry<ConnectionSocketFactory> registry = RegistryBuilder
  138. .<ConnectionSocketFactory> create()
  139. .register("https", sslConnectionFactory)
  140. .register("http", PlainConnectionSocketFactory.INSTANCE)
  141. .build();
  142. clientBuilder.setConnectionManager(
  143. new BasicHttpClientConnectionManager(registry));
  144. }
  145. clientBuilder.setDefaultRequestConfig(configBuilder.build());
  146. client = clientBuilder.build();
  147. }
  148. return client;
  149. }
  150. private SSLContext getSSLContext() {
  151. if (ctx == null) {
  152. try {
  153. ctx = SSLContext.getInstance("TLS"); //$NON-NLS-1$
  154. } catch (NoSuchAlgorithmException e) {
  155. throw new IllegalStateException(
  156. HttpApacheText.get().unexpectedSSLContextException, e);
  157. }
  158. }
  159. return ctx;
  160. }
  161. /**
  162. * Sets the buffer from which to take the request body
  163. *
  164. * @param buffer
  165. */
  166. public void setBuffer(TemporaryBuffer buffer) {
  167. this.entity = new TemporaryBufferEntity(buffer);
  168. }
  169. /**
  170. * Constructor for HttpClientConnection.
  171. *
  172. * @param urlStr
  173. * @throws MalformedURLException
  174. */
  175. public HttpClientConnection(String urlStr) throws MalformedURLException {
  176. this(urlStr, null);
  177. }
  178. /**
  179. * Constructor for HttpClientConnection.
  180. *
  181. * @param urlStr
  182. * @param proxy
  183. * @throws MalformedURLException
  184. */
  185. public HttpClientConnection(String urlStr, Proxy proxy)
  186. throws MalformedURLException {
  187. this(urlStr, proxy, null);
  188. }
  189. /**
  190. * Constructor for HttpClientConnection.
  191. *
  192. * @param urlStr
  193. * @param proxy
  194. * @param cl
  195. * @throws MalformedURLException
  196. */
  197. public HttpClientConnection(String urlStr, Proxy proxy, HttpClient cl)
  198. throws MalformedURLException {
  199. this.client = cl;
  200. this.url = new URL(urlStr);
  201. this.proxy = proxy;
  202. }
  203. /** {@inheritDoc} */
  204. @Override
  205. public int getResponseCode() throws IOException {
  206. execute();
  207. return resp.getStatusLine().getStatusCode();
  208. }
  209. /** {@inheritDoc} */
  210. @Override
  211. public URL getURL() {
  212. return url;
  213. }
  214. /** {@inheritDoc} */
  215. @Override
  216. public String getResponseMessage() throws IOException {
  217. execute();
  218. return resp.getStatusLine().getReasonPhrase();
  219. }
  220. private void execute() throws IOException, ClientProtocolException {
  221. if (resp != null) {
  222. return;
  223. }
  224. if (entity == null) {
  225. resp = getClient().execute(req);
  226. return;
  227. }
  228. try {
  229. if (req instanceof HttpEntityEnclosingRequest) {
  230. HttpEntityEnclosingRequest eReq = (HttpEntityEnclosingRequest) req;
  231. eReq.setEntity(entity);
  232. }
  233. resp = getClient().execute(req);
  234. } finally {
  235. entity.close();
  236. entity = null;
  237. }
  238. }
  239. /** {@inheritDoc} */
  240. @Override
  241. public Map<String, List<String>> getHeaderFields() {
  242. Map<String, List<String>> ret = new HashMap<>();
  243. for (Header hdr : resp.getAllHeaders()) {
  244. List<String> list = ret.get(hdr.getName());
  245. if (list == null) {
  246. list = new LinkedList<>();
  247. ret.put(hdr.getName(), list);
  248. }
  249. for (HeaderElement hdrElem : hdr.getElements()) {
  250. list.add(hdrElem.toString());
  251. }
  252. }
  253. return ret;
  254. }
  255. /** {@inheritDoc} */
  256. @Override
  257. public void setRequestProperty(String name, String value) {
  258. req.addHeader(name, value);
  259. }
  260. /** {@inheritDoc} */
  261. @Override
  262. public void setRequestMethod(String method) throws ProtocolException {
  263. this.method = method;
  264. if (METHOD_GET.equalsIgnoreCase(method)) {
  265. req = new HttpGet(url.toString());
  266. } else if (METHOD_HEAD.equalsIgnoreCase(method)) {
  267. req = new HttpHead(url.toString());
  268. } else if (METHOD_PUT.equalsIgnoreCase(method)) {
  269. req = new HttpPut(url.toString());
  270. } else if (METHOD_POST.equalsIgnoreCase(method)) {
  271. req = new HttpPost(url.toString());
  272. } else {
  273. this.method = null;
  274. throw new UnsupportedOperationException();
  275. }
  276. }
  277. /** {@inheritDoc} */
  278. @Override
  279. public void setUseCaches(boolean usecaches) {
  280. // not needed
  281. }
  282. /** {@inheritDoc} */
  283. @Override
  284. public void setConnectTimeout(int timeout) {
  285. this.timeout = Integer.valueOf(timeout);
  286. }
  287. /** {@inheritDoc} */
  288. @Override
  289. public void setReadTimeout(int readTimeout) {
  290. this.readTimeout = Integer.valueOf(readTimeout);
  291. }
  292. /** {@inheritDoc} */
  293. @Override
  294. public String getContentType() {
  295. HttpEntity responseEntity = resp.getEntity();
  296. if (responseEntity != null) {
  297. Header contentType = responseEntity.getContentType();
  298. if (contentType != null)
  299. return contentType.getValue();
  300. }
  301. return null;
  302. }
  303. /** {@inheritDoc} */
  304. @Override
  305. public InputStream getInputStream() throws IOException {
  306. return resp.getEntity().getContent();
  307. }
  308. // will return only the first field
  309. /** {@inheritDoc} */
  310. @Override
  311. public String getHeaderField(String name) {
  312. Header header = resp.getFirstHeader(name);
  313. return (header == null) ? null : header.getValue();
  314. }
  315. /** {@inheritDoc} */
  316. @Override
  317. public int getContentLength() {
  318. Header contentLength = resp.getFirstHeader("content-length"); //$NON-NLS-1$
  319. if (contentLength == null) {
  320. return -1;
  321. }
  322. try {
  323. int l = Integer.parseInt(contentLength.getValue());
  324. return l < 0 ? -1 : l;
  325. } catch (NumberFormatException e) {
  326. return -1;
  327. }
  328. }
  329. /** {@inheritDoc} */
  330. @Override
  331. public void setInstanceFollowRedirects(boolean followRedirects) {
  332. this.followRedirects = Boolean.valueOf(followRedirects);
  333. }
  334. /** {@inheritDoc} */
  335. @Override
  336. public void setDoOutput(boolean dooutput) {
  337. // TODO: check whether we can really ignore this.
  338. }
  339. /** {@inheritDoc} */
  340. @Override
  341. public void setFixedLengthStreamingMode(int contentLength) {
  342. if (entity != null)
  343. throw new IllegalArgumentException();
  344. entity = new TemporaryBufferEntity(new LocalFile(null));
  345. entity.setContentLength(contentLength);
  346. }
  347. /** {@inheritDoc} */
  348. @Override
  349. public OutputStream getOutputStream() throws IOException {
  350. if (entity == null)
  351. entity = new TemporaryBufferEntity(new LocalFile(null));
  352. return entity.getBuffer();
  353. }
  354. /** {@inheritDoc} */
  355. @Override
  356. public void setChunkedStreamingMode(int chunklen) {
  357. if (entity == null)
  358. entity = new TemporaryBufferEntity(new LocalFile(null));
  359. entity.setChunked(true);
  360. }
  361. /** {@inheritDoc} */
  362. @Override
  363. public String getRequestMethod() {
  364. return method;
  365. }
  366. /** {@inheritDoc} */
  367. @Override
  368. public boolean usingProxy() {
  369. return isUsingProxy;
  370. }
  371. /** {@inheritDoc} */
  372. @Override
  373. public void connect() throws IOException {
  374. execute();
  375. }
  376. /** {@inheritDoc} */
  377. @Override
  378. public void setHostnameVerifier(HostnameVerifier hostnameverifier) {
  379. this.hostnameverifier = hostnameverifier;
  380. }
  381. /** {@inheritDoc} */
  382. @Override
  383. public void configure(KeyManager[] km, TrustManager[] tm,
  384. SecureRandom random) throws KeyManagementException {
  385. getSSLContext().init(km, tm, random);
  386. }
  387. }