org.apache.commons.collections.IteratorUtils Java Examples
The following examples show how to use
org.apache.commons.collections.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: JobContextAdapterStore.java From geowave with Apache License 2.0 | 6 votes |
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 #2
Source File: ModbusBinding.java From openhab1-addons with Eclipse Public License 2.0 | 6 votes |
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 #3
Source File: TestSimpleXJoinResultsFactory.java From BioSolr with Apache License 2.0 | 6 votes |
@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 #4
Source File: ChildrenDataSourceServletTest.java From commerce-cif-connector with Apache License 2.0 | 6 votes |
@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 #5
Source File: TestSimpleXJoinResultsFactory.java From BioSolr with Apache License 2.0 | 6 votes |
@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 #6
Source File: ChildrenDataSourceServletTest.java From commerce-cif-connector with Apache License 2.0 | 6 votes |
@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 #7
Source File: YangXmlUtilsTest.java From onos with Apache License 2.0 | 6 votes |
/** * 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 #8
Source File: JobContextAdapterStore.java From geowave with Apache License 2.0 | 6 votes |
@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 #9
Source File: YangXmlUtilsTest.java From onos with Apache License 2.0 | 6 votes |
/** * 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 #10
Source File: ReflectionUtilTest.java From hugegraph-common with Apache License 2.0 | 6 votes |
@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 #11
Source File: TaskScheduler.java From spacewalk with GNU General Public License v2.0 | 6 votes |
/** * 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 #12
Source File: BalanceServiceImpl.java From kfs with GNU Affero General Public License v3.0 | 6 votes |
/** * 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 #13
Source File: LaborLedgerBalanceServiceImpl.java From kfs with GNU Affero General Public License v3.0 | 6 votes |
@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 #14
Source File: MultiVariantWalkerGroupedOnStartUnitTest.java From gatk with BSD 3-Clause "New" or "Revised" License | 6 votes |
@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 #15
Source File: CsvReaderDataSource.java From obevo with Apache License 2.0 | 6 votes |
/** * 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 #16
Source File: MultiVariantWalkerGroupedOnStartUnitTest.java From gatk with BSD 3-Clause "New" or "Revised" License | 6 votes |
@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 #17
Source File: QueryProfileParser.java From dremio-oss with Apache License 2.0 | 6 votes |
@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 #18
Source File: ExternalResourceUtilsTest.java From flink with Apache License 2.0 | 6 votes |
@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 #19
Source File: SqlScriptTest.java From jpa-unit with Apache License 2.0 | 6 votes |
@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 #20
Source File: ConvertIteratorToArrayList.java From levelup-java-examples with Apache License 2.0 | 5 votes |
@Test public void convert_iterator_to_list_apache() { Iterator<String> iteratorToArrayList = collection.iterator(); @SuppressWarnings("unchecked") List<String> convertedIteratorToList = IteratorUtils .toList(iteratorToArrayList); assertTrue(convertedIteratorToList.size() == 4); }
Example #21
Source File: TableDataProvider.java From nextreports-server with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Override public Iterator<RowData> iterator(long first, long count) { try { List<RowData> data = getCache(); String username = ServerUtil.getUsername(); String sortPosKey = username == null ? widgetId + SORT_PROP_POS_SUFFIX : widgetId + "_" + username + SORT_PROP_POS_SUFFIX; String sortDirKey = username == null ? widgetId + SORT_PROP_DIR_SUFFIX : widgetId + "_" + username + SORT_PROP_DIR_SUFFIX; if (getSort() != null) { sortDir = getSort().isAscending() ? 1 : -1; sortPos = getPropertyPosition(getSort().getProperty()); // save these properties to be used by TableResource (save to excel) System.setProperty(sortPosKey, String.valueOf(sortPos)); System.setProperty(sortDirKey, String.valueOf(sortDir)); Collections.sort(data, new Comparator<RowData>() { public int compare(RowData o1, RowData o2) { if (sortPos != -1) { if ((o1.getCellValues(sortPos) == null) && (o2.getCellValues(sortPos) == null)) { return 0; } else if (o1.getCellValues(sortPos) == null) { return sortDir; } else if (o2.getCellValues(sortPos) == null) { return -sortDir; } else { return sortDir * new TableObjectComparator().compare(o1.getCellValues(sortPos), o2.getCellValues(sortPos)); } } return 0; } }); } else { System.clearProperty(sortPosKey); System.clearProperty(sortDirKey); } return getCache().subList((int) first, (int) (first + count)).iterator(); } catch (Exception e) { LOG.error(e.getMessage(), e); return IteratorUtils.EMPTY_ITERATOR; } }
Example #22
Source File: InstanceResolver.java From phoenix with Apache License 2.0 | 5 votes |
/** * Resolves all instances of a specified class and add it to the list of default implementations * @param clazz Type of the instance to resolve * @param defaultInstances {@link List} of instances that match the type clazz * @param <T> Type of class passed * @return {@link List} of instance of the specified class. Newly found instances will be added * to the existing contents of defaultInstances */ @SuppressWarnings("unchecked") public static <T> List get(Class<T> clazz, List<T> defaultInstances) { Iterator<T> iterator = ServiceLoader.load(clazz).iterator(); if (defaultInstances != null) { defaultInstances.addAll(IteratorUtils.toList(iterator)); } else { defaultInstances = IteratorUtils.toList(iterator); } return defaultInstances; }
Example #23
Source File: AbstractErrata.java From spacewalk with GNU General Public License v2.0 | 5 votes |
/** * {@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 #24
Source File: CogroupLeftOuterJoinRestrictionFlatMapFunction.java From spliceengine with GNU Affero General Public License v3.0 | 5 votes |
@Override public Iterator<ExecRow> call(Tuple2<ExecRow,Tuple2<Iterable<ExecRow>, Iterable<ExecRow>>> tuple) throws Exception { checkInit(); //linked list saves memory, and since we are just doing iteration anyway, there isn't really much penalty here List<Iterable<ExecRow>> returnRows = new LinkedList<>(); for(ExecRow a_1 : tuple._2._1){ Iterable<ExecRow> locatedRows=tuple._2._2; returnRows.add(IteratorUtils.toList(leftOuterJoinRestrictionFlatMapFunction.call(new Tuple2<>(a_1,locatedRows)))); } return new ConcatenatedIterable<>(returnRows).iterator(); }
Example #25
Source File: ReturnEmptyListIterator.java From levelup-java-examples with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Test public void return_empty_list_iterator_apache () { ListIterator<String> strings = IteratorUtils.emptyListIterator(); assertFalse(strings.hasNext()); }
Example #26
Source File: JobContextIndexStore.java From geowave with Apache License 2.0 | 5 votes |
@Override public CloseableIterator<Index> getIndices() { final CloseableIterator<Index> it = persistentIndexStore.getIndices(); // cache any results return new CloseableIteratorWrapper<Index>( it, IteratorUtils.transformedIterator(it, new Transformer() { @Override public Object transform(final Object obj) { indexCache.put(((Index) obj).getName(), (Index) obj); return obj; } })); }
Example #27
Source File: ExternalResourceUtilsTest.java From flink with Apache License 2.0 | 5 votes |
@Test public void testFactoryFailedToCreateDriver() { final Configuration config = new Configuration(); final String driverFactoryClassName = TestingFailedExternalResourceDriverFactory.class.getName(); final Map<Class<?>, Iterator<?>> plugins = new HashMap<>(); plugins.put(ExternalResourceDriverFactory.class, IteratorUtils.singletonIterator(new TestingFailedExternalResourceDriverFactory())); 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.entrySet(), is(empty())); }
Example #28
Source File: TestPropertiesConfiguration.java From commons-configuration with Apache License 2.0 | 5 votes |
/** * Tests that {@link PropertiesConfiguration.JupIOFactory} reads the same keys * and values as {@link Properties} based on a test file. */ @Test public void testJupRead() throws IOException, ConfigurationException { conf.clear(); conf.setIOFactory(new PropertiesConfiguration.JupIOFactory()); final String testFilePath = ConfigurationAssert.getTestFile("jup-test.properties").getAbsolutePath(); load(conf, testFilePath); final Properties jup = new Properties(); try (InputStream in = Files.newInputStream(Paths.get(testFilePath))) { jup.load(in); } @SuppressWarnings("unchecked") final Set<Object> pcKeys = new HashSet<>(IteratorUtils.toList(conf.getKeys())); assertEquals(jup.keySet(), pcKeys); for (final Object key : jup.keySet()) { final String keyString = key.toString(); // System.out.println(keyString); assertEquals("Wrong property value for '" + keyString + "'", jup.getProperty(keyString), conf.getProperty(keyString)); } }
Example #29
Source File: TaskSlotTableImplTest.java From flink with Apache License 2.0 | 5 votes |
/** * Tests that one can can mark allocated slots as active. */ @Test public void testTryMarkSlotActive() throws Exception { final TaskSlotTableImpl<?> taskSlotTable = createTaskSlotTableAndStart(3); try { 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.close(); assertThat(taskSlotTable.isClosed(), is(true)); } }
Example #30
Source File: AccountBalanceServiceImpl.java From kfs with GNU Affero General Public License v3.0 | 5 votes |
/** * This method gets the number of the available account balances according to input fields and values * * @param fieldValues the input fields and values * @param isConsolidated determine whether the search results are consolidated * @return the number of the available account balances * @see org.kuali.kfs.gl.service.AccountBalanceService#getAvailableAccountBalanceCount(java.util.Map, boolean) */ public Integer getAvailableAccountBalanceCount(Map fieldValues, boolean isConsolidated) { Integer recordCount = null; if (!isConsolidated) { recordCount = OJBUtility.getResultSizeFromMap(fieldValues, new AccountBalance()).intValue(); } else { Iterator recordCountIterator = accountBalanceDao.findConsolidatedAvailableAccountBalance(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; }