Search in sources :

Example 1 with SearchResults

use of org.opennms.newts.api.search.SearchResults in project newts by OpenNMS.

the class CassandraResourceTreeWalker method depthFirstSearch.

/**
     * Visits all nodes in the resource tree bellow the given resource using
     * depth-first search.
     */
public void depthFirstSearch(Context context, SearchResultVisitor visitor, Resource root) {
    ArrayDeque<SearchResults.Result> stack = Queues.newArrayDeque();
    // Build an instance of a SearchResult for the root resource
    // but don't invoke the visitor with it
    boolean skipFirstVisit = true;
    SearchResults initialResults = new SearchResults();
    initialResults.addResult(root, new ArrayList<String>(0));
    stack.add(initialResults.iterator().next());
    while (!stack.isEmpty()) {
        SearchResults.Result r = stack.pop();
        if (skipFirstVisit) {
            skipFirstVisit = false;
        } else {
            if (!visitor.visit(r)) {
                return;
            }
        }
        // Reverse the order of the results so we walk the left-most
        // branches first
        ImmutableList<SearchResults.Result> results = ImmutableList.copyOf(m_searcher.search(context, matchKeyAndValue(Constants.PARENT_TERM_FIELD, r.getResource().getId())));
        for (SearchResults.Result result : results.reverse()) {
            stack.push(result);
        }
    }
}
Also used : Result(org.opennms.newts.api.search.SearchResults.Result) SearchResults(org.opennms.newts.api.search.SearchResults) Result(org.opennms.newts.api.search.SearchResults.Result)

Example 2 with SearchResults

use of org.opennms.newts.api.search.SearchResults in project opennms by OpenNMS.

the class NewtsResourceStorageDao method children.

@Override
public Set<ResourcePath> children(ResourcePath path, int depth) {
    Preconditions.checkArgument(depth >= 0, "depth must be non-negative");
    Set<ResourcePath> matches = Sets.newTreeSet();
    SearchResults results = searchFor(path, depth, false);
    for (Result result : results) {
        // Relativize the path
        ResourcePath child = toChildResourcePath(path, result.getResource().getId());
        if (child == null) {
            // This shouldn't happen
            LOG.warn("Encountered non-child resource {} when searching for {} with depth {}. Ignoring resource.", result.getResource(), path, depth);
            continue;
        }
        matches.add(child);
    }
    return matches;
}
Also used : NewtsUtils.toResourcePath(org.opennms.netmgt.newts.support.NewtsUtils.toResourcePath) ResourcePath(org.opennms.netmgt.model.ResourcePath) SearchResults(org.opennms.newts.api.search.SearchResults) Result(org.opennms.newts.api.search.SearchResults.Result)

Example 3 with SearchResults

use of org.opennms.newts.api.search.SearchResults in project opennms by OpenNMS.

the class NewtsResourceStorageDaoTest method replay.

private void replay() {
    EasyMock.expect(m_searcher.search(EasyMock.eq(m_context), EasyMock.anyObject(), EasyMock.anyBoolean())).andAnswer(new IAnswer<SearchResults>() {

        public SearchResults answer() throws Throwable {
            // Assume there is a single term query
            Query q = (Query) EasyMock.getCurrentArguments()[1];
            BooleanQuery bq = (BooleanQuery) q;
            TermQuery tq = (TermQuery) bq.getClauses().get(0).getQuery();
            String field = tq.getTerm().getField("");
            String value = tq.getTerm().getValue();
            SearchResults searchResults = new SearchResults();
            for (Entry<ResourcePath, Set<String>> entry : m_indexedPaths.entrySet()) {
                Map<String, String> attributes = Maps.newHashMap();
                // Build the indexed attributes and attempt to match them against the given query
                NewtsUtils.addIndicesToAttributes(entry.getKey(), attributes);
                if (value.equals(attributes.get(field))) {
                    searchResults.addResult(new Resource(NewtsUtils.toResourceId(entry.getKey())), entry.getValue());
                }
            }
            return searchResults;
        }
    }).atLeastOnce();
    EasyMock.expect(m_searcher.getResourceAttributes(EasyMock.eq(m_context), EasyMock.anyObject())).andReturn(Maps.newHashMap()).anyTimes();
    EasyMock.replay(m_searcher);
}
Also used : IAnswer(org.easymock.IAnswer) BooleanQuery(org.opennms.newts.api.search.BooleanQuery) TermQuery(org.opennms.newts.api.search.TermQuery) ResourcePath(org.opennms.netmgt.model.ResourcePath) Set(java.util.Set) TermQuery(org.opennms.newts.api.search.TermQuery) BooleanQuery(org.opennms.newts.api.search.BooleanQuery) Query(org.opennms.newts.api.search.Query) Resource(org.opennms.newts.api.Resource) SearchResults(org.opennms.newts.api.search.SearchResults)

Example 4 with SearchResults

use of org.opennms.newts.api.search.SearchResults in project newts by OpenNMS.

the class ResultSerializationTest method testSearchResults.

@Test
public void testSearchResults() throws JsonProcessingException {
    SearchResults results = new SearchResults();
    results.addResult(new Resource("localhost"), Lists.newArrayList("beer", "sausages"));
    String json = "[" + "  {" + "    \"resource\": {" + "      \"id\":\"localhost\"," + "      \"attributes\":{}" + "    }," + "    \"metrics\":[" + "       \"beer\"," + "       \"sausages\"" + "    ]" + "   }" + "]";
    assertThat(new ObjectMapper().writeValueAsString(Transform.searchResultDTOs(results)), is(normalize(json)));
}
Also used : Resource(org.opennms.newts.api.Resource) SearchResults(org.opennms.newts.api.search.SearchResults) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 5 with SearchResults

use of org.opennms.newts.api.search.SearchResults in project newts by OpenNMS.

the class CassandraIndexerITCase method canWalkTheResourceTree.

@Test
public void canWalkTheResourceTree() {
    Map<String, String> base = map("meat", "people", "bread", "beer");
    List<Sample> samples = Lists.newArrayList();
    samples.add(sampleFor(new Resource("a:b:c", Optional.of(base)), "m0"));
    samples.add(sampleFor(new Resource("a:b", Optional.of(base)), "m1"));
    samples.add(sampleFor(new Resource("x:b:z", Optional.of(base)), "m2"));
    CassandraSession session = newtsInstance.getCassandraSession();
    ResourceMetadataCache mockCache = mock(ResourceMetadataCache.class);
    when(mockCache.get(any(Context.class), any(Resource.class))).thenReturn(Optional.<ResourceMetadata>absent());
    MetricRegistry registry = new MetricRegistry();
    ContextConfigurations contextConfigurations = new ContextConfigurations();
    CassandraIndexingOptions options = new CassandraIndexingOptions.Builder().withHierarchicalIndexing(true).build();
    Indexer indexer = new CassandraIndexer(session, 86400, mockCache, registry, options, new SimpleResourceIdSplitter(), contextConfigurations);
    indexer.update(samples);
    CassandraSearcher searcher = new CassandraSearcher(session, registry, contextConfigurations);
    // Verify specific search results
    SearchResults results = searcher.search(Context.DEFAULT_CONTEXT, matchKeyAndValue("_parent", "_root"));
    Iterator<Result> it = results.iterator();
    Result result = it.next();
    assertThat(result.getResource().getId(), equalTo("a"));
    // a is a resource with no metrics
    assertThat(result.getMetrics().size(), equalTo(0));
    result = it.next();
    assertThat(result.getResource().getId(), equalTo("x"));
    // x is a resource with no metrics
    assertThat(result.getMetrics().size(), equalTo(0));
    results = searcher.search(Context.DEFAULT_CONTEXT, matchKeyAndValue("_parent", "a"));
    result = results.iterator().next();
    assertThat(result.getResource().getId(), equalTo("a:b"));
    assertThat(result.getMetrics().size(), equalTo(1));
    results = searcher.search(Context.DEFAULT_CONTEXT, matchKeyAndValue("_parent", "a:b"));
    result = results.iterator().next();
    assertThat(result.getResource().getId(), equalTo("a:b:c"));
    assertThat(result.getMetrics().size(), equalTo(1));
    results = searcher.search(Context.DEFAULT_CONTEXT, matchKeyAndValue("_parent", "a:b:c"));
    assertThat(results.iterator().hasNext(), equalTo(false));
    // Walk the tree via BFS
    LoggingResourceVisitor visitor = new LoggingResourceVisitor();
    CassandraResourceTreeWalker resourceTreeWalker = new CassandraResourceTreeWalker(searcher);
    resourceTreeWalker.breadthFirstSearch(Context.DEFAULT_CONTEXT, visitor);
    assertThat(visitor.getResourceIds(), equalTo(Lists.newArrayList("a", "x", "a:b", "x:b", "a:b:c", "x:b:z")));
    // Walk the tree via DFS
    visitor = new LoggingResourceVisitor();
    resourceTreeWalker.depthFirstSearch(Context.DEFAULT_CONTEXT, visitor);
    assertThat(visitor.getResourceIds(), equalTo(Lists.newArrayList("a", "a:b", "a:b:c", "x", "x:b", "x:b:z")));
}
Also used : Context(org.opennms.newts.api.Context) Sample(org.opennms.newts.api.Sample) MetricRegistry(com.codahale.metrics.MetricRegistry) QueryBuilder(org.opennms.newts.api.search.QueryBuilder) Resource(org.opennms.newts.api.Resource) CassandraSession(org.opennms.newts.cassandra.CassandraSession) SearchResults(org.opennms.newts.api.search.SearchResults) Result(org.opennms.newts.api.search.SearchResults.Result) Indexer(org.opennms.newts.api.search.Indexer) ContextConfigurations(org.opennms.newts.cassandra.ContextConfigurations) Test(org.junit.Test)

Aggregations

SearchResults (org.opennms.newts.api.search.SearchResults)9 Resource (org.opennms.newts.api.Resource)5 Result (org.opennms.newts.api.search.SearchResults.Result)5 Query (org.opennms.newts.api.search.Query)4 ResourcePath (org.opennms.netmgt.model.ResourcePath)3 Set (java.util.Set)2 ExecutionException (java.util.concurrent.ExecutionException)2 Test (org.junit.Test)2 NewtsUtils.toResourcePath (org.opennms.netmgt.newts.support.NewtsUtils.toResourcePath)2 Context (org.opennms.newts.api.Context)2 Sample (org.opennms.newts.api.Sample)2 BooleanQuery (org.opennms.newts.api.search.BooleanQuery)2 MetricRegistry (com.codahale.metrics.MetricRegistry)1 Timer (com.codahale.metrics.Timer)1 ConsistencyLevel (com.datastax.driver.core.ConsistencyLevel)1 ResultSetFuture (com.datastax.driver.core.ResultSetFuture)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 Optional (com.google.common.base.Optional)1 Preconditions (com.google.common.base.Preconditions)1