本文整理汇总了Java中org.apache.http.nio.entity.NStringEntity类的典型用法代码示例。如果您正苦于以下问题:Java NStringEntity类的具体用法?Java NStringEntity怎么用?Java NStringEntity使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
NStringEntity类属于org.apache.http.nio.entity包,在下文中一共展示了NStringEntity类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: bulkIndexMember
import org.apache.http.nio.entity.NStringEntity; //导入依赖的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());
}
}
示例2: bulkIndex
import org.apache.http.nio.entity.NStringEntity; //导入依赖的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);
}
}
示例3: doActivate
import org.apache.http.nio.entity.NStringEntity; //导入依赖的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");
}
示例4: search
import org.apache.http.nio.entity.NStringEntity; //导入依赖的package包/类
public String search(String q) throws IOException {
HttpEntity entity1 = new NStringEntity(
"{\n" +
" \"query\" : {\n" +
" \"match\": { \"dc\":\""+q+"\"} \n" +
"}, \n"+
" \"sort\" : [\n" +
" {\"title.keyword\": { \"order\":\"desc\"}} \n" +
"], \n"+
"\"_source\":\"title\""+
"}"
, ContentType.APPLICATION_JSON);
Response response = restClient.performRequest("GET", "/harvester/_search", Collections.singletonMap("pretty", "true"),
entity1);
String result = ( EntityUtils.toString(response.getEntity()));
System.out.println(result);
return "<pre>"+result+"</pre>"; //pre tag for json, otherwise it didnt show pretty in browser
}
示例5: advance
import org.apache.http.nio.entity.NStringEntity; //导入依赖的package包/类
@Override
public boolean advance() throws IOException {
if (batchIterator.hasNext()) {
current = batchIterator.next();
return true;
} else {
String requestBody =
String.format(
"{\"scroll\" : \"%s\",\"scroll_id\" : \"%s\"}",
source.spec.getScrollKeepalive(), scrollId);
HttpEntity scrollEntity = new NStringEntity(requestBody, ContentType.APPLICATION_JSON);
Response response =
restClient.performRequest(
"GET",
"/_search/scroll",
Collections.<String, String>emptyMap(),
scrollEntity);
JsonNode searchResult = parseResponse(response);
updateScrollId(searchResult);
return readNextBatchAndReturnFirstDocument(searchResult);
}
}
示例6: close
import org.apache.http.nio.entity.NStringEntity; //导入依赖的package包/类
@Override
public void close() throws IOException {
// remove the scroll
String requestBody = String.format("{\"scroll_id\" : [\"%s\"]}", scrollId);
HttpEntity entity = new NStringEntity(requestBody, ContentType.APPLICATION_JSON);
try {
restClient.performRequest(
"DELETE",
"/_search/scroll",
Collections.<String, String>emptyMap(),
entity);
} finally {
if (restClient != null) {
restClient.close();
}
}
}
示例7: flushBatch
import org.apache.http.nio.entity.NStringEntity; //导入依赖的package包/类
private void flushBatch() throws IOException {
if (batch.isEmpty()) {
return;
}
StringBuilder bulkRequest = new StringBuilder();
for (String json : batch) {
bulkRequest.append(json);
}
batch.clear();
currentBatchSizeBytes = 0;
Response response;
String endPoint =
String.format(
"/%s/%s/_bulk",
spec.getConnectionConfiguration().getIndex(),
spec.getConnectionConfiguration().getType());
HttpEntity requestBody =
new NStringEntity(bulkRequest.toString(), ContentType.APPLICATION_JSON);
response =
restClient.performRequest(
"POST",
endPoint,
Collections.<String, String>emptyMap(),
requestBody);
checkForErrors(response, backendVersion);
}
示例8: insertTestDocuments
import org.apache.http.nio.entity.NStringEntity; //导入依赖的package包/类
/** Inserts the given number of test documents into Elasticsearch. */
static void insertTestDocuments(ConnectionConfiguration connectionConfiguration,
long numDocs, RestClient restClient) throws IOException {
List<String> data =
ElasticSearchIOTestUtils.createDocuments(
numDocs, ElasticSearchIOTestUtils.InjectionMode.DO_NOT_INJECT_INVALID_DOCS);
StringBuilder bulkRequest = new StringBuilder();
int i = 0;
for (String document : data) {
bulkRequest.append(String.format(
"{ \"index\" : { \"_index\" : \"%s\", \"_type\" : \"%s\", \"_id\" : \"%s\" } }%n%s%n",
connectionConfiguration.getIndex(), connectionConfiguration.getType(), i++, document));
}
String endPoint = String.format("/%s/%s/_bulk", connectionConfiguration.getIndex(),
connectionConfiguration.getType());
HttpEntity requestBody =
new NStringEntity(bulkRequest.toString(), ContentType.APPLICATION_JSON);
Response response = restClient.performRequest("POST", endPoint,
Collections.singletonMap("refresh", "true"), requestBody);
ElasticsearchIO
.checkForErrors(response, ElasticsearchIO.getBackendVersion(connectionConfiguration));
}
示例9: failed
import org.apache.http.nio.entity.NStringEntity; //导入依赖的package包/类
public void failed(final Exception ex) {
synchronized (this.httpExchange) {
if (this.completed) {
return;
}
this.completed = true;
this.httpExchange.setException(ex);
HttpAsyncExchange responseTrigger = this.httpExchange.getResponseTrigger();
if (responseTrigger != null && !responseTrigger.isCompleted()) {
System.out.println("[client<-proxy] " + this.httpExchange.getId() + " " + ex);
ConsoleFactory.printToConsole("[client<-proxy] " + this.httpExchange.getId() + " " + ex,true);
int status = HttpStatus.SC_INTERNAL_SERVER_ERROR;
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, status,
EnglishReasonPhraseCatalog.INSTANCE.getReason(status, Locale.US));
String message = ex.getMessage();
if (message == null) {
message = "Unexpected error";
}
response.setEntity(new NStringEntity(message, ContentType.DEFAULT_TEXT));
responseTrigger.submitResponse(new BasicAsyncResponseProducer(response));
}
}
}
示例10: execute
import org.apache.http.nio.entity.NStringEntity; //导入依赖的package包/类
/**
*
* @param targetClass
* @param path
* @param params
* @return
*/
public <T>Result<T> execute(Class<T> targetClass,
String path, Object params) {
HttpPost post = new HttpPost(getContext().getApiUrl(path));
String data = convertParamsToJson(params);
NStringEntity entity = new NStringEntity(data, ContentType.APPLICATION_JSON);
post.setEntity(entity);
Result<T> result = null;
try (CloseableHttpResponse response = httpClient.execute(post)) {
InputStream in = response.getEntity().getContent();
if (response.getStatusLine().getStatusCode() == 200) {
result = new Result<>(context.getObjectMapper()
.readValue(in, targetClass));
} else {
result = new Result<>(context.getObjectMapper()
.readValue(in, ErrorInfo.class));
}
} catch (IOException e) {
throw new IORuntimeException(e);
}
return result;
}
示例11: indexMember
import org.apache.http.nio.entity.NStringEntity; //导入依赖的package包/类
private void indexMember(String sellerId, Object mem) throws IOException {
if (sellerId == null)
sellerId = "";
long startTime = System.currentTimeMillis();
RestClient client = Plugin.client;
String json = Gson.toJson(mem);
HttpEntity entity = new NStringEntity(json, ContentType.APPLICATION_JSON);
String path = "/weike/member";
if (!"".equals(sellerId)) {
path += "?routing=" + sellerId;
}
Response indexResponse = client.performRequest("POST", path, Collections.<String, String>emptyMap(), entity);
if (LOG.isDebugEnabled()) {
LOG.debug("indexMember {}ms", System.currentTimeMillis() - startTime);
LOG.debug("indexResponse {}", indexResponse.toString());
}
}
示例12: testSearch
import org.apache.http.nio.entity.NStringEntity; //导入依赖的package包/类
@Test
@Ignore
public void testSearch() throws Exception {
// JsonObject json = new JsonObject();
// json.addProperty("from", "0");
// json.addProperty("size", "10");
// json.addProperty("explain", true);
// JsonObject query = new JsonObject();
// query.add
// json.add("query", query);
String json = "{\"explain\":false,\"from\":0,\"size\":1,\"query\":{\"range\":{\"tradeAmount\":{\"gte\":10,\"lte\":2000}}}}";
long startTime = System.currentTimeMillis();
HttpEntity entity = new NStringEntity(json, ContentType.APPLICATION_JSON);
Response response = client.performRequest("GET", "/weike/member/_search", Collections.singletonMap("pretty", "true"), entity);
LOG.info("search-{} {}ms", EntityUtils.toString(response.getEntity()), System.currentTimeMillis() - startTime);
}
示例13: createLoginRequest
import org.apache.http.nio.entity.NStringEntity; //导入依赖的package包/类
/**
* Creates a {@link EntityRequest} that can be used to authenticate the user against the server.
* @param store The {@link Store} this request should be executed against.
* @return A request that can be used to authenticate the user.
*/
public EntityRequest createLoginRequest(final Store store) {
final EntityRequest request = new EntityRequest(
Method.POST,
this.getUrl(store, URL_AUTH_LOGIN));
final JsonObject credentials = new JsonObject();
credentials.addProperty("userName", store.getUsername());
credentials.addProperty("password", store.getPassword());
final NStringEntity entity = new NStringEntity(credentials.toString(), CHARSET);
request.setEntity(entity);
request.setHeader(Headers.CONTENT_TYPE, APPLICATION_JSON);
return request;
}
示例14: doPost
import org.apache.http.nio.entity.NStringEntity; //导入依赖的package包/类
public String doPost(String url, String data, String charset) {
if (StringUtils.isBlank(url)) {
return null;
}
log.info(" post url=" + url);
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new NStringEntity(data, charset));
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, charset);
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (Exception e) {
log.error("to request addr=" + url + ", " + e.getMessage());
e.printStackTrace();
}
return null;
}
示例15: search
import org.apache.http.nio.entity.NStringEntity; //导入依赖的package包/类
@Override
public boolean search(String source) {
HttpEntity searchBody = new NStringEntity(source, StandardCharsets.UTF_8);
try {
Response response = client.performRequest("GET", endpoint, Collections.emptyMap(), searchBody);
return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
} catch (IOException e) {
throw new ElasticsearchException(e);
}
}