Java Examples for io.searchbox.client.JestResult

The following java examples will help you to understand the usage of io.searchbox.client.JestResult. These source code samples are taken from different open source projects.

Example 1
Project: Jest-master  File: BulkIntegrationTest.java View source code
@Test
public void bulkOperationWithIndexWithParam() throws IOException {
    String index = "twitter";
    String type = "tweet";
    Map<String, String> source = new HashMap<String, String>();
    source.put("user", "kimchy");
    Bulk bulk = new Bulk.Builder().addAction(new Index.Builder(source).index(index).type(type).id("1").setParameter(Parameters.VERSION, 6).build()).build();
    JestResult result = client.execute(bulk);
    assertFalse(result.getErrorMessage(), result.isSucceeded());
}
Example 2
Project: sagan-master  File: SearchResultParser_WithHighlightTests.java View source code
@Before
public void setup() {
    JsonParser jsonParser = new JsonParser();
    searchResultParser = new SearchResultParser();
    JestResult jestResult = new JestResult(gson);
    jestResult.setJsonObject(jsonParser.parse(RESULT_STRING).getAsJsonObject());
    Pageable pageable = new PageRequest(1, 10);
    content = searchResultParser.parseResults(jestResult, pageable, "search term").getPage().getContent();
}
Example 3
Project: gerrit-master  File: ElasticChangeIndex.java View source code
@Override
public void replace(ChangeData cd) throws IOException {
    String deleteIndex;
    String insertIndex;
    try {
        if (cd.change().getStatus().isOpen()) {
            insertIndex = OPEN_CHANGES;
            deleteIndex = CLOSED_CHANGES;
        } else {
            insertIndex = CLOSED_CHANGES;
            deleteIndex = OPEN_CHANGES;
        }
    } catch (OrmException e) {
        throw new IOException(e);
    }
    Bulk bulk = new Bulk.Builder().defaultIndex(indexName).defaultType("changes").addAction(insert(insertIndex, cd)).addAction(delete(deleteIndex, cd.getId())).refresh(true).build();
    JestResult result = client.execute(bulk);
    if (!result.isSucceeded()) {
        throw new IOException(String.format("Failed to replace change %s in index %s: %s", cd.getId(), indexName, result.getErrorMessage()));
    }
}
Example 4
Project: Team5GeoTopics-master  File: EsTestsB.java View source code
public void testPullTopLevel() {
    CommentListModel listModel = new CommentListModel();
    Cache cache = Cache.getInstance();
    CommentSearch search = new CommentSearch(listModel, cache);
    Thread thread = search.pullTopLevel((BrowseActivity) mActivity);
    try {
        thread.join();
    } catch (InterruptedException e) {
        Log.w("EsTestPullTopLevel", "Thread interrupt");
    }
    JestResult result = search.returnResult();
    assertTrue("Result is not null", result != null);
    assertTrue("Result is successful", result.isSucceeded());
}
Example 5
Project: spring-boot-master  File: ElasticsearchJestHealthIndicatorTests.java View source code
private static JestResult createJestResult(int shards, int failedShards) {
    String json = String.format("{_shards: {\n" + "total: %s,\n" + "successful: %s,\n" + "failed: %s\n" + "}}", shards, shards - failedShards, failedShards);
    SearchResult searchResult = new SearchResult(new Gson());
    searchResult.setJsonString(json);
    searchResult.setJsonObject(new JsonParser().parse(json).getAsJsonObject());
    return searchResult;
}
Example 6
Project: apiman-master  File: EsStorage.java View source code
/**
     * Called to initialize the storage.
     */
@Override
public void initialize() {
    try {
        esClient.execute(new Health.Builder().build());
        // TODO Do we need a loop to wait for all nodes to join the cluster?
        Action<JestResult> action = new IndicesExists.Builder(getIndexName()).build();
        JestResult result = esClient.execute(action);
        if (!result.isSucceeded()) {
            createIndex(getIndexName());
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 7
Project: bearchoke-master  File: LocationRepositoryImpl.java View source code
/**
     * What we want this complex elasticsearch query to do is:
     * 1. Match user search input to the fields code, name and description
     * 2. If any of the documents are of type REGION --> boost document 4
     * 2. If any of the documents are of type CITY --> boost document 3
     * 3. If any of the documents are of type AIRPORT --> boost document 2
     * 4. If any of the documents are of type COUNTRY --> boost document 1
     * 4. If any of the documents are of type HOTEL --> no boost necessary
     *
     * @param userInput user input from search
     * @return
     */
public List<Location> locationSearch(String userInput) {
    List<Location> locations = null;
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(QueryBuilders.queryStringQuery(userInput));
    Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(LOCATION_INDEX_NAME).addType(LOCATION_INDEX_TYPE).build();
    try {
        JestResult result = jestClient.execute(search);
        locations = result.getSourceAsObjectList(Location.class);
    } catch (Exception e) {
        log.error(e.getMessage());
    }
    return locations;
}
Example 8
Project: graylog2-server-master  File: Indices.java View source code
public void move(String source, String target) {
    // TODO: This method should use the Re-index API: https://www.elastic.co/guide/en/elasticsearch/reference/5.3/docs-reindex.html
    final String query = SearchSourceBuilder.searchSource().query(QueryBuilders.matchAllQuery()).size(350).sort(SortBuilders.fieldSort(SortParseElement.DOC_FIELD_NAME)).toString();
    final Search request = new Search.Builder(query).setParameter(Parameters.SCROLL, "10s").addIndex(source).build();
    final SearchResult searchResult = JestUtils.execute(jestClient, request, () -> "Couldn't process search query response");
    final String scrollId = Optional.of(searchResult.getJsonObject()).map( json -> asString(json.get("_scroll_id"))).orElseThrow(() -> new ElasticsearchException("Couldn't find scroll ID in search query response"));
    final Type type = new TypeToken<Map<String, Object>>() {
    }.getType();
    while (true) {
        final SearchScroll scrollRequest = new SearchScroll.Builder(scrollId, "1m").build();
        final JestResult scrollResult = JestUtils.execute(jestClient, scrollRequest, () -> "Couldn't process result of scroll query");
        final JsonArray scrollHits = Optional.of(scrollResult.getJsonObject()).map( json -> asJsonObject(json.get("hits"))).map( hits -> asJsonArray(hits.get("hits"))).orElse(new JsonArray());
        // No more hits.
        if (scrollHits.size() == 0) {
            break;
        }
        final Bulk.Builder bulkRequestBuilder = new Bulk.Builder();
        for (JsonElement jsonElement : scrollHits) {
            final Map<String, Object> doc = Optional.ofNullable(asJsonObject(jsonElement)).map( hitsJson -> asJsonObject(hitsJson.get("_source"))).map( sourceJson -> gson.<Map<String, Object>>fromJson(sourceJson, type)).orElse(Collections.emptyMap());
            final String id = (String) doc.remove("_id");
            bulkRequestBuilder.addAction(messages.prepareIndexRequest(target, doc, id));
        }
        bulkRequestBuilder.setParameter(Parameters.CONSISTENCY, "one");
        final BulkResult bulkResult = JestUtils.execute(jestClient, bulkRequestBuilder.build(), () -> "Couldn't bulk index messages into index " + target);
        final boolean hasFailedItems = !bulkResult.getFailedItems().isEmpty();
        LOG.info("Moving index <{}> to <{}>: Bulk indexed {} messages, took {} ms, failures: {}", source, target, bulkResult.getItems().size(), asLong(bulkResult.getJsonObject().get("took")), hasFailedItems);
        if (hasFailedItems) {
            throw new ElasticsearchException("Failed to move a message. Check your indexer log.");
        }
    }
}
Example 9
Project: baleen-master  File: ElasticsearchTemplateRecordConsumer.java View source code
/**
	 * Create an index in Elasticsearch. If necessary, this function should
	 * check whether a new index is required.
	 * 
	 * @return true if a new index has been created, false otherwise
	 */
public boolean createIndex() {
    JestClient client = esrResource.getClient();
    try {
        JestResult result = client.execute(new IndicesExists.Builder(index).build());
        if (result.getResponseCode() != 200) {
            client.execute(new CreateIndex.Builder(index).build());
            return true;
        }
    } catch (IOException ioe) {
        getMonitor().error("Unable to create index", ioe);
    }
    return false;
}
Example 10
Project: GeoChan-master  File: GetThreadCommentsRunnable.java View source code
/**
	 * Forms a query and sends a Get request to ES, then processes
	 * retrieved data as an array of ThreadComment objects.
	 */
@Override
public void run() {
    task.setGetThreadCommentsThread(Thread.currentThread());
    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
    task.handleGetThreadCommentsState(STATE_GET_THREADS_RUNNING);
    JestResult result = null;
    try {
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        String query = ElasticSearchQueries.SEARCH_MATCH_ALL;
        Search search = new Search.Builder(query).addIndex(ElasticSearchClient.URL_INDEX).addType(type).build();
        result = ElasticSearchClient.getInstance().getClient().execute(search);
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        Type elasticSearchSearchResponseType = new TypeToken<ElasticSearchSearchResponse<ThreadComment>>() {
        }.getType();
        Gson gson = GsonHelper.getOnlineGson();
        ElasticSearchSearchResponse<ThreadComment> esResponse = gson.fromJson(result.getJsonString(), elasticSearchSearchResponseType);
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        ArrayList<ThreadComment> list = new ArrayList<ThreadComment>();
        for (ElasticSearchResponse<ThreadComment> r : esResponse.getHits()) {
            ThreadComment object = r.getSource();
            list.add(object);
        }
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        ThreadList.setThreads(list);
        task.handleGetThreadCommentsState(STATE_GET_THREADS_COMPLETE);
    } catch (Exception e) {
    } finally {
        if (result == null || !result.isSucceeded()) {
            task.handleGetThreadCommentsState(STATE_GET_THREADS_FAILED);
        }
        // task.setGetCommentListThread(null);
        Thread.interrupted();
    }
}
Example 11
Project: elasticsearch-jenkins-master  File: BuildListener.java View source code
@Override
public void onCompleted(Run run, TaskListener listener) {
    loadConfig();
    final boolean validConfig = config != null && config.nonEmptyValues();
    if (validConfig) {
        final Build build = createBuild(run, listener);
        try {
            final Index index = new Index.Builder(build).index(config.getIndexName()).type(config.getTypeName()).build();
            final JestResult result = jestClient.execute(index);
            if (result.isSucceeded()) {
                LOG.fine("Sent build to Elasticsearch: " + build);
            } else {
                LOG.warning("Failed to index build, got error message: " + result.getErrorMessage());
            }
        } catch (Exception e) {
            LOG.log(Level.SEVERE, "Error when sending build data: " + build, e);
        }
    } else {
        LOG.fine("The configuration is not valid, can not index the build");
    }
}
Example 12
Project: xwiki-platform-master  File: DatePingDataProvider.java View source code
@Override
public Map<String, Object> provideData() {
    Map<String, Object> jsonMap = new HashMap<>();
    try {
        String instanceId = this.instanceIdManager.getInstanceId().toString();
        Search search = new Search.Builder(constructSearchJSON(instanceId)).addIndex(JestClientManager.INDEX).addType(JestClientManager.TYPE).setSearchType(SearchType.COUNT).build();
        JestResult result = this.jestClientManager.getClient().execute(search);
        if (!result.isSucceeded()) {
            this.logger.warn(ERROR_MESSAGE, result.getErrorMessage());
            return jsonMap;
        }
        @SuppressWarnings("unchecked") Map<String, Object> aggregationsMap = (Map<String, Object>) result.getValue("aggregations");
        // Get the current server time and the first timestamp of the ping for this instance id and compute the
        // since days from them.
        @SuppressWarnings("unchecked") Map<String, Object> serverTimeMap = (Map<String, Object>) aggregationsMap.get(PROPERTY_SERVER_TIME);
        Object serverTimeObject = serverTimeMap.get(PROPERTY_VALUE);
        @SuppressWarnings("unchecked") Map<String, Object> firstPingDateMap = (Map<String, Object>) aggregationsMap.get(PROPERTY_FIRST_PING_DATE);
        Object firstPingDateObject = firstPingDateMap.get(PROPERTY_VALUE);
        if (serverTimeObject != null && firstPingDateObject != null) {
            long sinceDays = Math.round(((double) serverTimeObject - (double) firstPingDateObject) / 86400000D);
            jsonMap.put(PROPERTY_SINCE_DAYS, sinceDays);
            long firstPingDate = Math.round((double) firstPingDateObject);
            jsonMap.put(PROPERTY_FIRST_PING_DATE, firstPingDate);
        } else {
            // This means it's the first ping and thus there was no previous _timestamp. Thus we set the since Days
            // to 0.
            jsonMap.put(PROPERTY_SINCE_DAYS, 0);
        }
    } catch (Exception e) {
        this.logger.warn(ERROR_MESSAGE, ExceptionUtils.getRootCauseMessage(e));
    }
    return jsonMap;
}
Example 13
Project: metamodel-master  File: ElasticSearchRestDataContext.java View source code
/**
     * Performs an analysis of the available indexes in an ElasticSearch cluster
     * {@link JestClient} instance and detects the elasticsearch types structure
     * based on the metadata provided by the ElasticSearch java client.
     *
     * @see {@link #detectTable(JsonObject, String)}
     * @return a mutable schema instance, useful for further fine tuning by the
     *         user.
     */
private SimpleTableDef[] detectSchema() {
    logger.info("Detecting schema for index '{}'", indexName);
    final JestResult jestResult;
    try {
        final GetMapping getMapping = new GetMapping.Builder().addIndex(indexName).build();
        jestResult = elasticSearchClient.execute(getMapping);
    } catch (Exception e) {
        logger.error("Failed to retrieve mappings", e);
        throw new MetaModelException("Failed to execute request for index information needed to detect schema", e);
    }
    if (!jestResult.isSucceeded()) {
        logger.error("Failed to retrieve mappings; {}", jestResult.getErrorMessage());
        throw new MetaModelException("Failed to retrieve mappings; " + jestResult.getErrorMessage());
    }
    final List<SimpleTableDef> result = new ArrayList<>();
    final Set<Map.Entry<String, JsonElement>> mappings = jestResult.getJsonObject().getAsJsonObject(indexName).getAsJsonObject("mappings").entrySet();
    if (mappings.size() == 0) {
        logger.warn("No metadata returned for index name '{}' - no tables will be detected.");
    } else {
        for (Map.Entry<String, JsonElement> entry : mappings) {
            final String documentType = entry.getKey();
            try {
                final SimpleTableDef table = detectTable(entry.getValue().getAsJsonObject().get("properties").getAsJsonObject(), documentType);
                result.add(table);
            } catch (Exception e) {
                logger.error("Unexpected error during detectTable for document type '{}'", documentType, e);
            }
        }
    }
    final SimpleTableDef[] tableDefArray = result.toArray(new SimpleTableDef[result.size()]);
    Arrays.sort(tableDefArray, new Comparator<SimpleTableDef>() {

        @Override
        public int compare(SimpleTableDef o1, SimpleTableDef o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    return tableDefArray;
}
Example 14
Project: sofia-master  File: RESTProvider.java View source code
@SuppressWarnings("rawtypes")
@Override
public Iterator<Example> iterator() {
    Search search = new Search(Search.createQueryWithBuilder(this.qbuilder.toString()));
    search.addParameter("from", this.start);
    search.addParameter("size", this.total);
    search.addParameter("fields", "[]");
    search.addParameter("sort", "post_creation_date");
    search.addIndex("sof-sample");
    JestResult result;
    try {
        result = this.client.execute(search);
    } catch (Exception e) {
        return new RESTProviderIterator(new HashMap<String, StringMap>(), this);
    }
    RESTProviderIterator iter = new RESTProviderIterator(result.getJsonMap(), this);
    return iter;
}
Example 15
Project: jenkins-elasticsearch-plugin-master  File: ElasticsearchPluginRunListener.java View source code
@Override
public void onCompleted(final Run run, final TaskListener listener) {
    final DescriptorImpl descriptor = (DescriptorImpl) getDescriptor();
    JestClient client = null;
    try {
        final JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig.Builder(descriptor.getServer()).multiThreaded(true).build());
        client = factory.getObject();
        final BuildResult buildResult = new BuildResult();
        buildResult.setIdentifier(descriptor.getIdentifier());
        buildResult.setUniqueJobName(descriptor.getIdentifier() + ":" + run.getParent().getName());
        buildResult.setBuildDescription(run.getDescription());
        buildResult.setDuration(run.getDuration());
        buildResult.setEnvironmentVariables(run.getEnvironment(listener));
        buildResult.setBuildNumber(run.getNumber());
        buildResult.setResult(run.getResult().toString());
        buildResult.setStartTime(toISODateString(new Date(run.getStartTimeInMillis())));
        buildResult.setTimestamp(toISODateString(run.getTime()));
        buildResult.setBuildUrl(run.getUrl());
        try {
            buildResult.setJobUrl(run.getParent().getAbsoluteUrl());
        } catch (final IllegalStateException e) {
            buildResult.setJobUrl(run.getParent().getUrl());
        }
        buildResult.setJobDescription(run.getParent().getDescription());
        buildResult.setJobDescription(run.getParent().getDescription());
        buildResult.setJobName(run.getParent().getName());
        buildResult.setSystemProperties(getSystemPropertiesMap());
        final Index index = new Index.Builder(buildResult).index(descriptor.getIndex()).type(descriptor.getType()).id(run.getId()).build();
        final JestResult result = client.execute(index);
        if (result.isSucceeded()) {
            listener.getLogger().println("[SUCCESS] Elasticsearch Plugin Index(" + run.getId() + ")");
        } else {
            listener.getLogger().println("[WARN] Elasticsearch Plugin Index failed. (" + run.getId() + ")" + result.getErrorMessage());
        }
    } catch (final IOException e) {
        listener.getLogger().println("[WARN] Elasticsearch Plugin Failed. " + e.getLocalizedMessage());
        e.printStackTrace();
    } catch (final InterruptedException e) {
        listener.getLogger().println("[WARN] Elasticsearch Plugin Failed. " + e.getLocalizedMessage());
        e.printStackTrace();
    } finally {
        if (client != null) {
            client.shutdownClient();
        }
    }
}
Example 16
Project: jmxtrans-master  File: ElasticWriter.java View source code
@Override
protected void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
    for (Result result : results) {
        log.debug("Query result: [{}]", result);
        Map<String, Object> resultValues = result.getValues();
        for (Entry<String, Object> values : resultValues.entrySet()) {
            Object value = values.getValue();
            if (isNumeric(value)) {
                Map<String, Object> map = new HashMap<>();
                map.put("serverAlias", server.getAlias());
                map.put("server", server.getHost());
                map.put("port", server.getPort());
                map.put("objDomain", result.getObjDomain());
                map.put("className", result.getClassName());
                map.put("typeName", result.getTypeName());
                map.put("attributeName", result.getAttributeName());
                map.put("key", values.getKey());
                map.put("keyAlias", result.getKeyAlias());
                map.put("value", Double.parseDouble(value.toString()));
                map.put("timestamp", result.getEpoch());
                log.debug("Insert into Elastic: Index: [{}] Type: [{}] Map: [{}]", indexName, ELASTIC_TYPE_NAME, map);
                Index index = new Index.Builder(map).index(indexName).type(ELASTIC_TYPE_NAME).build();
                JestResult addToIndex = jestClient.execute(index);
                if (!addToIndex.isSucceeded()) {
                    throw new ElasticWriterException(String.format("Unable to write entry to elastic: %s", addToIndex.getErrorMessage()));
                }
            } else {
                log.warn("Unable to submit non-numeric value to Elastic: [{}] from result [{}]", value, result);
            }
        }
    }
}
Example 17
Project: ff4j-master  File: ElasticQueryBuilder.java View source code
public String getFeatureTechId(String uid) {
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(QueryBuilders.matchQuery("uid", uid));
    Search search = new Search.Builder(//
    searchSourceBuilder.toString()).addIndex(//
    connection.getIndexName()).addType(//
    ElasticConstants.TYPE_FEATURE).build();
    // feature existence must have been checked before (technical function)
    @SuppressWarnings("rawtypes") List<Hit<Map, Void>> items = connection.search(search).getHits(Map.class);
    if (null != items && !items.isEmpty()) {
        return connection.search(search).getHits(Map.class).get(0).source.get(JestResult.ES_METADATA_ID).toString();
    }
    return null;
}
Example 18
Project: nutch-master  File: ElasticRestIndexWriter.java View source code
@Override
public void commit() throws IOException {
    if (basicFuture != null) {
        // wait for previous to finish
        long beforeWait = System.currentTimeMillis();
        try {
            JestResult result = basicFuture.get();
            if (result == null) {
                throw new RuntimeException();
            }
            long msWaited = System.currentTimeMillis() - beforeWait;
            LOG.info("Previous took in ms {}, including wait {}", millis, msWaited);
        } catch (InterruptedExceptionExecutionException |  e) {
            LOG.error("Error waiting for result ", e);
        }
        basicFuture = null;
    }
    if (bulkBuilder != null) {
        if (bulkDocs > 0) {
            // start a flush, note that this is an asynchronous call
            basicFuture = new BasicFuture<>(null);
            millis = System.currentTimeMillis();
            client.executeAsync(bulkBuilder.build(), new JestResultHandler<BulkResult>() {

                @Override
                public void completed(BulkResult bulkResult) {
                    basicFuture.completed(bulkResult);
                    millis = System.currentTimeMillis() - millis;
                }

                @Override
                public void failed(Exception e) {
                    basicFuture.completed(null);
                    LOG.error("Failed result: ", e);
                }
            });
        }
        bulkBuilder = null;
    }
    if (createNewBulk) {
        // Prepare a new bulk request
        bulkBuilder = new Bulk.Builder().defaultIndex(defaultIndex).defaultType(defaultType);
        bulkDocs = 0;
        bulkLength = 0;
    }
}
Example 19
Project: dig-elasticsearch-master  File: ScanAndScroll.java View source code
public void executeQuery(String query, int pageSize, String index, String docType, int docLimit) {
    Search search = new Search.Builder(query).addIndex(index).addType(docType).setParameter(Parameters.SEARCH_TYPE, SearchType.SCAN).setParameter(Parameters.SIZE, pageSize).setParameter(Parameters.SCROLL, SCROLL).build();
    System.out.println(query + "$$$$");
    boolean runTikaExtractor = true;
    if (this.runTika == 0) {
        runTikaExtractor = false;
    } else if (this.runTika == 1) {
        runTikaExtractor = true;
    }
    try {
        JestResult searchResult = client.execute(search);
        //System.out.println(searchResult.getJsonString());
        String scrollId = searchResult.getJsonObject().get("_scroll_id").getAsString();
        int currentResultSize = 0;
        int numDocs = 0;
        do {
            JSONArray jArrayResult = new JSONArray();
            SearchScroll scrollRequest = new SearchScroll.Builder(scrollId, SCROLL).setParameter(Parameters.SIZE, pageSize).build();
            JestResult scrollResult = client.execute(scrollRequest);
            scrollId = scrollResult.getJsonObject().get("_scroll_id").getAsString();
            JSONObject jObj = (JSONObject) JSONSerializer.toJSON(scrollResult.getJsonString());
            JSONArray jArrayHits = jObj.getJSONObject("hits").getJSONArray("hits");
            for (int i = 0; i < jArrayHits.size(); i++) {
                if (runTikaExtractor) {
                    jArrayResult.add(extractTika(jArrayHits.getString(i)).toString());
                } else {
                    jArrayResult.add(jArrayHits.getString(i).toString());
                }
            }
            writeToFile(jArrayResult);
            // Note: Current result size will be Page Size * number of shards
            currentResultSize = jArrayHits.size();
            numDocs += currentResultSize;
            System.out.println("num docs:" + String.valueOf(numDocs));
            if (docLimit != -1 && numDocs >= docLimit) {
                break;
            }
        } while (currentResultSize != 0);
    } catch (IOException e) {
        LOG.error("Error retrieving from Elasticsearch", e);
    }
}
Example 20
Project: PerfCake-master  File: ElasticsearchDestination.java View source code
@Override
public void open() {
    startTime = Long.getLong(PerfCakeConst.TIMESTAMP_PROPERTY);
    try {
        if ((keyStore != null && !"".equals(keyStore)) || (trustStore != null && !"".equals(trustStore))) {
            sslContext = SslSocketFactoryFactory.newSslContext(keyStore, keyStorePassword, trustStore, trustStorePassword);
        }
    } catch (PerfCakeException e) {
        log.warn("Unable to initialize SSL socket factory: ", e);
    }
    final List<String> serverUris = Arrays.asList(serverUrl.split(",")).stream().map(StringUtil::trim).collect(Collectors.toList());
    final HttpClientConfig.Builder builder = new HttpClientConfig.Builder(serverUris);
    if (sslContext != null) {
        builder.sslSocketFactory(new SSLConnectionSocketFactory(sslContext));
    }
    Arrays.stream(tags.split(",")).map(StringUtil::trim).forEach(tagsArray::add);
    builder.multiThreaded(true);
    builder.connTimeout(timeout);
    builder.readTimeout(timeout);
    builder.maxTotalConnection(1);
    if (userName != null) {
        builder.defaultCredentials(userName, password);
    }
    final JestClientFactory factory = new JestClientFactory();
    factory.setHttpClientConfig(builder.build());
    jest = factory.getObject();
    if (configureMapping) {
        final String mappings = "{ \"mappings\": {" + " \"" + type + "\": {" + "\"properties\" : { " + "\"" + PeriodType.TIME.toString().toLowerCase() + "\" : {" + "\"type\" : \"date\", " + "\"format\" : \"epoch_millis\"" + "}, " + "\"" + PerfCakeConst.REAL_TIME_TAG + "\" : {" + "\"type\" : \"date\", " + "\"format\" : \"epoch_millis\"" + "} " + "} " + "} " + "} " + "}";
        try {
            final JestResult result = jest.execute(new CreateIndex.Builder(index).settings(mappings).build());
            if (result.isSucceeded()) {
                log.info("Correctly configured mapping.");
            } else {
                if (result.getErrorMessage().contains("index_already_exists")) {
                    log.warn("Index already exists, cannot re-configure mapping.");
                } else {
                    throw new IOException(result.getErrorMessage());
                }
            }
        } catch (IOException e) {
            log.warn("Unable to configure mapping: ", e);
        }
    }
}
Example 21
Project: adventure.datetime-master  File: WebStorage.java View source code
/* (non-Javadoc)
	 * @see ca.cmput301f13t03.adventure_datetime.model.IWebStorage#getStory(java.util.UUID)
	 */
@Override
public Story getStory(UUID storyId) throws Exception {
    Get get = new Get.Builder(_index, storyId.toString()).type("story").build();
    JestResult result = execute(get);
    Story story = result.getSourceAsObject(Story.class);
    Image image = getImage(storyId);
    if (image != null)
        story.setThumbnail(image.getEncodedBitmap());
    return story;
}
Example 22
Project: tsdr-master  File: ElasticsearchStore.java View source code
/**
     * Method is a wrapper for {@link JestClient#executeAsync(Action, JestResultHandler)}
     * in order to avoid repeatedly handle failures.
     */
private <T extends JestResult> void executeAsync(final Action<T> action) {
    client.executeAsync(action, new JestResultHandler<JestResult>() {

        @Override
        public void completed(JestResult result) {
            if (result == null) {
                LOGGER.error("Failed to execute action: {}, got null result", action);
                return;
            }
            if (!result.isSucceeded()) {
                LOGGER.error("Failed to execute action: {}, cause: {}", action, result.getErrorMessage());
            }
        }

        @Override
        public void failed(Exception ex) {
            LOGGER.error("Failed to execute action: {}, cause: {}", action, ex);
        }
    });
}
Example 23
Project: shopizer-master  File: SearchDelegateImpl.java View source code
/* (non-Javadoc)
	 * @see com.shopizer.search.services.impl.SearchService#indexExist(java.lang.String)
	 */
@Override
public boolean indexExist(String indexName) throws Exception {
    JestClient client = searchClient.getClient();
    IndicesExists.Builder builder = new IndicesExists.Builder(indexName);
    if (!StringUtils.isBlank(searchClient.getAuthenticationHeader())) {
        builder.setHeader("Authorization", searchClient.getAuthenticationHeader());
    }
    @SuppressWarnings("rawtypes") Action action = builder.build();
    @SuppressWarnings("unchecked") JestResult result = client.execute(action);
    return result.isSucceeded();
}
Example 24
Project: play2-elasticsearch-jest-master  File: JestClientCredentialsTest.java View source code
@Test
public void testBasicAuth_ValidCredentials() throws Exception {
    final Action action = new GetRestAction("cgatay/test");
    final JestResult jestResult = jestClient.execute(action);
    Assert.assertTrue("Credentials should be valid", jestResult.isSucceeded());
}
Example 25
Project: gradle-metrics-plugin-master  File: HttpESMetricsDispatcher.java View source code
@Override
protected String index(String indexName, String type, String source, Optional<String> id) {
    if (!id.isPresent()) {
        id = Optional.of(UUID.randomUUID().toString());
    }
    Index index = buildIndex(indexName, type, source, id.get());
    JestResult result = execute(index, false);
    return result.getJsonObject().get("_id").getAsString();
}