List of usage examples for org.apache.http.nio.entity NStringEntity NStringEntity
public NStringEntity(final String s, String charset) throws UnsupportedEncodingException
From source file:org.kitodo.data.elasticsearch.index.type.TaskType.java
@SuppressWarnings("unchecked") @Override//w ww . j av a 2s . co m public HttpEntity createDocument(Task task) { JSONObject taskObject = new JSONObject(); taskObject.put("title", task.getTitle()); taskObject.put("priority", task.getPriority()); taskObject.put("ordering", task.getOrdering()); Integer processingStatus = task.getProcessingStatusEnum() != null ? task.getProcessingStatusEnum().getValue() : null; taskObject.put("processingStatus", processingStatus); String processingTime = task.getProcessingTime() != null ? formatDate(task.getProcessingTime()) : null; taskObject.put("processingTime", processingTime); String processingBegin = task.getProcessingBegin() != null ? formatDate(task.getProcessingBegin()) : null; taskObject.put("processingBegin", processingBegin); String processingEnd = task.getProcessingEnd() != null ? formatDate(task.getProcessingEnd()) : null; taskObject.put("processingEnd", processingEnd); taskObject.put("homeDirectory", String.valueOf(task.getHomeDirectory())); taskObject.put("typeMetadata", String.valueOf(task.isTypeMetadata())); taskObject.put("typeAutomatic", String.valueOf(task.isTypeAutomatic())); taskObject.put("typeImportFileUpload", String.valueOf(task.isTypeImportFileUpload())); taskObject.put("typeExportRussian", String.valueOf(task.isTypeExportRussian())); taskObject.put("typeImagesRead", String.valueOf(task.isTypeImagesRead())); taskObject.put("typeImagesWrite", String.valueOf(task.isTypeImagesWrite())); taskObject.put("typeModuleName", task.getTypeModuleName()); taskObject.put("batchStep", String.valueOf(task.isBatchStep())); Integer processingUser = task.getProcessingUser() != null ? task.getProcessingUser().getId() : null; taskObject.put("processingUser", processingUser); Integer process = task.getProcess() != null ? task.getProcess().getId() : null; taskObject.put("process", process); taskObject.put("users", addObjectRelation(task.getUsers())); taskObject.put("userGroups", addObjectRelation(task.getUserGroups())); return new NStringEntity(taskObject.toJSONString(), ContentType.APPLICATION_JSON); }
From source file:marytts.tools.perceptiontest.PerceptionRequestHandler.java
@Override protected void handleClientRequest(String absPath, Map<String, String> queryItems, HttpResponse response, Address serverAddressAtClient) throws IOException { Set<String> keySet = queryItems.keySet(); if (absPath.equals("/perceptionTest") && keySet.size() > 0) { String infoResponse = null; if (keySet.size() == 1 && keySet.contains("EMAIL")) { infoResponse = getCaseOneInfoResponse(queryItems); } else if (keySet.size() > 1 && keySet.contains("EMAIL") && keySet.contains("RESULTS") && keySet.contains("PRESENT_SAMPLE_BASENAME") && keySet.contains("PRESENT_SAMPLE_NUMBER")) { infoResponse = storeUserRatings(queryItems); } else if (keySet.size() > 1 && keySet.contains("EMAIL") && keySet.contains("PRESENT_SAMPLE_NUMBER")) { infoResponse = getCaseTwoInfoResponse(queryItems); }/*from w ww .j a v a 2s. c o m*/ if (infoResponse == null) { // error condition, handleInfoRequest has set an error message return; } response.setStatusCode(HttpStatus.SC_OK); try { NStringEntity entity = new NStringEntity(infoResponse, "UTF-8"); entity.setContentType("text/plain; charset=UTF-8"); response.setEntity(entity); } catch (UnsupportedEncodingException e) { } } }
From source file:org.elasticsearch.test.NativeRealmIntegTestCase.java
public void setupReservedPasswords(RestClient restClient) throws IOException { logger.info("setting up reserved passwords for test"); {/*from w w w . j av a 2s. com*/ String payload = "{\"password\": \"" + new String(reservedPassword.getChars()) + "\"}"; HttpEntity entity = new NStringEntity(payload, ContentType.APPLICATION_JSON); BasicHeader authHeader = new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(ElasticUser.NAME, BOOTSTRAP_PASSWORD)); String route = "/_xpack/security/user/elastic/_password"; Response response = restClient.performRequest("PUT", route, Collections.emptyMap(), entity, authHeader); assertEquals(response.getStatusLine().getReasonPhrase(), 200, response.getStatusLine().getStatusCode()); } for (String username : Arrays.asList(KibanaUser.NAME, LogstashSystemUser.NAME, BeatsSystemUser.NAME)) { String payload = "{\"password\": \"" + new String(reservedPassword.getChars()) + "\"}"; HttpEntity entity = new NStringEntity(payload, ContentType.APPLICATION_JSON); BasicHeader authHeader = new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(ElasticUser.NAME, reservedPassword)); String route = "/_xpack/security/user/" + username + "/_password"; Response response = restClient.performRequest("PUT", route, Collections.emptyMap(), entity, authHeader); assertEquals(response.getStatusLine().getReasonPhrase(), 200, response.getStatusLine().getStatusCode()); } logger.info("setting up reserved passwords finished"); }
From source file:org.apache.beam.sdk.io.elasticsearch.ElasticSearchIOTestUtils.java
/** 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;/* w w w . j a v a2 s . com*/ 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)); }
From source file:org.elasticsearch.client.RequestLoggerTests.java
public void testTraceRequest() throws IOException, URISyntaxException { HttpHost host = new HttpHost("localhost", 9200, randomBoolean() ? "http" : "https"); String expectedEndpoint = "/index/type/_api"; URI uri;/* ww w .ja v a 2s. c o m*/ if (randomBoolean()) { uri = new URI(expectedEndpoint); } else { uri = new URI("index/type/_api"); } HttpUriRequest request = randomHttpRequest(uri); String expected = "curl -iX " + request.getMethod() + " '" + host + expectedEndpoint + "'"; boolean hasBody = request instanceof HttpEntityEnclosingRequest && randomBoolean(); String requestBody = "{ \"field\": \"value\" }"; if (hasBody) { expected += " -d '" + requestBody + "'"; HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request; HttpEntity entity; switch (randomIntBetween(0, 4)) { case 0: entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); break; case 1: entity = new InputStreamEntity( new ByteArrayInputStream(requestBody.getBytes(StandardCharsets.UTF_8)), ContentType.APPLICATION_JSON); break; case 2: entity = new NStringEntity(requestBody, ContentType.APPLICATION_JSON); break; case 3: entity = new NByteArrayEntity(requestBody.getBytes(StandardCharsets.UTF_8), ContentType.APPLICATION_JSON); break; case 4: // Evil entity without a charset entity = new StringEntity(requestBody, ContentType.create("application/json", (Charset) null)); break; default: throw new UnsupportedOperationException(); } enclosingRequest.setEntity(entity); } String traceRequest = RequestLogger.buildTraceRequest(request, host); assertThat(traceRequest, equalTo(expected)); if (hasBody) { //check that the body is still readable as most entities are not repeatable String body = EntityUtils.toString(((HttpEntityEnclosingRequest) request).getEntity(), StandardCharsets.UTF_8); assertThat(body, equalTo(requestBody)); } }
From source file:org.kitodo.data.index.elasticsearch.type.ProjectType.java
@SuppressWarnings("unchecked") @Override//from ww w . ja v a 2 s .co m public HttpEntity createDocument(Project project) { LinkedHashMap<String, String> orderedProjectMap = new LinkedHashMap<>(); orderedProjectMap.put("name", project.getTitle()); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String startDate = project.getStartDate() != null ? dateFormat.format(project.getStartDate()) : null; orderedProjectMap.put("startDate", startDate); String endDate = project.getEndDate() != null ? dateFormat.format(project.getEndDate()) : null; orderedProjectMap.put("endDate", endDate); String numberOfPages = project.getNumberOfPages() != null ? project.getNumberOfPages().toString() : "null"; orderedProjectMap.put("numberOfPages", numberOfPages); String numberOfVolumes = project.getNumberOfVolumes() != null ? project.getNumberOfVolumes().toString() : "null"; orderedProjectMap.put("numberOfVolumes", numberOfVolumes); String archived = project.getProjectIsArchived() != null ? project.getProjectIsArchived().toString() : "null"; orderedProjectMap.put("archived", archived); JSONObject projectObject = new JSONObject(orderedProjectMap); JSONArray processes = new JSONArray(); List<Process> projectProcesses = project.getProcesses(); for (Process process : projectProcesses) { JSONObject processObject = new JSONObject(); processObject.put("id", process.getId().toString()); processes.add(processObject); } projectObject.put("processes", processes); JSONArray users = new JSONArray(); List<User> projectUsers = project.getUsers(); for (User user : projectUsers) { JSONObject userObject = new JSONObject(); userObject.put("id", user.getId().toString()); users.add(userObject); } projectObject.put("users", users); JSONArray projectFileGroups = new JSONArray(); List<ProjectFileGroup> projectProjectFileGroups = project.getProjectFileGroups(); for (ProjectFileGroup projectFileGroup : projectProjectFileGroups) { JSONObject projectFileGroupObject = new JSONObject(); projectFileGroupObject.put("name", projectFileGroup.getName()); projectFileGroupObject.put("path", projectFileGroup.getPath()); projectFileGroupObject.put("mimeType", projectFileGroup.getMimeType()); projectFileGroupObject.put("suffix", projectFileGroup.getSuffix()); projectFileGroupObject.put("folder", projectFileGroup.getFolder()); projectFileGroups.add(projectFileGroupObject); } projectObject.put("projectFileGroups", projectFileGroups); return new NStringEntity(projectObject.toJSONString(), ContentType.APPLICATION_JSON); }
From source file:dataprocessing.elasticsearch.ElasticSearchClient.java
/** *************************************************************** * @param corpus Corpus line is from//from w w w .j ava 2s .c o m * @param line Line number in corpus * @param text line text * Indexes line from corpus * * Mapping for chatbot/dialog: PUT chatbot { "mappings": { "dialog": { "properties": { "corpus": { "type": "string", "index": "not_analyzed" }, "file": { "type": "string", "index": "not_analyzed" }, "line": { "type": "long", "index": "not_analyzed" }, "text": { "type": "string", "index": "analyzed", "analyzer": "english" } } } } } */ public void indexDocument(String corpus, String file, int line, String text) { try { JSONObject entity = new JSONObject(); entity.put("corpus", corpus); entity.put("file", file); entity.put("line", line); entity.put("text", text); // Post JSON entity client.performRequest("POST", String.format("/%s/%s/%s", index, type, corpus + "_" + file + "_" + line), Collections.emptyMap(), new NStringEntity(entity.toString(), ContentType.APPLICATION_JSON), header); } catch (IOException e) { e.printStackTrace(); } }
From source file:io.opentracing.contrib.elasticsearch5.TracingTest.java
@Test public void restClient() throws Exception { RestClient restClient = RestClient.builder(new HttpHost("localhost", HTTP_PORT, "http")) .setHttpClientConfigCallback(new TracingHttpClientConfigCallback(mockTracer)).build(); HttpEntity entity = new NStringEntity( "{\n" + " \"user\" : \"kimchy\",\n" + " \"post_date\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elasticsearch\"\n" + "}", ContentType.APPLICATION_JSON); Response indexResponse = restClient.performRequest("PUT", "/twitter/tweet/1", Collections.<String, String>emptyMap(), entity); assertNotNull(indexResponse);//from w w w . j ava 2s . com final CountDownLatch latch = new CountDownLatch(1); restClient.performRequestAsync("PUT", "/twitter/tweet/2", Collections.<String, String>emptyMap(), entity, new ResponseListener() { @Override public void onSuccess(Response response) { latch.countDown(); } @Override public void onFailure(Exception exception) { latch.countDown(); } }); latch.await(30, TimeUnit.SECONDS); restClient.close(); List<MockSpan> finishedSpans = mockTracer.finishedSpans(); assertEquals(2, finishedSpans.size()); checkSpans(finishedSpans, "PUT"); assertNull(mockTracer.activeSpan()); }
From source file:org.thingsboard.server.dao.audit.sink.ElasticsearchAuditLogSink.java
@Override public void logAction(AuditLog auditLogEntry) { String jsonContent = createElasticJsonRecord(auditLogEntry); HttpEntity entity = new NStringEntity(jsonContent, ContentType.APPLICATION_JSON); restClient.performRequestAsync(HttpMethod.POST.name(), String.format("/%s/%s", getIndexName(auditLogEntry.getTenantId()), INDEX_TYPE), Collections.emptyMap(), entity, responseListener); }
From source file:org.kitodo.data.index.elasticsearch.type.TaskType.java
@SuppressWarnings("unchecked") @Override/*from w w w . j a v a 2s .c om*/ public HttpEntity createDocument(Task task) { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); LinkedHashMap<String, String> orderedTaskMap = new LinkedHashMap<>(); orderedTaskMap.put("title", task.getTitle()); String priority = task.getPriority() != null ? task.getPriority().toString() : "null"; orderedTaskMap.put("priority", priority); String ordering = task.getOrdering() != null ? task.getOrdering().toString() : "null"; orderedTaskMap.put("ordering", ordering); String processingStatus = task.getProcessingStatusEnum() != null ? task.getProcessingStatusEnum().toString() : "null"; orderedTaskMap.put("processingStatus", processingStatus); String processingTime = task.getProcessingTime() != null ? dateFormat.format(task.getProcessingTime()) : null; orderedTaskMap.put("processingTime", processingTime); String processingBegin = task.getProcessingBegin() != null ? dateFormat.format(task.getProcessingBegin()) : null; orderedTaskMap.put("processingBegin", processingBegin); String processingEnd = task.getProcessingEnd() != null ? dateFormat.format(task.getProcessingEnd()) : null; orderedTaskMap.put("processingEnd", processingEnd); orderedTaskMap.put("homeDirectory", String.valueOf(task.getHomeDirectory())); orderedTaskMap.put("typeMetadata", String.valueOf(task.isTypeMetadata())); orderedTaskMap.put("typeAutomatic", String.valueOf(task.isTypeAutomatic())); orderedTaskMap.put("typeImportFileUpload", String.valueOf(task.isTypeImportFileUpload())); orderedTaskMap.put("typeExportRussian", String.valueOf(task.isTypeExportRussian())); orderedTaskMap.put("typeImagesRead", String.valueOf(task.isTypeImagesRead())); orderedTaskMap.put("typeImagesWrite", String.valueOf(task.isTypeImagesWrite())); orderedTaskMap.put("batchStep", String.valueOf(task.isBatchStep())); String processingUser = task.getProcessingUser() != null ? task.getProcessingUser().getId().toString() : "null"; orderedTaskMap.put("processingUser", processingUser); String process = task.getProcess() != null ? task.getProcess().getId().toString() : "null"; orderedTaskMap.put("process", process); JSONObject taskObject = new JSONObject(orderedTaskMap); JSONArray users = new JSONArray(); List<User> taskUsers = task.getUsers(); for (User user : taskUsers) { JSONObject propertyObject = new JSONObject(); propertyObject.put("id", user.getId()); users.add(propertyObject); } taskObject.put("users", users); JSONArray userGroups = new JSONArray(); List<UserGroup> taskUserGroups = task.getUserGroups(); for (UserGroup userGroup : taskUserGroups) { JSONObject userGroupObject = new JSONObject(); userGroupObject.put("id", userGroup.getId().toString()); userGroups.add(userGroupObject); } taskObject.put("userGroups", userGroups); return new NStringEntity(taskObject.toJSONString(), ContentType.APPLICATION_JSON); }