|
1 | 1 | package lt.tokenmill.crawling.es; |
2 | 2 |
|
3 | 3 | import org.apache.http.HttpHost; |
| 4 | +import org.apache.http.auth.AuthScope; |
| 5 | +import org.apache.http.auth.UsernamePasswordCredentials; |
| 6 | +import org.apache.http.client.CredentialsProvider; |
| 7 | +import org.apache.http.impl.client.BasicCredentialsProvider; |
4 | 8 | import org.elasticsearch.action.DocWriteRequest; |
5 | 9 | import org.elasticsearch.action.bulk.BulkItemResponse; |
6 | 10 | import org.elasticsearch.action.bulk.BulkProcessor; |
@@ -38,6 +42,30 @@ private ElasticConnection(BulkProcessor processor, RestHighLevelClient restHighL |
38 | 42 | this.restClientBuilder = restClient; |
39 | 43 | } |
40 | 44 |
|
| 45 | + private static class ESCredentials{ |
| 46 | + private final String username; |
| 47 | + private final String password; |
| 48 | + private final CredentialsProvider credentialsProvider; |
| 49 | + public ESCredentials(){ |
| 50 | + this.username = System.getenv("ES_USERNAME"); |
| 51 | + this.password = System.getenv("ES_PASSWORD"); |
| 52 | + this.credentialsProvider = new BasicCredentialsProvider(); |
| 53 | + } |
| 54 | + |
| 55 | + public boolean hasCredentials(){ |
| 56 | + return this.username != null && this.password != null; |
| 57 | + } |
| 58 | + |
| 59 | + public CredentialsProvider getCredentials(){ |
| 60 | + this.credentialsProvider.setCredentials( |
| 61 | + AuthScope.ANY, |
| 62 | + new UsernamePasswordCredentials(this.username, this.password) |
| 63 | + ); |
| 64 | + |
| 65 | + return this.credentialsProvider; |
| 66 | + } |
| 67 | + } |
| 68 | + |
41 | 69 | public static Builder builder() { |
42 | 70 | return new Builder(); |
43 | 71 | } |
@@ -109,8 +137,13 @@ private static ElasticConnection getConnection(String hostname, int restPort, St |
109 | 137 | System.setProperty("es.set.netty.runtime.available.processors", "false"); |
110 | 138 |
|
111 | 139 | TimeValue flushInterval = TimeValue.parseTimeValue(flushIntervalString, TimeValue.timeValueSeconds(5), "flush"); |
112 | | - |
| 140 | + ESCredentials credentials = new ESCredentials(); |
113 | 141 | RestClientBuilder restClient = RestClient.builder(new HttpHost(hostname, restPort, restScheme)); |
| 142 | + if(credentials.hasCredentials()) { |
| 143 | + LOG.info("Found credentials. Applying"); |
| 144 | + restClient.setHttpClientConfigCallback(b -> b.setDefaultCredentialsProvider(credentials.getCredentials())); |
| 145 | + } |
| 146 | + |
114 | 147 | RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClient); |
115 | 148 |
|
116 | 149 | BulkProcessor bulkProcessor = BulkProcessor.builder(restHighLevelClient::bulkAsync, listener) |
|
0 commit comments