Example usage for java.util Collections emptyIterator

List of usage examples for java.util Collections emptyIterator

Introduction

In this page you can find the example usage for java.util Collections emptyIterator.

Prototype

@SuppressWarnings("unchecked")
public static <T> Iterator<T> emptyIterator() 

Source Link

Document

Returns an iterator that has no elements.

Usage

From source file:grakn.core.server.session.computer.GraknSparkExecutor.java

public static <M> JavaPairRDD<Object, ViewIncomingPayload<M>> executeVertexProgramIteration(
        final JavaPairRDD<Object, VertexWritable> graphRDD,
        final JavaPairRDD<Object, ViewIncomingPayload<M>> viewIncomingRDD, final GraknSparkMemory memory,
        final Configuration graphComputerConfiguration, // has the Graph/GraphComputer.configuration() information
        final Configuration vertexProgramConfiguration) { // has the VertexProgram.loadState() information

    boolean partitionedGraphRDD = graphRDD.partitioner().isPresent();

    if (partitionedGraphRDD && null != viewIncomingRDD) // the graphRDD and the viewRDD must have the same partitioner
    {/*  w w  w  .  j a  v a2s  .c  o m*/
        assert graphRDD.partitioner().get().equals(viewIncomingRDD.partitioner().get());
    }
    final JavaPairRDD<Object, ViewOutgoingPayload<M>> viewOutgoingRDD = ((null == viewIncomingRDD)
            ? graphRDD.mapValues(
                    vertexWritable -> new Tuple2<>(vertexWritable, Optional.<ViewIncomingPayload<M>>absent()))
            : // first iteration will not have any views or messages
            graphRDD.leftOuterJoin(viewIncomingRDD)) // every other iteration may have views and messages
                    // for each partition of vertices emit a view and their outgoing messages
                    .mapPartitionsToPair(partitionIterator -> {
                        KryoShimServiceLoader.applyConfiguration(graphComputerConfiguration);

                        // if the partition is empty, return without starting a new VP iteration
                        if (!partitionIterator.hasNext()) {
                            return Collections.emptyIterator();
                        }

                        final VertexProgram<M> workerVertexProgram = VertexProgram.createVertexProgram(
                                HadoopGraph.open(graphComputerConfiguration), vertexProgramConfiguration); // each partition(Spark)/worker(TP3) has a local copy of the vertex program (a worker's task)
                        final String[] vertexComputeKeysArray = VertexProgramHelper
                                .vertexComputeKeysAsArray(workerVertexProgram.getVertexComputeKeys()); // the compute keys as an array
                        final SparkMessenger<M> messenger = new SparkMessenger<>();

                        workerVertexProgram.workerIterationStart(memory.asImmutable()); // start the worker
                        return IteratorUtils.map(partitionIterator, vertexViewIncoming -> {
                            final StarGraph.StarVertex vertex = vertexViewIncoming._2()._1().get(); // get the vertex from the vertex writable
                            final boolean hasViewAndMessages = vertexViewIncoming._2()._2().isPresent(); // if this is the first iteration, then there are no views or messages
                            final List<DetachedVertexProperty<Object>> previousView = hasViewAndMessages
                                    ? vertexViewIncoming._2()._2().get().getView()
                                    : memory.isInitialIteration() ? new ArrayList<>() : Collections.emptyList();
                            // revive compute properties if they already exist
                            if (memory.isInitialIteration() && vertexComputeKeysArray.length > 0) {
                                vertex.properties(vertexComputeKeysArray)
                                        .forEachRemaining(vertexProperty -> previousView
                                                .add(DetachedFactory.detach(vertexProperty, true)));
                            }
                            // drop any computed properties that are cached in memory
                            vertex.dropVertexProperties(vertexComputeKeysArray);
                            final List<M> incomingMessages = hasViewAndMessages
                                    ? vertexViewIncoming._2()._2().get().getIncomingMessages()
                                    : Collections.emptyList();
                            IteratorUtils.removeOnNext(previousView.iterator()).forEachRemaining(
                                    property -> property.attach(Attachable.Method.create(vertex))); // attach the view to the vertex
                            assert previousView.isEmpty();
                            // do the vertex's vertex program iteration
                            messenger.setVertexAndIncomingMessages(vertex, incomingMessages); // set the messenger with the incoming messages
                            workerVertexProgram.execute(
                                    ComputerGraph.vertexProgram(vertex, workerVertexProgram), messenger,
                                    memory); // execute the vertex program on this vertex for this iteration
                            // assert incomingMessages.isEmpty();  // maybe the program didn't read all the messages
                            incomingMessages.clear();
                            // detached the compute property view from the vertex
                            final List<DetachedVertexProperty<Object>> nextView = vertexComputeKeysArray.length == 0
                                    ? // not all vertex programs have compute keys
                            Collections.emptyList()
                                    : IteratorUtils.list(IteratorUtils.map(
                                            vertex.properties(vertexComputeKeysArray),
                                            vertexProperty -> DetachedFactory.detach(vertexProperty, true)));
                            // drop compute property view as it has now been detached from the vertex
                            vertex.dropVertexProperties(vertexComputeKeysArray);
                            final List<Tuple2<Object, M>> outgoingMessages = messenger.getOutgoingMessages(); // get the outgoing messages being sent by this vertex
                            if (!partitionIterator.hasNext()) {
                                workerVertexProgram.workerIterationEnd(memory.asImmutable()); // if no more vertices in the partition, end the worker's iteration}
                            }
                            return (nextView.isEmpty() && outgoingMessages.isEmpty()) ? null : // if there is no view nor outgoing messages, emit nothing
                            new Tuple2<>(vertex.id(), new ViewOutgoingPayload<>(nextView, outgoingMessages)); // else, emit the vertex id, its view, and its outgoing messages
                        });
                    }, true) // true means that the partition is preserved
                    .filter(tuple -> null != tuple); // if there are no messages or views, then the tuple is null (memory optimization)
    // the graphRDD and the viewRDD must have the same partitioner
    if (partitionedGraphRDD) {
        assert graphRDD.partitioner().get().equals(viewOutgoingRDD.partitioner().get());
    }
    /////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////
    final PairFlatMapFunction<Tuple2<Object, ViewOutgoingPayload<M>>, Object, Payload> messageFunction = tuple -> IteratorUtils
            .concat(IteratorUtils.of(new Tuple2<>(tuple._1(), tuple._2().getView())), // emit the view payload
                    IteratorUtils.map(tuple._2().getOutgoingMessages().iterator(),
                            message -> new Tuple2<>(message._1(), new MessagePayload<>(message._2()))));
    final MessageCombiner<M> messageCombiner = VertexProgram
            .<VertexProgram<M>>createVertexProgram(HadoopGraph.open(vertexProgramConfiguration),
                    vertexProgramConfiguration)
            .getMessageCombiner().orElse(null);
    final Function2<Payload, Payload, Payload> reducerFunction = (a, b) -> { // reduce the view and outgoing messages into a single payload object representing the new view and incoming messages for a vertex
        if (a instanceof ViewIncomingPayload) {
            ((ViewIncomingPayload<M>) a).mergePayload(b, messageCombiner);
            return a;
        } else if (b instanceof ViewIncomingPayload) {
            ((ViewIncomingPayload<M>) b).mergePayload(a, messageCombiner);
            return b;
        } else {
            final ViewIncomingPayload<M> c = new ViewIncomingPayload<>(messageCombiner);
            c.mergePayload(a, messageCombiner);
            c.mergePayload(b, messageCombiner);
            return c;
        }
    };
    /////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////
    // "message pass" by reducing on the vertex object id of the view and message payloads
    final JavaPairRDD<Object, ViewIncomingPayload<M>> newViewIncomingRDD = (partitionedGraphRDD
            ? viewOutgoingRDD.flatMapToPair(messageFunction).reduceByKey(graphRDD.partitioner().get(),
                    reducerFunction)
            : viewOutgoingRDD.flatMapToPair(messageFunction).reduceByKey(reducerFunction))
                    .mapValues(payload -> { // handle various corner cases of when views don't exist, messages don't exist, or neither exists.
                        if (payload instanceof ViewIncomingPayload) {// this happens if there is a vertex view with incoming messages
                            return (ViewIncomingPayload<M>) payload;
                        } else if (payload instanceof ViewPayload) { // this happens if there is a vertex view with no incoming messages
                            return new ViewIncomingPayload<>((ViewPayload) payload);
                        } else { // this happens when there is a single message to a vertex that has no view or outgoing messages
                            return new ViewIncomingPayload<>((MessagePayload<M>) payload);
                        }
                    });
    // the graphRDD and the viewRDD must have the same partitioner
    if (partitionedGraphRDD) {
        assert graphRDD.partitioner().get().equals(newViewIncomingRDD.partitioner().get());
    }
    newViewIncomingRDD.foreachPartition(partitionIterator -> {
        KryoShimServiceLoader.applyConfiguration(graphComputerConfiguration);
    }); // need to complete a task so its BSP and the memory for this iteration is updated
    return newViewIncomingRDD;
}

From source file:apps.core.wcm.components.list.v1.list.List.java

public void activate() {
    request = getRequest();/*from  ww  w.  j  a  va 2  s  . co  m*/
    pageManager = getPageManager();
    properties = getProperties();
    resource = getResource();
    ResourceResolver resourceResolver = resource.getResourceResolver();
    readListConfiguration();
    listHTMLElement = Boolean.valueOf(ordered) ? "ol" : "ul";
    Source source = Source.getSource(listSource);
    if (source == null) {
        throw new IllegalArgumentException("Unknown list source: " + listSource);
    }
    Iterator<Page> pageIterator = Collections.emptyIterator();
    if (source == Source.CHILDREN) {
        String parentPath = properties.get(PROP_PARENT_PAGE, resource.getPath());
        Resource parentResource = resource.getPath().equals(parentPath) ? resource
                : resourceResolver.getResource(parentPath);
        Page startPage = pageManager.getContainingPage(parentResource);
        if (startPage != null) {
            pageIterator = startPage.listChildren();
        } else {
            pageIterator = Collections.emptyIterator();
        }
    } else if (source == Source.QUERYBUILDER) {
        QueryBuilder queryBuilder = resourceResolver.adaptTo(QueryBuilder.class);
        Session session = resourceResolver.adaptTo(Session.class);
        if (queryBuilder != null && session != null) {
            try {
                Query query = queryBuilder.loadQuery(resource.getPath() + "/" + PROP_SAVED_QUERY, session);
                if (query != null) {
                    query.setHitsPerPage(limit);
                    SearchResult result = query.getResult();
                    pageIterator = new HitPageIterator(pageManager, result.getHits().iterator(),
                            !allowDuplicates);
                }
            } catch (Exception e) {
                LOGGER.error("Unable to load stored query for " + resource.getPath(), e);
            }
        } else {
            LOGGER.error("Error loading query builder.");
        }
    } else if (source == Source.SEARCH) {
        if (!StringUtils.isEmpty(query)) {
            SimpleSearch search = resource.adaptTo(SimpleSearch.class);
            if (search != null) {
                search.setQuery(query);
                search.setSearchIn(startIn);
                search.addPredicate(new Predicate("type", "type").set("type", NameConstants.NT_PAGE));
                search.setHitsPerPage(limit);
                try {
                    SearchResult result = search.getResult();
                    pageIterator = new HitPageIterator(pageManager, result.getHits().iterator(),
                            !allowDuplicates);
                } catch (RepositoryException e) {
                    LOGGER.error("Unable to retrieve search results for query.", e);
                }
            }
        }
    } else if (source == Source.TAGS) {
        String parentPath = properties.get(PROP_TAG_SEARCH_ROOT, resource.getPath());
        String[] tags = properties.get(PROP_TAGS, new String[0]);
        boolean matchAny = properties.get(PROP_TAGS_MATCH, "any").equals("any");
        Page startPage = pageManager.getPage(parentPath);
        if (startPage != null && tags.length > 0) {
            TagManager tagManager = resourceResolver.adaptTo(TagManager.class);
            RangeIterator<Resource> rangeIterator = tagManager.find(startPage.getPath(), tags, matchAny);
            java.util.List<Page> taggedPages = new ArrayList<>();
            while (rangeIterator.hasNext()) {
                Resource r = rangeIterator.next();
                taggedPages.add(pageManager.getContainingPage(r));
            }
            pageIterator = taggedPages.iterator();
        }
    } else if (source == Source.STATIC) {
        String[] pagesPaths = properties.get(PROP_PAGES, new String[0]);
        java.util.List<Page> pages = new ArrayList<>(pagesPaths.length);
        for (String path : pagesPaths) {
            Page page = pageManager.getContainingPage(path);
            if (page != null) {
                pages.add(page);
            }
        }
        pageIterator = pages.iterator();
    }
    if (!pageIterator.hasNext() && LOGGER.isDebugEnabled()) {
        LOGGER.debug("Cannot find any elements for this list.");
    } else {
        resultPages = new ArrayList<>();
        while (pageIterator.hasNext()) {
            Page page = pageIterator.next();
            resultPages.add(page);
        }
        if (StringUtils.isNotEmpty(orderBy)) {
            Collections.sort(resultPages, new PageComparator(orderBy));
        }
        if (resultPages.size() > limit) {
            resultPages = resultPages.subList(0, limit);
        }
        int index = 0, count = 0;
        for (Page p : resultPages) {
            if (pageMax > 0 && count >= pageMax) {
                break;
            }
            if (pageStart >= 0 && index < pageStart) {
                index++;
                continue;
            }
            ListItem item = new ListItem(p.getTitle(), p.getPath(), p.getLastModified(), p.getDescription(),
                    hasImage(p.adaptTo(Resource.class)));
            listItems.add(item);
            count++;
        }
    }

}

From source file:io.wcm.caconfig.extensions.contextpath.impl.AbsoluteParentContextPathStrategy.java

@Override
public @NotNull Iterator<ContextResource> findContextResources(@NotNull Resource resource) {
    if (!isValidConfig()) {
        return Collections.emptyIterator();
    }//from  www. ja  va2  s.co  m

    ResourceResolver resourceResolver = resource.getResourceResolver();
    PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
    List<ContextResource> contextResources = new ArrayList<>();

    int maxLevel = Path.getAbsoluteLevel(resource.getPath(), resourceResolver);
    for (int level = 0; level <= maxLevel; level++) {
        if (levels.contains(level) || (unlimited && level >= unlimitedLevelStart)) {
            String contextPath = Path.getAbsoluteParent(resource.getPath(), level, resourceResolver);
            if (StringUtils.isNotEmpty(contextPath)) {
                Resource contextResource = resource.getResourceResolver().getResource(contextPath);
                if (contextResource != null) {
                    // first check if resource is blacklisted
                    if (isResourceBelongingToBlacklistedTemplates(contextResource, pageManager)) {
                        log.trace(
                                "Resource '{}' is belonging to a page derived from a blacklisted template, skipping level {}",
                                contextPath, level);
                        break;
                    }
                    for (String configPathPattern : configPathPatterns) {
                        String configRef = deriveConfigRef(contextPath, configPathPattern, resourceResolver);
                        if (configRef != null) {
                            contextResources
                                    .add(new ContextResource(contextResource, configRef, serviceRanking));
                        }
                    }
                }
            }
        }
    }

    Collections.reverse(contextResources);
    return contextResources.iterator();
}

From source file:com.adobe.acs.commons.packaging.impl.PackageHelperImplTest.java

@Test
public void testAddThumbnail() throws Exception {
    Resource thumbnailResource = mock(Resource.class);
    Node thumbnailNode = mock(Node.class);
    NodeType ntFile = mock(NodeType.class);

    when(thumbnailResource.adaptTo(Node.class)).thenReturn(thumbnailNode);
    when(thumbnailNode.isNodeType("nt:file")).thenReturn(true);
    when(thumbnailNode.getPrimaryNodeType()).thenReturn(ntFile);
    when(ntFile.getName()).thenReturn("nt:file");
    when(thumbnailNode.getMixinNodeTypes()).thenReturn(new NodeType[0]);
    when(thumbnailNode.getProperties()).thenReturn(new PropertyIteratorAdapter(Collections.emptyIterator()));
    when(thumbnailNode.getNodes()).thenReturn(new NodeIteratorAdapter(Collections.emptyIterator()));

    when(packageOneDefNode.getSession()).thenReturn(mock(Session.class));

    packageHelper.addThumbnail(packageOne, thumbnailResource);

    // Verification
    verify(packageOneDefNode, times(1)).addNode(eq("thumbnail.png"), eq("nt:file"));
}

From source file:com.intuit.wasabi.repository.cassandra.impl.CassandraPagesRepository.java

Stream<AppPage> getAppPagesFromCassandra(Application.Name applicationName) {
    Optional<Iterator<AppPage>> optionalResult = Optional.empty();
    try {//from  ww w  .  j  ava 2s  .  com
        optionalResult = Optional
                .ofNullable(appPageIndexAccessor.selectBy(applicationName.toString()).iterator());
    } catch (ReadTimeoutException | UnavailableException | NoHostAvailableException e) {
        throw new RepositoryException(
                "Could not retrieve the pages and its associated experiments for application:\""
                        + applicationName + "\"",
                e);
    }
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
            optionalResult.orElse(Collections.emptyIterator()), Spliterator.ORDERED), false);
}

From source file:com.emc.ecs.sync.source.S3Source.java

/**
 * This source is designed to query all objects under the root prefix as a flat list of results (no hierarchy),
 * which means <strong>no</strong> objects should have children
 *//*from  ww  w .ja v a  2 s.c o  m*/
@Override
public Iterator<S3SyncObject> childIterator(S3SyncObject syncObject) {
    return Collections.emptyIterator();
}

From source file:name.marcelomorales.siqisiqi.examples.crud.webapp.HomePage.java

public HomePage(final PageParameters parameters) {
    super(parameters);

    add(new Form<Void>("newdept") {

        final Model<String> deptNameModel;
        final Model<String> buildingModel;

        {//w  w w  .  ja v a 2 s.  co m
            add(new TextField<>("deptname", deptNameModel = Model.of("")));
            add(new TextField<>("building", buildingModel = Model.of("")));
        }

        @Override
        protected void onSubmit() {
            empDeptDao.newDept(deptNameModel.getObject(), buildingModel.getObject());
            setResponsePage(HomePage.class);
        }
    });

    add(new DefaultDataTable<>("depts",
            ImmutableList.<IColumn<Dept, String>>of(new PropertyColumn<Dept, String>(Model.of("id"), "deptno"),
                    new PropertyColumn<Dept, String>(Model.of("totalSalaries"), "totalSalaries"),
                    new PropertyColumn<Dept, String>(Model.of("building"), "building"),
                    new PropertyColumn<Dept, String>(Model.of("deptname"), "deptname")),
            new SortableDataProvider<Dept, String>() {

                @Override
                public Iterator<? extends Dept> iterator(long first, long count) {
                    return deptRepository.findByExample(null, null, null, first, count).iterator();
                }

                @Override
                public long size() {
                    return deptRepository.count();
                }

                @Override
                public IModel<Dept> model(Dept object) {
                    Dept dept = new Dept();
                    BeanUtils.copyProperties(object, dept);
                    return Model.of(dept);
                }
            }, 5));

    add(new Form<Emp>("newemp", new CompoundPropertyModel<>(Model.of(new Emp()))) {
        {
            add(new TextField<String>("fname"));
            add(new TextField<String>("lname"));
            add(new DropDownChoice<>("sex", ImmutableList.copyOf(Sex.values())));
            add(new TextField<String>("ssn"));
            add(new TextField<BigDecimal>("salary"));
            add(new DropDownChoice<>("dept", new LoadableDetachableModel<List<Dept>>() {

                @Override
                protected List<Dept> load() {
                    return Lists.newLinkedList(deptRepository.findAll());
                }
            }, new ChoiceRenderer<Dept>("deptname")));
        }

        @Override
        protected void onSubmit() {
            empDeptDao.saveEmp(getModelObject());
            setResponsePage(HomePage.class);
        }
    });

    add(new DefaultDataTable<>("emps",
            ImmutableList.<IColumn<Emp, String>>of(new PropertyColumn<Emp, String>(Model.of("id"), "empid"),
                    new PropertyColumn<Emp, String>(Model.of("fname"), "fname"),
                    new PropertyColumn<Emp, String>(Model.of("lname"), "lname"),
                    new PropertyColumn<Emp, String>(Model.of("sex"), "sex"),
                    new PropertyColumn<Emp, String>(Model.of("ssn"), "ssn"),
                    new PropertyColumn<Emp, String>(Model.of("salary"), "salary"),
                    new PropertyColumn<Emp, String>(Model.of("dept"), "dept.deptname")),
            new SortableDataProvider<Emp, String>() {

                @Override
                public Iterator<? extends Emp> iterator(long first, long count) {
                    return empRepository.findByExample(null, null, null, first, count).iterator();
                }

                @Override
                public long size() {
                    return empRepository.count();
                }

                @Override
                public IModel<Emp> model(Emp object) {
                    Emp emp = new Emp();
                    BeanUtils.copyProperties(object, emp);
                    return Model.of(emp);
                }
            }, 5));

    fullTextModel = Model.of("");
    add(new Form<String>("fulltexts", fullTextModel) {
        {
            add(new TextField<>("search", getModel()));
        }
    });

    add(new DefaultDataTable<>("fulltextdept",
            ImmutableList.<IColumn<Dept, String>>of(new PropertyColumn<Dept, String>(Model.of("id"), "deptno"),
                    new PropertyColumn<Dept, String>(Model.of("totalSalaries"), "totalSalaries"),
                    new PropertyColumn<Dept, String>(Model.of("building"), "building"),
                    new PropertyColumn<Dept, String>(Model.of("deptname"), "deptname")),
            new SortableDataProvider<Dept, String>() {

                @Override
                public Iterator<? extends Dept> iterator(long first, long count) {
                    return deptRepository.findByFullTexts(fullTextModel.getObject(), null, first, count)
                            .iterator();
                }

                @Override
                public long size() {
                    return deptRepository.countByFullTexts(fullTextModel.getObject());
                }

                @Override
                public IModel<Dept> model(Dept object) {
                    Dept dept = new Dept();
                    BeanUtils.copyProperties(object, dept);
                    return Model.of(dept);
                }
            }, 5));

    sexModel = Model.of();
    add(new Form<Sex>("findBySex", sexModel) {
        {
            add(new DropDownChoice<>("sex", getModel(), ImmutableList.copyOf(Sex.values())));
        }
    });

    add(new DefaultDataTable<>("empbysex",
            ImmutableList.<IColumn<Emp, String>>of(new PropertyColumn<Emp, String>(Model.of("id"), "empid"),
                    new PropertyColumn<Emp, String>(Model.of("fname"), "fname"),
                    new PropertyColumn<Emp, String>(Model.of("lname"), "lname"),
                    new PropertyColumn<Emp, String>(Model.of("sex"), "sex"),
                    new PropertyColumn<Emp, String>(Model.of("ssn"), "ssn"),
                    new PropertyColumn<Emp, String>(Model.of("salary"), "salary"),
                    new PropertyColumn<Emp, String>(Model.of("dept"), "dept.deptname")),
            new SortableDataProvider<Emp, String>() {

                @Override
                public Iterator<? extends Emp> iterator(long first, long count) {
                    if (sexModel.getObject() == null) {
                        return Collections.emptyIterator();
                    }
                    return empRepository.findBySex(sexModel.getObject(), new PageRequest((int) (first / 5), 5))
                            .iterator();
                }

                @Override
                public long size() {
                    if (sexModel.getObject() == null) {
                        return 0;
                    }
                    return empRepository.countBySex(sexModel.getObject());
                }

                @Override
                public IModel<Emp> model(Emp object) {
                    Emp emp = new Emp();
                    BeanUtils.copyProperties(object, emp);
                    return Model.of(emp);
                }
            }, 5));

    add(new WebMarkupContainer("stats", new CompoundPropertyModel<>(new LoadableDetachableModel<Statistics>() {

        @Override
        protected Statistics load() {
            return boneCPAdm.getStatistics();
        }
    })) {
        {
            add(new Label("connectionsRequested"));
            add(new Label("statementExecuteTimeAvg"));
            add(new Label("statementsExecuted"));
            add(new Label("totalCreatedConnections"));
            add(new Label("totalFree"));
        }
    });

}

From source file:com.emc.ecs.sync.source.EcsS3Source.java

/**
 * This source is designed to query all objects under the root prefix as a flat list of results (no hierarchy),
 * which means <strong>no</strong> objects should have children
 *//*from ww  w.j a va  2  s.c om*/
@Override
public Iterator<EcsS3SyncObject> childIterator(EcsS3SyncObject syncObject) {
    return Collections.emptyIterator();
}

From source file:fr.landel.utils.commons.StringUtilsTest.java

/**
 * Test method for {@link StringUtils#join(Iterable, String, Function)}
 * {@link StringUtils#join(Iterator, String, Function)} .
 *///  ww  w  . j  a va2s. c  om
@Test
public void testJoin() {
    Function<Object, String> fKey = e -> "x" + String.valueOf(e);

    assertNull(StringUtils.join((Iterable<?>) null, null, null));
    assertEquals("", StringUtils.join(Collections.emptyList(), null, null));
    assertEquals("v", StringUtils.join(Arrays.asList("v"), null, null));
    assertEquals("xv", StringUtils.join(Arrays.asList("v"), null, fKey));
    assertEquals("12", StringUtils.join(Arrays.asList(1, 2), null, null));
    assertEquals("x1,x2", StringUtils.join(Arrays.asList(1, 2), ",", fKey));

    Function<String, String> fKeyStr = e -> "x" + String.valueOf(e);
    Function<Integer, String> fKeyInt = e -> "x" + String.valueOf(e);

    assertNull(StringUtils.join((Iterator<?>) null, null, null));
    assertEquals("", StringUtils.join(Collections.emptyIterator(), null, null));
    assertEquals("v", StringUtils.join(Arrays.asList("v").iterator(), null, null));
    assertEquals("xv", StringUtils.join(Arrays.asList("v").iterator(), null, fKeyStr));
    assertEquals("12", StringUtils.join(Arrays.asList(1, 2).iterator(), null, null));
    assertEquals("x1,x2", StringUtils.join(Arrays.asList(1, 2).iterator(), ",", fKeyInt));

    assertNull(StringUtils.join((Object[]) null, null, 0, 0, null));
    assertEquals("", StringUtils.join(new Object[0], null, 0, 0, null));
    assertEquals("v", StringUtils.join(new Object[] { "v", null }, null, 0, 2, null));
    assertEquals("v", StringUtils.join(new Object[] { "v" }, null, 0, 1, null));
    assertEquals("", StringUtils.join(new Object[] { "v" }, null, 1, 1, null));
    assertEquals("xv", StringUtils.join(new Object[] { "v" }, null, 0, 1, fKey));
    assertEquals("12", StringUtils.join(new Object[] { 1, 2 }, null, 0, 2, null));
    assertEquals("1", StringUtils.join(new Object[] { 1, 2 }, null, 0, 1, null));
    assertEquals("x1,x2", StringUtils.join(new Object[] { 1, 2 }, ",", 0, 2, fKey));
    assertEquals("x2", StringUtils.join(new Object[] { 1, 2 }, ",", 1, 2, fKey));

    assertNull(StringUtils.join((Object[]) null, null, null));
    assertEquals("", StringUtils.join(new Object[0], null, null));
    assertEquals("v", StringUtils.join(new Object[] { "v" }, null, null));
    assertEquals("xv", StringUtils.join(new Object[] { "v" }, null, fKey));
    assertEquals("12", StringUtils.join(new Object[] { 1, 2 }, null, null));
    assertEquals("x1,x2", StringUtils.join(new Object[] { 1, 2 }, ",", fKey));
}

From source file:net.orfjackal.retrolambda.test.DefaultMethodsTest.java

@Test
public void trying_to_use_default_methods_of_library_interfaces_causes_NoSuchMethodError() {
    assumeThat(SystemUtils.JAVA_VERSION_FLOAT, is(lessThan(1.8f)));

    class C implements Iterable<String> {
        @Override/*from   ww w. j a v  a2  s  .  c  o m*/
        public Iterator<String> iterator() {
            return Collections.emptyIterator();
        }
    }

    thrown.expect(NoSuchMethodError.class);
    thrown.expectMessage("spliterator");
    // Called directly on the class (invokevirtual) instead of the interface (invokeinterface),
    // to make sure that no method was inserted to the class (in which case this call would not fail)
    new C().spliterator();
}