Java Code Examples for org.apache.commons.collections.IteratorUtils

The following examples show how to use org.apache.commons.collections.IteratorUtils. These examples are extracted from open source projects. 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 Project: onos   Source File: YangXmlUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests getting a multiple object nested configuration via passing the path
 * and a list of YangElements containing with the element and desired value.
 *
 * @throws ConfigurationException
 */
@Test
public void getXmlConfigurationFromYangElements() throws ConfigurationException {

    assertNotEquals("Null testConfiguration", new XMLConfiguration(), testCreateConfig);
    testCreateConfig.load(getClass().getResourceAsStream("/testYangConfig.xml"));
    List<YangElement> elements = new ArrayList<>();
    elements.add(new YangElement("capable-switch", ImmutableMap.of("id", "openvswitch")));
    elements.add(new YangElement("switch", ImmutableMap.of("id", "ofc-bridge")));
    List<ControllerInfo> controllers =
            ImmutableList.of(new ControllerInfo(IpAddress.valueOf("1.1.1.1"), 1, "tcp"),
                             new ControllerInfo(IpAddress.valueOf("2.2.2.2"), 2, "tcp"));
    controllers.forEach(cInfo -> {
        elements.add(new YangElement("controller", ImmutableMap.of("id", cInfo.target(),
                                                                   "ip-address", cInfo.ip().toString())));
    });
    XMLConfiguration cfg =
            new XMLConfiguration(YangXmlUtils.getInstance()
                                         .getXmlConfiguration(OF_CONFIG_XML_PATH, elements));
    assertEquals("Wrong configuaration", IteratorUtils.toList(testCreateConfig.getKeys()),
                 IteratorUtils.toList(cfg.getKeys()));
    assertEquals("Wrong string configuaration", canonicalXml(utils.getString(testCreateConfig)),
                 canonicalXml(utils.getString(cfg)));
}
 
Example 2
@Test
public void testFolderOrProductOrVariantFilter() {
    dataSourceProperties.put("path", TEST_PATH);
    dataSourceProperties.put("filter", Filter.folderOrProductOrVariant);
    children.add(mockSomeResource());
    children.add(mockVariantResource());
    children.add(mockFolderResource());
    children.add(mockSomeResource());

    servlet.doGet(request, response);

    DataSource dataSource = (DataSource) request.getAttribute(DataSource.class.getName());
    assertNotNull(dataSource);
    assertTrue(dataSource.iterator().hasNext());
    assertEquals(2, IteratorUtils.toList(dataSource.iterator()).size());
}
 
Example 3
@Test
public void testQueryWithPath() {
    dataSourceProperties.put("query", TEST_PATH + "variant");
    dataSourceProperties.put("rootPath", TEST_PATH);
    dataSourceProperties.put("path", TEST_PATH);
    dataSourceProperties.put("filter", Filter.folderOrProductOrVariant);
    children.add(mockVariantResource());
    children.add(mockFolderResource());

    servlet.doGet(request, response);

    DataSource dataSource = (DataSource) request.getAttribute(DataSource.class.getName());
    assertNotNull(dataSource);
    assertTrue(dataSource.iterator().hasNext());
    assertTrue(dataSource.iterator().next().getName().startsWith("variant"));
    assertEquals(1, IteratorUtils.toList(dataSource.iterator()).size());
}
 
Example 4
Source Project: onos   Source File: YangXmlUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests getting a single object configuration via passing the path and the map of the desired values.
 *
 * @throws ConfigurationException if the testing xml file is not there.
 */
@Test
public void testGetXmlConfigurationFromMap() throws ConfigurationException {
    Map<String, String> pathAndValues = new HashMap<>();
    pathAndValues.put("capable-switch.id", "openvswitch");
    pathAndValues.put("switch.id", "ofc-bridge");
    pathAndValues.put("controller.id", "tcp:1.1.1.1:1");
    pathAndValues.put("controller.ip-address", "1.1.1.1");
    XMLConfiguration cfg = utils.getXmlConfiguration(OF_CONFIG_XML_PATH, pathAndValues);
    testCreateConfig.load(getClass().getResourceAsStream("/testCreateSingleYangConfig.xml"));
    assertNotEquals("Null testConfiguration", new XMLConfiguration(), testCreateConfig);

    assertEquals("Wrong configuaration", IteratorUtils.toList(testCreateConfig.getKeys()),
                 IteratorUtils.toList(cfg.getKeys()));

    assertEquals("Wrong string configuaration", canonicalXml(utils.getString(testCreateConfig)),
                 canonicalXml(utils.getString(cfg)));
}
 
Example 5
Source Project: hugegraph-common   Source File: ReflectionUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testClasses() throws IOException {
    @SuppressWarnings("unchecked")
    List<ClassInfo> classes = IteratorUtils.toList(ReflectionUtil.classes(
                              "com.baidu.hugegraph.util"));
    Assert.assertEquals(16, classes.size());
    classes.sort((c1, c2) -> c1.getName().compareTo(c2.getName()));
    Assert.assertEquals("com.baidu.hugegraph.util.Bytes",
                        classes.get(0).getName());
    Assert.assertEquals("com.baidu.hugegraph.util.CheckSocket",
                        classes.get(1).getName());
    Assert.assertEquals("com.baidu.hugegraph.util.CollectionUtil",
                        classes.get(2).getName());
    Assert.assertEquals("com.baidu.hugegraph.util.VersionUtil",
                        classes.get(15).getName());
}
 
Example 6
Source Project: obevo   Source File: CsvReaderDataSource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Putting this init here so that we can discover the file fields before running the actual rec
 */
public void init() {
    if (!this.initialized) {
        try {
            MutableList<String> fields;
            if (csvVersion == CsvStaticDataReader.CSV_V2) {
                CSVFormat csvFormat = CsvStaticDataReader.getCsvFormat(delim, nullToken);
                this.csvreaderV2 = new CSVParser(reader, csvFormat);
                this.iteratorV2 = csvreaderV2.iterator();
                fields = ListAdapter.adapt(IteratorUtils.toList(iteratorV2.next().iterator()));
            } else {
                this.csvreaderV1 = new au.com.bytecode.opencsv.CSVReader(this.reader, this.delim);
                fields = ArrayAdapter.adapt(this.csvreaderV1.readNext());
            }

            this.fields = fields.collect(this.convertDbObjectName);
        } catch (Exception e) {
            throw new DeployerRuntimeException(e);
        }
        this.initialized = true;
    }
}
 
Example 7
Source Project: dremio-oss   Source File: QueryProfileParser.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void parsePhysicalPlan() throws IOException {
  if (queryProfile.getJsonPlan() == null || queryProfile.getJsonPlan().isEmpty()) {
    return;
  }
  // Parse the plan and map tables to major fragment and operator ids.
  final Map<String, Object> plan = mapper.readValue(queryProfile.getJsonPlan(), Map.class);
  for (Map.Entry<String, Object> entry: plan.entrySet()) {
    checkIsAssignable(entry.getKey(), entry.getValue().getClass(), Map.class);
    final Map<String, Object> operatorInfo = (Map)entry.getValue();
    final String operator = (String) operatorInfo.get("\"op\"");
    if (operator != null && operator.contains("Scan") && operatorInfo.containsKey("\"values\"")) {
      // Get table name
      checkIsAssignable(entry.getKey() + ": values", operatorInfo.get("\"values\"").getClass(), Map.class);
      final Map<String, Object> values = (Map)operatorInfo.get("\"values\"");
      if (values.containsKey("\"table\"")) {
        // TODO (Amit H) remove this after we clean up code.
        final String tokens = ((String) values.get("\"table\"")).replaceAll("^\\[|\\]$", "");
        final String tablePath = PathUtils.constructFullPath(IteratorUtils.toList(splitter.split(tokens).iterator()));
        operatorToTable.put(entry.getKey(), tablePath);
      }
    }
  }
}
 
Example 8
Source Project: jpa-unit   Source File: SqlScriptTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testRemovalOfCommentsProperSplittingOfStatementsAndTrimmingOfEachOfIt() {
    // GIVEN
    final SqlScript script = new SqlScript(TEST_SCRIPT);

    // WHEN
    final List<String> list = IteratorUtils.toList(script.iterator());

    // THEN
    assertThat(list.size(), equalTo(12));
    assertThat(list, everyItem(not(containsString("comment"))));
    assertThat(list, everyItem(not(startsWith(" "))));
    assertThat(list, everyItem(not(startsWith("\t"))));
    assertThat(list, everyItem(not(endsWith(" "))));
    assertThat(list, everyItem(not(endsWith("\t"))));
}
 
Example 9
Source Project: flink   Source File: ExternalResourceUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testConstructExternalResourceDriversFromConfig() {
	final Configuration config = new Configuration();
	final String driverFactoryClassName = TestingExternalResourceDriverFactory.class.getName();
	final Map<Class<?>, Iterator<?>> plugins = new HashMap<>();
	plugins.put(ExternalResourceDriverFactory.class, IteratorUtils.singletonIterator(new TestingExternalResourceDriverFactory()));
	final PluginManager testingPluginManager = new TestingPluginManager(plugins);

	config.set(ExternalResourceOptions.EXTERNAL_RESOURCE_LIST, Collections.singletonList(RESOURCE_NAME_1));
	config.setString(ExternalResourceOptions.getExternalResourceDriverFactoryConfigOptionForResource(RESOURCE_NAME_1), driverFactoryClassName);

	final Map<String, ExternalResourceDriver> externalResourceDrivers = ExternalResourceUtils.externalResourceDriversFromConfig(config, testingPluginManager);

	assertThat(externalResourceDrivers.size(), is(1));
	assertThat(externalResourceDrivers.get(RESOURCE_NAME_1), instanceOf(TestingExternalResourceDriver.class));
}
 
Example 10
@Test (dataProvider = "vcfExampleFiles")
@SuppressWarnings({"unchecked"})
public void testSimpleCaseDuplicateFile(File file, File file2) {
    final DummyExampleGroupingMultiVariantWalker tool = new DummyExampleGroupingMultiVariantWalker();
    final String[] args = {"--variant", file.getAbsolutePath(), "--variant", file2.getAbsolutePath(), "-R", b37_reference_20_21};
    tool.instanceMain(args);

    //Check that we get the right number of apply calls and the right number of variants
    try(final FeatureDataSource<VariantContext> variantContextFeatureDataSource = new FeatureDataSource<>(file)) {
        List<VariantContext> inputList = IteratorUtils.toList(variantContextFeatureDataSource.iterator());

        Assert.assertEquals(tool.seenVariants.size(), inputList.size());

        // We expect each variant in a duplicate file to be applied once but duplicated across the files
        for (int i = 0; i < inputList.size(); i++) {
            Assert.assertEquals(tool.seenVariants.get(i).size(),2);
            Assert.assertEquals(tool.seenVariants.get(i).get(0).getStart(),inputList.get(i).getStart());
            Assert.assertEquals(tool.seenVariants.get(i).get(1).getStart(),inputList.get(i).getStart());
        }
    }
}
 
Example 11
@Test
@SuppressWarnings({"unchecked"})
public void testMergingTwoFilesCorrectBehavior() {
    final DummyExampleGroupingMultiVariantWalker tool = new DummyExampleGroupingMultiVariantWalker();
    final String[] args = {"--variant", getToolTestDataDir()+"gvcfExample1.vcf", "--variant", getToolTestDataDir()+"gvcfExample2.vcf", "-R", b37_reference_20_21};
    tool.instanceMain(args);

    //Check that we get the right number of apply calls and the right number of variants
    try(final FeatureDataSource<VariantContext> variantContextFeatureDataSource1 = new FeatureDataSource<>(getTestFile("gvcfExample1.vcf"));
        final FeatureDataSource<VariantContext> variantContextFeatureDataSource2 = new FeatureDataSource<>(getTestFile("gvcfExample2.vcf"))){
        List<String> inputList1 = ((List<VariantContext>)IteratorUtils.toList(variantContextFeatureDataSource1.iterator())).stream().map(VariantContext::toString).collect(Collectors.toList());
        List<String> inputList2 = ((List<VariantContext>)IteratorUtils.toList(variantContextFeatureDataSource2.iterator())).stream().map(VariantContext::toString).collect(Collectors.toList());

        Assert.assertEquals(tool.seenVariants.size(), 13);
        int total = 0;
        // We expect each variant in a duplicate file to be applied once but duplicated across the files
        for (int i = 0; i < tool.seenVariants.size(); i++) {
            total += tool.seenVariants.get(i).size();
            Assert.assertTrue(tool.seenVariants.get(i).size()==1 || tool.seenVariants.get(i).size()==2);
            Assert.assertTrue(inputList1.contains(tool.seenVariants.get(i).get(0).toString()) || inputList2.contains(tool.seenVariants.get(i).get(0).toString()));
        }
        Assert.assertEquals(total, inputList1.size()+inputList2.size());
    }
}
 
Example 12
@Override
@NonTransactional
@Deprecated
public Integer getBalanceRecordCount(Map fieldValues, boolean isConsolidated, List<String> encumbranceBalanceTypes) {
    LOG.debug("getBalanceRecordCount() started");

    Integer recordCount = null;
    if (!isConsolidated) {
        recordCount = OJBUtility.getResultSizeFromMap(fieldValues, new LedgerBalance()).intValue();
    }
    else {
        Iterator recordCountIterator = laborLedgerBalanceDao.getConsolidatedBalanceRecordCount(fieldValues, encumbranceBalanceTypes);
        List recordCountList = IteratorUtils.toList(recordCountIterator);
        recordCount = recordCountList.size();
    }
    return recordCount;
}
 
Example 13
/**
 * This method finds the summary records of balance entries according to input fields and values
 *
 * @param fieldValues the input fields and values
 * @param isConsolidated consolidation option is applied or not
 * @return the summary records of balance entries
 * @see org.kuali.kfs.gl.service.BalanceService#getBalanceRecordCount(java.util.Map, boolean)
 */
@Override
public Integer getBalanceRecordCount(Map fieldValues, boolean isConsolidated) {
    LOG.debug("getBalanceRecordCount() started");

    Integer recordCount = null;
    if (!isConsolidated) {
        recordCount = OJBUtility.getResultSizeFromMap(fieldValues, new Balance()).intValue();
    }
    else {
        Iterator recordCountIterator = balanceDao.getConsolidatedBalanceRecordCount(fieldValues, getEncumbranceBalanceTypes(fieldValues));
        // TODO: WL: why build a list and waste time/memory when we can just iterate through the iterator and do a count?
        List recordCountList = IteratorUtils.toList(recordCountIterator);
        recordCount = recordCountList.size();
    }
    return recordCount;
}
 
Example 14
Source Project: spacewalk   Source File: TaskScheduler.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method inserts/updates tasks by the channels in an errata. This method
 * corresponds to {@literal ChannelEditor.pm -> schedule_errata_cache_update}
 * method in the perl codebase.
 */
public void updateByChannels() {
    //Get the channels for this errata
    Set channels = errata.getChannels();

    //Loop through the channels and either insert or update a task
    Iterator itr = IteratorUtils.getIterator(channels);
    while (itr.hasNext()) {
        Channel channel = (Channel) itr.next();

        //Look to see if task already exists...
        Task task = TaskFactory.lookup(org, ErrataCacheWorker.BY_CHANNEL, channel
                .getId());
        if (task == null) { //if not, create a new task
            task = TaskFactory.createTask(org, ErrataCacheWorker.BY_CHANNEL, channel
                    .getId());
        }
        else { //if so, update the earliest column
            task.setEarliest(new Date(System.currentTimeMillis() + DELAY));
        }
        //save the task
        TaskFactory.save(task);
    }
}
 
Example 15
Source Project: openhab1-addons   Source File: ModbusBinding.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private static Iterator<String> stringArrayIterator(final String[] chunks) {
    Iterator<String> settingIterator = new Iterator<String>() {

        private ResettableIterator inner = IteratorUtils.arrayIterator(chunks);

        @Override
        public String next() {
            return (String) inner.next();
        }

        @Override
        public boolean hasNext() {
            return inner.hasNext();
        }

        @Override
        public void remove() {
            inner.remove();
        }

    };
    return settingIterator;
}
 
Example 16
Source Project: BioSolr   Source File: TestSimpleXJoinResultsFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected=PathNotFoundException.class)
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testNoJoinIdsAtPath() throws IOException {
  NamedList args = new NamedList();
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_TYPE, SimpleXJoinResultsFactory.Type.JSON.toString());
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_ROOT_URL, getClass().getResource("results.json").toString());
  
  NamedList globalPaths = new NamedList();
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_GLOBAL_FIELD_PATHS, globalPaths);
  globalPaths.add("total", "$.count");
  
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_JOIN_ID_PATH, "$.no.ids.at.this.path");
  
  SimpleXJoinResultsFactory factory = new SimpleXJoinResultsFactory();
  factory.init(args);
  
  SolrParams params = new ModifiableSolrParams();
  XJoinResults<String> results = factory.getResults(params);
  
  assertEquals(0, IteratorUtils.toArray(results.getJoinIds().iterator()).length);
}
 
Example 17
Source Project: BioSolr   Source File: TestSimpleXJoinResultsFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected=PathNotFoundException.class)
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testNoJoinIdsAtPath() throws IOException {
  NamedList args = new NamedList();
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_TYPE, SimpleXJoinResultsFactory.Type.JSON.toString());
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_ROOT_URL, getClass().getResource("results.json").toString());
  
  NamedList globalPaths = new NamedList();
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_GLOBAL_FIELD_PATHS, globalPaths);
  globalPaths.add("total", "$.count");
  
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_JOIN_ID_PATH, "$.no.ids.at.this.path");
  
  SimpleXJoinResultsFactory factory = new SimpleXJoinResultsFactory();
  factory.init(args);
  
  SolrParams params = new ModifiableSolrParams();
  XJoinResults<String> results = factory.getResults(params);
  
  assertEquals(0, IteratorUtils.toArray(results.getJoinIds().iterator()).length);
}
 
Example 18
Source Project: geowave   Source File: JobContextAdapterStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CloseableIterator<DataTypeAdapter<?>> getAdapters() {
  final CloseableIterator<InternalDataAdapter<?>> it = persistentAdapterStore.getAdapters();
  // cache any results
  return new CloseableIteratorWrapper<DataTypeAdapter<?>>(
      it,
      IteratorUtils.transformedIterator(it, new Transformer() {

        @Override
        public Object transform(final Object obj) {
          if (obj instanceof DataTypeAdapter) {
            adapterCache.put(((DataTypeAdapter) obj).getTypeName(), (DataTypeAdapter) obj);
          }
          return obj;
        }
      }));
}
 
Example 19
Source Project: geowave   Source File: JobContextAdapterStore.java    License: Apache License 2.0 6 votes vote down vote up
public List<String> getTypeNames() {
  final DataTypeAdapter<?>[] userAdapters =
      GeoWaveConfiguratorBase.getDataAdapters(CLASS, context);
  if ((userAdapters == null) || (userAdapters.length <= 0)) {
    return IteratorUtils.toList(
        IteratorUtils.transformedIterator(getAdapters(), new Transformer() {

          @Override
          public Object transform(final Object input) {
            if (input instanceof DataTypeAdapter) {
              return ((DataTypeAdapter) input).getTypeName();
            }
            return input;
          }
        }));
  } else {
    final List<String> retVal = new ArrayList<>(userAdapters.length);
    for (final DataTypeAdapter<?> adapter : userAdapters) {
      retVal.add(adapter.getTypeName());
    }
    return retVal;
  }
}
 
Example 20
@Test
public void testProductFilter() {
    dataSourceProperties.put("path", TEST_PATH);
    dataSourceProperties.put("filter", Filter.product);
    children.add(mockSomeResource());
    children.add(mockProductResource());
    children.add(mockFolderResource());

    servlet.doGet(request, response);

    DataSource dataSource = (DataSource) request.getAttribute(DataSource.class.getName());
    assertNotNull(dataSource);
    assertTrue(dataSource.iterator().hasNext());
    assertEquals(1, IteratorUtils.toList(dataSource.iterator()).size());
}
 
Example 21
@Override
public Iterator<ExecRow> call(Tuple2<Iterable<ExecRow>, Iterable<ExecRow>> tuple) throws Exception {
    checkInit();
    Iterable<ExecRow> rightSide = tuple._2; // Memory Issue, HashSet ?
    List<Iterable<ExecRow>> returnRows = new LinkedList<>();
    for(ExecRow a_1 : tuple._1){
        returnRows.add(IteratorUtils.toList(innerJoinRestrictionFlatMapFunction.call(new Tuple2<>(a_1,rightSide))));
    }
    return new ConcatenatedIterable<>(returnRows).iterator();
}
 
Example 22
Source Project: flink   Source File: TaskSlotTableTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests that one can can mark allocated slots as active.
 */
@Test
public void testTryMarkSlotActive() throws SlotNotFoundException {
	final TaskSlotTable taskSlotTable = createTaskSlotTable(Collections.nCopies(3, ResourceProfile.UNKNOWN));

	try {
		taskSlotTable.start(new TestingSlotActionsBuilder().build());

		final JobID jobId1 = new JobID();
		final AllocationID allocationId1 = new AllocationID();
		taskSlotTable.allocateSlot(0, jobId1, allocationId1, SLOT_TIMEOUT);
		final AllocationID allocationId2 = new AllocationID();
		taskSlotTable.allocateSlot(1, jobId1, allocationId2, SLOT_TIMEOUT);
		final AllocationID allocationId3 = new AllocationID();
		final JobID jobId2 = new JobID();
		taskSlotTable.allocateSlot(2, jobId2, allocationId3, SLOT_TIMEOUT);

		taskSlotTable.markSlotActive(allocationId1);

		assertThat(taskSlotTable.isAllocated(0, jobId1, allocationId1), is(true));
		assertThat(taskSlotTable.isAllocated(1, jobId1, allocationId2), is(true));
		assertThat(taskSlotTable.isAllocated(2, jobId2, allocationId3), is(true));

		assertThat(IteratorUtils.toList(taskSlotTable.getActiveSlots(jobId1)), is(equalTo(Arrays.asList(allocationId1))));

		assertThat(taskSlotTable.tryMarkSlotActive(jobId1, allocationId1), is(true));
		assertThat(taskSlotTable.tryMarkSlotActive(jobId1, allocationId2), is(true));
		assertThat(taskSlotTable.tryMarkSlotActive(jobId1, allocationId3), is(false));

		assertThat(Sets.newHashSet(taskSlotTable.getActiveSlots(jobId1)), is(equalTo(new HashSet<>(Arrays.asList(allocationId2, allocationId1)))));
	} finally {
		taskSlotTable.stop();
	}
}
 
Example 23
Source Project: uyuni   Source File: ErrataSearchActionTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testExecute() throws Exception {

        ErrataSearchAction action = new ErrataSearchAction();
        ActionHelper ah = new ActionHelper();
        Errata e = ErrataFactoryTest.createTestErrata(UserTestUtils.createOrg("testOrg" +
                    this.getClass().getSimpleName()));
        String name = e.getAdvisory();

        ah.setUpAction(action, RhnHelper.DEFAULT_FORWARD);
        ah.getForm().set(BaseSearchAction.VIEW_MODE, BaseSearchAction.OPT_ADVISORY);
        ah.getForm().set(RhnAction.SUBMITTED, Boolean.TRUE);
        // these are duplicated on PURPOSE! Because mockobjects SUCK ASS!
        ah.getRequest().setupAddParameter(BaseSearchAction.SEARCH_STR, name);
        ah.getRequest().setupAddParameter(BaseSearchAction.SEARCH_STR, name);
        ah.getRequest().setupAddParameter(BaseSearchAction.VIEW_MODE,
                        BaseSearchAction.OPT_ADVISORY);
        ah.getRequest().setupAddParameter(BaseSearchAction.VIEW_MODE,
                        BaseSearchAction.OPT_ADVISORY);
        ah.getRequest().setupAddParameter(BaseSearchAction.FINE_GRAINED, "on");
        ah.getRequest().setupAddParameter(BaseSearchAction.FINE_GRAINED, "on");

        // I *HATE* Mockobjects
        Map paramnames = new HashMap();
        paramnames.put(BaseSearchAction.SEARCH_STR, name);
        paramnames.put(BaseSearchAction.VIEW_MODE, BaseSearchAction.OPT_ADVISORY);
        paramnames.put(BaseSearchAction.FINE_GRAINED, "on");
        paramnames.put(RhnAction.SUBMITTED, "true");
        ah.getRequest().setupGetParameterNames(
                IteratorUtils.asEnumeration(paramnames.keySet().iterator()));

        ah.setupClampListBounds();

        ActionForward af = ah.executeAction();
    }
 
Example 24
Source Project: uyuni   Source File: AbstractErrata.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void clearChannels() {
    if (this.getChannels() != null) {
        this.getChannels().clear();
    }
    Iterator<ErrataFile> i = IteratorUtils.getIterator(this.getFiles());
    while (i.hasNext()) {
        PublishedErrataFile pf = (PublishedErrataFile) i.next();
        pf.getChannels().clear();
    }
}
 
Example 25
Source Project: hugegraph-client   Source File: GraphManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testIterateVertices() {
    Iterator<Vertex> vertices = graph().iterateVertices(1);
    List<Vertex> results = IteratorUtils.toList(vertices);
    Assert.assertEquals(6, results.size());

    vertices = graph().iterateVertices(6);
    results = IteratorUtils.toList(vertices);
    Assert.assertEquals(6, results.size());

    vertices = graph().iterateVertices(100);
    results = IteratorUtils.toList(vertices);
    Assert.assertEquals(6, results.size());
}
 
Example 26
Source Project: hugegraph-client   Source File: GraphManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testIterateEdgesWithPageLtThanTotal() {
    Iterator<Edge> edes = graph().iterateEdges(1);
    List<Edge> results = IteratorUtils.toList(edes);
    Assert.assertEquals(6, results.size());

    edes = graph().iterateEdges(6);
    results = IteratorUtils.toList(edes);
    Assert.assertEquals(6, results.size());

    edes = graph().iterateEdges(100);
    results = IteratorUtils.toList(edes);
    Assert.assertEquals(6, results.size());
}
 
Example 27
Source Project: iceberg   Source File: SnapshotFunctionalityTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Expires anything older than a given timestamp, NOT including that timestamp.
 */
@Test
public void retireAllSnapshotsOlderThanTimestamp() {
  long secondLatestTimestamp = table.history().get(2).timestampMillis();
  Iterator<Snapshot> beforeIterator = table.snapshots().iterator();
  List<Snapshot> beforeSnapshots = IteratorUtils.toList(beforeIterator);

  //Delete the 2 oldest snapshots
  table.expireSnapshots().expireOlderThan(secondLatestTimestamp).commit();
  table.refresh();

  Iterator<Snapshot> afterIterator = table.snapshots().iterator();
  List<Snapshot> afterSnapshots = IteratorUtils.toList(afterIterator);
}
 
Example 28
Source Project: atlas   Source File: GraphHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static List<AtlasEdge> getMapValuesUsingRelationship(AtlasVertex vertex, AtlasAttribute attribute) {
    String                         edgeLabel     = attribute.getRelationshipEdgeLabel();
    AtlasRelationshipEdgeDirection edgeDirection = attribute.getRelationshipEdgeDirection();
    Iterator<AtlasEdge>            edgesForLabel = getEdgesForLabel(vertex, edgeLabel, edgeDirection);

    return (List<AtlasEdge>) IteratorUtils.toList(edgesForLabel);
}
 
Example 29
Source Project: atlas   Source File: GraphHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static List<AtlasEdge> getCollectionElementsUsingRelationship(AtlasVertex vertex, AtlasAttribute attribute) {
    List<AtlasEdge>                ret;
    String                         edgeLabel     = attribute.getRelationshipEdgeLabel();
    AtlasRelationshipEdgeDirection edgeDirection = attribute.getRelationshipEdgeDirection();
    Iterator<AtlasEdge>            edgesForLabel = getEdgesForLabel(vertex, edgeLabel, edgeDirection);

    ret = IteratorUtils.toList(edgesForLabel);

    sortCollectionElements(attribute, ret);

    return ret;
}
 
Example 30
@Override
public Iterator<InventoryManifest.Locator> call(Iterator<InventoryReportLine> inventoryReport) throws IOException {
    // Exclude the empty iterators which are caused by the mapPartitions
    // when one partition only owns empty InventoryReportLine iterator after the filtering
    if (!inventoryReport.hasNext()){
        return Collections.emptyIterator();
    }
    List<InventoryReportLine> inventoryReportLineList = IteratorUtils.toList(inventoryReport);
    InventoryReportLineWriter scvWriter = new InventoryReportLineWriter(s3ClientFactory.getValue().get(),
            destBucket, destPrefix, srcBucket, manifestStorage);
    return Collections.singletonList(scvWriter.writeCsvFile(inventoryReportLineList)).iterator();
}