AsyncHttpClient to push Json in ElasticSearch with authentication
static AsyncHttpClient asyncHttpClient;
static Realm realm;
final static String ES_URL = "http://localhost:9200/";
final static String ES_INDEX = "indexName";
final static String AUTH_LOGIN = "someLogin";
final static String AUTH_PWD = "s0m3P-@ssw0rd!";
final static int REQ_TIMEOUT_MS = 2000;
final static int MAX_CON_PER_HOST = 10;
final static int MAX_CON_TOTAL = 100;
public void init() {
AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder();
builder.setRequestTimeoutInMs(2000);
builder.setMaximumConnectionsPerHost(10);
builder.setMaximumConnectionsTotal(100);
asyncHttpClient = new AsyncHttpClient(builder.build());
realm = new Realm.RealmBuilder().setPrincipal(AUTH_LOGIN) //
.setPassword(AUTH_PWD) //
.setUsePreemptiveAuth(true) //
.setScheme(AuthScheme.BASIC).build();
}
public void put(Stuff stuff) {
String id = stuff.getUniqueId();
String type = stuff.getClass().getSimpleName().toLowerCase();
String urlToIndex = ES_URL + "/" + ES_INDEX + "/" + type + "/" + id;
byte[] json = stuff.toJsonByteArray(); // use org.codehaus.jackson.map.ObjectMapper
Future<Response> future = asyncHttpClient.preparePut(urlToIndex)
.addHeader("Content-Type", "application/json") //
.addHeader("Content-Length", "" + json.length) //
.setBody(json) //
.setRealm(realm).execute();
int statusCode = future.get().getStatusCode();
if (statusCode != 201 && statusCode != 200) {
// ...
}
}