Java Code Examples for org.apache.commons.collections4.IteratorUtils#toList()

The following examples show how to use org.apache.commons.collections4.IteratorUtils#toList() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OccurrenceIndexTest.java    From ontopia with Apache License 2.0 6 votes vote down vote up
@Test
public void testValuesSmallerThanOrEqual() {
  Assert.assertFalse(ix.getValuesSmallerThanOrEqual("").hasNext());
  
  builder.makeOccurrence(builder.makeTopic(), builder.makeTopic(), "a");
  builder.makeOccurrence(builder.makeTopic(), builder.makeTopic(), "b");
  builder.makeOccurrence(builder.makeTopic(), builder.makeTopic(), "c");
  
  List<String> values = IteratorUtils.toList(ix.getValuesSmallerThanOrEqual("c"));
  
  Assert.assertEquals(3, values.size());
  Assert.assertTrue(values.contains("a"));
  Assert.assertTrue(values.contains("b"));
  Assert.assertTrue(values.contains("c"));

  values = IteratorUtils.toList(ix.getValuesSmallerThanOrEqual("a"));
  Assert.assertEquals(1, values.size());
  Assert.assertTrue(values.contains("a"));
}
 
Example 2
Source File: TologQueryTag.java    From ontopia with Apache License 2.0 6 votes vote down vote up
/**
  * INTERNAL: Wraps a QueryResultIF instance in a suitable
  * MapCollection implementation.
  */ 
 protected Collection getMapCollection(QueryResultIF result) {

   if (select != null) {
     int index = result.getIndex(select);
     if (index < 0)
throw new IndexOutOfBoundsException("No query result column named '" + select + "'");

     List list = new ArrayList();
     while (result.next())
       list.add(result.getValue(index));
     result.close();
     return list;
   }

   if (result instanceof net.ontopia.topicmaps.query.impl.basic.QueryResult)
     // BASIC
     return net.ontopia.topicmaps.query.impl.basic.QueryResultWrappers.getWrapper(result);
   else {
     // FIXME: Should pass collection size if available.
     return IteratorUtils.toList(new QueryResultIterator(result));
   }
 }
 
Example 3
Source File: AbstractMemSearchTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
protected void checkMarkerSet(List<Address> expected) {

		TableComponentProvider<?>[] providers = tableServicePlugin.getManagedComponents();
		TableComponentProvider<?> tableProvider = providers[0];
		assertTrue(tool.isVisible(tableProvider));

		List<Address> highlights = getHighlightAddresses();
		assertListEqualUnordered("Search highlights not correctly generated", expected, highlights);

		MarkerSet markers =
			runSwing(() -> markerService.getMarkerSet(tableProvider.getName(), program));
		assertNotNull(markers);

		AddressSet addressSet = runSwing(() -> markers.getAddressSet());
		AddressIterator it = addressSet.getAddresses(true);
		List<Address> list = IteratorUtils.toList(it);

		assertListEqualUnordered("Search markers not correctly generated", expected, list);
	}
 
Example 4
Source File: TupleCombiner.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the set of once-only tuple definitions for this combiner.
 */
private Set<Tuple> getOnceTupleDefs( final List<VarDef> combinedVars)
  {
  try
    {
    return
      new HashSet<Tuple>(
        IteratorUtils.toList(
          IteratorUtils.transformedIterator(
            getOnceTuples(),
            tupleRef -> toTuple( combinedVars, tupleRef))));
    }
  catch( Exception e)
    {
    throw new IllegalStateException( "Invalid once-only tuple definition", e);
    }
  }
 
Example 5
Source File: HBaseWriterFunctionTest.java    From metron with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteNone() throws Exception {

  // there are no profile measurements to write
  List<ProfileMeasurement> measurements = new ArrayList<>();

  // setup the function to test
  HBaseWriterFunction function = new HBaseWriterFunction(profilerProperties);
  function.withTableProviderImpl(MockHBaseTableProvider.class.getName());

  // write the measurements
  Iterator<Integer> results = function.call(measurements.iterator());

  // validate the result
  List<Integer> counts = IteratorUtils.toList(results);
  assertEquals(1, counts.size());
  assertEquals(0, counts.get(0).intValue());
}
 
Example 6
Source File: IndexResource.java    From ontopia with Apache License 2.0 6 votes vote down vote up
protected Collection<?> getOccurrences(String value, String datatype) {
	OccurrenceIndexIF index = getIndex(OccurrenceIndexIF.class);
	
	try {
		switch (getAttribute("type").toUpperCase()) {
			case "VALUE":
				if (datatype == null) return index.getOccurrences(value);
				else return index.getOccurrences(value, new URILocator(datatype));
			case "PREFIX":
				if (value == null) throw OntopiaRestErrors.MANDATORY_ATTRIBUTE_IS_NULL.build("value", "String");
				if (datatype == null) return index.getOccurrencesByPrefix(value);
				else return index.getOccurrencesByPrefix(value, new URILocator(datatype));
			case "GTE": return IteratorUtils.toList(index.getValuesGreaterThanOrEqual(value));
			case "LTE": return IteratorUtils.toList(index.getValuesSmallerThanOrEqual(value));

			default: 
				setStatus(Status.CLIENT_ERROR_NOT_FOUND, TYPE_ERROR_MESSAGE);
				return null;
		}
	} catch (MalformedURLException mufe) {
		throw OntopiaRestErrors.MALFORMED_LOCATOR.build(mufe, datatype);
	}
}
 
Example 7
Source File: TestTupleGenerator.java    From tcases with MIT License 6 votes vote down vote up
@Test
public void getTests_FromBaseTests_Same()
  {
  // Given...
  SystemInputDef systemInputDef = getSystemInputDefBase();
  FunctionInputDef functionInputDef = systemInputDef.getFunctionInputDef( "Make");
  TupleGenerator generator = new TupleGenerator();

  generator.addCombiner
    ( new TupleCombiner(2)
      .addIncludedVar( "Shape")
      .addIncludedVar( "Size"));
  
  // When...
  FunctionTestDef baseTestDef = generator.getTests( functionInputDef, null);
  FunctionTestDef functionTestDef = generator.getTests( functionInputDef, baseTestDef);

  // Expect...
  List<TestCase> expectedTestCases = IteratorUtils.toList( baseTestDef.getTestCases());
  List<TestCase> actualTestCases = IteratorUtils.toList( functionTestDef.getTestCases());
  assertThat( "When base tests same", actualTestCases, containsMembers( expectedTestCases));
  }
 
Example 8
Source File: HBaseWriterFunctionTest.java    From metron with Apache License 2.0 6 votes vote down vote up
@Test
public void testWrite() throws Exception {

  JSONObject message = getMessage();
  String entity = (String) message.get("ip_src_addr");
  long timestamp = (Long) message.get("timestamp");
  ProfileConfig profile = getProfile();

  // setup the profile measurements that will be written
  List<ProfileMeasurement> measurements = createMeasurements(1, entity, timestamp, profile);

  // setup the function to test
  HBaseWriterFunction function = new HBaseWriterFunction(profilerProperties);
  function.withTableProviderImpl(MockHBaseTableProvider.class.getName());

  // write the measurements
  Iterator<Integer> results = function.call(measurements.iterator());

  // validate the result
  List<Integer> counts = IteratorUtils.toList(results);
  assertEquals(1, counts.size());
  assertEquals(1, counts.get(0).intValue());
}
 
Example 9
Source File: TestVertexNavToEdges.java    From sqlg with MIT License 6 votes vote down vote up
@Test
public void testFromVertexGetEdges() {
    Vertex v1 = sqlgGraph.addVertex();
    Vertex v2 = sqlgGraph.addVertex();
    Edge e = v1.addEdge("label1", v2, "name", "marko");
    sqlgGraph.tx().commit();
    assertDb(Topology.EDGE_PREFIX + "label1", 1);
    assertDb(Topology.VERTEX_PREFIX  +  "vertex", 2);

    Iterator<Edge> edges = v1.edges(Direction.BOTH, "label1");
    List<Edge> toList= IteratorUtils.toList(edges);
    assertEquals(1, toList.size());
    Edge edge = toList.get(0);
    assertEquals(e, edge);
    String name = edge.<String>property("name").value();
    assertEquals("marko", name);

    assertFalse(vertexTraversal(this.sqlgGraph, v1).inE("label1").hasNext());
    edge = vertexTraversal(this.sqlgGraph, v1).bothE("label1").next();
    assertEquals(e, edge);

    name = edge.<String>property("name").value();
    assertEquals("marko", name);
}
 
Example 10
Source File: AssertTestDef.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns a list of tuples combining the give var binding with all bindings for the other variable (set).
 */
public static Iterable<Tuple> tuplesFor( FunctionInputDef inputDef, String var, String value, String otherVar)
  {
  List<Tuple> tuples = new ArrayList<Tuple>();

  IVarDef otherVarDef = inputDef.findVarPath( otherVar);
  List<VarDef> otherVarDefs =
    otherVarDef.getMembers() == null
    ? Arrays.asList( (VarDef) otherVarDef)
    : IteratorUtils.toList( new VarDefIterator( otherVarDef.getMembers()));

  TupleBuilder builder = tupleFor( inputDef);
  for( VarDef varDef : otherVarDefs)
    {
    for( Iterator<VarValueDef> values = varDef.getValues(); values.hasNext(); )
      {
      tuples.add
        ( builder
          .clear()
          .bind( var, value)
          .bind( varDef.getPathName(), values.next().getName())
          .build());
      }
    }
  
  return tuples;
  }
 
Example 11
Source File: HBaseWriterFunction.java    From metron with Apache License 2.0 5 votes vote down vote up
/**
 * Writes a set of measurements to HBase.
 *
 * @param iterator The measurements to write.
 * @return The number of measurements written to HBase.
 */
@Override
public Iterator<Integer> call(Iterator<ProfileMeasurement> iterator) throws Exception {
  int count = 0;
  LOG.debug("About to write profile measurement(s) to HBase");

  // do not open hbase connection, if nothing to write
  List<ProfileMeasurement> measurements = IteratorUtils.toList(iterator);
  if(measurements.size() > 0) {

    // open an HBase connection
    Configuration config = HBaseConfiguration.create();
    try (HBaseClient client = new HBaseClient(tableProvider, config, tableName)) {

      for (ProfileMeasurement m : measurements) {
        client.addMutation(rowKeyBuilder.rowKey(m), columnBuilder.columns(m), durability);
      }
      count = client.mutate();

    } catch (IOException e) {
      LOG.error("Unable to open connection to HBase", e);
      throw new RuntimeException(e);
    }
  }

  LOG.debug("{} profile measurement(s) written to HBase", count);
  return IteratorUtils.singletonIterator(count);
}
 
Example 12
Source File: Asserts.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns a list containing the given sequence of elements.
 */
public static <T> List<T> toList( Iterator<T> elements)
  {
  return
    elements == null
    ? null
    : IteratorUtils.toList( elements);
  }
 
Example 13
Source File: AssertTestDef.java    From tcases with MIT License 5 votes vote down vote up
/**
 * If <CODE>included</CODE> is true, returns the subset of the given set of tuples that are included in at least one test case
 * from the given test definition.
 *
 * Otherwise, if <CODE>included</CODE> is false, returns the subset of the given set of tuples that are not included in any test case.
 */
private static Collection<Tuple> getTuplesIncluded( Collection<Tuple> tuples, final FunctionTestDef testDef, final boolean included)
  {
  return
    IteratorUtils.toList(
      IteratorUtils.filteredIterator(
        tuples.iterator(),
        tuple ->
          IteratorUtils.filteredIterator(
            testDef.getTestCases(),
            testCase -> testCaseIncludes( testCase, tuple))
          .hasNext() == included));
    }
 
Example 14
Source File: RequestUtils.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
/**
 * From a given request, return the best locale for the user
 *
 * @param request
 * @param event
 * @return
 */
public static Locale getMatchingLocale(ServletWebRequest request, Event event) {
    var allowedLanguages = event.getContentLanguages().stream().map(ContentLanguage::getLanguage).collect(Collectors.toSet());
    var l = request.getNativeRequest(HttpServletRequest.class).getLocales();
    List<Locale> locales = l != null ? IteratorUtils.toList(l.asIterator()) : Collections.emptyList();
    var selectedLocale = locales.stream().map(Locale::getLanguage).filter(allowedLanguages::contains).findFirst()
        .orElseGet(() -> event.getContentLanguages().stream().findFirst().get().getLanguage());
    return LocaleUtil.forLanguageTag(selectedLocale);
}
 
Example 15
Source File: TupleGenerator.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the members of the given set of input variables not bound by the given test case.
 */
private List<VarDef> getVarsRemaining( Iterator<VarDef> vars, final TestCaseDef testCase)
  {
  return
    IteratorUtils.toList(
      IteratorUtils.filteredIterator(
        vars,
        var -> testCase.getBinding( var) == null));
  }
 
Example 16
Source File: ObjectTableView.java    From OpenLabeler with Apache License 2.0 4 votes vote down vote up
public ObjectTableView() {
    super(null);
    FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/ObjectTableView.fxml"), bundle);
    loader.setRoot(this);
    loader.setController(this);

    try {
        loader.load();
    }
    catch (Exception ex) {
        LOG.log(Level.SEVERE, "Unable to load FXML", ex);
    }

    getSelectionModel().setSelectionMode(SelectionMode.SINGLE);

    showAllCheckBox.setAllowIndeterminate(true);

    visibleColumn.setCellFactory(CheckBoxTableCell.forTableColumn(visibleColumn));
    visibleColumn.setCellValueFactory(cell -> cell.getValue().visibleProperty());

    thumbColumn.setCellFactory(param -> new ImageViewTableCell<>());
    thumbColumn.setCellValueFactory(cell -> cell.getValue().thumbProperty());

    List<String> names = IteratorUtils.toList(Settings.recentNamesProperty.stream().map(NameColor::getName).iterator());
    nameColumn.setCellFactory(ComboBoxTableCell.forTableColumn(FXCollections.observableList(names)));
    nameColumn.setCellValueFactory(cell -> cell.getValue().nameProperty());

    itemsProperty().addListener((observable, oldValue, newValue) -> {
        ObservableList<ObservableValue<Boolean>> visibles = EasyBind.map(newValue, ObjectTag::visibleProperty);
        visibleCount = EasyBind.combine(visibles, stream -> stream.filter(b -> b).count());
        visibleCount.addListener((obs, oldCount, newCount) -> {
            if (newCount == 0) {
                showAllCheckBox.setIndeterminate(false);
                showAllCheckBox.setSelected(false);
            }
            else if (newCount < getItems().size()) {
                showAllCheckBox.setIndeterminate(true);
            }
            else {
                showAllCheckBox.setIndeterminate(false);
                showAllCheckBox.setSelected(true);
            }
        });
    });
}
 
Example 17
Source File: MRCounters.java    From tez with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public synchronized Collection<String> getGroupNames() {
  return IteratorUtils.toList(raw.getGroupNames().iterator());  }
 
Example 18
Source File: children.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response){

        final SlingScriptHelper sling = getScriptHelper(request);

        final ExpressionHelper ex = new ExpressionHelper(sling.getService(ExpressionResolver.class), request);
        final Config dsCfg = new Config(request.getResource().getChild(Config.DATASOURCE));
        final CommerceBasePathsService cbps = sling.getService(CommerceBasePathsService.class);

        final String query = ex.getString(dsCfg.get("query", String.class));

        final String parentPath;
        final String searchName;
        final String rootPath = ex.getString(dsCfg.get("rootPath", cbps.getProductsBasePath()));

        if (query != null) {
            final int slashIndex = query.lastIndexOf('/');
            if (slashIndex < 0) {
                parentPath = rootPath;
                searchName = query.toLowerCase();
            } else if (!query.startsWith(rootPath)) {
                parentPath = rootPath;
                searchName = null;
            } else if (slashIndex == query.length() - 1) {
                parentPath = query;
                searchName = null;
            } else {
                parentPath = query.substring(0, slashIndex + 1);
                searchName = query.substring(slashIndex + 1).toLowerCase();
            }
        } else {
            parentPath = ex.getString(dsCfg.get("path", String.class));
            searchName = null;
        }

        final Resource parent = request.getResourceResolver().getResource(parentPath);

        final DataSource ds;
        if (parent == null) {
            ds = EmptyDataSource.instance();
        } else {
            final Integer offset = ex.get(dsCfg.get("offset", String.class), Integer.class);
            final Integer limit = ex.get(dsCfg.get("limit", String.class), Integer.class);
            final String itemRT = dsCfg.get("itemResourceType", String.class);
            final String filter = ex.getString(dsCfg.get("filter", String.class));

            final Collection<Predicate<Resource>> predicates = new ArrayList<>(2);
            predicates.add(createPredicate(filter));

            if (searchName != null) {
                final Pattern searchNamePattern = Pattern.compile(Pattern.quote(searchName), Pattern.CASE_INSENSITIVE);
                predicates.add(resource -> searchNamePattern.matcher(resource.getName()).lookingAt());
            }

            final Predicate predicate = PredicateUtils.allPredicate(predicates);
            final Transformer transformer = createTransformer(itemRT, predicate);


            final List<Resource> list;
            if (FILTER_CATEGORY.equals(filter)) {
                class CategoryFinder extends AbstractResourceVisitor {
                    private CategoryPredicate categoryPredicate = new CategoryPredicate();
                    private List<Resource> categories = new ArrayList<Resource>();
                    @Override
                    protected void visit(Resource res) {
                        if (categoryPredicate.evaluate(res)) {
                            categories.add(res);
                        }
                    }
                };
                CategoryFinder categoryFinder = new CategoryFinder();
                categoryFinder.accept(parent);
                list = IteratorUtils.toList(new FilterIterator(categoryFinder.categories.iterator(), predicate));
            } else {
                list =IteratorUtils.toList(new FilterIterator(parent.listChildren(), predicate));
            }

            //force reloading the children of the root node to hit the virtual resource provider
            if (rootPath.equals(parentPath)) {
                for (int i = 0; i < list.size(); i++) {
                    list.set(i, request.getResourceResolver().getResource(list.get(i).getPath()));
                }
            }

            @SuppressWarnings("unchecked")
            DataSource datasource = new AbstractDataSource() {

                public Iterator<Resource> iterator() {
                    Collections.sort(list, Comparator.comparing(Resource::getName));
                    return new TransformIterator(new PagingIterator<>(list.iterator(), offset, limit), transformer);
                }
            };

            ds = datasource;
        }

        request.setAttribute(DataSource.class.getName(), ds);
    }
 
Example 19
Source File: IterableToCollectionUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void whenConvertIteratorToListUsingApacheCommons_thenSuccess() {
    List<String> result = IteratorUtils.toList(iterator);

    assertThat(result, contains("john", "tom", "jane"));
}
 
Example 20
Source File: Schema2MarkupProperties.java    From swagger2markup with Apache License 2.0 2 votes vote down vote up
/**
 * Return the list of keys.
 *
 * @return the list of keys.
 */
public List<String> getKeys() {
    return IteratorUtils.toList(configuration.getKeys());
}