Skip to content

Commit 0ea0afd

Browse files
author
a-brandt
committed
fixed sonarlint issue
1 parent 4a50960 commit 0ea0afd

File tree

2 files changed

+174
-141
lines changed

2 files changed

+174
-141
lines changed

src/main/java/com/arangodb/http/CURLLogger.java

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ private CURLLogger() {
3737
// this is a helper class
3838
}
3939

40-
public static void log(String url, HttpRequestEntity requestEntity, String userAgent, Credentials credencials) {
40+
public static void log(String url, HttpRequestEntity requestEntity, Credentials credencials) {
4141

4242
boolean includeBody = (requestEntity.type == RequestType.POST || requestEntity.type == RequestType.PUT
4343
|| requestEntity.type == RequestType.PATCH) && StringUtils.isNotEmpty(requestEntity.bodyText);
@@ -65,9 +65,6 @@ public static void log(String url, HttpRequestEntity requestEntity, String userA
6565
.append(credencials.getPassword());
6666
}
6767

68-
// user-agent
69-
// buffer.append(" -A '").append(userAgent).append("'");
70-
7168
if (includeBody) {
7269
buffer.append(" -d @-");
7370
}

src/main/java/com/arangodb/http/HttpManager.java

Lines changed: 173 additions & 137 deletions
Original file line numberDiff line numberDiff line change
@@ -150,23 +150,7 @@ public void init() {
150150

151151
@Override
152152
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
153-
// Honor 'keep-alive' header
154-
HeaderElementIterator it = new BasicHeaderElementIterator(
155-
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
156-
while (it.hasNext()) {
157-
HeaderElement he = it.nextElement();
158-
String param = he.getName();
159-
String value = he.getValue();
160-
if (value != null && "timeout".equalsIgnoreCase(param)) {
161-
try {
162-
return Long.parseLong(value) * 1000L;
163-
} catch (NumberFormatException ignore) {
164-
// ignore this exception
165-
}
166-
}
167-
}
168-
// otherwise keep alive for 30 seconds
169-
return 30L * 1000L;
153+
return HttpManager.this.getKeepAliveDuration(response);
170154
}
171155

172156
};
@@ -176,25 +160,38 @@ public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
176160
builder.setRetryHandler(new DefaultHttpRequestRetryHandler(configure.getRetryCount(), false));
177161

178162
// Proxy
163+
addProxyToBuilder(builder);
164+
165+
// Client
166+
client = builder.build();
167+
}
168+
169+
private long getKeepAliveDuration(HttpResponse response) {
170+
// Honor 'keep-alive' header
171+
HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
172+
while (it.hasNext()) {
173+
HeaderElement he = it.nextElement();
174+
String param = he.getName();
175+
String value = he.getValue();
176+
if (value != null && "timeout".equalsIgnoreCase(param)) {
177+
try {
178+
return Long.parseLong(value) * 1000L;
179+
} catch (NumberFormatException ignore) {
180+
// ignore this exception
181+
}
182+
}
183+
}
184+
// otherwise keep alive for 30 seconds
185+
return 30L * 1000L;
186+
}
187+
188+
private void addProxyToBuilder(HttpClientBuilder builder) {
179189
if (configure.getProxyHost() != null && configure.getProxyPort() != 0) {
180190
HttpHost proxy = new HttpHost(configure.getProxyHost(), configure.getProxyPort(), "http");
181191

182192
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
183193
builder.setRoutePlanner(routePlanner);
184194
}
185-
186-
// Client
187-
client = builder.build();
188-
189-
// Basic Auth
190-
// if (configure.getUser() != null && configure.getPassword() != null) {
191-
// AuthScope scope = AuthScope.ANY; // TODO
192-
// this.credentials = new
193-
// UsernamePasswordCredentials(configure.getUser(),
194-
// configure.getPassword());
195-
// client.getCredentialsProvider().setCredentials(scope, credentials);
196-
// }
197-
198195
}
199196

200197
public void destroy() {
@@ -389,17 +386,142 @@ private HttpResponseEntity executeInternal(String baseUrl, HttpRequestEntity req
389386

390387
String url = buildUrl(baseUrl, requestEntity);
391388

392-
if (logger.isDebugEnabled()) {
393-
if (requestEntity.type == RequestType.POST || requestEntity.type == RequestType.PUT
394-
|| requestEntity.type == RequestType.PATCH) {
395-
logger.debug("[REQ]http-{}: url={}, headers={}, body={}",
396-
new Object[] { requestEntity.type, url, requestEntity.headers, requestEntity.bodyText });
397-
} else {
398-
logger.debug("[REQ]http-{}: url={}, headers={}",
399-
new Object[] { requestEntity.type, url, requestEntity.headers });
389+
logRequest(requestEntity, url);
390+
391+
HttpRequestBase request = buildHttpRequestBase(requestEntity, url);
392+
393+
// common-header
394+
String userAgent = "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.1; +http://mt.orz.at/)";
395+
request.setHeader("User-Agent", userAgent);
396+
397+
addOptionalHeaders(requestEntity, request);
398+
399+
addHttpModeHeader(request);
400+
401+
// Basic Auth
402+
Credentials credentials = addCredentials(requestEntity, request);
403+
404+
// CURL/HTTP Logger
405+
if (configure.isEnableCURLLogger()) {
406+
CURLLogger.log(url, requestEntity, credentials);
407+
}
408+
409+
HttpResponseEntity responseEntity = null;
410+
if (preDefinedResponse != null) {
411+
responseEntity = preDefinedResponse;
412+
} else {
413+
HttpResponse response = executeRequest(request);
414+
if (response != null) {
415+
try {
416+
responseEntity = buildHttpResponseEntity(requestEntity, response);
417+
} catch (IOException e) {
418+
throw new ArangoException(e);
419+
}
420+
421+
if (this.getHttpMode().equals(HttpMode.ASYNC)) {
422+
Map<String, String> map = responseEntity.getHeaders();
423+
this.addJob(map.get("X-Arango-Async-Id"), this.getCurrentObject());
424+
} else if (this.getHttpMode().equals(HttpMode.FIREANDFORGET)) {
425+
responseEntity = null;
426+
}
427+
}
428+
}
429+
430+
return responseEntity;
431+
}
432+
433+
private HttpResponse executeRequest(HttpRequestBase request) throws SocketException, ArangoException {
434+
try {
435+
return client.execute(request);
436+
} catch (SocketException ex) {
437+
// catch SocketException before IOException
438+
throw ex;
439+
} catch (ClientProtocolException e) {
440+
throw new ArangoException(e);
441+
} catch (IOException e) {
442+
throw new ArangoException(e);
443+
}
444+
}
445+
446+
private HttpResponseEntity buildHttpResponseEntity(HttpRequestEntity requestEntity, HttpResponse response)
447+
throws IOException {
448+
HttpResponseEntity responseEntity = new HttpResponseEntity();
449+
450+
// http status
451+
StatusLine status = response.getStatusLine();
452+
responseEntity.statusCode = status.getStatusCode();
453+
responseEntity.statusPhrase = status.getReasonPhrase();
454+
455+
logger.debug("[RES]http-{}: statusCode={}", requestEntity.type, responseEntity.statusCode);
456+
457+
// ヘッダの処理
458+
// // TODO etag特殊処理は削除する。
459+
Header etagHeader = response.getLastHeader("etag");
460+
if (etagHeader != null) {
461+
responseEntity.etag = Long.parseLong(etagHeader.getValue().replace("\"", ""));
462+
}
463+
// ヘッダをMapに変換する
464+
responseEntity.headers = new TreeMap<String, String>();
465+
for (Header header : response.getAllHeaders()) {
466+
responseEntity.headers.put(header.getName(), header.getValue());
467+
}
468+
469+
// レスポンスの取得
470+
HttpEntity entity = response.getEntity();
471+
if (entity != null) {
472+
Header contentType = entity.getContentType();
473+
if (contentType != null) {
474+
responseEntity.contentType = contentType.getValue();
475+
if (responseEntity.isDumpResponse()) {
476+
responseEntity.stream = entity.getContent();
477+
logger.debug("[RES]http-{}: stream, {}", requestEntity.type, contentType.getValue());
478+
}
479+
}
480+
// Close stream in this method.
481+
if (responseEntity.stream == null) {
482+
responseEntity.text = IOUtils.toString(entity.getContent());
483+
logger.debug("[RES]http-{}: text={}", requestEntity.type, responseEntity.text);
484+
}
485+
}
486+
return responseEntity;
487+
}
488+
489+
private void addHttpModeHeader(HttpRequestBase request) {
490+
if (this.getHttpMode().equals(HttpMode.ASYNC)) {
491+
request.addHeader("x-arango-async", "store");
492+
} else if (this.getHttpMode().equals(HttpMode.FIREANDFORGET)) {
493+
request.addHeader("x-arango-async", "true");
494+
}
495+
}
496+
497+
private Credentials addCredentials(HttpRequestEntity requestEntity, HttpRequestBase request)
498+
throws ArangoException {
499+
Credentials credentials = null;
500+
if (requestEntity.username != null && requestEntity.password != null) {
501+
credentials = new UsernamePasswordCredentials(requestEntity.username, requestEntity.password);
502+
} else if (configure.getUser() != null && configure.getPassword() != null) {
503+
credentials = new UsernamePasswordCredentials(configure.getUser(), configure.getPassword());
504+
}
505+
if (credentials != null) {
506+
BasicScheme basicScheme = new BasicScheme();
507+
try {
508+
request.addHeader(basicScheme.authenticate(credentials, request, null));
509+
} catch (AuthenticationException e) {
510+
throw new ArangoException(e);
400511
}
401512
}
513+
return credentials;
514+
}
402515

516+
private void addOptionalHeaders(HttpRequestEntity requestEntity, HttpRequestBase request) {
517+
if (requestEntity.headers != null) {
518+
for (Entry<String, Object> keyValue : requestEntity.headers.entrySet()) {
519+
request.setHeader(keyValue.getKey(), keyValue.getValue().toString());
520+
}
521+
}
522+
}
523+
524+
private HttpRequestBase buildHttpRequestBase(HttpRequestEntity requestEntity, String url) {
403525
HttpRequestBase request;
404526
switch (requestEntity.type) {
405527
case POST:
@@ -428,107 +550,19 @@ private HttpResponseEntity executeInternal(String baseUrl, HttpRequestEntity req
428550
request = new HttpGet(url);
429551
break;
430552
}
553+
return request;
554+
}
431555

432-
// common-header
433-
String userAgent = "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.1; +http://mt.orz.at/)";
434-
request.setHeader("User-Agent", userAgent);
435-
436-
// optinal-headers
437-
if (requestEntity.headers != null) {
438-
for (Entry<String, Object> keyValue : requestEntity.headers.entrySet()) {
439-
request.setHeader(keyValue.getKey(), keyValue.getValue().toString());
440-
}
441-
}
442-
443-
// Basic Auth
444-
Credentials credentials = null;
445-
if (requestEntity.username != null && requestEntity.password != null) {
446-
credentials = new UsernamePasswordCredentials(requestEntity.username, requestEntity.password);
447-
} else if (configure.getUser() != null && configure.getPassword() != null) {
448-
credentials = new UsernamePasswordCredentials(configure.getUser(), configure.getPassword());
449-
}
450-
if (credentials != null) {
451-
BasicScheme basicScheme = new BasicScheme();
452-
try {
453-
request.addHeader(basicScheme.authenticate(credentials, request, null));
454-
} catch (AuthenticationException e) {
455-
throw new ArangoException(e);
456-
}
457-
}
458-
459-
if (this.getHttpMode().equals(HttpMode.ASYNC)) {
460-
request.addHeader("x-arango-async", "store");
461-
} else if (this.getHttpMode().equals(HttpMode.FIREANDFORGET)) {
462-
request.addHeader("x-arango-async", "true");
463-
}
464-
// CURL/httpie Logger
465-
if (configure.isEnableCURLLogger()) {
466-
CURLLogger.log(url, requestEntity, userAgent, credentials);
467-
}
468-
HttpResponse response;
469-
if (preDefinedResponse != null) {
470-
return preDefinedResponse;
471-
}
472-
try {
473-
response = client.execute(request);
474-
if (response == null) {
475-
return null;
476-
}
477-
478-
HttpResponseEntity responseEntity = new HttpResponseEntity();
479-
480-
// http status
481-
StatusLine status = response.getStatusLine();
482-
responseEntity.statusCode = status.getStatusCode();
483-
responseEntity.statusPhrase = status.getReasonPhrase();
484-
485-
logger.debug("[RES]http-{}: statusCode={}", requestEntity.type, responseEntity.statusCode);
486-
487-
// ヘッダの処理
488-
// // TODO etag特殊処理は削除する。
489-
Header etagHeader = response.getLastHeader("etag");
490-
if (etagHeader != null) {
491-
responseEntity.etag = Long.parseLong(etagHeader.getValue().replace("\"", ""));
492-
}
493-
// ヘッダをMapに変換する
494-
responseEntity.headers = new TreeMap<String, String>();
495-
for (Header header : response.getAllHeaders()) {
496-
responseEntity.headers.put(header.getName(), header.getValue());
497-
}
498-
499-
// レスポンスの取得
500-
HttpEntity entity = response.getEntity();
501-
if (entity != null) {
502-
Header contentType = entity.getContentType();
503-
if (contentType != null) {
504-
responseEntity.contentType = contentType.getValue();
505-
if (responseEntity.isDumpResponse()) {
506-
responseEntity.stream = entity.getContent();
507-
logger.debug("[RES]http-{}: stream, {}", requestEntity.type, contentType.getValue());
508-
}
509-
}
510-
// Close stream in this method.
511-
if (responseEntity.stream == null) {
512-
responseEntity.text = IOUtils.toString(entity.getContent());
513-
logger.debug("[RES]http-{}: text={}", requestEntity.type, responseEntity.text);
514-
}
515-
}
516-
517-
if (this.getHttpMode().equals(HttpMode.ASYNC)) {
518-
Map<String, String> map = responseEntity.getHeaders();
519-
this.addJob(map.get("X-Arango-Async-Id"), this.getCurrentObject());
520-
} else if (this.getHttpMode().equals(HttpMode.FIREANDFORGET)) {
521-
return null;
556+
private void logRequest(HttpRequestEntity requestEntity, String url) {
557+
if (logger.isDebugEnabled()) {
558+
if (requestEntity.type == RequestType.POST || requestEntity.type == RequestType.PUT
559+
|| requestEntity.type == RequestType.PATCH) {
560+
logger.debug("[REQ]http-{}: url={}, headers={}, body={}",
561+
new Object[] { requestEntity.type, url, requestEntity.headers, requestEntity.bodyText });
562+
} else {
563+
logger.debug("[REQ]http-{}: url={}, headers={}",
564+
new Object[] { requestEntity.type, url, requestEntity.headers });
522565
}
523-
524-
return responseEntity;
525-
} catch (SocketException ex) {
526-
// catch SocketException before IOException
527-
throw ex;
528-
} catch (ClientProtocolException e) {
529-
throw new ArangoException(e);
530-
} catch (IOException e) {
531-
throw new ArangoException(e);
532566
}
533567
}
534568

@@ -597,10 +631,12 @@ public CloseableHttpClient getClient() {
597631
}
598632

599633
public InvocationObject getCurrentObject() {
634+
// do nothing here (used in BatchHttpManager)
600635
return null;
601636
}
602637

603638
public void setCurrentObject(InvocationObject currentObject) {
639+
// do nothing here (used in BatchHttpManager)
604640
}
605641

606642
public void setPreDefinedResponse(HttpResponseEntity preDefinedResponse) {

0 commit comments

Comments
 (0)