org.apache.commons.collections4.IteratorUtils Java Examples

The following examples show how to use org.apache.commons.collections4.IteratorUtils. 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: SystemTestHtmlWriter.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Writes the input value definitions for all variables of the given type.
 */
protected void writeInputs( TestCase testCase, String type)
  {
  Iterator<VarBinding> varBindings =
    IteratorUtils.filteredIterator
      ( testCase.getVarBindings( type),
        binding -> !binding.isValueNA());

  if( varBindings.hasNext())
    {
    xmlWriter_
      .element( "DIV")
      .attribute( "class", "input " + type)
      .content( () ->
        {
        if( !IVarDef.ARG.equals( type))
          {
          xmlWriter_.element( "H3").content( type).write();
          }
  
        writeVarSets( 0, varBindings);
        })
      .write();
    }
  }
 
Example #2
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 #3
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 #4
Source File: TabuSearch.java    From tabu with MIT License 6 votes vote down vote up
/**
 * Execute the algorithm to perform a minimization.
 * @param initialSolution the start point of the algorithm
 * @return the best solution found in the given conditions
 */
public Solution run(Solution initialSolution) {
	Solution bestSolution = initialSolution;
	Solution currentSolution = initialSolution;
	
	Integer currentIteration = 0;
	while (!stopCondition.mustStop(++currentIteration, bestSolution)) {
		
		List<Solution> candidateNeighbors = currentSolution.getNeighbors();
		List<Solution> solutionsInTabu = IteratorUtils.toList(tabuList.iterator());
		
		Solution bestNeighborFound = solutionLocator.findBestNeighbor(candidateNeighbors, solutionsInTabu);
		if (bestNeighborFound.getValue() < bestSolution.getValue()) {
			bestSolution = bestNeighborFound;
		}
		
		tabuList.add(currentSolution);
		currentSolution = bestNeighborFound;
		
		tabuList.updateSize(currentIteration, bestSolution);
	}
	
	return bestSolution;
}
 
Example #5
Source File: HBaseWriterFunctionTest.java    From metron with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteMany() 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(10, 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(10, counts.get(0).intValue());
}
 
Example #6
Source File: ToolActions.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Iterator<DockingActionIf> getAllActionsIterator() {

		// chain all items together, rather than copy the data
		Iterator<DockingActionIf> iterator = IteratorUtils.emptyIterator();
		Collection<Map<String, Set<DockingActionIf>>> maps = actionsByNameByOwner.values();
		for (Map<String, Set<DockingActionIf>> actionsByName : maps) {
			for (Set<DockingActionIf> actions : actionsByName.values()) {
				Iterator<DockingActionIf> next = actions.iterator();

				// Note: do not use apache commons here--the code below degrades exponentially
				//iterator = IteratorUtils.chainedIterator(iterator, next);
				iterator = Iterators.concat(iterator, next);
			}
		}

		return Iterators.concat(iterator, sharedActionMap.values().iterator());
	}
 
Example #7
Source File: PopupActionManager.java    From ghidra with Apache License 2.0 6 votes vote down vote up
JPopupMenu createPopupMenu(Iterator<DockingActionIf> localActions, ActionContext context) {

		if (localActions == null) {
			localActions = IteratorUtils.emptyIterator();
		}

		MenuHandler popupMenuHandler = new PopupMenuHandler(windowManager, context);
		MenuManager menuMgr =
			new MenuManager("Popup", '\0', null, true, popupMenuHandler, menuGroupMap);
		populatePopupMenuActions(localActions, context, menuMgr);
		if (menuMgr.isEmpty()) {
			return null;
		}

		// Popup menu if items are available
		JPopupMenu popupMenu = menuMgr.getPopupMenu();
		popupMenu.addPopupMenuListener(popupMenuHandler);
		return popupMenu;
	}
 
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: FelixGoPluginOSGiFramework.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Override
public void start() {
    List<FrameworkFactory> frameworkFactories = IteratorUtils.toList(ServiceLoader.load(FrameworkFactory.class).iterator());

    if (frameworkFactories.size() != 1) {
        throw new RuntimeException("One OSGi framework expected. Got " + frameworkFactories.size() + ": " + frameworkFactories);
    }

    try {
        framework = getFelixFramework(frameworkFactories);
        framework.start();
        registerInternalServices(framework.getBundleContext());
    } catch (BundleException e) {
        throw new RuntimeException("Failed to initialize OSGi framework", e);
    }
}
 
Example #10
Source File: SystemInputJson.java    From tcases with MIT License 6 votes vote down vote up
public void visit( Not condition)
{
ICondition[] conditions = IteratorUtils.toArray( condition.getConditions(), ICondition.class);

JsonObjectBuilder builder = Json.createObjectBuilder();
if( conditions.length > 1)
  {
  builder.add( NOT_KEY, toJson( new AnyOf( conditions)));
  }
else if( conditions[0].getClass().equals( ContainsAny.class))
  {
  // Special case: abbreviate "not:{hasAny:[...]}" as "hasNone:[...]".
  JsonArrayBuilder properties = Json.createArrayBuilder();
  toStream( ((ContainsAny) conditions[0]).getProperties()).forEach( property -> properties.add( property));
  builder.add( HAS_NONE_KEY, properties);
  }
else
  {
  builder.add( NOT_KEY, toJson( conditions[0]));
  }

json_ = builder.build();
}
 
Example #11
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 #12
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 #13
Source File: AssertTestDef.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Reports a failure if any TestCase fails to bind the variables defined by the FunctionInputDef.
 */
public static void assertTestCasesComplete( FunctionInputDef inputDef, FunctionTestDef testDef)
  {
  List<String> vars =
    IteratorUtils.toList(
      IteratorUtils.transformedIterator(
        new VarDefIterator( inputDef),
        VarDef::getPathName));
  
  for( Iterator<TestCase> testCases = testDef.getTestCases(); testCases.hasNext(); )
    {
    TestCase testCase = testCases.next();
    assertThat(
      "Vars, testCase=" + testCase.getId(),
      IteratorUtils.transformedIterator(
        testCase.getVarBindings(),
        VarBinding::getVar),
      visitsMembers( vars));
    }
  }
 
Example #14
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 #15
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 #16
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 #17
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 #18
Source File: TestTupleCombiner.java    From tcases with MIT License 6 votes vote down vote up
@Test
public void getCombinedVars_Some()
  {
  // Given...
  SystemInputDef systemInputDef = getSystemInputDef();
  FunctionInputDef functionInputDef = systemInputDef.getFunctionInputDef( "Make");
  TupleCombiner combiner = new TupleCombiner().addIncludedVar( "Color.*").addExcludedVar( "Color.Hue");
  
  // When...
  List<VarDef> combined = combiner.getCombinedVars( functionInputDef);
  
  // Then...
  assertThat(
    "Combined vars",
    IteratorUtils.transformedIterator(
      combined.iterator(),
      VarDef::getPathName),
    visitsMembers(
      "Color.Lightness",
      "Color.Saturation"));
  }
 
Example #19
Source File: TestTupleCombiner.java    From tcases with MIT License 6 votes vote down vote up
@Test
public void getCombinedVars_Excluded()
  {
  // Given...
  SystemInputDef systemInputDef = getSystemInputDef();
  FunctionInputDef functionInputDef = systemInputDef.getFunctionInputDef( "Make");
  TupleCombiner combiner = new TupleCombiner().addExcludedVar( "Size");
  
  // When...
  List<VarDef> combined = combiner.getCombinedVars( functionInputDef);
  
  // Then...
  assertThat(
    "Combined vars",
    IteratorUtils.transformedIterator(
      combined.iterator(),
      VarDef::getPathName),
    visitsMembers(
      "Color.Hue",
      "Color.Lightness",
      "Color.Saturation",
      "Shape"));
  }
 
Example #20
Source File: TestTupleCombiner.java    From tcases with MIT License 6 votes vote down vote up
@Test
public void getCombinedVars_Included()
  {
  // Given...
  SystemInputDef systemInputDef = getSystemInputDef();
  FunctionInputDef functionInputDef = systemInputDef.getFunctionInputDef( "Make");
  TupleCombiner combiner = new TupleCombiner().addIncludedVar( "Size");
  
  // When...
  List<VarDef> combined = combiner.getCombinedVars( functionInputDef);
  
  // Then...
  assertThat(
    "Combined vars",
    IteratorUtils.transformedIterator(
      combined.iterator(),
      VarDef::getPathName),
    visitsMembers( "Size"));
  }
 
Example #21
Source File: Cnf.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns true if the given disjunction is universally true.
 */
public static boolean isTautology( IDisjunct disjunct)
  {
  boolean tautology = false;
  if( disjunct != null)
    {
    IAssertion[] assertions = IteratorUtils.toArray( disjunct.getAssertions(), IAssertion.class);
    int max = assertions.length;
    int maxCompared = max - 1;
    
    for( int compared = 0;
         !tautology && compared < maxCompared;
         compared++)
      {
      IAssertion assertCompared = assertions[ compared];
      
      for( int other = compared + 1;
           !tautology && other < max;
           tautology = assertCompared.negates( assertions[ other++]));
      }
    }
  
  return tautology;
  }
 
Example #22
Source File: TestTupleCombiner.java    From tcases with MIT License 6 votes vote down vote up
@Test
public void getCombinedVars_All()
  {
  // Given...
  SystemInputDef systemInputDef = getSystemInputDef();
  FunctionInputDef functionInputDef = systemInputDef.getFunctionInputDef( "Make");
  TupleCombiner combiner = new TupleCombiner();
  
  // When...
  List<VarDef> combined = combiner.getCombinedVars( functionInputDef);
  
  // Then...
  assertThat(
    "Combined vars",
    IteratorUtils.transformedIterator(
      combined.iterator(),
      VarDef::getPathName),
    visitsMembers(
      "Color.Hue",
      "Color.Lightness",
      "Color.Saturation",
      "Shape",
      "Size"));
  }
 
Example #23
Source File: TestVarDefIterator.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Test when traversing a list of various {@link IVarDef} types.
 */
@Test
public void testListTraversal()
  {
  // Given...
  FunctionInputDef inputDef = new FunctionInputDef( "testListTraversal");
  VarSet varSet;

  inputDef.addVarDef( new VarDef( "1"));

  varSet = new VarSet( "2");
  varSet.addMember( new VarDef( "1"));
  varSet.addMember( new VarDef( "2"));
  varSet.addMember( new VarDef( "3"));
  inputDef.addVarDef( varSet);

  varSet = new VarSet( "empty-1");
  inputDef.addVarDef( varSet);

  varSet = new VarSet( "empty-2");
  inputDef.addVarDef( varSet);

  inputDef.addVarDef( new VarDef( "3"));

  // When...
  String[] varDefNames =
    IteratorUtils.toArray(
      IteratorUtils.transformedIterator(
        new VarDefIterator( inputDef),
        VarDef::getPathName),
      String.class);
  
  // Then...
  assertThat
    ( "VarDef sequence",
      varDefNames,
      listsElements( "1", "2.1", "2.2", "2.3", "3"));
  }
 
Example #24
Source File: Disjunction.java    From tcases with MIT License 5 votes vote down vote up
public boolean equals( Object object)
{
IDisjunct other =
  object != null && object instanceof IDisjunct
  ? (IDisjunct) object
  : null;

return
  other != null
  && assertions_.equals( new HashSet<IDisjunct>( IteratorUtils.toList( other.getAssertions())));
}
 
Example #25
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 #26
Source File: ToIteratorTest.java    From feilong-core with Apache License 2.0 5 votes vote down vote up
/**
 * Test to iterator primitive array.
 */
@Test
public void testToIteratorPrimitiveArray(){
    int[] i2 = { 1, 2 };
    Iterator<Integer> iterator = toIterator(i2);
    assertThat(IteratorUtils.toList(iterator), contains(1, 2));
}
 
Example #27
Source File: ToIteratorTest.java    From feilong-core with Apache License 2.0 5 votes vote down vote up
/**
 * Test to iterator array.
 */
@Test
public void testToIteratorArray(){
    Object[] array = { "5", 8 };

    Iterator<Object> iterator = toIterator(array);
    assertThat(IteratorUtils.toList(iterator), org.hamcrest.Matchers.<Object> contains("5", 8));
}
 
Example #28
Source File: ToIteratorTest.java    From feilong-core with Apache License 2.0 5 votes vote down vote up
/**
 * Test to iterator enumeration.
 */
@Test
public void testToIteratorEnumeration(){
    Enumeration<Object> enumeration = new StringTokenizer("this is a test");

    Iterator<String> iterator = toIterator(enumeration);
    assertThat(IteratorUtils.toList(iterator), contains("this", "is", "a", "test"));
}
 
Example #29
Source File: GraphPath.java    From riiablo with Apache License 2.0 5 votes vote down vote up
public Iterator<Vector2> vectorIterator() {
  return IteratorUtils.transformedIterator(new Array.ArrayIterator<>(nodes), new Transformer<Point2, Vector2>() {
    final Vector2 tmp = new Vector2();

    @Override
    public Vector2 transform(Point2 input) {
      return tmp.set(input.x, input.y);
    }
  });
}
 
Example #30
Source File: ToIteratorTest.java    From feilong-core with Apache License 2.0 5 votes vote down vote up
/**
 * Test to iterator collection.
 */
@Test
public void testToIteratorCollection(){
    List<String> list = newArrayList();
    list.add("aaaa");
    list.add("nnnnn");

    Iterator<String> iterator = toIterator(list);
    assertThat(IteratorUtils.toList(iterator), contains("aaaa", "nnnnn"));
}