本文整理汇总了Java中org.elasticsearch.client.Response类的典型用法代码示例。如果您正苦于以下问题:Java Response类的具体用法?Java Response怎么用?Java Response使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Response类属于org.elasticsearch.client包,在下文中一共展示了Response类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: ClientYamlTestResponse
import org.elasticsearch.client.Response; //导入依赖的package包/类
ClientYamlTestResponse(Response response) throws IOException {
this.response = response;
if (response.getEntity() != null) {
String contentType = response.getHeader("Content-Type");
this.bodyContentType = XContentType.fromMediaTypeOrFormat(contentType);
try {
byte[] bytes = EntityUtils.toByteArray(response.getEntity());
//skip parsing if we got text back (e.g. if we called _cat apis)
if (bodyContentType != null) {
this.parsedResponse = ObjectPath.createFromXContent(bodyContentType.xContent(), new BytesArray(bytes));
}
this.body = bytes;
} catch (IOException e) {
EntityUtils.consumeQuietly(response.getEntity());
throw e;
}
} else {
this.body = null;
this.bodyContentType = null;
}
}
示例2: createIndex
import org.elasticsearch.client.Response; //导入依赖的package包/类
/**
* Creates the specified index in ElasticSearch
*
* @param indexName
* the index name to augment
* @param typeName
* the type name to augment
* @param id
* the id of the document to add
* @param jsonDocument
* the String JSON document to add
*/
protected static void createIndex(String indexName) {
try {
// Create our expand / search indices
String endpoint = String.format("/%s", indexName);
Map<String, String> params = new HashMap<String, String>();
StringEntity requestBody = new StringEntity(INDEX_JSON);
Response resp = client.performRequest("PUT", endpoint, params, requestBody, contentTypeHeader);
staticLogger.debug("Response: " + resp.getStatusLine());
} catch (IOException e) {
// Ignore this...? probably already exists
staticLogger.error(e.getMessage(), e);
if (e instanceof UnsupportedEncodingException) {
staticLogger.error("Error encoding JSON: " + e.getMessage(), e);
return;
}
}
}
示例3: addDocument
import org.elasticsearch.client.Response; //导入依赖的package包/类
/**
* Adds a document to the specified ElasticSearch index / type
*
* @param indexName
* the index name to augment
* @param typeName
* the type name to augment
* @param id
* the id of the document to add
* @param jsonDocument
* the String JSON document to add
*/
protected static void addDocument(String indexName, String typeName, Integer id, String jsonDocument) {
try {
String documentEndpoint = String.format("/%s/%s/%d", indexName, typeName, id);
StringEntity requestBody = new StringEntity(jsonDocument);
Map<String, String> params = new HashMap<String, String>();
Response resp = client.performRequest("PUT", documentEndpoint, params, requestBody, contentTypeHeader);
staticLogger.debug("Response: " + resp.getStatusLine());
} catch (IOException e) {
// Ignore this...? probably already exists
staticLogger.error(e.getMessage(), e);
if (e instanceof UnsupportedEncodingException) {
staticLogger.error("Error encoding JSON: " + e.getMessage(), e);
return;
}
}
}
示例4: bulkIndexMember
import org.elasticsearch.client.Response; //导入依赖的package包/类
private void bulkIndexMember(List<?> memList) throws Exception {
StringBuilder buf = new StringBuilder(1024);
for (Object mem : memList) {
buf.append("{\"index\": {}}");
buf.append("\n");
buf.append(Gson.toJson(mem));
buf.append("\n");
}
long startTime = System.currentTimeMillis();
RestClient client = Plugin.client;
HttpEntity entity = new NStringEntity(buf.toString(), ContentType.APPLICATION_JSON);
Response indexResponse = client.performRequest("POST", "/weike/member/_bulk",
Collections.<String, String>emptyMap(), entity);
if (LOG.isDebugEnabled()) {
LOG.debug("indexMember {}ms", System.currentTimeMillis() - startTime);
LOG.debug("indexResponse {}", indexResponse.toString());
}
}
示例5: start
import org.elasticsearch.client.Response; //导入依赖的package包/类
private ActionFuture<String> start(String method, String path, HttpEntity body) {
PlainActionFuture<String> future = new PlainActionFuture<>();
Map<String, String> params = new HashMap<>();
params.put("refresh", "wait_for");
params.put("error_trace", "");
client().performRequestAsync(method, docPath() + path, params, body, new ResponseListener() {
@Override
public void onSuccess(Response response) {
try {
future.onResponse(EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));
} catch (IOException e) {
future.onFailure(e);
}
}
@Override
public void onFailure(Exception exception) {
future.onFailure(exception);
}
});
return future;
}
示例6: bulkIndex
import org.elasticsearch.client.Response; //导入依赖的package包/类
@Override
public boolean bulkIndex(List<String> bulkData) {
StringBuilder bulkRequestBody = new StringBuilder();
for (String bulkItem : bulkData) {
bulkRequestBody.append(actionMetaData);
bulkRequestBody.append(bulkItem);
bulkRequestBody.append("\n");
}
HttpEntity entity = new NStringEntity(bulkRequestBody.toString(), ContentType.APPLICATION_JSON);
try {
Response response = client.performRequest("POST", "/geonames/type/_noop_bulk", Collections.emptyMap(), entity);
return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
} catch (Exception e) {
throw new ElasticsearchException(e);
}
}
示例7: buildShards
import org.elasticsearch.client.Response; //导入依赖的package包/类
private List<Shard> buildShards(Nodes nodes, RestClient client) throws IOException {
Response response = client.performRequest("GET", "test/_stats", singletonMap("level", "shards"));
List<Object> shardStats = ObjectPath.createFromResponse(response).evaluate("indices.test.shards.0");
ArrayList<Shard> shards = new ArrayList<>();
for (Object shard : shardStats) {
final String nodeId = ObjectPath.evaluate(shard, "routing.node");
final Boolean primary = ObjectPath.evaluate(shard, "routing.primary");
final Node node = nodes.getSafe(nodeId);
final SeqNoStats seqNoStats;
if (node.getVersion().onOrAfter(Version.V_6_0_0_alpha1_UNRELEASED)) {
Integer maxSeqNo = ObjectPath.evaluate(shard, "seq_no.max_seq_no");
Integer localCheckpoint = ObjectPath.evaluate(shard, "seq_no.local_checkpoint");
Integer globalCheckpoint = ObjectPath.evaluate(shard, "seq_no.global_checkpoint");
seqNoStats = new SeqNoStats(maxSeqNo, localCheckpoint, globalCheckpoint);
} else {
seqNoStats = null;
}
shards.add(new Shard(node, primary, seqNoStats));
}
return shards;
}
示例8: buildNodeAndVersions
import org.elasticsearch.client.Response; //导入依赖的package包/类
private Nodes buildNodeAndVersions() throws IOException {
Response response = client().performRequest("GET", "_nodes");
ObjectPath objectPath = ObjectPath.createFromResponse(response);
Map<String, Object> nodesAsMap = objectPath.evaluate("nodes");
Nodes nodes = new Nodes();
for (String id : nodesAsMap.keySet()) {
nodes.add(new Node(
id,
objectPath.evaluate("nodes." + id + ".name"),
Version.fromString(objectPath.evaluate("nodes." + id + ".version")),
HttpHost.create(objectPath.evaluate("nodes." + id + ".http.publish_address"))));
}
response = client().performRequest("GET", "_cluster/state");
nodes.setMasterNodeId(ObjectPath.createFromResponse(response).evaluate("master_node"));
return nodes;
}
示例9: createFromResponse
import org.elasticsearch.client.Response; //导入依赖的package包/类
public static ObjectPath createFromResponse(Response response) throws IOException {
byte[] bytes = EntityUtils.toByteArray(response.getEntity());
String contentType = response.getHeader("Content-Type");
XContentType xContentType = XContentType.fromMediaTypeOrFormat(contentType);
return ObjectPath.createFromXContent(xContentType.xContent(), new BytesArray(bytes));
}
示例10: readVersionsFromInfo
import org.elasticsearch.client.Response; //导入依赖的package包/类
private static Version readVersionsFromInfo(RestClient restClient, int numHosts) throws IOException {
Version version = null;
for (int i = 0; i < numHosts; i++) {
//we don't really use the urls here, we rely on the client doing round-robin to touch all the nodes in the cluster
Response response = restClient.performRequest("GET", "/");
ClientYamlTestResponse restTestResponse = new ClientYamlTestResponse(response);
Object latestVersion = restTestResponse.evaluate("version.number");
if (latestVersion == null) {
throw new RuntimeException("elasticsearch version not found in the response");
}
final Version currentVersion = Version.fromString(latestVersion.toString());
if (version == null) {
version = currentVersion;
} else if (version.onOrAfter(currentVersion)) {
version = currentVersion;
}
}
return version;
}
示例11: findIndex
import org.elasticsearch.client.Response; //导入依赖的package包/类
/**
* Probably there is a better way to get the index name with the alias.
* If there is no such index, than null is returned.
* @param aliasName
* @return
*/
public String findIndex(String aliasName) {
String indexName = null;
try {
Response response = this.restClient.performRequest("HEAD", aliasName);
if (response.getStatusLine().getStatusCode() != 404) {
// Index with aliasName exists, so we need to get real index name from settings
response = this.restClient.performRequest("GET", aliasName.concat("/_settings"));
// JSONObject json = new JSONObject(EntityUtils.toString(response.getEntity()));
// indexName = json.keySet().stream().findFirst().orElse("");
}
} catch (IOException e) {
LOG.debug("OK. No index with a given alias exists.");
}
return indexName;
}
示例12: createIndex
import org.elasticsearch.client.Response; //导入依赖的package包/类
private void createIndex() {
Response response;
try (InputStream payload = FactSearchManager.class.getClassLoader().getResourceAsStream(MAPPINGS_JSON)) {
// Need to use low-level client here because the Index API is not yet supported by the high-level client.
HttpEntity body = new InputStreamEntity(payload, ContentType.APPLICATION_JSON);
response = clientFactory.getLowLevelClient().performRequest("PUT", INDEX_NAME, Collections.emptyMap(), body);
} catch (IOException ex) {
throw logAndExit(ex, "Could not perform request to create index.");
}
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
String msg = String.format("Could not create index '%s'.", INDEX_NAME);
LOGGER.error(msg);
throw new IllegalStateException(msg);
}
LOGGER.info("Successfully created index '%s'.", INDEX_NAME);
}
示例13: testPluginIsLoaded
import org.elasticsearch.client.Response; //导入依赖的package包/类
@Test
@SuppressWarnings("unchecked")
public void testPluginIsLoaded() throws Exception {
Response response = client.performRequest("GET", "/_nodes/plugins");
Map<String, Object> nodes = (Map<String, Object>) entityAsMap(response).get("nodes");
for (String nodeName : nodes.keySet()) {
boolean pluginFound = false;
Map<String, Object> node = (Map<String, Object>) nodes.get(nodeName);
List<Map<String, Object>> plugins = (List<Map<String, Object>>) node.get("plugins");
for (Map<String, Object> plugin : plugins) {
String pluginName = (String) plugin.get("name");
if (pluginName.equals("rocchio")) {
pluginFound = true;
break;
}
}
assertThat(pluginFound, is(true));
}
}
示例14: doDeactivate
import org.elasticsearch.client.Response; //导入依赖的package包/类
private ReplicationResult doDeactivate(TransportContext ctx, ReplicationTransaction tx, RestClient restClient) throws ReplicationException, JSONException, IOException {
ReplicationLog log = tx.getLog();
ObjectMapper mapper = new ObjectMapper();
IndexEntry content = mapper.readValue(tx.getContent().getInputStream(), IndexEntry.class);
Response deleteResponse = restClient.performRequest(
"DELETE",
"/" + content.getIndex() + "/" + content.getType() + "/" + DigestUtils.md5Hex(content.getPath()),
Collections.<String, String>emptyMap());
LOG.debug(deleteResponse.toString());
log.info(getClass().getSimpleName() + ": Delete Call returned " + deleteResponse.getStatusLine().getStatusCode() + ": " + deleteResponse.getStatusLine().getReasonPhrase());
if (deleteResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED || deleteResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return ReplicationResult.OK;
}
LOG.error("Could not delete " + content.getType() + " at " + content.getPath());
return new ReplicationResult(false, 0, "Replication failed");
}
示例15: doActivate
import org.elasticsearch.client.Response; //导入依赖的package包/类
/**
* Perform the replication. All logic is covered in {@link ElasticSearchIndexContentBuilder} so we only need to transmit the JSON to ElasticSearch
*
* @param ctx
* @param tx
* @param restClient
* @return
* @throws ReplicationException
*/
private ReplicationResult doActivate(TransportContext ctx, ReplicationTransaction tx, RestClient restClient) throws ReplicationException, JSONException, IOException {
ReplicationLog log = tx.getLog();
ObjectMapper mapper = new ObjectMapper();
IndexEntry content = mapper.readValue(tx.getContent().getInputStream(), IndexEntry.class);
if (content != null) {
log.info(getClass().getSimpleName() + ": Indexing " + content.getPath());
String contentString = mapper.writeValueAsString(content.getContent());
log.debug(getClass().getSimpleName() + ": Index-Content: " + contentString);
LOG.debug("Index-Content: " + contentString);
HttpEntity entity = new NStringEntity(contentString, "UTF-8");
Response indexResponse = restClient.performRequest(
"PUT",
"/" + content.getIndex() + "/" + content.getType() + "/" + DigestUtils.md5Hex(content.getPath()),
Collections.<String, String>emptyMap(),
entity);
LOG.debug(indexResponse.toString());
log.info(getClass().getSimpleName() + ": " + indexResponse.getStatusLine().getStatusCode() + ": " + indexResponse.getStatusLine().getReasonPhrase());
if (indexResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED || indexResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return ReplicationResult.OK;
}
}
LOG.error("Could not replicate");
return new ReplicationResult(false, 0, "Replication failed");
}