src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
HealthStatsMetrics extends SystemMetrics<HealthStatsMetrics> { @VisibleForTesting static <K, V> ArrayMap<K, V> opArrayMaps(int op, ArrayMap<K, V> a, @Nullable ArrayMap<K, V> b) { int aSize = a.size(); ArrayMap<K, V> output = new ArrayMap<>(); for (int i = 0; i < aSize; i++) { K key = a.keyAt(i); V bValue = b == null ? ...
@Test public void testSumArrayMaps() { ArrayMap<String, Long> a = new ArrayMap<>(); a.put("a", 1L); a.put("c", 2L); ArrayMap<String, Long> b = new ArrayMap<>(); b.put("b", 1L); b.put("c", 3L); ArrayMap<String, Long> sum = HealthStatsMetrics.opArrayMaps(OP_SUM, a, b); assertThat(sum.get("a")).isEqualTo(1); assertThat(su...
HealthStatsMetrics extends SystemMetrics<HealthStatsMetrics> { @VisibleForTesting static <K> SparseArray<K> op(int op, SparseArray<K> a, SparseArray<K> b, SparseArray<K> output) { output.clear(); for (int i = 0; i < a.size(); i++) { int aKey = a.keyAt(i); output.put(aKey, (K) opValues(op, a.valueAt(i), b.get(aKey))); }...
@Test public void testSumSparseArrays() { SparseArray<Long> a = new SparseArray<>(); a.put(10, 10L); a.put(30, 30L); SparseArray<Long> b = new SparseArray<>(); b.put(10, 10L); b.put(20, 20L); SparseArray<Long> sum = new SparseArray<>(); HealthStatsMetrics.op(OP_SUM, a, b, sum); assertThat(sum.get(10)).isEqualTo(20); as...
HealthStatsMetrics extends SystemMetrics<HealthStatsMetrics> { @Override public HealthStatsMetrics sum( @Nullable HealthStatsMetrics b, @Nullable HealthStatsMetrics output) { if (output == null) { output = new HealthStatsMetrics(); } output.dataType = dataType; if (b == null) { output.set(this); } else if (!strEquals(b...
@Test public void testSum() { HealthStatsMetrics a = createTestMetrics(); HealthStatsMetrics b = createTestMetrics(); HealthStatsMetrics sum = a.sum(b, null); HealthStatsMetrics expectedSum = new HealthStatsMetrics(); expectedSum.dataType = TEST_DATATYPE; expectedSum.measurement.put(123, 2000L); expectedSum.measurement...
HealthStatsMetrics extends SystemMetrics<HealthStatsMetrics> { @Override public HealthStatsMetrics diff( @Nullable HealthStatsMetrics b, @Nullable HealthStatsMetrics output) { if (output == null) { output = new HealthStatsMetrics(); } output.dataType = dataType; if (b == null || compareSnapshotAge(this, b) < 0 ) { outp...
@Test public void testDiff() { HealthStatsMetrics a = createTestMetrics(); HealthStatsMetrics b = createTestMetrics(); HealthStatsMetrics diff = a.diff(b, null); HealthStatsMetrics expectedDiff = new HealthStatsMetrics(); expectedDiff.dataType = TEST_DATATYPE; expectedDiff.measurement.put(123, 0L); expectedDiff.measure...
HealthStatsMetrics extends SystemMetrics<HealthStatsMetrics> { public JSONObject toJSONObject() throws JSONException { JSONObject output = new JSONObject(); output.put("type", dataType); addMeasurement(output); addTimer(output); addMeasurements(output); addTimers(output); addStats(output); return output; } HealthStatsM...
@Test public void datatypeToJSON() throws Exception { HealthStatsMetrics metrics = new HealthStatsMetrics(); metrics.dataType = TEST_DATATYPE; JSONObject json = metrics.toJSONObject(); assertThat(json.getString("type")).isEqualTo(TEST_DATATYPE); } @Test public void measurementToJSON() throws Exception { HealthStatsMetr...
SensorMetrics extends SystemMetrics<SensorMetrics> { @Override public SensorMetrics set(SensorMetrics b) { total.set(b.total); if (isAttributionEnabled && b.isAttributionEnabled) { sensorConsumption.clear(); for (int i = 0, l = b.sensorConsumption.size(); i < l; i++) { sensorConsumption.put(b.sensorConsumption.keyAt(i)...
@Test public void testSet() { SensorMetrics metrics = new SensorMetrics(true); metrics.set(createAttributedMetrics()); assertThat(metrics).isEqualTo(createAttributedMetrics()); } @Test public void testUnattributedSet() { SensorMetrics metrics = new SensorMetrics(); metrics.set(createAttributedMetrics()); SensorMetrics ...
TimeMetricsCollector extends SystemMetricsCollector<TimeMetrics> { @Override @ThreadSafe(enableChecks = false) public boolean getSnapshot(TimeMetrics snapshot) { checkNotNull(snapshot, "Null value passed to getSnapshot!"); snapshot.realtimeMs = SystemClock.elapsedRealtime(); snapshot.uptimeMs = SystemClock.uptimeMillis...
@Test public void testTimes() { ShadowSystemClock.setUptimeMillis(1234); ShadowSystemClock.setElapsedRealtime(9876); TimeMetrics snapshot = new TimeMetrics(); TimeMetricsCollector collector = new TimeMetricsCollector(); collector.getSnapshot(snapshot); assertThat(snapshot.uptimeMs).isEqualTo(1234); assertThat(snapshot....
BluetoothMetrics extends SystemMetrics<BluetoothMetrics> { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BluetoothMetrics that = (BluetoothMetrics) o; if (bleScanCount != that.bleScanCount || bleScanDurationMs != that.bleScanDu...
@Test public void testEquals() { BluetoothMetrics metricsA = new BluetoothMetrics(); metricsA.bleScanDurationMs = 1000; metricsA.bleScanCount = 2; metricsA.bleOpportunisticScanDurationMs = 4000; metricsA.bleOpportunisticScanCount = 8; BluetoothMetrics metricsB = new BluetoothMetrics(); metricsB.bleScanDurationMs = 1000...
BluetoothMetrics extends SystemMetrics<BluetoothMetrics> { @Override public BluetoothMetrics set(BluetoothMetrics b) { bleScanCount = b.bleScanCount; bleScanDurationMs = b.bleScanDurationMs; bleOpportunisticScanCount = b.bleOpportunisticScanCount; bleOpportunisticScanDurationMs = b.bleOpportunisticScanDurationMs; retur...
@Test public void testSet() { BluetoothMetrics metrics = new BluetoothMetrics(); metrics.bleScanDurationMs = 1000; metrics.bleScanCount = 10; metrics.bleOpportunisticScanDurationMs = 5000; metrics.bleOpportunisticScanCount = 3; BluetoothMetrics alternate = new BluetoothMetrics(); alternate.set(metrics); assertThat(alte...
BluetoothMetrics extends SystemMetrics<BluetoothMetrics> { @Override public BluetoothMetrics diff(@Nullable BluetoothMetrics b, @Nullable BluetoothMetrics output) { if (output == null) { output = new BluetoothMetrics(); } if (b == null) { output.set(this); } else { output.bleScanCount = bleScanCount - b.bleScanCount; o...
@Test public void testDiff() { BluetoothMetrics metrics = new BluetoothMetrics(); metrics.bleScanDurationMs = 1000; metrics.bleScanCount = 10; metrics.bleOpportunisticScanDurationMs = 5000; metrics.bleOpportunisticScanCount = 3; BluetoothMetrics olderMetrics = new BluetoothMetrics(); olderMetrics.bleScanDurationMs = 80...
BluetoothMetrics extends SystemMetrics<BluetoothMetrics> { @Override public BluetoothMetrics sum(@Nullable BluetoothMetrics b, @Nullable BluetoothMetrics output) { if (output == null) { output = new BluetoothMetrics(); } if (b == null) { output.set(this); } else { output.bleScanCount = bleScanCount + b.bleScanCount; ou...
@Test public void testSum() { BluetoothMetrics metricsA = new BluetoothMetrics(); metricsA.bleScanDurationMs = 1000; metricsA.bleScanCount = 10; metricsA.bleOpportunisticScanDurationMs = 4000; metricsA.bleOpportunisticScanCount = 1; BluetoothMetrics metricsB = new BluetoothMetrics(); metricsB.bleScanDurationMs = 2000; ...
CpuFrequencyMetrics extends SystemMetrics<CpuFrequencyMetrics> { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CpuFrequencyMetrics that = (CpuFrequencyMetrics) o; if (timeInStateS.length != that.timeInStateS.length) { return fa...
@Test public void testEquals() { CpuFrequencyMetrics metricsA = new CpuFrequencyMetrics(); metricsA.timeInStateS[0].put(200, 2000); metricsA.timeInStateS[0].put(100, 1000); metricsA.timeInStateS[1].put(300, 3000); CpuFrequencyMetrics metricsB = new CpuFrequencyMetrics(); metricsB.timeInStateS[0].put(100, 1000); metrics...
CpuFrequencyMetrics extends SystemMetrics<CpuFrequencyMetrics> { @Override public CpuFrequencyMetrics sum( @Nullable CpuFrequencyMetrics b, @Nullable CpuFrequencyMetrics output) { if (output == null) { output = new CpuFrequencyMetrics(); } if (b == null) { output.set(this); } else { for (int i = 0; i < timeInStateS.len...
@Test public void testSum() { CpuFrequencyMetrics metricsA = new CpuFrequencyMetrics(); metricsA.timeInStateS[0].put(100, 1); metricsA.timeInStateS[0].put(200, 2); metricsA.timeInStateS[1].put(1000, 1); CpuFrequencyMetrics metricsB = new CpuFrequencyMetrics(); metricsB.timeInStateS[0].put(200, 5); metricsB.timeInStateS...
CpuFrequencyMetrics extends SystemMetrics<CpuFrequencyMetrics> { @Override public CpuFrequencyMetrics diff( @Nullable CpuFrequencyMetrics b, @Nullable CpuFrequencyMetrics output) { if (output == null) { output = new CpuFrequencyMetrics(); } if (b == null) { output.set(this); } else { for (int i = 0; i < timeInStateS.le...
@Test public void testDiff() { CpuFrequencyMetrics metricsA = new CpuFrequencyMetrics(); metricsA.timeInStateS[0].put(100, 100); metricsA.timeInStateS[0].put(200, 200); metricsA.timeInStateS[1].put(300, 300); metricsA.timeInStateS[2].put(400, 400); CpuFrequencyMetrics metricsB = new CpuFrequencyMetrics(); metricsB.time...
SensorMetrics extends SystemMetrics<SensorMetrics> { @Override public SensorMetrics sum(@Nullable SensorMetrics b, @Nullable SensorMetrics output) { if (output == null) { output = new SensorMetrics(isAttributionEnabled); } if (b == null) { output.set(this); } else { total.sum(b.total, output.total); if (output.isAttrib...
@Test public void testAttributedSum() { SensorMetrics a = createAttributedMetrics(); SensorMetrics b = createAttributedMetrics(); SensorMetrics result = a.sum(b); assertThat(result.total.powerMah).isEqualTo(a.total.powerMah * 2); assertThat(result.total.wakeUpTimeMs).isEqualTo(a.total.wakeUpTimeMs * 2); assertThat(resu...
CpuMetricsCollector extends SystemMetricsCollector<CpuMetrics> { @Override @ThreadSafe(enableChecks = false) public boolean getSnapshot(CpuMetrics snapshot) { checkNotNull(snapshot, "Null value passed to getSnapshot!"); try { ProcFileReader reader = mProcFileReader.get(); if (reader == null) { reader = new ProcFileRead...
@Test public void testBrokenFile() throws Exception { TestableCpuMetricsCollector collector = new TestableCpuMetricsCollector().setPath(createFile("I am a weird android manufacturer")); CpuMetrics snapshot = new CpuMetrics(); assertThat(collector.getSnapshot(snapshot)).isFalse(); } @Test public void testNegativeFields(...
WakeLockMetrics extends SystemMetrics<WakeLockMetrics> { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WakeLockMetrics that = (WakeLockMetrics) o; if (isAttributionEnabled != that.isAttributionEnabled || heldTimeMs != that.held...
@Test public void testEquals() { assertThat(new WakeLockMetrics()).isEqualTo(new WakeLockMetrics()); assertThat(createInitializedMetrics()).isEqualTo(createInitializedMetrics()); }
SensorMetrics extends SystemMetrics<SensorMetrics> { @Override public SensorMetrics diff(@Nullable SensorMetrics b, @Nullable SensorMetrics output) { if (output == null) { output = new SensorMetrics(isAttributionEnabled); } if (b == null) { output.set(this); } else { total.diff(b.total, output.total); if (output.isAttr...
@Test public void testAttributedDiff() { SensorMetrics a = createAttributedMetrics(); SensorMetrics b = createAttributedMetrics(); SensorMetrics result = a.diff(b); assertThat(result).isEqualTo(new SensorMetrics(true)); }
UndertowEndpointManager implements WebSocketConnectionCallback, XEndpointManager<UndertowEndpoint> { UndertowEndpoint createEndpoint(WebSocketChannel channel) { final UndertowEndpoint endpoint = new UndertowEndpoint(this, channel); try { channel.setOption(Options.TCP_NODELAY, NODELAY); } catch (IOException e) { throw n...
@Test(expected=OptionAssignmentException.class) public void testCreateEndpointWithError() throws IOException { @SuppressWarnings("unchecked") final XEndpointListener<UndertowEndpoint> listener = mock(XEndpointListener.class); final UndertowEndpointManager mgr = new UndertowEndpointManager(null, 0, new DerivedEndpointCo...
UndertowEndpoint extends AbstractReceiveListener implements XEndpoint { WebSocketCallback<Void> wrapCallback(XSendCallback callback) { return new WebSocketCallback<Void>() { private final AtomicBoolean onceOnly = new AtomicBoolean(); @Override public void complete(WebSocketChannel channel, Void context) { if (onceOnly....
@Test public void testCallbackOnceOnlyComplete() { createEndpointManager(); final XSendCallback callback = mock(XSendCallback.class); final WebSocketCallback<Void> wsCallback = endpoint.wrapCallback(callback); wsCallback.complete(channel, null); verify(callback, times(1)).onComplete(eq(endpoint)); wsCallback.complete(c...
PomHelper { public static boolean updatePomVersions(List<PomUpdateStatus> pomsToChange, List<DependencyVersionChange> changes) throws IOException { Map<String, String> propertyChanges = new TreeMap<>(); for (PomUpdateStatus status : pomsToChange) { status.updateVersions(changes, propertyChanges); } if (!propertyChanges...
@Test public void testVersionReplacement() throws Exception { File outDir = Tests.copyPackageSources(getClass()); LOG.info("Updating poms in " + outDir); File[] files = outDir.listFiles(); assertNotNull("No output files!", files); assertTrue("No output files!", files.length > 0); List<PomUpdateStatus> pomsToChange = ne...
BorderingDistanceMetric implements SpatialDistanceMetric { @Override public double distance(Geometry g1, Geometry g2) { if (adjacencyList.isEmpty()) { throw new UnsupportedOperationException(); } int srcId = getContainingGeometry(g1); int destId = getContainingGeometry(g2); if (srcId < 0) { throw new IllegalArgumentExc...
@Test public void testSimple() throws DaoException { assertEquals(0, metric.distance(g("Minnesota"), g("Minnesota")), 0.01); assertEquals(1, metric.distance(g("Wisconsin"), g("Minnesota")), 0.01); assertEquals(1, metric.distance(g("North Dakota"), g("Minnesota")), 0.01); assertEquals(1, metric.distance(g("South Dakota"...
Configurator implements Cloneable { public <T> T get(Class<T> klass, String name) throws ConfigurationException { return get(klass, name, null); } Configurator(Configuration conf); Configuration getConf(); T get(Class<T> klass, String name); T get(Class<T> klass, String name, String runtimeKey, String runtimeValue); T ...
@Test public void testRuntimeParams() throws ConfigurationException, IOException { Configurator conf = new Configurator(new Configuration()); Integer i1 = conf.get(Integer.class, "foo"); assertEquals(i1, 42); Integer i2 = conf.get(Integer.class, "foo"); assertEquals(i1, i2); Map<String, String> args3 = new HashMap<Stri...
SparseMatrix implements Matrix<SparseMatrixRow> { @Override public Iterator<SparseMatrixRow> iterator() { return new SparseMatrixIterator(); } SparseMatrix(File path); long lastModified(); @Override SparseMatrixRow getRow(int rowId); @Override int[] getRowIds(); @Override int getNumRows(); ValueConf getValueConf(); @Ov...
@Test public void testWrite() throws IOException { File tmp = File.createTempFile("matrix", null); SparseMatrixWriter.write(tmp, srcRows.iterator()); } @Test public void testReadWrite() throws IOException { File tmp = File.createTempFile("matrix", null); SparseMatrixWriter.write(tmp, srcRows.iterator()); Matrix m1 = ne...
DenseMatrix implements Matrix<DenseMatrixRow> { @Override public Iterator<DenseMatrixRow> iterator() { return new DenseMatrixIterator(); } DenseMatrix(File path); @Override DenseMatrixRow getRow(int rowId); @Override int[] getRowIds(); int[] getColIds(); @Override int getNumRows(); ValueConf getValueConf(); @Override I...
@Test public void testWrite() throws IOException { File tmp = File.createTempFile("matrix", null); DenseMatrixWriter.write(tmp, srcRows.iterator()); } @Test public void testReadWrite() throws IOException { File tmp = File.createTempFile("matrix", null); DenseMatrixWriter.write(tmp, srcRows.iterator()); DenseMatrix m1 =...
PageViewUtils { public static SortedSet<DateTime> timestampsInInterval(DateTime start, DateTime end) { if (start.isAfter(end)) { throw new IllegalArgumentException(); } DateTime current = new DateTime( start.year().get(), start.monthOfYear().get(), start.dayOfMonth().get(), start.hourOfDay().get(), 0); if (current.isBe...
@Test public void testTstampsInRange() { long now = System.currentTimeMillis(); Random random = new Random(); for (int i = 0; i < 1000; i++) { long tstamp = (long) (random.nextDouble() * now); DateTime beg = new DateTime(tstamp); DateTime end = beg.plusHours(1); SortedSet<DateTime> tstamps = PageViewUtils.timestampsInI...
BorderingDistanceMetric implements SpatialDistanceMetric { @Override public List<Neighbor> getNeighbors(Geometry g, int maxNeighbors) { return getNeighbors(g, maxNeighbors, Double.MAX_VALUE); } BorderingDistanceMetric(SpatialDataDao dao, String layer); @Override void setValidConcepts(TIntSet concepts); @Override void e...
@Test public void testKnn() throws DaoException { List<SpatialDistanceMetric.Neighbor> neighbors = metric.getNeighbors(g("Minnesota"), 100); for (int i = 0; i < neighbors.size(); i++) { SpatialDistanceMetric.Neighbor n = neighbors.get(i); String name = n(n.conceptId); if (i == 0) { assertEquals(name, "Minnesota"); } el...
Language implements Comparable<Language>, Serializable { public static Language getByLangCode(String langCode) { langCode = langCode.replace('_', '-').toLowerCase(); if (WIKIDATA.getLangCode().equals(langCode)) { return WIKIDATA; } for (Language lang : LANGUAGES) { if (lang.langCode.equalsIgnoreCase(langCode)) { return...
@Test(expected=IllegalArgumentException.class) public void testNonexistentByLangCode() { Language.getByLangCode("zz"); }
Language implements Comparable<Language>, Serializable { public static Language getById(int id) { if (0 < id && id <= LANGUAGES.length) { return LANGUAGES[id-1]; } else { throw new IllegalArgumentException("unknown language id: '" + id + "'"); } } private Language(short id, String langCode, String enLangName, String n...
@Test(expected=IllegalArgumentException.class) public void testNonexistentById() { Language.getById(-1); }
Title implements Externalizable { public Title(String text, LanguageInfo language) { this(text, false, language); } Title(String text, LanguageInfo language); Title(String text, boolean isCanonical, LanguageInfo lang); Title(String title, Language language); String getCanonicalTitle(); LanguageInfo getLanguageInfo();...
@Test public void testTitle(){ LanguageInfo lang = LanguageInfo.getByLangCode("en"); Title pokemon = new Title("Pokemon: The Movie",lang); assert (pokemon.getNamespaceString() == null); assert (pokemon.getNamespace()==NameSpace.ARTICLE); assert (pokemon.getTitleStringWithoutNamespace().equals("Pokemon: The Movie")); Ti...
WikidataParser { public WikidataEntity parse(String json) throws WpParseException { JacksonTermedStatementDocument mwDoc; try { mwDoc = mapper.readValue(json, JacksonTermedStatementDocument.class); } catch (IOException e) { LOG.info("Error parsing: " + json); throw new WpParseException(e); } WikidataEntity record = new...
@Test public void testWikidataRawRecord() throws IOException, WpParseException { String json = WpIOUtils.resourceToString("/testPage.json"); WikidataParser parser = new WikidataParser(); WikidataEntity entity = parser.parse(json); assertEquals(entity.getType(), WikidataEntity.Type.ITEM); assertEquals(entity.getId(), 15...
GoogleSimilarity implements VectorSimilarity { public GoogleSimilarity(int numPages) { this.numPages = numPages; } GoogleSimilarity(int numPages); @Override synchronized void setMatrices(SparseMatrix features, SparseMatrix transpose, File dataDir); @Override double similarity(TIntFloatMap vector1, TIntFloatMap vector2)...
@Test public void testUtils() { TIntFloatMap row1 = getMap(ROW1_IDS, ROW1_VALS); TIntFloatMap row2 = getMap(ROW2_IDS, ROW2_VALS); double expected = googleSimilarity(row1, row2); double actual = SimUtils.googleSimilarity(6, 5, 3, NUM_PAGES); assertEquals(expected, actual, 0.0001); }
CosineSimilarity implements VectorSimilarity { @Override public double similarity(MatrixRow a, MatrixRow b) { return SimUtils.cosineSimilarity(a, b); } @Override synchronized void setMatrices(SparseMatrix features, SparseMatrix transpose, File dataDir); @Override double similarity(MatrixRow a, MatrixRow b); @Override ...
@Test public void testMap() { TIntFloatMap row1 = getMap(ROW1_IDS, ROW1_VALS); TIntFloatMap row2 = getMap(ROW2_IDS, ROW2_VALS); double expected = cosineSimilarity(row1, row2); double actual = new CosineSimilarity().similarity(row1, row2); assertEquals(expected, actual, 0.0001); actual = new CosineSimilarity().similarit...
SimUtils { public static double cosineSimilarity(TIntDoubleMap X, TIntDoubleMap Y) { double xDotX = 0.0; double yDotY = 0.0; double xDotY = 0.0; for (int id : X.keys()) { double x = X.get(id); xDotX += x * x; if (Y.containsKey(id)) { xDotY += x * Y.get(id); } } for (double y : Y.values()) { yDotY += y * y; } return xDo...
@Test public void testCosineSimilarity() { TIntDoubleHashMap zeroVector = zeroVector(keyList1); TIntDoubleHashMap testVector1 = testVector(keyList2, 0); TIntDoubleHashMap testVector2 = testVector(keyList2, 1); assertEquals("Cosine similarity between a vector and itself must be 1", 1.0, SimUtils.cosineSimilarity(testVec...
SimUtils { public static TIntDoubleMap normalizeVector(TIntDoubleMap X) { TIntDoubleHashMap Y = new TIntDoubleHashMap(); double sumSquares = 0.0; for (double x : X.values()) { sumSquares += x * x; } if (sumSquares != 0.0) { double norm = Math.sqrt(sumSquares); for (int id : X.keys()) { Y.put(id, X.get(id) / norm); } re...
@Test public void testNormalizeVector() { TIntDoubleHashMap zeroVector1 = zeroVector(keyList1); TIntDoubleHashMap testVector1 = testVector(keyList2, 0); TIntDoubleHashMap testVector2 = testVector(keyList2, 1); TIntDoubleMap zeroVector1Normalized = SimUtils.normalizeVector(zeroVector1); TIntDoubleMap testVector1Normaliz...
GraphDistanceMetric implements SpatialDistanceMetric { @Override public double distance(Geometry g1, Geometry g2) { if (adjacencyList.isEmpty()) { throw new UnsupportedOperationException(); } List<ClosestPointIndex.Result> closest = index.query(g2, 1); int maxSteps = maxDistance; if (maxSteps == 0 || closest.isEmpty())...
@Test public void testLattice() throws DaoException { GraphDistanceMetric metric = getLatticeMetric(); assertEquals(1.0, metric.distance(lattice[2][0], lattice[0][0]), 0.01); assertEquals(1.0, metric.distance(lattice[2][0], lattice[1][0]), 0.01); assertEquals(0.0, metric.distance(lattice[2][0], lattice[2][0]), 0.01); a...
SimUtils { public static Map sortByValue(TIntDoubleHashMap unsortMap) { if (unsortMap.isEmpty()) { return new HashMap(); } HashMap<Integer, Double> tempMap = new HashMap<Integer, Double>(); TIntDoubleIterator iterator = unsortMap.iterator(); for ( int i = unsortMap.size(); i-- > 0; ) { iterator.advance(); tempMap.put( ...
@Test public void testSortByValue() { int testMapSize = 1000; Random random = new Random(System.currentTimeMillis()); TIntDoubleHashMap testMap = new TIntDoubleHashMap(); for(int i = 0 ; i < testMapSize ; ++i) { testMap.put(random.nextInt(), random.nextDouble()); } Map<Integer, Double> sortedMap = SimUtils.sortByValue(...
DatasetDao { public static Collection<Info> readInfos() throws DaoException { try { return readInfos(WpIOUtils.openResource(RESOURCE_DATASET_INFO)); } catch (IOException e) { throw new DaoException(e); } } DatasetDao(); DatasetDao(Collection<Info> info); void setNormalize(boolean normalize); List<Dataset> getAllInLang...
@Test public void testInfos() throws DaoException { Collection<DatasetDao.Info> infos = DatasetDao.readInfos(); assertEquals(18, infos.size()); }
DatasetDao { public Dataset get(Language language, String name) throws DaoException { if (groups.containsKey(name)) { List<Dataset> members = new ArrayList<Dataset>(); for (String n : groups.get(name)) { members.add(get(language, n)); } return new Dataset(name, members); } if (name.contains("/") || name.contains("\\"))...
@Test public void testDaoRead() throws DaoException { DatasetDao dao = new DatasetDao(); Dataset ds = dao.get(Language.getByLangCode("en"), "wordsim353.txt"); assertEquals(353, ds.getData().size()); assertEquals("en", ds.getLanguage().getLangCode()); double sim = Double.NaN; for (KnownSim ks : ds.getData()) { if (ks.ph...
MostSimilarGuess { public double getNDGC() { if (observations.isEmpty()) { return 0.0; } TIntDoubleMap actual = new TIntDoubleHashMap(); for (KnownSim ks : known.getMostSimilar()) { actual.put(ks.wpId2, ks.similarity); } int ranks[] = new int[observations.size()]; double scores[] = new double[observations.size()]; doub...
@Test public void testNdgc() { double ndgc = ( (0.80 + 0.00 / Math.log(2+1) + 0.95 / Math.log(4+1) + 0.91 / Math.log(7+1)) / (0.95 + 0.91 / Math.log(2+1) + 0.80 / Math.log(4+1) + 0.00 / Math.log(7+1))); assertEquals(ndgc, guess.getNDGC(), 0.001); }
MostSimilarGuess { public PrecisionRecallAccumulator getPrecisionRecall(int n, double threshold) { PrecisionRecallAccumulator pr = new PrecisionRecallAccumulator(n, threshold); TIntDoubleMap actual = new TIntDoubleHashMap(); for (KnownSim ks : known.getMostSimilar()) { pr.observe(ks.similarity); actual.put(ks.wpId2, ks...
@Test public void testPrecisionRecall() { PrecisionRecallAccumulator pr = guess.getPrecisionRecall(1, 0.7); assertEquals(pr.getN(), 1); assertEquals(1.0, pr.getPrecision(), 0.001); assertEquals(0.333333, pr.getRecall(), 0.001); pr = guess.getPrecisionRecall(2, 0.7); assertEquals(0.5, pr.getPrecision(), 0.001); assertEq...
FileDownloader { public File download(URL url, File file) throws InterruptedException { LOG.info("beginning download of " + url + " to " + file); for (int i=1; i <= maxAttempts; i++) { try { AtomicBoolean stop = new AtomicBoolean(false); DownloadInfo info = new DownloadInfo(url); DownloadMonitor monitor = new DownloadM...
@Test public void testDownloader() throws IOException, InterruptedException { URL url = new URL("http: File tmp1 = File.createTempFile("downloader-test", ".txt"); FileDownloader downloader = new FileDownloader(); downloader.download(url, tmp1); assertTrue(tmp1.isFile()); List<String> lines = FileUtils.readLines(tmp1); ...
WpIOUtils { public static Serializable bytesToObject(byte input[]) throws IOException, ClassNotFoundException { return (Serializable) new ObjectInputStream( new ByteArrayInputStream(input)) .readObject(); } static void mkdirsQuietly(File dir); static void writeObjectToFile(File file, Object o); static Object readObjec...
@Test public void testSerialization() throws IOException, ClassNotFoundException { String hex = "aced0005757200025b460b9c818922e00c4202000078700000055b402a056a3ff3a176400797813ffba962401a234e3ff8e2093fef799d40369d60403ef48e4011aa844001c25240321b0a3fdd8e863ff8e599400d8398400a180240032f43402841f23fe5936d4016e1014010ffae3...
JvmUtils { public synchronized static String getFullClassName(String shortName) { if (NAME_TO_CLASS != null) { return NAME_TO_CLASS.get(shortName); } NAME_TO_CLASS = new HashMap<String, String>(); for (File file : getClassPathAsList()) { if (file.length() > MAX_FILE_SIZE) { LOG.debug("skipping looking for providers in ...
@Test public void testFullClassName() { assertEquals("org.wikibrain.utils.JvmUtils", JvmUtils.getFullClassName("JvmUtils")); assertNull(JvmUtils.getFullClassName("Foozkjasdf")); }
JvmUtils { public static Class classForShortName(String shortName) { String fullName = getFullClassName(shortName); if (fullName == null) { return null; } try { return Class.forName(fullName); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } static String getClassPath(); synchronized static List...
@Test public void testClassForShortName() { assertEquals(JvmUtils.class, JvmUtils.classForShortName("JvmUtils")); assertNull(JvmUtils.classForShortName("Foozkjasdf")); }
MetricsService { public Map<String, String> getMetrics(ProcessGroupStatus status, boolean appendPgId) { final Map<String, String> metrics = new HashMap<>(); metrics.put(appendPgId(MetricNames.FLOW_FILES_RECEIVED, status, appendPgId), String.valueOf(status.getFlowFilesReceived())); metrics.put(appendPgId(MetricNames.BYT...
@Test public void testGetProcessGroupStatusMetrics() { ProcessGroupStatus status = new ProcessGroupStatus(); status.setId("1234"); status.setFlowFilesReceived(5); status.setBytesReceived(10000); status.setFlowFilesSent(10); status.setBytesSent(20000); status.setQueuedCount(100); status.setQueuedContentSize(1024L); stat...
PrometheusReportingTask extends AbstractReportingTask { @Override public void onTrigger(final ReportingContext context) { final String metricsCollectorUrl = context.getProperty(METRICS_COLLECTOR_URL) .evaluateAttributeExpressions().getValue() .replace("http: final String applicationId = context.getProperty(APPLICATION_...
@Test public void testOnTrigger() throws InitializationException { final String metricsUrl = "http: final String applicationId = "nifi"; final String hostName = "localhost"; final String jobName = "nifi_reporting_job"; final boolean jvmMetrics = true; final boolean authentication = false; final Client client = Mockito....
KafkaSinkFactory implements SinkFactory { @Override public String name() { return "kafka"; } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config config); }
@Test public void testName() { assertThat(factory.name()).isEqualTo("kafka"); }
ReflectionHelper { public static void invokeTransformationMethod(Object mediator, Method method) { method = ReflectionHelper.makeAccessibleIfNot(method); List<Object> values = getParameterFromTransformationMethod(method); try { Class<?> returnType = method.getReturnType(); Outbound outbound = method.getAnnotation(Outbo...
@Test(expected = IllegalArgumentException.class) public void testTransformationWithNotAnnotatedParameter() throws NoSuchMethodException { InvalidBecauseOfBadParams test = new InvalidBecauseOfBadParams(); Method method = test.getClass().getMethod("trans", Source.class); ReflectionHelper.invokeTransformationMethod(test, ...
ReflectionHelper { static Sink<Object> getSinkOrFail(String name) { Sink<Object> sink = FluidRegistry.sink(Objects.requireNonNull(name)); if (sink == null) { throw new IllegalArgumentException("Unable to find the sink " + name); } return sink; } private ReflectionHelper(); static void set(Object mediator, Field field,...
@Test public void testGettingAMissingSink() { FluidRegistry.register("my-sink", Sink.list()); Sink<Object> sink = ReflectionHelper.getSinkOrFail("my-sink"); assertThat(sink).isNotNull(); try { ReflectionHelper.getSinkOrFail("missing"); fail("The sink should be missing"); } catch (IllegalArgumentException e) { } }
ReflectionHelper { static Source<Object> getSourceOrFail(String name) { Source<Object> src = FluidRegistry.source(Objects.requireNonNull(name)); if (src == null) { throw new IllegalArgumentException("Unable to find the source " + name); } return src; } private ReflectionHelper(); static void set(Object mediator, Field...
@Test public void testGettingAMissingSource() { FluidRegistry.register("my-source", Source.empty()); Source<Object> source = ReflectionHelper.getSourceOrFail("my-source"); assertThat(source).isNotNull(); try { ReflectionHelper.getSourceOrFail("missing"); fail("The source should be missing"); } catch (IllegalArgumentExc...
FluidRegistry { public static synchronized <T> void register(Source<T> source) { sources.put(Objects.requireNonNull(source.name(), NAME_NOT_PROVIDED_MESSAGE), source); } private FluidRegistry(); static synchronized void initialize(Vertx vertx, FluidConfig config); static void reset(); static synchronized void register...
@Test(expected = NullPointerException.class) public void testRegistrationOfSinkWithNullName() { Sink<String> discard = Sink.discard(); FluidRegistry.register(null, discard); } @Test(expected = NullPointerException.class) public void testRegistrationOfSourceWithNullName() { Source<String> source = Source.empty(); FluidR...
FluidRegistry { public static synchronized void initialize(Vertx vertx, FluidConfig config) { sinks.putAll(SourceAndSinkBuilder.createSinksFromConfiguration(vertx, config)); sources.putAll(SourceAndSinkBuilder.createSourcesFromConfiguration(vertx, config)); } private FluidRegistry(); static synchronized void initializ...
@Test public void testInitialize() { Fluid fluid = Fluid.create(); assertThat(FluidRegistry.source("unknown")).isNull(); assertThat(FluidRegistry.sink("unknown")).isNull(); fluid.vertx().close(); }
SourceAndSinkBuilder { public static Map<String, Source> createSourcesFromConfiguration(Vertx vertx, FluidConfig config) { Map<String, Source> map = new HashMap<>(); Optional<Config> sources = config.getConfig("sources"); if (sources.isPresent()) { Iterator<String> names = sources.get().names(); while (names.hasNext())...
@SuppressWarnings("unchecked") @Test public void loadSourceTest() { Map<String, Source> sources = SourceAndSinkBuilder.createSourcesFromConfiguration(vertx, fluid.getConfig()); assertThat(sources).hasSize(2); Source<String> source1 = sources.get("source1"); assertThat(source1).isNotNull(); Source<Integer> source2 = sou...
SourceAndSinkBuilder { public static Map<String, Sink> createSinksFromConfiguration(Vertx vertx, FluidConfig config) { Map<String, Sink> map = new HashMap<>(); Optional<Config> sinks = config.getConfig("sinks"); if (sinks.isPresent()) { Iterator<String> names = sinks.get().names(); while (names.hasNext()) { String name...
@SuppressWarnings("unchecked") @Test public void loadSinkTest() { Map<String, Sink> sinks = SourceAndSinkBuilder.createSinksFromConfiguration(vertx, fluid.getConfig()); assertThat(sinks).hasSize(2); Sink<String> sink1 = sinks.get("sink1"); assertThat(sink1).isNotNull().isInstanceOf(ListSink.class); Sink<Integer> sink2 ...
CommonHeaders { public static String address(Message message) { return (String) message.get(ADDRESS); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); static String address(Message message); @Su...
@Test public void shouldGetRequiredAddress() { assertThat(address(messageWithCommonHeaders)).isEqualTo("address"); }
CommonHeaders { @SuppressWarnings("unchecked") public static Optional<String> addressOpt(Message message) { return message.getOpt(ADDRESS); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); stati...
@Test public void shouldHandleEmptyAddress() { assertThat(addressOpt(messageWithoutCommonHeaders)).isEmpty(); }
KafkaSinkFactory implements SinkFactory { @Override public <T> Single<Sink<T>> create(Vertx vertx, String name, Config config) { return Single.just(new KafkaSink<>(vertx, name, config)); } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config config); }
@Test(expected = ConfigException.class) public void testCreationWithoutParameter() { factory.create(vertx, null, new Config(NullNode.getInstance())); } @Test public void testCreationWithMinimalConfiguration() throws IOException { Single<Sink<Object>> single = factory.create(vertx, null, new Config(new JsonObject() .put...
CommonHeaders { public static String key(Message message) { return (String) message.get(KEY); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); static String address(Message message); @SuppressWa...
@Test public void shouldGetRequiredKey() { assertThat(key(messageWithCommonHeaders)).isEqualTo("key"); }
CommonHeaders { @SuppressWarnings("unchecked") public static Optional<String> keyOpt(Message message) { return message.getOpt(KEY); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); static String...
@Test public void shouldHandleEmptyKey() { assertThat(keyOpt(messageWithoutCommonHeaders)).isEmpty(); }
CommonHeaders { @SuppressWarnings("unchecked") public static <T> T original(Message message) { return (T) message.get(ORIGINAL); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); static String ad...
@Test public void shouldGetRequiredOriginalData() { assertThat(CommonHeaders.<String>original(messageWithCommonHeaders)).isEqualTo("original"); }
CommonHeaders { @SuppressWarnings("unchecked") public static <T> Optional<T> originalOpt(Message message) { return message.getOpt(ORIGINAL); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); stat...
@Test public void shouldHandleEmptyOriginal() { assertThat(originalOpt(messageWithoutCommonHeaders)).isEmpty(); }
DefaultSource implements Source<T> { @Override public Source<T> named(String name) { if (Strings.isBlank(name)) { throw new IllegalArgumentException("The name cannot be `null` or blank"); } return new DefaultSource<>(flow, name, attributes); } DefaultSource(Publisher<Message<T>> items, String name, Map<String, Object> ...
@Test(expected = IllegalArgumentException.class) public void testNullName() { Source.from("a", "b", "c").named(null); } @Test(expected = IllegalArgumentException.class) public void testBlankName() { Source.from("a", "b", "c").named(" "); }
DefaultSource implements Source<T> { @Override public Source<T> orElse(Source<T> alt) { Objects.requireNonNull(alt, "The alternative source must not be `null`"); return new DefaultSource<>(Flowable.fromPublisher(flow).switchIfEmpty(alt), name, attributes); } DefaultSource(Publisher<Message<T>> items, String name, Map<S...
@Test public void testOrElse() { Source<String> source = Source.from("a", "b", "c") .named("my source"); Source<String> empty = Source.<String>empty().named("empty"); Source<String> another = Source.from("d", "e", "f"); ListSink<String> sink = Sink.list(); source.orElse(another).to(sink); assertThat(sink.values()).cont...
DefaultSource implements Source<T> { @Override public <X> Source<X> flatMap(Function<Message<T>, Publisher<Message<X>>> mapper) { Objects.requireNonNull(mapper, FUNCTION_CANNOT_BE_NULL_MESSAGE); return new DefaultSource<>(Flowable.fromPublisher(flow).flatMap(mapper::apply), name, attributes); } DefaultSource(Publisher<...
@Test public void testFlatMap() { ListSink<Integer> sink = Sink.list(); Random random = new Random(); Source.from(1, 2, 3, 4, 5) .flatMap(i -> Flowable.fromArray(i, i).delay(random.nextInt(10), TimeUnit.MILLISECONDS)) .to(sink); await().until(() -> sink.values().size() == 10); assertThat(sink.values()).contains(1, 1, 2...
DefaultSource implements Source<T> { @Override public <X> Source<X> concatMap(Function<Message<T>, Publisher<Message<X>>> mapper) { Objects.requireNonNull(mapper, FUNCTION_CANNOT_BE_NULL_MESSAGE); return new DefaultSource<>(Flowable.fromPublisher(flow).concatMap(mapper::apply), name, attributes); } DefaultSource(Publis...
@Test public void testConcatMap() { ListSink<Integer> sink = Sink.list(); Random random = new Random(); Source.from(1, 2, 3, 4, 5) .concatMap(i -> Flowable.fromArray(i, i).delay(random.nextInt(10), TimeUnit.MILLISECONDS)) .to(sink); await().until(() -> sink.values().size() == 10); assertThat(sink.values()).containsExac...
DefaultSource implements Source<T> { @Override public <X> Source<X> compose(Function<Publisher<Message<T>>, Publisher<Message<X>>> mapper) { return new DefaultSource<>(asFlowable().compose(mapper::apply), name, attributes); } DefaultSource(Publisher<Message<T>> items, String name, Map<String, Object> attr); @Override S...
@Test public void testCompose() { ListSink<Integer> list = Sink.list(); Source.from(1, 2, 3, 4, 5) .composeFlowable(flow -> flow.map(Message::payload).map(i -> i + 1).map(Message::new)) .to(list); assertThat(list.values()).containsExactly(2, 3, 4, 5, 6); }
DefaultSource implements Source<T> { @Override public Source<T> mergeWith(Publisher<Message<T>> source) { return new DefaultSource<>(asFlowable().mergeWith(source), name, attributes); } DefaultSource(Publisher<Message<T>> items, String name, Map<String, Object> attr); @Override Source<T> named(String name); @Override S...
@Test public void testMergeWith() { Source<String> s1 = Source.from("a", "b", "c"); Source<String> s2 = Source.from("d", "e", "f"); Source<String> s3 = Source.from("g", "h"); ListSink<String> list = Sink.list(); s1.mergeWith(s2).to(list); assertThat(list.values()).containsExactly("a", "b", "c", "d", "e", "f"); Random r...
DefaultSource implements Source<T> { @Override public <K> Publisher<GroupedDataStream<K, T>> groupBy(Function<Message<T>, K> keySupplier) { Objects.requireNonNull(keySupplier, "The function computing the key must not be `null`"); return Flowable.fromPublisher(flow) .groupBy(keySupplier::apply) .flatMapSingle(gf -> { Gr...
@Test public void testGroupBy() { String text = "In 1815, M. Charles–Francois-Bienvenu Myriel was Bishop of D He was an old man of about seventy-five " + "years of age; he had occupied the see of D since 1806. Although this detail has no connection whatever with the " + "real substance of what we are about to relate, i...
DefaultSource implements Source<T> { @Override public Pair<Source<T>, Source<T>> branch(Predicate<Message<T>> condition) { List<Source<T>> sources = broadcast(2); Source<T> left = sources.get(0).filter(condition); Source<T> right = sources.get(0).filterNot(condition); return pair(left, right); } DefaultSource(Publisher...
@Test public void testBranch() { Pair<Source<Integer>, Source<Integer>> branches = Source.from(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .branch(i -> i.payload() % 3 == 0); ListSink<String> left = Sink.list(); ListSink<String> right = Sink.list(); branches.left().mapPayload(i -> Integer.toString(i)).to(left); branches.right().map...
DefaultSource implements Source<T> { @Override public Pair<Source<T>, Source<T>> branchOnPayload(Predicate<T> condition) { List<Source<T>> sources = broadcast(2); Source<T> left = sources.get(0).filterPayload(condition); Source<T> right = sources.get(0).filterNotPayload(condition); return pair(left, right); } DefaultSo...
@Test public void testBranchOnPayload() { Pair<Source<Integer>, Source<Integer>> branches = Source.from(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .branchOnPayload(i -> i % 3 == 0); ListSink<String> left = Sink.list(); ListSink<String> right = Sink.list(); branches.left().mapPayload(i -> Integer.toString(i)).to(left); branches.rig...
Tuple implements Iterable<Object> { Tuple(Object... items) { if (items == null) { this.items = Collections.emptyList(); } else { for (Object o : items) { if (o == null) { throw new IllegalArgumentException("A tuple cannot contain a `null` value"); } } this.items = Collections.unmodifiableList(Arrays.asList(items)); } }...
@Test(expected = IllegalArgumentException.class) public void testTupleWithNull() { Tuple.tuple("a", "b", null, "c"); }
EventBusSourceFactory implements SourceFactory { @Override public String name() { return "eventbus"; } @Override String name(); @Override Single<Source<T>> create(Vertx vertx, String name, Config config); }
@Test public void testName() { assertThat(factory.name()).isEqualTo("eventbus"); }
EventBusSourceFactory implements SourceFactory { @Override public <T> Single<Source<T>> create(Vertx vertx, String name, Config config) { String address = config.getString("address") .orElse(name); if (address == null) { throw new IllegalArgumentException("Either address or name must be set"); } return Single.just(new ...
@Test(expected = IllegalArgumentException.class) public void testCreationWithoutParameter() { factory.create(vertx, null, new Config(NullNode.getInstance())); } @Test public void testCreationWithAddress() throws IOException { Single<Source<Object>> single = factory.create(vertx, null, new Config(new JsonObject().put("a...
EventBusSinkFactory implements SinkFactory { @Override public String name() { return "eventbus"; } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config conf); }
@Test public void testName() { assertThat(factory.name()).isEqualTo("eventbus"); }
EventBusSinkFactory implements SinkFactory { @Override public <T> Single<Sink<T>> create(Vertx vertx, String name, Config conf) { return Single.just(new EventBusSink<>(vertx, conf)); } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config conf); }
@Test(expected = IllegalArgumentException.class) public void testCreationWithoutParameter() { factory.create(vertx, null, new Config(NullNode.getInstance())); } @Test public void testCreationWithAddress() throws IOException { Single<Sink<Object>> single = factory.create(vertx, null, new Config(new JsonObject().put("add...
KafkaSourceFactory implements SourceFactory { @Override public String name() { return "kafka"; } @Override String name(); @Override Single<Source<T>> create(Vertx vertx, String name, Config config); }
@Test public void testName() { assertThat(factory.name()).isEqualTo("kafka"); }
CamelSink implements Sink<T> { public CamelContext camelContext() { return camelContext; } CamelSink(String name, Config config); @Override String name(); @Override Completable dispatch(Message<T> message); CamelContext camelContext(); }
@Test public void shouldWrapIntegersIntoCamelBodies(TestContext context) throws Exception { Async async = context.async(); CamelSink<Integer> sink = new CamelSink<>( null, new Config( new JsonObject().put("endpoint", "direct:test") ) ); CamelContext camelContext = sink.camelContext(); camelContext.addRoutes(new RouteBu...
CamelSinkFactory implements SinkFactory { @Override public String name() { return "camel"; } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config config); }
@Test public void testName() { CamelSinkFactory factory = new CamelSinkFactory(); assertThat(factory.name()).isEqualTo("camel"); }
CamelSinkFactory implements SinkFactory { @Override public <T> Single<Sink<T>> create(Vertx vertx, String name, Config config) { return Single.just(new CamelSink<>(name, config)); } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config config); }
@Test(expected = IllegalArgumentException.class) public void testCreationWithoutParameter() { CamelSinkFactory factory = new CamelSinkFactory(); factory.create(vertx, null , new Config(NullNode.getInstance())); } @Test public void testCreationWithEndpoint() throws IOException { CamelSinkFactory factory = new CamelSinkF...
InMemoryDocumentView implements DocumentView { @Override public synchronized Completable save(String collection, String key, Map<String, Object> document) { Objects.requireNonNull(collection, NULL_COLLECTION_MESSAGE); Objects.requireNonNull(key, NULL_KEY_MESSAGE); Objects.requireNonNull(collection, "The `document` must...
@Test public void shouldCallSubscriberOnSave(TestContext context) { Async async = context.async(); view.save(collection, key, document).subscribe(async::complete); }
KafkaSourceFactory implements SourceFactory { @Override public <T> Single<Source<T>> create(Vertx vertx, String name, Config config) { return Single.just(new KafkaSource<>(vertx, name, config)); } @Override String name(); @Override Single<Source<T>> create(Vertx vertx, String name, Config config); }
@Test(expected = ConfigException.class) public void testCreationWithoutParameter() { factory.create(vertx, null, new Config(NullNode.getInstance())); } @Test public void testCreationWithMinimalConfiguration() throws IOException { Single<Source<Object>> single = factory.create(vertx, null, new Config(new JsonObject() .p...
ReflectionHelper { public static void set(Object mediator, Field field, Object source) { if (!field.isAccessible()) { field.setAccessible(true); } try { field.set(mediator, source); } catch (IllegalAccessException e) { throw new IllegalStateException("Unable to set field " + field.getName() + " from " + mediator.getCla...
@Test public void testValidSet() throws NoSuchFieldException { Test1 test = new Test1(); Field field = Test1.class.getDeclaredField("foo"); ReflectionHelper.set(test, field, "hello"); assertThat(test.foo).isEqualTo("hello"); } @Test(expected = IllegalArgumentException.class) public void testInvalidSet() throws NoSuchFi...
ReflectionHelper { public static void invokeFunction(Object mediator, Method method) { method = ReflectionHelper.makeAccessibleIfNot(method); List<Flowable<Object>> sources = getFlowableForParameters(method); Function function = method.getAnnotation(Function.class); Sink<Object> sink = null; if (function.outbound().len...
@Test(expected = IllegalArgumentException.class) public void testFunctionWithNotAnnotatedParameter() throws NoSuchMethodException { InvalidBecauseOfBadParams test = new InvalidBecauseOfBadParams(); Method method = test.getClass().getMethod("function", String.class); ReflectionHelper.invokeFunction(test, method); } @Tes...
ObjectMapperJsonSerializer implements JsonSerializer { @Override public <T> T clone(T object) { if (object instanceof Collection) { Object firstElement = findFirstNonNullElement((Collection) object); if (firstElement != null && !(firstElement instanceof Serializable)) { JavaType type = TypeFactory.defaultInstance().con...
@Test public void should_clone_empty_collection() { List<?> original = new ArrayList(); Object cloned = serializer.clone(original); assertEquals(original, cloned); assertNotSame(original, cloned); } @Test public void should_clone_map_of_non_serializable_key() { Map<NonSerializableObject, String> original = new HashMap<...
PostgreSQLHStoreType extends ImmutableType<Map> { @Override protected Map get(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws SQLException { return (Map) rs.getObject(names[0]); } PostgreSQLHStoreType(); @Override int[] sqlTypes(); static final PostgreSQLHStoreType INSTANCE; }
@Test public void test() { doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager entityManager) { Book book = new Book(); book.setIsbn("978-9730228236"); book.getProperties().put("title", "High-Performance Java Persistence"); book.getProperties().put("author", "Vlad Mihalcea"); book.get...
Range implements Serializable { @SuppressWarnings("unchecked") public static <T extends Comparable> Range<T> ofString(String str, Function<String, T> converter, Class<T> clazz) { if(str.equals(EMPTY)) { return emptyRange(clazz); } int mask = str.charAt(0) == '[' ? LOWER_INCLUSIVE : LOWER_EXCLUSIVE; mask |= str.charAt(s...
@Test public void ofStringTest() { assertThat(integerRange("[1,3]").lower(), is(1)); assertThat(integerRange("[1,3]").upper(), is(3)); assertThat(integerRange("[1,3]").isUpperBoundClosed(), is(true)); assertThat(integerRange("[1,3]").isLowerBoundClosed(), is(true)); assertThat(integerRange("[,3]").lower(), is(nullValue...
PostgreSQLGuavaRangeType extends ImmutableType<Range> implements DynamicParameterizedType { public static Range<Integer> integerRange(String range) { return ofString(range, new Function<String, Integer>() { @Override public Integer apply(String s) { return Integer.parseInt(s); } }, Integer.class); } PostgreSQLGuavaRang...
@Test public void testUnboundedRangeStringIsRejected() { try { PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE; instance.integerRange("(,)"); fail("An unbounded range string should throw an exception!"); } catch (Exception e) { Throwable rootCause = Throwables.getRootCause(e); assertTrue(rootCause...
JacksonUtil { public static <T> T clone(T value) { return ObjectMapperWrapper.INSTANCE.clone(value); } static T fromString(String string, Class<T> clazz); static T fromString(String string, Type type); static String toString(Object value); static JsonNode toJsonNode(String value); static T clone(T value); }
@Test public void cloneDeserializeStepErrorTest() { MyEntity entity = new MyEntity(); entity.setValue("some value"); entity.setPojos(Arrays.asList( createMyPojo("first value", MyType.A, "1.1", createOtherPojo("USD")), createMyPojo("second value", MyType.B, "1.2", createOtherPojo("BRL")) )); MyEntity clone = JacksonUtil...
JsonTypeDescriptor extends AbstractTypeDescriptor<Object> implements DynamicParameterizedType { @Override public boolean areEqual(Object one, Object another) { if (one == another) { return true; } if (one == null || another == null) { return false; } if (one instanceof String && another instanceof String) { return one....
@Test public void testSetsAreEqual() { JsonTypeDescriptor descriptor = new JsonTypeDescriptor(); Form theFirst = createForm(1, 2, 3); Form theSecond = createForm(3, 2, 1); assertTrue(descriptor.areEqual(theFirst, theSecond)); }
SQLExtractor { public static String from(Query query) { AbstractProducedQuery abstractProducedQuery = query.unwrap(AbstractProducedQuery.class); String[] sqls = abstractProducedQuery .getProducer() .getFactory() .getQueryPlanCache() .getHQLQueryPlan(abstractProducedQuery.getQueryString(), false, Collections.emptyMap())...
@Test public void testJPQL() { doInJPA(entityManager -> { Query jpql = entityManager .createQuery( "select " + " YEAR(p.createdOn) as year, " + " count(p) as postCount " + "from " + " Post p " + "group by " + " YEAR(p.createdOn)", Tuple.class); String sql = SQLExtractor.from(jpql); assertNotNull(sql); LOGGER.info( "The...
Configuration { public Properties getProperties() { return properties; } private Configuration(); Properties getProperties(); ObjectMapperWrapper getObjectMapperWrapper(); Integer integerProperty(PropertyKey propertyKey); Long longProperty(PropertyKey propertyKey); Boolean booleanProperty(PropertyKey propertyKey); Cla...
@Test public void testHibernateProperties() { assertNull(Configuration.INSTANCE.getProperties().getProperty("hibernate.types.nothing")); assertEquals("def", Configuration.INSTANCE.getProperties().getProperty("hibernate.types.abc")); } @Test public void testHibernateTypesOverrideProperties() { assertEquals("ghi", Config...
PostgreSQLHStoreType extends ImmutableType<Map> { @Override protected Map get(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws SQLException { return (Map) rs.getObject(names[0]); } PostgreSQLHStoreType(); @Override int[] sqlTypes(); static final PostgreSQLHStoreType INSTANCE;...
@Test public void test() { doInJPA(entityManager -> { Book book = new Book(); book.setIsbn("978-9730228236"); book.getProperties().put("title", "High-Performance Java Persistence"); book.getProperties().put("author", "Vlad Mihalcea"); book.getProperties().put("publisher", "Amazon"); book.getProperties().put("price", "$...
Range implements Serializable { @SuppressWarnings("unchecked") public static <T extends Comparable> Range<T> ofString(String str, Function<String, T> converter, Class<T> clazz) { if(str.equals(EMPTY)) { return emptyRange(clazz); } int mask = str.charAt(0) == '[' ? LOWER_INCLUSIVE : LOWER_EXCLUSIVE; mask |= str.charAt(s...
@Test public void ofStringTest() { assertThat(integerRange("[1,3]").lower(), is(1)); assertThat(integerRange("[1,3]").upper(), is(3)); assertThat(integerRange("[1,3]").isUpperBoundClosed(), is(true)); assertThat(integerRange("[1,3]").isLowerBoundClosed(), is(true)); assertThat(integerRange("[,3]").lower(), is(nullValue...
Range implements Serializable { public static Range<LocalDateTime> localDateTimeRange(String range) { return ofString(range, parseLocalDateTime().compose(unquote()), LocalDateTime.class); } private Range(T lower, T upper, int mask, Class<T> clazz); @SuppressWarnings("unchecked") static Range<T> closed(T lower, T upper...
@Test public void localDateTimeTest() { assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.1,)")); assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.12,)")); assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.123,)")); assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.1234,)"))...
Range implements Serializable { public static Range<ZonedDateTime> zonedDateTimeRange(String rangeStr) { Range<ZonedDateTime> range = ofString(rangeStr, parseZonedDateTime().compose(unquote()), ZonedDateTime.class); if (range.hasLowerBound() && range.hasUpperBound()) { ZoneId lowerZone = range.lower().getZone(); ZoneId...
@Test public void zonedDateTimeTest() { assertNotNull(Range.zonedDateTimeRange("[2019-03-27 16:33:10.1-06,)")); assertNotNull(Range.zonedDateTimeRange("[2019-03-27 16:33:10.12-06,)")); assertNotNull(Range.zonedDateTimeRange("[2019-03-27 16:33:10.123-06,)")); assertNotNull(Range.zonedDateTimeRange("[2019-03-27 16:33:10....
PostgreSQLGuavaRangeType extends ImmutableType<Range> implements DynamicParameterizedType { public static Range<Integer> integerRange(String range) { return ofString(range, Integer::parseInt, Integer.class); } PostgreSQLGuavaRangeType(); @Override int[] sqlTypes(); @SuppressWarnings("unchecked") static Range<T> ofStrin...
@Test public void testUnboundedRangeStringIsRejected() { try { PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE; instance.integerRange("(,)"); fail("An unbounded range string should throw an exception!"); } catch (Exception e) { IllegalArgumentException rootCause = ExceptionUtil.rootCause(e); asser...
SQLExtractor { public static String from(Query query) { AbstractQueryImpl abstractQuery = query.unwrap(AbstractQueryImpl.class); SessionImplementor session = ReflectionUtils.getFieldValue(abstractQuery, "session"); String[] sqls = session.getFactory() .getQueryPlanCache() .getHQLQueryPlan(abstractQuery.getQueryString()...
@Test public void testJPQL() { doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager entityManager) { Query query = entityManager .createQuery( "select " + " YEAR(p.createdOn) as year, " + " count(p) as postCount " + "from " + " Post p " + "group by " + " YEAR(p.createdOn)", Tuple.class...
PostgreSQLGuavaRangeType extends ImmutableType<Range> { public static Range<Integer> integerRange(String range) { return ofString(range, new Function<String, Integer>() { @Override public Integer apply(String s) { return Integer.parseInt(s); } }, Integer.class); } PostgreSQLGuavaRangeType(); @Override int[] sqlTypes();...
@Test public void testUnboundedRangeStringIsRejected() { try { PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE; instance.integerRange("(,)"); fail("An unbounded range string should throw an exception!"); } catch (Exception e) { Throwable rootCause = Throwables.getRootCause(e); assertTrue(rootCause...
AuthorizationsCollector implements IAuthorizator { protected Authorization parseAuthLine(String line) throws ParseException { String[] tokens = line.split("\\s+"); String keyword = tokens[0].toLowerCase(); switch (keyword) { case "topic": return createAuthorization(line, tokens); case "user": m_parsingUsersSpecificSect...
@Test public void testParseAuthLineValid() throws ParseException { Authorization authorization = authorizator.parseAuthLine("topic /weather/italy/anemometer"); assertEquals(RW_ANEMOMETER, authorization); } @Test public void testParseAuthLineValid_read() throws ParseException { Authorization authorization = authorizator...