Created
May 31, 2013 13:01
-
-
Save thbkrkr/5684830 to your computer and use it in GitHub Desktop.
AsyncHttpClient to push Json in ElasticSearch with authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) { | |
// ... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment