Example usage for org.apache.commons.collections IteratorUtils toList

List of usage examples for org.apache.commons.collections IteratorUtils toList

Introduction

In this page you can find the example usage for org.apache.commons.collections IteratorUtils toList.

Prototype

public static List toList(Iterator iterator) 

Source Link

Document

Gets a list based on an iterator.

Usage

From source file:org.apache.sling.superimposing.impl.SuperimposingManagerImpl.java

/**
 * Find all existing superimposing registrations using all query defined in service configuration.
 * @param resolver Resource resolver//from   ww  w.j ava  2 s. c  om
 * @return All superimposing registrations
 */
@SuppressWarnings("unchecked")
private List<Resource> findSuperimposings(ResourceResolver resolver) {
    List<Resource> allResources = new ArrayList<Resource>();
    for (String queryString : this.findAllQueries) {
        if (!StringUtils.contains(queryString, "|")) {
            throw new IllegalArgumentException(
                    "Query string does not contain query syntax seperated by '|': " + queryString);
        }
        String queryLanguage = StringUtils.substringBefore(queryString, "|");
        String query = StringUtils.substringAfter(queryString, "|");
        allResources.addAll(IteratorUtils.toList(resolver.findResources(query, queryLanguage)));
    }
    return allResources;
}

From source file:org.apache.sling.superimposing.impl.SuperimposingManagerImplTest.java

@SuppressWarnings("unchecked")
@Test//from ww w.j ava  2  s  . c o m
public void testFindAllSuperimposings() throws InterruptedException, LoginException, RepositoryException {
    // prepare a query that returns one existing superimposed resource
    when(componentContextProperties.get(SuperimposingManagerImpl.FINDALLQUERIES_PROPERTY))
            .thenReturn("syntax|query");
    when(resourceResolver.findResources("query", "syntax")).then(new Answer<Iterator<Resource>>() {
        public Iterator<Resource> answer(InvocationOnMock invocation) {
            return Arrays
                    .asList(new Resource[] {
                            prepareSuperimposingResource(SUPERIMPOSED_PATH, ORIGINAL_PATH, false, false) })
                    .iterator();
        }
    });
    initialize(true);

    // ensure the superimposed resource is detected and registered
    List<SuperimposingResourceProvider> providers = IteratorUtils.toList(underTest.getRegisteredProviders());
    assertEquals(1, providers.size());
    SuperimposingResourceProvider provider = providers.iterator().next();
    assertEquals(SUPERIMPOSED_PATH, provider.getRootPath());
    assertEquals(ORIGINAL_PATH, provider.getSourcePath());
    assertFalse(provider.isOverlayable());
    verify(bundleContext).registerService(anyString(), same(provider), any(Dictionary.class));
}

From source file:org.apache.sling.superimposing.impl.SuperimposingManagerImplTest.java

@SuppressWarnings("unchecked")
@Test//from  w  w w  .  j a va  2  s.  c  o m
public void testSuperimposedResourceCreateUpdateRemove()
        throws InterruptedException, LoginException, RepositoryException {
    initialize(true);

    // simulate node create event
    Resource superimposedResource = prepareSuperimposingResource(SUPERIMPOSED_PATH, ORIGINAL_PATH, false,
            false);
    underTest.onEvent(prepareNodeCreateEvent(superimposedResource));

    // ensure the superimposed resource is detected and registered
    List<SuperimposingResourceProvider> providers = IteratorUtils.toList(underTest.getRegisteredProviders());
    assertEquals(1, providers.size());
    SuperimposingResourceProvider provider = providers.iterator().next();
    assertEquals(SUPERIMPOSED_PATH, provider.getRootPath());
    assertEquals(ORIGINAL_PATH, provider.getSourcePath());
    assertFalse(provider.isOverlayable());
    verify(bundleContext).registerService(anyString(), same(provider), any(Dictionary.class));

    // simulate a change in the original path
    superimposedResource.adaptTo(ValueMap.class).put(PROP_SUPERIMPOSE_SOURCE_PATH, "/other/path");
    underTest.onEvent(prepareNodeChangeEvent(superimposedResource));

    // ensure the superimposed resource update is detected and a new provider instance is registered
    providers = IteratorUtils.toList(underTest.getRegisteredProviders());
    assertEquals(1, providers.size());
    SuperimposingResourceProvider provider2 = providers.iterator().next();
    assertEquals(SUPERIMPOSED_PATH, provider2.getRootPath());
    assertEquals("/other/path", provider2.getSourcePath());
    assertFalse(provider2.isOverlayable());
    verify(bundleContext).registerService(anyString(), same(provider2), any(Dictionary.class));

    // simulate node removal
    underTest.onEvent(prepareNodeRemoveEvent(superimposedResource));

    // ensure provider is removed
    providers = IteratorUtils.toList(underTest.getRegisteredProviders());
    assertEquals(0, providers.size());
}

From source file:org.apache.sling.superimposing.impl.SuperimposingManagerImplTest.java

@SuppressWarnings("unchecked")
@Test//from   w w  w.  j a v  a2 s .  com
public void testSuperimposedResourceCreateMove()
        throws InterruptedException, LoginException, RepositoryException {
    when(componentContextProperties.get(SuperimposingManagerImpl.FINDALLQUERIES_PROPERTY))
            .thenReturn("syntax|query");
    initialize(true);

    // simulate node create event
    final Resource superimposedResource = prepareSuperimposingResource(SUPERIMPOSED_PATH, ORIGINAL_PATH, false,
            false);
    underTest.onEvent(prepareNodeCreateEvent(superimposedResource));

    // simulate a node move event
    String oldPath = superimposedResource.getPath();
    moveSuperimposedResource(superimposedResource, "/new/path");

    // prepare a query that returns the moved superimposed resource
    when(resourceResolver.findResources("query", "syntax")).then(new Answer<Iterator<Resource>>() {
        public Iterator<Resource> answer(InvocationOnMock invocation) {
            return Arrays.asList(new Resource[] { superimposedResource }).iterator();
        }
    });

    underTest.onEvent(prepareNodeMoveEvent(superimposedResource, oldPath));

    // ensure the superimposed resource update is detected and a new provider instance is registered
    List<SuperimposingResourceProvider> providers = IteratorUtils.toList(underTest.getRegisteredProviders());
    assertEquals(1, providers.size());
    SuperimposingResourceProvider provider = providers.iterator().next();
    assertEquals("/new/path", provider.getRootPath());
    assertEquals(ORIGINAL_PATH, provider.getSourcePath());
    assertFalse(provider.isOverlayable());
    verify(bundleContext).registerService(anyString(), same(provider), any(Dictionary.class));
}

From source file:org.apache.solr.search.xjoin.simple.TestSimpleXJoinResultsFactory.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private void testResultsFile(NamedList args, boolean globalValues, boolean resultValues) throws IOException {
    SimpleXJoinResultsFactory factory = new SimpleXJoinResultsFactory();
    factory.init(args);//from   w  w w .  jav  a  2 s.  c  o  m

    SolrParams params = new ModifiableSolrParams();
    XJoinResults<String> results = factory.getResults(params);

    Map<String, String> values = (Map<String, String>) results;
    if (globalValues) {
        assertEquals(312, values.get("total"));
    } else {
        assertEquals(0, values.size());
    }

    Set<String> joinIds = new HashSet<>(IteratorUtils.toList(results.getJoinIds().iterator()));
    assertEquals(new HashSet<>(Arrays.asList(new String[] { "a3e5bd", "252ae1", "912151" })), joinIds);
    Map<String, String> result1 = (Map<String, String>) results.getResult("a3e5bd");
    Map<String, String> result2 = (Map<String, String>) results.getResult("252ae1");
    if (resultValues) {
        assertEquals("blue", result1.get("colour"));
        assertEquals(10.5, result2.get("value"));
    } else {
        assertEquals(0, result1.size());
        assertEquals(0, result2.size());
    }
}

From source file:org.apache.tez.mapreduce.hadoop.mapred.MRCounters.java

@SuppressWarnings("unchecked")
@Override/*  w w  w.  j  a  v a 2 s . com*/
public synchronized Collection<String> getGroupNames() {
    return IteratorUtils.toList(raw.getGroupNames().iterator());
}

From source file:org.apereo.openlrs.repositories.statements.ElasticSearchStatementRepository.java

@SuppressWarnings("unchecked")
@Override/*from   w w w  .  j  a  v  a  2s  .c o m*/
public List<Statement> get() {
    Iterable<Statement> iterableStatements = esSpringDataRepository.findAll();
    if (iterableStatements != null) {
        return IteratorUtils.toList(iterableStatements.iterator());
    }
    return null;
}

From source file:org.apereo.openlrs.repositories.statements.ElasticSearchStatementRepository.java

@SuppressWarnings("unchecked")
@Override/* w ww .ja  v  a2 s .  c  om*/
public List<Statement> get(Map<String, String> filters) {
    String actor = filters.get(StatementUtils.ACTOR_FILTER);
    String activity = filters.get(StatementUtils.ACTIVITY_FILTER);
    String since = filters.get(StatementUtils.SINCE_FILTER);
    String until = filters.get(StatementUtils.UNTIL_FILTER);
    int limit = getLimit(filters.get(StatementUtils.LIMIT_FILTER));
    ;

    XApiActor xApiActor = null;

    if (StringUtils.isNotBlank(actor)) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            xApiActor = objectMapper.readValue(actor.getBytes(), XApiActor.class);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    SearchQuery searchQuery = null;

    if (StringUtils.isNotBlank(activity) && xApiActor != null) {
        QueryBuilder actorQuery = buildActorQuery(xApiActor);
        QueryBuilder activityQuery = nestedQuery("object", boolQuery().must(matchQuery("object.id", activity)));

        BoolQueryBuilder boolQuery = boolQuery().must(actorQuery).must(activityQuery);

        searchQuery = startQuery(limit, boolQuery).build();
    } else if (xApiActor != null) {

        QueryBuilder query = buildActorQuery(xApiActor);

        if (query != null) {
            searchQuery = startQuery(limit, query).build();
        }
    } else if (StringUtils.isNotBlank(activity)) {
        QueryBuilder query = nestedQuery("object", boolQuery().must(matchQuery("object.id", activity)));
        searchQuery = startQuery(limit, query).build();
    } else if (StringUtils.isNotBlank(since) || StringUtils.isNotBlank(until)) {
        QueryBuilder query = null;

        if (StringUtils.isNotBlank(since) && StringUtils.isNotBlank(until)) {
            query = new RangeQueryBuilder("stored").from(since).to(until);
        } else {
            if (StringUtils.isNotBlank(since)) {
                query = new RangeQueryBuilder("stored").from(since).to("now");
            }

            if (StringUtils.isNotBlank(until)) {
                try {

                    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                    TimeZone tz = TimeZone.getTimeZone("UTC");
                    formatter.setTimeZone(tz);
                    Date date = (Date) formatter.parse(until);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    calendar.add(Calendar.YEAR, -1);

                    query = new RangeQueryBuilder("stored").from(formatter.format(calendar.getTime()))
                            .to(until);
                } catch (ParseException e) {
                    log.error(e.getMessage(), e);
                    return null;
                }
            }
        }

        NativeSearchQueryBuilder searchQueryBuilder = startQuery(limit, query);

        searchQuery = searchQueryBuilder.withSort(new FieldSortBuilder("stored").order(SortOrder.DESC)).build();
    } else if (limit > 0) {
        searchQuery = startQuery(limit, null).build();
    }

    if (searchQuery != null) {
        if (log.isDebugEnabled()) {
            if (searchQuery.getQuery() != null) {
                log.debug(String.format("Elasticsearch query %s", searchQuery.getQuery().toString()));
            }
        }

        Iterable<Statement> iterableStatements = esSpringDataRepository.search(searchQuery);
        if (iterableStatements != null) {
            return IteratorUtils.toList(iterableStatements.iterator());
        }
    }
    return null;
}

From source file:org.apereo.openlrs.storage.aws.elasticsearch.XApiOnlyAwsElasticsearchTierTwoStorage.java

@Override
public List<OpenLRSEntity> findAll() {
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    List<OpenLRSEntity> openLRSentities = new ArrayList<OpenLRSEntity>();
    searchSourceBuilder.query(QueryBuilders.matchAllQuery());
    Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(STATEMENT_INDEX)
            .addType(STATEMENT_TYPE).setParameter("from", 0).setParameter(Parameters.SIZE, 100) // default elasticsearch returns only 10 results.
            .build();//from   w w w  . ja  v  a2 s  . co m
    try {
        SearchResult result = jestClient.execute(search);
        //TODO remove deprecated.
        Iterable<Statement> iterableStatements = result.getSourceAsObjectList(Statement.class);
        if (iterableStatements != null) {
            openLRSentities = new ArrayList<OpenLRSEntity>(IteratorUtils.toList(iterableStatements.iterator()));
        }

    } catch (IOException e) {
        log.error("Could not findAll AWS Statements");
        e.printStackTrace();
    }

    return openLRSentities;
}

From source file:org.apereo.openlrs.storage.aws.elasticsearch.XApiOnlyAwsElasticsearchTierTwoStorage.java

private Page<OpenLRSEntity> createPage(Iterable<Statement> statements) {
    if (statements != null) {
        return new PageImpl<OpenLRSEntity>(IteratorUtils.toList(statements.iterator()));
    }//from w  ww . j ava  2s  . c  om
    return null;
}