This repository has been archived by the owner on Aug 11, 2020. It is now read-only.
/
HttpClientRemoteStorage.java
627 lines (559 loc) · 26.4 KB
/
HttpClientRemoteStorage.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
/**
* Sonatype Nexus (TM) Open Source Version
* Copyright (c) 2007-2012 Sonatype, Inc.
* All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions.
*
* This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0,
* which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html.
*
* Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks
* of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the
* Eclipse Foundation. All other trademarks are the property of their respective owners.
*/
package org.sonatype.nexus.proxy.storage.remote.httpclient;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.apache.commons.httpclient.util.DateParseException;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.util.EntityUtils;
import org.codehaus.plexus.util.StringUtils;
import org.sonatype.nexus.ApplicationStatusSource;
import org.sonatype.nexus.mime.MimeSupport;
import org.sonatype.nexus.proxy.ItemNotFoundException;
import org.sonatype.nexus.proxy.RemoteAccessDeniedException;
import org.sonatype.nexus.proxy.RemoteAuthenticationNeededException;
import org.sonatype.nexus.proxy.RemoteStorageException;
import org.sonatype.nexus.proxy.ResourceStoreRequest;
import org.sonatype.nexus.proxy.item.AbstractStorageItem;
import org.sonatype.nexus.proxy.item.DefaultStorageFileItem;
import org.sonatype.nexus.proxy.item.PreparedContentLocator;
import org.sonatype.nexus.proxy.item.StorageFileItem;
import org.sonatype.nexus.proxy.item.StorageItem;
import org.sonatype.nexus.proxy.repository.ProxyRepository;
import org.sonatype.nexus.proxy.storage.UnsupportedStorageOperationException;
import org.sonatype.nexus.proxy.storage.remote.AbstractHTTPRemoteRepositoryStorage;
import org.sonatype.nexus.proxy.storage.remote.RemoteItemNotFoundException;
import org.sonatype.nexus.proxy.storage.remote.RemoteRepositoryStorage;
import org.sonatype.nexus.proxy.storage.remote.RemoteStorageContext;
import org.sonatype.nexus.proxy.storage.remote.http.QueryStringBuilder;
import org.sonatype.nexus.proxy.utils.UserAgentBuilder;
import com.google.common.annotations.VisibleForTesting;
/**
* Apache HTTP client (4) {@link RemoteRepositoryStorage} implementation.
*
* @since 2.0
*/
@Named( HttpClientRemoteStorage.PROVIDER_STRING )
@Singleton
public class HttpClientRemoteStorage
extends AbstractHTTPRemoteRepositoryStorage
implements RemoteRepositoryStorage
{
// ----------------------------------------------------------------------
// Constants
// ----------------------------------------------------------------------
/**
* ID of this provider.
*/
public static final String PROVIDER_STRING = "apacheHttpClient4x";
/**
* The namespace prefix to be used to store provider specific keys in {@link RemoteStorageContext}.
*/
public static final String CTX_KEY = PROVIDER_STRING;
/**
* HTTP header key sent back by Nexus in case of a missing artifact.
*/
public static final String NEXUS_MISSING_ARTIFACT_HEADER = "x-nexus-missing-artifact";
/**
* Created items while retrieving, can be read.
*/
private static final boolean CAN_READ = true;
/**
* Created items while retrieving, can be written.
*/
private static final boolean CAN_WRITE = true;
private QueryStringBuilder queryStringBuilder;
// ----------------------------------------------------------------------
// Constructors
// ----------------------------------------------------------------------
@Inject
HttpClientRemoteStorage( final UserAgentBuilder userAgentBuilder,
final ApplicationStatusSource applicationStatusSource,
final MimeSupport mimeSupport, QueryStringBuilder queryStringBuilder)
{
super( userAgentBuilder, applicationStatusSource, mimeSupport );
this.queryStringBuilder = queryStringBuilder;
}
// ----------------------------------------------------------------------
// Public methods
// ----------------------------------------------------------------------
@Override
public String getProviderId()
{
return PROVIDER_STRING;
}
@Override
public AbstractStorageItem retrieveItem( final ProxyRepository repository,
final ResourceStoreRequest request,
final String baseUrl )
throws ItemNotFoundException, RemoteStorageException
{
final URL remoteURL =
appendQueryString( getAbsoluteUrlFromBase( baseUrl, request.getRequestPath() ), repository );
final String url = remoteURL.toExternalForm();
if ( remoteURL.getPath().endsWith( "/" ) )
{
// NEXUS-5125 we do not want to fetch any collection
// Even though it is unlikely that we actually see a request for a collection here,
// requests for paths like this over the REST layer will be localOnly not trigger a remote request.
//
// The usual case is that there is a request for a directory that is redirected to '/', see below behavior
// for SC_MOVED_*
throw new RemoteItemNotFoundException(
"The remoteURL we got to looks like is a collection, and Nexus cannot fetch collections over plain HTTP (remoteUrl=\""
+ remoteURL.toString() + "\")", request, repository );
}
final HttpGet method = new HttpGet( url );
final HttpResponse httpResponse = executeRequest( repository, request, method );
if ( httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK )
{
InputStream is;
try
{
is = httpResponse.getEntity().getContent();
String mimeType = EntityUtils.getContentMimeType( httpResponse.getEntity() );
if ( mimeType == null )
{
mimeType = getMimeSupport().guessMimeTypeFromPath(
repository.getMimeRulesSource(), request.getRequestPath()
);
}
final DefaultStorageFileItem httpItem = new DefaultStorageFileItem(
repository, request, CAN_READ, CAN_WRITE, new PreparedContentLocator( is, mimeType )
);
if ( httpResponse.getEntity().getContentLength() != -1 )
{
httpItem.setLength( httpResponse.getEntity().getContentLength() );
}
httpItem.setRemoteUrl( remoteURL.toString() );
httpItem.setModified( makeDateFromHeader( httpResponse.getFirstHeader( "last-modified" ) ) );
httpItem.setCreated( httpItem.getModified() );
httpItem.getItemContext().putAll( request.getRequestContext() );
return httpItem;
}
catch ( IOException ex )
{
release( httpResponse );
throw new RemoteStorageException( "IO Error during response stream handling [repositoryId=\""
+ repository.getId() + "\", requestPath=\""
+ request.getRequestPath() + "\", remoteUrl=\""
+ remoteURL.toString() + "\"]!", ex );
}
catch ( RuntimeException ex )
{
release( httpResponse );
throw ex;
}
}
else
{
release( httpResponse );
if ( httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND )
{
throw new RemoteItemNotFoundException(
"The remoteURL we requested does not exists on remote server (remoteUrl=\"" + remoteURL.toString()
+ "\", response code is 404)", request, repository );
}
else if ( httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY ||
httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY )
{
// NEXUS-5125 unfollowed redirect means collection (path.endsWith("/"))
// see also HttpClientUtil#configure
throw new RemoteItemNotFoundException(
"The remoteURL we got to looks like is a collection, and Nexus cannot fetch collections over plain HTTP (remoteUrl=\""
+ remoteURL.toString() + "\")", request, repository );
}
else
{
throw new RemoteStorageException( "The method execution returned result code " + httpResponse.getStatusLine().getStatusCode()
+ " (expected 200). [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath()
+ "\", remoteUrl=\"" + remoteURL.toString() + "\"]" );
}
}
}
@Override
public void storeItem( final ProxyRepository repository,
final StorageItem item )
throws UnsupportedStorageOperationException, RemoteStorageException
{
if ( !( item instanceof StorageFileItem ) )
{
throw new UnsupportedStorageOperationException( "Storing of non-files remotely is not supported!" );
}
final StorageFileItem fileItem = (StorageFileItem) item;
final ResourceStoreRequest request = new ResourceStoreRequest( item );
final URL remoteUrl = appendQueryString( getAbsoluteUrlFromBase( repository, request ), repository );
final HttpPut method = new HttpPut( remoteUrl.toExternalForm() );
final InputStreamEntity entity;
try
{
entity = new InputStreamEntity( fileItem.getInputStream(), fileItem.getLength() );
}
catch ( IOException e )
{
throw new RemoteStorageException(
e.getMessage()
+ " [repositoryId=\"" + repository.getId()
+ "\", requestPath=\"" + request.getRequestPath()
+ "\", remoteUrl=\"" + remoteUrl.toString()
+ "\"]",
e
);
}
entity.setContentType( fileItem.getMimeType() );
method.setEntity( entity );
final HttpResponse httpResponse = executeRequestAndRelease( repository, request, method );
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if ( statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
&& statusCode != HttpStatus.SC_NO_CONTENT && statusCode != HttpStatus.SC_ACCEPTED )
{
throw new RemoteStorageException( "Unexpected response code while executing " + method.getMethod()
+ " method [repositoryId=\"" + repository.getId()
+ "\", requestPath=\"" + request.getRequestPath()
+ "\", remoteUrl=\"" + remoteUrl.toString()
+ "\"]. Expected: \"any success (2xx)\". Received: "
+ statusCode + " : "
+ httpResponse.getStatusLine().getReasonPhrase() );
}
}
@Override
public void deleteItem( final ProxyRepository repository,
final ResourceStoreRequest request )
throws ItemNotFoundException, UnsupportedStorageOperationException, RemoteStorageException
{
final URL remoteUrl = appendQueryString( getAbsoluteUrlFromBase( repository, request ), repository );
final HttpDelete method = new HttpDelete( remoteUrl.toExternalForm() );
final HttpResponse httpResponse = executeRequestAndRelease( repository, request, method );
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if ( statusCode != HttpStatus.SC_OK
&& statusCode != HttpStatus.SC_NO_CONTENT
&& statusCode != HttpStatus.SC_ACCEPTED )
{
throw new RemoteStorageException( "The response to HTTP " + method.getMethod()
+ " was unexpected HTTP Code " + statusCode + " : "
+ httpResponse.getStatusLine().getReasonPhrase()
+ " [repositoryId=\"" + repository.getId() + "\", requestPath=\""
+ request.getRequestPath()
+ "\", remoteUrl=\"" + remoteUrl.toString() + "\"]" );
}
}
@Override
protected boolean checkRemoteAvailability( final long newerThen,
final ProxyRepository repository,
final ResourceStoreRequest request,
final boolean isStrict )
throws RemoteStorageException
{
final URL remoteUrl = appendQueryString( getAbsoluteUrlFromBase( repository, request ), repository );
HttpRequestBase method;
HttpResponse httpResponse = null;
int statusCode = HttpStatus.SC_BAD_REQUEST;
// artifactory hack, it pukes on HEAD so we will try with GET if HEAD fails
boolean doGet = false;
{
method = new HttpHead( remoteUrl.toExternalForm() );
try
{
httpResponse = executeRequestAndRelease( repository, request, method );
statusCode = httpResponse.getStatusLine().getStatusCode();
}
catch ( RemoteStorageException e )
{
// If HEAD failed, attempt a GET. Some repos may not support HEAD method
doGet = true;
getLogger().debug( "HEAD method failed, will attempt GET. Exception: " + e.getMessage(), e );
}
finally
{
// HEAD returned error, but not exception, try GET before failing
if ( !doGet && statusCode != HttpStatus.SC_OK )
{
doGet = true;
getLogger().debug( "HEAD method failed, will attempt GET. Status: " + statusCode );
}
}
}
{
if ( doGet )
{
// create a GET
method = new HttpGet( remoteUrl.toExternalForm() );
// execute it
httpResponse = executeRequestAndRelease( repository, request, method );
statusCode = httpResponse.getStatusLine().getStatusCode();
}
}
// if we are not strict and remote is S3
if ( !isStrict && isRemotePeerAmazonS3Storage( repository ) )
{
// if we are relaxed, we will accept any HTTP response code below 500. This means anyway the HTTP
// transaction succeeded. This method was never really detecting that the remoteUrl really denotes a root of
// repository (how could we do that?)
// this "relaxed" check will help us to "pass" S3 remote storage.
return statusCode >= HttpStatus.SC_OK && statusCode <= HttpStatus.SC_INTERNAL_SERVER_ERROR;
}
else
{
// non relaxed check is strict, and will select only the OK response
if ( statusCode == HttpStatus.SC_OK )
{
// we have it
// we have newer if this below is true
return makeDateFromHeader( httpResponse.getFirstHeader( "last-modified" ) ) > newerThen;
}
else if ( ( statusCode >= HttpStatus.SC_MULTIPLE_CHOICES && statusCode < HttpStatus.SC_BAD_REQUEST )
|| statusCode == HttpStatus.SC_NOT_FOUND )
{
return false;
}
else
{
throw new RemoteStorageException( "Unexpected response code while executing " + method.getMethod()
+ " method [repositoryId=\"" + repository.getId()
+ "\", requestPath=\"" + request.getRequestPath()
+ "\", remoteUrl=\"" + remoteUrl.toString()
+ "\"]. Expected: \"SUCCESS (200)\". Received: "
+ statusCode + " : " +
httpResponse.getStatusLine().getReasonPhrase() );
}
}
}
@Override
protected void updateContext( final ProxyRepository repository,
final RemoteStorageContext ctx )
{
// reset current http client, if exists
HttpClientUtil.release( CTX_KEY, ctx );
// and create a new one
HttpClientUtil.configure( CTX_KEY, ctx, getLogger() );
}
@Override
protected String getS3FlagKey()
{
return HttpClientUtil.getS3FlagKey( CTX_KEY );
}
// ----------------------------------------------------------------------
// Implementation methods
// ----------------------------------------------------------------------
/**
* Executes the HTTP request.
* <p/>
* In case of any exception thrown by HttpClient, it will release the connection. In other cases it
* is the duty of caller to do it, or process the input stream.
*
* @param repository to execute the HTTP method fpr
* @param request resource store request that triggered the HTTP request
* @param httpRequest HTTP request to be executed
* @return response of making the request
* @throws RemoteStorageException If an error occurred during execution of HTTP request
*/
@VisibleForTesting
HttpResponse executeRequest( final ProxyRepository repository,
final ResourceStoreRequest request,
final HttpUriRequest httpRequest )
throws RemoteStorageException
{
final URI methodUri = httpRequest.getURI();
if ( getLogger().isDebugEnabled() )
{
getLogger().debug(
"Invoking HTTP " + httpRequest.getMethod() + " method against remote location " + methodUri
);
}
final RemoteStorageContext ctx = getRemoteStorageContext( repository );
final HttpClient httpClient = HttpClientUtil.getHttpClient( CTX_KEY, ctx );
httpRequest.setHeader( "user-agent", formatUserAgentString( ctx, repository ) );
httpRequest.setHeader( "accept", "*/*" );
httpRequest.setHeader( "accept-language", "en-us" );
httpRequest.setHeader( "accept-encoding", "gzip,deflate,identity" );
httpRequest.setHeader( "cache-control", "no-cache" );
// HTTP keep alive should not be used, except when NTLM is used
final Boolean isNtlmUsed = HttpClientUtil.isNTLMAuthenticationUsed( CTX_KEY, ctx );
if ( isNtlmUsed == null || !isNtlmUsed )
{
httpRequest.setHeader( "Connection", "close" );
httpRequest.setHeader( "Proxy-Connection", "close" );
}
HttpResponse httpResponse = null;
try
{
httpResponse = httpClient.execute( httpRequest );
final int statusCode = httpResponse.getStatusLine().getStatusCode();
final Header httpServerHeader = httpResponse.getFirstHeader( "server" );
checkForRemotePeerAmazonS3Storage(
repository, httpServerHeader == null ? null : httpServerHeader.getValue()
);
Header proxyReturnedErrorHeader = httpResponse.getFirstHeader( NEXUS_MISSING_ARTIFACT_HEADER );
boolean proxyReturnedError =
proxyReturnedErrorHeader != null && Boolean.valueOf( proxyReturnedErrorHeader.getValue() );
if ( statusCode == HttpStatus.SC_FORBIDDEN )
{
throw new RemoteAccessDeniedException(
repository, methodUri.toASCIIString(), httpResponse.getStatusLine().getReasonPhrase()
);
}
else if ( statusCode == HttpStatus.SC_UNAUTHORIZED )
{
throw new RemoteAuthenticationNeededException(
repository, httpResponse.getStatusLine().getReasonPhrase()
);
}
else if ( statusCode == HttpStatus.SC_OK && proxyReturnedError )
{
throw new RemoteStorageException(
"Invalid artifact found, most likely a proxy redirected to an HTML error page."
);
}
return httpResponse;
}
catch ( RemoteStorageException ex )
{
release( httpResponse );
throw ex;
}
catch ( ClientProtocolException ex )
{
release( httpResponse );
throw new RemoteStorageException( "Protocol error while executing " + httpRequest.getMethod()
+ " method. [repositoryId=\"" + repository.getId()
+ "\", requestPath=\"" + request.getRequestPath()
+ "\", remoteUrl=\"" + methodUri.toASCIIString() + "\"]", ex );
}
catch ( IOException ex )
{
release( httpResponse );
throw new RemoteStorageException( "Transport error while executing " + httpRequest.getMethod()
+ " method [repositoryId=\"" + repository.getId()
+ "\", requestPath=\"" + request.getRequestPath()
+ "\", remoteUrl=\"" + methodUri.toASCIIString() + "\"]", ex );
}
}
/**
* Executes the HTTP request and automatically releases any related resources.
*
* @param repository to execute the HTTP method fpr
* @param request resource store request that triggered the HTTP request
* @param httpRequest HTTP request to be executed
* @return response of making the request
* @throws RemoteStorageException If an error occurred during execution of HTTP request
*/
private HttpResponse executeRequestAndRelease( final ProxyRepository repository,
final ResourceStoreRequest request,
final HttpUriRequest httpRequest )
throws RemoteStorageException
{
final HttpResponse httpResponse = executeRequest( repository, request, httpRequest );
release( httpResponse );
return httpResponse;
}
/**
* Make date from header.
*
* @param date the date
* @return the long
*/
private long makeDateFromHeader( final Header date )
{
long result = System.currentTimeMillis();
if ( date != null )
{
try
{
result = DateUtil.parseDate( date.getValue() ).getTime();
}
catch ( DateParseException ex )
{
getLogger().warn(
"Could not parse date '" + date + "', using system current time as item creation time.", ex );
}
catch ( NullPointerException ex )
{
getLogger().warn( "Parsed date is null, using system current time as item creation time." );
}
}
return result;
}
/**
* Appends repository configured additional query string to provided URL.
*
* @param url to append to
* @param repository that may contain additional query string
* @return URL with appended query string or original URL if repository does not have an configured query string
* @throws RemoteStorageException if query string could not be appended (resulted in an Malformed URL exception)
*/
private URL appendQueryString( final URL url,
final ProxyRepository repository )
throws RemoteStorageException
{
final RemoteStorageContext ctx = getRemoteStorageContext( repository );
String queryString = queryStringBuilder.getQueryString( ctx, repository );
if ( StringUtils.isNotBlank( queryString ) )
{
try
{
if ( StringUtils.isBlank( url.getQuery() ) )
{
return new URL( url.toExternalForm() + "?" + queryString );
}
else
{
return new URL( url.toExternalForm() + "&" + queryString );
}
}
catch ( MalformedURLException e )
{
throw new RemoteStorageException(
"Could not append query string \"" + queryString + "\" to url \"" + url + "\"", e
);
}
}
return url;
}
/**
* Releases connection resources (back to pool). If an exception appears during releasing, exception is just logged.
*
* @param httpResponse to be released
*/
private void release( final HttpResponse httpResponse )
{
if ( httpResponse != null )
{
try
{
EntityUtils.consume( httpResponse.getEntity() );
}
catch ( IOException e )
{
getLogger().warn( e.getMessage() );
}
}
}
}