src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
IoTDBConnection implements Connection { public ServerProperties getServerProperties() throws TException { return client.getProperties(); } IoTDBConnection(); IoTDBConnection(String url, Properties info); static TSIService.Iface newSynchronizedClient(TSIService.Iface client); @Override boolean isWrapperFor(Class<?> arg... | @Test public void testGetServerProperties() throws IoTDBSQLException, TException { final String version = "v0.1"; @SuppressWarnings("serial") final List<String> supportedAggregationTime = new ArrayList<String>() { { add("max_time"); add("min_time"); } }; when(client.getProperties()) .thenReturn(new ServerProperties(ver... |
Utils { public static IoTDBConnectionParams parseUrl(String url, Properties info) throws IoTDBURLException { IoTDBConnectionParams params = new IoTDBConnectionParams(url); if (url.trim().equalsIgnoreCase(Config.IOTDB_URL_PREFIX)) { return params; } Pattern pattern = Pattern.compile("([^;]*):([^;]*)/"); Matcher matcher ... | @Test public void testParseURL() throws IoTDBURLException { String userName = "test"; String userPwd = "test"; String host = "localhost"; int port = 6667; Properties properties = new Properties(); properties.setProperty(Config.AUTH_USER, userName); properties.setProperty(Config.AUTH_PASSWORD, userPwd); IoTDBConnectionP... |
Utils { public static void verifySuccess(TS_Status status) throws IoTDBSQLException { if (status.getStatusCode() != TS_StatusCode.SUCCESS_STATUS) { throw new IoTDBSQLException(status.errorMessage); } } static IoTDBConnectionParams parseUrl(String url, Properties info); static void verifySuccess(TS_Status status); stat... | @Test public void testVerifySuccess() { try { Utils.verifySuccess(new TS_Status(TS_StatusCode.SUCCESS_STATUS)); } catch (Exception e) { fail(); } try { Utils.verifySuccess(new TS_Status(TS_StatusCode.ERROR_STATUS)); } catch (Exception e) { return; } fail(); } |
Utils { public static List<RowRecord> convertRowRecords(TSQueryDataSet tsQueryDataSet) { List<RowRecord> records = new ArrayList<>(); for (TSRowRecord ts : tsQueryDataSet.getRecords()) { RowRecord r = new RowRecord(ts.getTimestamp()); int l = ts.getValuesSize(); for (int i = 0; i < l; i++) { TSDataValue value = ts.getV... | @Test public void testConvertRowRecords() { final int DATA_TYPE_NUM = 6; Object[][] input = { {100L, "sensor1_boolean", TSDataType.BOOLEAN, false, "sensor1_int32", TSDataType.INT32, 100, "sensor1_int64", TSDataType.INT64, 9999999999L, "sensor1_float", TSDataType.FLOAT, 1.23f, "sensor1_double", TSDataType.DOUBLE, 100423... |
PriorityMergeReaderByTimestamp extends PriorityMergeReader implements
EngineReaderByTimeStamp { @Override public TsPrimitiveType getValueInTimestamp(long timestamp) throws IOException { if (hasCachedTimeValuePair) { if (cachedTimeValuePair.getTimestamp() == timestamp) { hasCachedTimeValuePair = false; return cached... | @Test public void test() throws IOException { FakedPrioritySeriesReaderByTimestamp reader1 = new FakedPrioritySeriesReaderByTimestamp(100, 200, 5, 11); FakedPrioritySeriesReaderByTimestamp reader2 = new FakedPrioritySeriesReaderByTimestamp(850, 200, 7, 19); FakedPrioritySeriesReaderByTimestamp reader3 = new FakedPriori... |
MTree implements Serializable { public void addTimeseriesPath(String timeseriesPath, String dataType, String encoding, String[] args) throws PathErrorException { String[] nodeNames = timeseriesPath.trim().split(separator); if (nodeNames.length <= 1 || !nodeNames[0].equals(root.getName())) { throw new PathErrorException... | @Test public void testAddLeftNodePath() { MTree root = new MTree("root"); try { root.addTimeseriesPath("root.laptop.d1.s1", "INT32", "RLE", new String[0]); } catch (PathErrorException e) { e.printStackTrace(); fail(e.getMessage()); } try { root.addTimeseriesPath("root.laptop.d1.s1.b", "INT32", "RLE", new String[0]); } ... |
MTree implements Serializable { public void setStorageGroup(String path) throws PathErrorException { String[] nodeNames = path.split(separator); MNode cur = root; if (nodeNames.length <= 1 || !nodeNames[0].equals(root.getName())) { throw new PathErrorException( String.format("The storage group can't be set to the %s no... | @Test public void testSetStorageGroup() { MTree root = new MTree("root"); try { root.setStorageGroup("root.laptop.d1"); assertEquals(true, root.isPathExist("root.laptop.d1")); assertEquals(true, root.checkFileNameByPath("root.laptop.d1")); assertEquals("root.laptop.d1", root.getFileNameByPath("root.laptop.d1")); assert... |
Processor { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Processor other = (Processor) obj; if (processorName == null) { if (other.processorName != null) { return false; } } else if (!processorName.... | @Test public void testEquals() { assertEquals(processor1, processor3); assertFalse(processor1.equals(processor2)); } |
GorillaDecoder extends Decoder { @Override public boolean hasNext(ByteBuffer buffer) throws IOException { if (buffer.remaining() > 0 || !isEnd) { return true; } return false; } GorillaDecoder(); @Override void reset(); @Override boolean hasNext(ByteBuffer buffer); } | @Test public void testNegativeNumber() throws IOException { Encoder encoder = new SinglePrecisionEncoder(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); float value = -7.101f; encoder.encode(value, baos); encoder.encode(value - 2, baos); encoder.encode(value - 4, baos); encoder.flush(baos); encoder.encode(... |
OFFileMetadata { public OFFileMetadata() { } OFFileMetadata(); OFFileMetadata(long lastFooterOffset, List<OFRowGroupListMetadata> rowGroupLists); static OFFileMetadata deserializeFrom(InputStream inputStream); static OFFileMetadata deserializeFrom(ByteBuffer buffer); void addRowGroupListMetaData(OFRowGroupListMetadata... | @Test public void testOFFileMetadata() throws Exception { OFFileMetadata ofFileMetadata = OverflowTestHelper.createOFFileMetadata(); serialize(ofFileMetadata); OFFileMetadata deOFFileMetadata = deSerialize(); OverflowUtils.isOFFileMetadataEqual(ofFileMetadata, deOFFileMetadata); } |
OFRowGroupListMetadata { private OFRowGroupListMetadata() { } private OFRowGroupListMetadata(); OFRowGroupListMetadata(String deviceId); static OFRowGroupListMetadata deserializeFrom(InputStream inputStream); static OFRowGroupListMetadata deserializeFrom(ByteBuffer buffer); void addSeriesListMetaData(OFSeriesListMeta... | @Test public void testOFRowGroupListMetadata() throws Exception { OFRowGroupListMetadata ofRowGroupListMetadata = OverflowTestHelper .createOFRowGroupListMetadata(); serialize(ofRowGroupListMetadata); OFRowGroupListMetadata deOfRowGroupListMetadata = deSerialized(); OverflowUtils.isOFRowGroupListMetadataEqual(ofRowGrou... |
OverflowProcessor extends Processor { private void recovery(File parentFile) throws IOException { String[] subFilePaths = clearFile(parentFile.list()); if (subFilePaths.length == 0) { workResource = new OverflowResource(parentPath, String.valueOf(dataPahtCount.getAndIncrement())); return; } else if (subFilePaths.length... | @Test public void testRecovery() throws OverflowProcessorException, IOException { processor = new OverflowProcessor(processorName, parameters, OverflowTestUtils.getFileSchema()); processor.close(); processor.switchWorkToMerge(); assertEquals(true, processor.isMerge()); processor.clear(); OverflowProcessor overflowProce... |
OverflowIO extends TsFileIOWriter { public void close() throws IOException { overflowReadWriter.close(); } OverflowIO(OverflowReadWriter overflowReadWriter); @Deprecated static InputStream readOneTimeSeriesChunk(ChunkMetaData chunkMetaData,
TsFileInput fileReader); @Deprecated ChunkMetaData flush(OverflowSeriesIm... | @Test public void testFileCutoff() throws IOException { File file = new File("testoverflowfile"); FileOutputStream fileOutputStream = new FileOutputStream(file); byte[] bytes = new byte[20]; fileOutputStream.write(bytes); fileOutputStream.close(); assertEquals(20, file.length()); OverflowIO overflowIO = new OverflowIO(... |
OverflowSupport { public void insert(TSRecord tsRecord) { for (DataPoint dataPoint : tsRecord.dataPointList) { memTable.write(tsRecord.deviceId, dataPoint.getMeasurementId(), dataPoint.getType(), tsRecord.time, dataPoint.getValue().toString()); } } OverflowSupport(); void insert(TSRecord tsRecord); @Deprecated void upd... | @Test public void testInsert() { support.clear(); assertEquals(true, support.isEmptyOfMemTable()); OverflowTestUtils.produceInsertData(support); assertEquals(false, support.isEmptyOfMemTable()); int num = 1; for (TimeValuePair pair : support .queryOverflowInsertInMemory(deviceId1, measurementId1, dataType1) .getSortedT... |
IoTDBThreadPoolFactory { public static ExecutorService newFixedThreadPool(int nthreads, String poolName) { return Executors.newFixedThreadPool(nthreads, new IoTThreadFactory(poolName)); } static ExecutorService newFixedThreadPool(int nthreads, String poolName); static ExecutorService newFixedThreadPool(int nthreads, S... | @Test public void testNewFixedThreadPool() throws InterruptedException, ExecutionException { String reason = "NewFixedThreadPool"; Thread.UncaughtExceptionHandler handler = new TestExceptionHandler(reason); int threadCount = 5; latch = new CountDownLatch(threadCount); ExecutorService exec = IoTDBThreadPoolFactory .newF... |
IoTDBThreadPoolFactory { public static ExecutorService newSingleThreadExecutor(String poolName) { return Executors.newSingleThreadExecutor(new IoTThreadFactory(poolName)); } static ExecutorService newFixedThreadPool(int nthreads, String poolName); static ExecutorService newFixedThreadPool(int nthreads, String poolName... | @Test public void testNewSingleThreadExecutor() throws InterruptedException { String reason = "NewSingleThreadExecutor"; Thread.UncaughtExceptionHandler handler = new TestExceptionHandler(reason); int threadCount = 1; latch = new CountDownLatch(threadCount); ExecutorService exec = IoTDBThreadPoolFactory.newSingleThread... |
IoTDBThreadPoolFactory { public static ExecutorService newCachedThreadPool(String poolName) { return Executors.newCachedThreadPool(new IoTThreadFactory(poolName)); } static ExecutorService newFixedThreadPool(int nthreads, String poolName); static ExecutorService newFixedThreadPool(int nthreads, String poolName,
... | @Test public void testNewCachedThreadPool() throws InterruptedException { String reason = "NewCachedThreadPool"; Thread.UncaughtExceptionHandler handler = new TestExceptionHandler(reason); int threadCount = 10; latch = new CountDownLatch(threadCount); ExecutorService exec = IoTDBThreadPoolFactory.newCachedThreadPool(PO... |
IoTDBThreadPoolFactory { public static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName) { return Executors.newSingleThreadScheduledExecutor(new IoTThreadFactory(poolName)); } static ExecutorService newFixedThreadPool(int nthreads, String poolName); static ExecutorService newFixedThreadPool(in... | @Test public void testNewSingleThreadScheduledExecutor() throws InterruptedException { String reason = "NewSingleThreadScheduledExecutor"; Thread.UncaughtExceptionHandler handler = new TestExceptionHandler(reason); int threadCount = 1; latch = new CountDownLatch(threadCount); ScheduledExecutorService exec = IoTDBThread... |
IoTDBThreadPoolFactory { public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName) { return Executors.newScheduledThreadPool(corePoolSize, new IoTThreadFactory(poolName)); } static ExecutorService newFixedThreadPool(int nthreads, String poolName); static ExecutorService newFixedT... | @Test public void testNewScheduledThreadPool() throws InterruptedException { String reason = "NewScheduledThreadPool"; Thread.UncaughtExceptionHandler handler = new TestExceptionHandler(reason); int threadCount = 10; latch = new CountDownLatch(threadCount); ScheduledExecutorService exec = IoTDBThreadPoolFactory .newSch... |
IoTDBThreadPoolFactory { public static ExecutorService createJDBCClientThreadPool(Args args, String poolName) { SynchronousQueue<Runnable> executorQueue = new SynchronousQueue<Runnable>(); return new ThreadPoolExecutor(args.minWorkerThreads, args.maxWorkerThreads, args.stopTimeoutVal, args.stopTimeoutUnit, executorQueu... | @Test public void testCreateJDBCClientThreadPool() throws InterruptedException { String reason = "CreateJDBCClientThreadPool"; TThreadPoolServer.Args args = new Args(null); args.maxWorkerThreads = 100; args.minWorkerThreads = 10; args.stopTimeoutVal = 10; args.stopTimeoutUnit = TimeUnit.SECONDS; Thread.UncaughtExceptio... |
OpenFileNumUtil { public int get(OpenFileNumStatistics statistics) { EnumMap<OpenFileNumStatistics, Integer> statisticsMap = getStatisticMap(); return statisticsMap.getOrDefault(statistics, UNKNOWN_STATISTICS_ERROR_CODE); } private OpenFileNumUtil(); static OpenFileNumUtil getInstance(); int get(OpenFileNumStatistics ... | @Test public void testDataOpenFileNumWhenCreateFile() { if (os.startsWith(MAC_OS_NAME) || os.startsWith(LINUX_OS_NAME)) { totalOpenFileNumBefore = openFileNumUtil .get(OpenFileNumUtil.OpenFileNumStatistics.DATA_OPEN_FILE_NUM); for (int i = 0; i < testFileNum; i++) { fileList.add(new File(currDir + testFileName + i)); }... |
LogicalGenerator { public long parseTimeFormat(String timestampStr) throws LogicalOperatorException { if (timestampStr == null || timestampStr.trim().equals("")) { throw new LogicalOperatorException("input timestamp cannot be empty"); } if (timestampStr.toLowerCase().equals(SQLConstant.NOW_FUNC)) { return System.curren... | @Test public void testParseTimeFormatNow() throws LogicalOperatorException { long now = generator.parseTimeFormat(SQLConstant.NOW_FUNC); for (int i = 0; i <= 12; i++) { ZoneOffset offset1, offset2; if (i < 10) { offset1 = ZoneOffset.of("+0" + i + ":00"); offset2 = ZoneOffset.of("-0" + i + ":00"); } else { offset1 = Zon... |
FileManager { public void backupNowLocalFileInfo(String backupFile) { BufferedWriter bufferedWriter = null; try { bufferedWriter = new BufferedWriter(new FileWriter(backupFile)); for (Entry<String, Set<String>> entry : nowLocalFiles.entrySet()) { for (String file : entry.getValue()) { bufferedWriter.write(file + "\n");... | @Test public void testBackupNowLocalFileInfo() throws IOException { Map<String, Set<String>> allFileList = new HashMap<>(); Random r = new Random(0); for (int i = 0; i < 3; i++) { for (int j = 0; j < 5; j++) { if (!allFileList.containsKey(String.valueOf(i))) { allFileList.put(String.valueOf(i), new HashSet<>()); } Stri... |
FileManager { public void getNowLocalFileList(String[] paths) { for (String path : paths) { if (!new File(path).exists()) { continue; } File[] listFiles = new File(path).listFiles(); for (File storageGroup : listFiles) { if (storageGroup.isDirectory() && !storageGroup.getName().equals("postback")) { if (!nowLocalFiles.... | @Test public void testGetNowLocalFileList() throws IOException { Map<String, Set<String>> allFileList = new HashMap<>(); Map<String, Set<String>> fileList = new HashMap<>(); manager.getNowLocalFileList(new String[]{SENDER_FILE_PATH_TEST}); fileList = manager.getNowLocalFiles(); assert (isEmpty(fileList)); Random r = ne... |
FileManager { public void getSendingFileList() { for (Entry<String, Set<String>> entry : nowLocalFiles.entrySet()) { for (String path : entry.getValue()) { if (!lastLocalFiles.contains(path)) { sendingFiles.get(entry.getKey()).add(path); } } } LOGGER.info("IoTDB sender : Sender has got list of sending files."); for (En... | @Test public void testGetSendingFileList() throws IOException { Map<String, Set<String>> allFileList = new HashMap<>(); Map<String, Set<String>> newFileList = new HashMap<>(); Map<String, Set<String>> sendingFileList = new HashMap<>(); Set<String> lastlocalList = new HashSet<>(); manager.setNowLocalFiles(new HashMap<>(... |
Pair { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Pair<?, ?> other = (Pair<?, ?>) obj; if (left == null) { if (other.left != null) { return false; } } else if (!left.equals(other.left)) { return f... | @Test public void testEqualsObject() { Pair<String, Integer> p1 = new Pair<String, Integer>("a", 123123); Pair<String, Integer> p2 = new Pair<String, Integer>("a", 123123); assertTrue(p1.equals(p2)); p1 = new Pair<String, Integer>("a", null); p2 = new Pair<String, Integer>("a", 123123); assertFalse(p1.equals(p2)); p1 =... |
IconHelper { public static int getTextBoxAlphaValue() { return textBoxAlphaValue; } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFolde... | @Test void testGetTextBoxAlphaValue() { IconHelper.setTextBoxAlphaValue(200); assertEquals(IconHelper.getTextBoxAlphaValue(), 200); } |
IconHelper { public static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType) { int scaledWidth = StreamDeck.ICON_SIZE; int scaledHeight = StreamDeck.ICON_SIZE; if (originalImage.getWidth() != originalImage.getHeight()) { float scalerWidth = ((float) StreamDeck.ICON_SIZE) / originalImage... | @Test void testCreateResizedCopy() { assertTrue(IconHelper.createResizedCopy(IconHelper.createColoredFrame(Color.GREEN).image, false) instanceof BufferedImage); } |
IconHelper { public static BufferedImage fillBackground(BufferedImage img, Color color) { BufferedImage nImg = new BufferedImage(img.getWidth(), img.getHeight(), img.getType()); Graphics2D g = nImg.createGraphics(); g.setColor(color); g.fillRect(0, 0, nImg.getWidth(), nImg.getHeight()); g.drawImage(img, 0, 0, null); g.... | @Test void testFillBackground() { assertTrue(IconHelper.fillBackground(IconHelper.createColoredFrame(Color.GREEN).image, Color.GREEN) instanceof BufferedImage); } |
IconHelper { public static BufferedImage flipHoriz(BufferedImage image) { BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR); Graphics2D gg = newImage.createGraphics(); gg.drawImage(image, image.getHeight(), 0, -image.getWidth(), image.getHeight(), null); gg.di... | @Test void testFlipHoriz() { assertTrue(IconHelper.flipHoriz(IconHelper.createColoredFrame(Color.GREEN).image) instanceof BufferedImage); } |
IconHelper { public static SDImage getImage(String string) { if (imageCache == null) imageCache = new HashMap<>(); return imageCache.get(string); } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollin... | @Test void testGetImage() { assertTrue(IconHelper.getImage(IconHelper.TEMP_BLACK_ICON) instanceof SDImage); } |
IconHelper { public static BufferedImage getImageFromResource(String fileName) { BufferedImage buff = null; try (InputStream inS = IconHelper.class.getResourceAsStream(fileName)) { if (inS != null) { logger.debug("Loading image as resource: " + fileName); buff = ImageIO.read(inS); } else { logger.error("Image does not ... | @Test void testGetImageFromResource() { assertTrue(IconHelper.getImageFromResource("/resources/icons/frame.png") instanceof BufferedImage); } |
IconHelper { public static IconPackage loadIconPackage(String pathToZip) throws IOException, URISyntaxException { if (packageCache.containsKey(pathToZip)) return packageCache.get(pathToZip); Path path = Paths.get(pathToZip); URI uri = new URI("jar", path.toUri().toString(), null); Map<String, String> env = new HashMap<... | @Test void testLoadIconPackage() { } |
IconHelper { public static SDImage loadImageSafe(String path) { return loadImageSafe(path, false, null); } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); sta... | @Test void testLoadImageSafeString() { assertTrue(IconHelper.loadImageSafe("/resources/icons/frame.png") instanceof SDImage); } |
IconHelper { public static SDImage loadImageFromResource(String path) { if (imageCache.containsKey(path)) return imageCache.get(path); BufferedImage img = getImageFromResource(path); if (img != null) { SDImage imgData = convertImage(img); cache(path, imgData); return imgData; } return null; } private IconHelper(); sta... | @Test void testLoadImageFromResource() { } |
IconHelper { public static SDImage loadImageFromResourceSafe(String path) { if (imageCache.containsKey(path)) return imageCache.get(path); BufferedImage img = getImageFromResource(path); if (img != null) { SDImage imgData = convertImage(img); cache(path, imgData); return imgData; } return IconHelper.getImage(TEMP_BLACK... | @Test void testLoadImageFromResourceSafe() { } |
IconHelper { public static SDImage[] loadImagesFromGif(String pathToGif) throws IOException { try { String[] imageatt = new String[] { "imageLeftPosition", "imageTopPosition", "imageWidth", "imageHeight" }; ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next(); ImageInputStream ciis = ImageIO.createIma... | @Test void testLoadImagesFromGif() { } |
IconHelper { public static void setTextBoxAlphaValue(int textBoxAlphaValue) { IconHelper.textBoxAlphaValue = textBoxAlphaValue; } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int r... | @Test void testSetTextBoxAlphaValue() { IconHelper.setTextBoxAlphaValue(200); assertEquals(IconHelper.getTextBoxAlphaValue(), 200); } |
IconHelper { public static BufferedImage rotate180(BufferedImage inputImage) { int width = inputImage.getWidth(); int height = inputImage.getHeight(); BufferedImage returnImage = new BufferedImage(height, width, inputImage.getType()); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int nX = height ... | @Test void testRotate180() { } |
IconHelper { public static int getRollingTextPadding() { return rollingTextPadding; } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFol... | @Test void testGetRollingTextPadding() { IconHelper.setRollingTextPadding(8); assertEquals(IconHelper.getRollingTextPadding(), 8); } |
IconHelper { public static void setRollingTextPadding(int rollingTextPadding) { IconHelper.rollingTextPadding = rollingTextPadding; } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(i... | @Test void testSetRollingTextPadding() { IconHelper.setRollingTextPadding(8); assertEquals(IconHelper.getRollingTextPadding(), 8); } |
IconHelper { public static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor) { String folderKey = FOLDER_IMAGE_PREFIX + String.format("#%02x%02x%02x", background.getRed(), background.getGreen(), background.getBlue()); if(imageCache.containsKey(folderKey)) return imageCache.get(folderKey)... | @Test void testCreateFolderImage() { assertTrue(IconHelper.createFolderImage(Color.GREEN, true, Color.GREEN.darker()) instanceof SDImage); } |
IconHelper { public static SDImage createColoredFrame(Color borderColor) { String frameKey = FRAME_IMAGE_PREFIX + String.format("#%02x%02x%02x", borderColor.getRed(), borderColor.getGreen(), borderColor.getBlue()); if(imageCache.containsKey(frameKey)) return imageCache.get(frameKey); BufferedImage img = new BufferedIma... | @Test void testCreateColoredFrame() { assertTrue(IconHelper.createColoredFrame(Color.GREEN) instanceof SDImage); } |
IconHelper { public static void applyAlpha(BufferedImage image, BufferedImage mask) { int width = image.getWidth(); int height = image.getHeight(); int[] imagePixels = image.getRGB(0, 0, width, height, null, 0, width); int[] maskPixels = mask.getRGB(0, 0, width, height, null, 0, width); for (int i = 0; i < imagePixels.... | @Test void testApplyAlpha() { IconHelper.applyAlpha(IconHelper.createColoredFrame(Color.GREEN).image, IconHelper.FRAME); assertTrue(true); } |
IconHelper { public static SDImage cacheImage(String path, BufferedImage img) { int[] pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData(); byte[] imgData = new byte[StreamDeck.ICON_SIZE * StreamDeck.ICON_SIZE * 3]; int imgDataCount = 0; for (int i = 0; i < StreamDeck.ICON_SIZE * StreamDeck.ICON_SIZE; i... | @Test void testCacheImage() { assertTrue(IconHelper.cacheImage("TEST-PATH", IconHelper.createFolderImage(Color.GREEN, true, Color.GREEN.darker()).image) instanceof SDImage); } |
IconHelper { public static SDImage applyImage(SDImage imgData, BufferedImage apply) { BufferedImage img = new BufferedImage(StreamDeck.ICON_SIZE, StreamDeck.ICON_SIZE, imgData. image. getType()); Graphics2D g2d = img.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_... | @Test void testApplyImage() { SDImage b1 = IconHelper.createFolderImage(Color.GREEN, true, Color.GREEN.darker()); BufferedImage b2 = IconHelper.createFolderImage(Color.GREEN, true, Color.GREEN.darker()).image; assertTrue(IconHelper.applyImage(b1, b2) instanceof SDImage); } |
IconHelper { public static BufferedImage applyFrame(BufferedImage img, Color frameColor) { if(img.getWidth() > StreamDeck.ICON_SIZE || img.getHeight() > StreamDeck.ICON_SIZE) img = createResizedCopy(img, true); BufferedImage nImg = new BufferedImage(img.getWidth(), img.getHeight(), img.getType()); Graphics2D g = nImg.c... | @Test void testApplyFrame() { assertTrue(IconHelper.applyFrame(IconHelper.createColoredFrame(Color.GREEN).image, Color.GREEN.darker()) instanceof BufferedImage); } |
BitStream { public void write(int n, long v) { if (n < 1 || n > 64) { throw new IllegalArgumentException( String.format("Unable to write %s bits to value %d", n, v)); } reserve(n); long v1 = v << 64 - n >>> shift; data[index] = data[index] | v1; shift += n; if (shift >= 64) { shift -= 64; index++; if (shift != 0) { lon... | @Test public void testNegativeBitEncoding() { thrown.expect(IllegalArgumentException.class); new BitStream( 2).write(-1, 10); }
@Test public void testZeroBitEncoding() { thrown.expect(IllegalArgumentException.class); new BitStream( 2).write(0, 10); }
@Test public void test9ByteEncoding() { thrown.expect(IllegalArgument... |
OffHeapChunkManagerTask implements Runnable { @VisibleForTesting void runAt(Instant instant) { LOG.info("Starting offHeapChunkManagerTask."); deleteStaleData(instant); detectReadOnlyChunks(instant); LOG.info("Finished offHeapChunkManagerTask."); } OffHeapChunkManagerTask(ChunkManager chunkManager); OffHeapChunkManager... | @Test public void testRunAtWithOverlappingOperations() { final int metricsDelaySecs = 0; offHeapChunkManagerTask = new OffHeapChunkManagerTask(chunkManager, metricsDelaySecs, 4 * 3600); assertTrue(chunkManager.getChunkMap().isEmpty()); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimeSecs)); assertTrue(chun... |
OffHeapChunkManagerTask implements Runnable { @VisibleForTesting int detectChunksPastCutOff(long offHeapCutoffSecs) { if (offHeapCutoffSecs <= 0) { throw new IllegalArgumentException("offHeapCutoffSecs can't be negative."); } LOG.info("offHeapCutOffSecs is {}", offHeapCutoffSecs); List<Map.Entry<Long, Chunk>> readOnlyC... | @Test(expected = ReadOnlyChunkInsertionException.class) public void testInsertionIntoOffHeapStore() { assertTrue(chunkManager.getChunkMap().isEmpty()); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimeSecs + 1, testValue)); assertEquals(1, chunkManager.getChunkMap().size())... |
OffHeapChunkManagerTask implements Runnable { int deleteStaleChunks(long staleDataCutoffSecs) { if (staleDataCutoffSecs <= 0) { throw new IllegalArgumentException("staleDateCutOffSecs can't be negative."); } LOG.info("stale data cut off secs is {}.", staleDataCutoffSecs); List<Map.Entry<Long, Chunk>> staleChunks = new ... | @Test public void testDeleteStaleChunks() { assertTrue(chunkManager.getChunkMap().isEmpty()); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 1)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs ... |
OffHeapChunkManagerTask implements Runnable { int deleteStaleData(Instant startInstant) { final long staleCutoffSecs = startInstant.minusSeconds(this.staleDataDelaySecs).getEpochSecond(); return deleteStaleChunks(staleCutoffSecs); } OffHeapChunkManagerTask(ChunkManager chunkManager); OffHeapChunkManagerTask(ChunkManag... | @Test public void testDeleteStaleData() { assertTrue(chunkManager.getChunkMap().isEmpty()); assertEquals(0, deleteStaleData(startTimeSecs)); assertEquals(0, deleteStaleData(startTimeSecs + 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 2)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 3)); chunkM... |
ChunkManager { public List<TimeSeries> query(Query query, long startTsSecs, long endTsSecs, QueryAggregation queryAggregation) { return queryAroundChunkBoundaries(query, startTsSecs, endTsSecs, queryAggregation); } ChunkManager(String chunkDataPrefix, int expectedTagStoreSize); ChunkManager(String chunkDataPrefix, int... | @Test public void testChunkWithRawMetricData() { long currentTs = Instant.now().getEpochSecond(); long previousHourTs = Instant.now().minusSeconds(3600).getEpochSecond(); final Query emptyQuery = new Query("test", Collections.emptyList()); assertTrue( chunkManager.query(emptyQuery, currentTs, previousHourTs, QueryAggre... |
ChunkManager { public void addMetric(final String metricString) { try { String[] metricParts = metricString.split(" "); if (metricParts.length > 1 && metricParts[0].equals("put")) { String metricName = metricParts[1].trim(); List<String> rawTags = Arrays.asList(metricParts).subList(4, metricParts.length); Metric metric... | @Test(expected = IllegalArgumentException.class) public void testInvalidMetricName() { chunkManager.addMetric("random"); }
@Test public void testMetricMissingTags() { String metric = "put a.b.c.d-e 1465530393 0"; chunkManager.addMetric(metric); }
@Test(expected = IllegalArgumentException.class) public void testMetricIn... |
ChunkManager { public void removeStaleChunks(List<Map.Entry<Long, Chunk>> staleChunks) { LOG.info("Stale chunks to be removed are: {}", staleChunks); if (chunkMap.isEmpty()) { LOG.warn("Possible bug or race condition. There are no chunks in chunk map."); } staleChunks.forEach(entry -> { try { if (chunkMap.containsKey(e... | @Test public void testRemoveStaleChunks() { final Map.Entry<Long, Chunk> fakeMapEntry = new Map.Entry<Long, Chunk>() { @Override public Long getKey() { return 100L; } @Override public Chunk getValue() { return null; } @Override public Chunk setValue(Chunk value) { return null; } }; assertTrue(chunkManager.getChunkMap()... |
InvertedIndexTagStore implements TagStore { @Override public Optional<Integer> get(Metric m) { if (metricIndex.containsKey(m.fullMetricName)) { return Optional.of(lookupMetricIndex(m.fullMetricName).getIntIterator().next()); } return Optional.empty(); } InvertedIndexTagStore(); InvertedIndexTagStore(int metricIdMapCap... | @Test public void testGet() { ids.add(store.getOrCreate(new Metric(METRIC1, Collections.singletonList("k1=v1")))); ids.add(store.getOrCreate(new Metric(METRIC2, Collections.singletonList("k1=v1")))); ids.add(store.getOrCreate(new Metric(METRIC1, Collections.singletonList("k1=v2")))); ids.add(store.getOrCreate(new Metri... |
InvertedIndexTagStore implements TagStore { @Override public int getOrCreate(final Metric m) { Optional<Integer> optionalMetric = get(m); return optionalMetric.isPresent() ? optionalMetric.get() : create(m); } InvertedIndexTagStore(); InvertedIndexTagStore(int metricIdMapCapacity, int initialIndexSize); InvertedIndex... | @Test(expected = PatternSyntaxException.class) public void testFailedRegExQuery() { ids.add(store.getOrCreate( new Metric(METRIC1, Collections.singletonList("host=ogg-01.ops.ankh.morpork.com")))); query(makeRegExQuery(METRIC1, HOST_TAG, "ogg-\\d(3.ops.ankh.morpork.com")); } |
TagMatcher { public static TagMatcher wildcardMatch(String key, String wildcardString) { return createWildCardTagMatcher(key, wildcardString, MatchType.WILDCARD); } TagMatcher(MatchType type, Tag tag); @Override boolean equals(Object o); @Override int hashCode(); static TagMatcher exactMatch(Tag tag); static TagMatcher... | @Test public void testTagMatcherCreation() { TagMatcher m2 = new TagMatcher(MatchType.WILDCARD, testTag); assertEquals(testTag, m2.tag); assertEquals(MatchType.WILDCARD, m2.type); TagMatcher m4 = TagMatcher.wildcardMatch(testKey, "*"); assertEquals(new Tag(testKey, "*"), m4.tag); assertEquals(MatchType.WILDCARD, m4.typ... |
Tag implements Comparable<Tag> { public static Tag parseTag(String rawTag) { int index = getDelimiterIndex(rawTag); String key = rawTag.substring(0, index); String value = rawTag.substring(index + 1); if (key.isEmpty() || value.isEmpty()) { throw new IllegalArgumentException("Invalid rawTag" + rawTag); } return new Tag... | @Test public void testTagParse() { testInvalidTagParse("a"); testInvalidTagParse("a="); testInvalidTagParse("=a"); testInvalidTagParse("="); Tag t = Tag.parseTag("k=v"); assertEquals("k", t.key); assertEquals("v", t.value); assertEquals("k=v", t.rawTag); Tag t1 = Tag.parseTag("k=v=1"); assertEquals("k", t1.key); assert... |
Query { public Query(final String metricName, final List<TagMatcher> tagMatchers) { if (metricName == null || metricName.isEmpty() || tagMatchers == null) { throw new IllegalArgumentException("metric name or tag matcher can't be null."); } final Map<String, List<TagMatcher>> tagNameMap = tagMatchers.stream() .map(t -> ... | @Test public void testQuery() { Query q = new Query(metric, Arrays.asList(tagMatcher1)); assertEquals(metric, q.metricName); assertEquals(1, q.tagMatchers.size()); assertEquals(tagMatcher1, q.tagMatchers.get(0)); Query q1 = Query.parse(metric); assertEquals(metric, q1.metricName); assertTrue(q1.tagMatchers.isEmpty()); ... |
Query { public static Query parse(String s) { List<String> splits = Arrays.asList(s.split(" ")); String metricName = splits.get(0); List<TagMatcher> matchers = new ArrayList<>(); for (String s2 : splits.subList(1, splits.size())) { Tag tag = Tag.parseTag(s2); if (tag.value.equals("*")) { matchers.add(TagMatcher.wildcar... | @Test(expected = IllegalArgumentException.class) public void testDuplicateTagKeysUsingParse() { Query.parse("metric k1=v1 k1=v2"); } |
OffHeapVarBitMetricStore implements MetricStore { @Override public List<Point> getSeries(long uuid) { final LongValue key = Values.newHeapInstance(LongValue.class); key.setValue(uuid); if (timeSeries.containsKey(key)) { ByteBuffer serializedValues = timeSeries.get(key); TimeSeriesIterator iterator = VarBitTimeSeries.de... | @Test public void testEmpty() { MetricStore store = new OffHeapVarBitMetricStore(1, testFileName); assertTrue(store.getSeries(1).isEmpty()); assertTrue(store.getSeries(2).isEmpty()); } |
OffHeapVarBitMetricStore implements MetricStore { public void addPoint(long uuid, ByteBuffer series) { LongValue key = Values.newHeapInstance(LongValue.class); key.setValue(uuid); timeSeries.put(key, series); } OffHeapVarBitMetricStore(long size, String chunkInfo); OffHeapVarBitMetricStore(long size, int valueSize, St... | @Test(expected = UnsupportedOperationException.class) public void testReadOnlyStore() { MetricStore store = new OffHeapVarBitMetricStore(1, testFileName); store.addPoint(1, 1, 1); } |
VarBitTimeSeries { public synchronized void append(long timestamp, double value) { if (timestamp < 0 || timestamp > MAX_UNIX_TIMESTAMP) { throw new IllegalArgumentException("Timestamp is not a valid unix timestamp: " + timestamp); } if (size == 0) { appendFirstPoint(timestamp, value); } else { appendNextPoint(timestamp... | @Test public void testMinTimestamp() { VarBitTimeSeries series = new VarBitTimeSeries(); thrown.expect(IllegalArgumentException.class); series.append(-1, 1); }
@Test public void testMaxTimestamp() { VarBitTimeSeries series = new VarBitTimeSeries(); thrown.expect(IllegalArgumentException.class); series.append(-1, 1); }
... |
VarBitTimeSeries { public synchronized TimeSeriesIterator read() { return new CachingVarBitTimeSeriesIterator(size, timestamps.read(), values.read()); } VarBitTimeSeries(); synchronized void append(long timestamp, double value); synchronized TimeSeriesIterator read(); Map<String, Double> getStats(); int getSerializedBy... | @Test public void testEmptyPoints() { VarBitTimeSeries series = new VarBitTimeSeries(); TimeSeriesIterator dr = series.read(); List<Point> points = dr.getPoints(); assertTrue(points.isEmpty()); } |
VarBitMetricStore implements MetricStore { @Override public List<Point> getSeries(long uuid) { mu.readLock().lock(); try { VarBitTimeSeries s = series.get(uuid); if (s == null) { return Collections.emptyList(); } return s.read().getPoints(); } finally { mu.readLock().unlock(); } } VarBitMetricStore(); VarBitMetricStor... | @Test public void testEmpty() { MetricStore store = new VarBitMetricStore(); assertTrue(store.getSeries(1).isEmpty()); assertTrue(store.getSeries(2).isEmpty()); } |
ChunkImpl implements Chunk { @Override public boolean containsDataInTimeRange(long startTs, long endTs) { return (chunkInfo.startTimeSecs <= startTs && chunkInfo.endTimeSecs >= startTs) || (chunkInfo.startTimeSecs <= endTs && chunkInfo.endTimeSecs >= endTs) || (chunkInfo.startTimeSecs >= startTs && chunkInfo.endTimeSec... | @Test public void testChunkContainsData() { assertTrue(chunk.containsDataInTimeRange(startTime - 1, endTime + 1)); assertTrue(chunk.containsDataInTimeRange(startTime + 1, endTime + 1)); assertTrue(chunk.containsDataInTimeRange(startTime + 1, endTime - 1)); assertTrue(chunk.containsDataInTimeRange(startTime - 1, endTime... |
ChunkImpl implements Chunk { @Override public List<TimeSeries> query(Query query) { return store.getSeries(query); } ChunkImpl(MetricAndTagStore store, ChunkInfo chunkInfo); @Override List<TimeSeries> query(Query query); @Override void addPoint(Metric metric, long ts, double value); @Override ChunkInfo info(); @Overrid... | @Test public void testChunkIngestion() { final String testMetricName1 = "testMetric1"; final String expectedMetricName1 = testMetricName1 + " dc=dc1 host=h1"; final String queryTagString = " host=h1 dc=dc1"; String inputTagString = "host=h1 dc=dc1"; parseAndAddOpenTSDBMetric(makeMetricString(testMetricName1, inputTagSt... |
OffHeapChunkManagerTask implements Runnable { @VisibleForTesting int detectReadOnlyChunks(Instant startInstant) { int secondsToSubtract = this.metricsDelay; final long offHeapCutoffSecs = startInstant.minusSeconds(secondsToSubtract).getEpochSecond(); return detectChunksPastCutOff(offHeapCutoffSecs); } OffHeapChunkManag... | @Test public void testDetectReadOnlyChunksWithDefaultValues() { assertTrue(chunkManager.getChunkMap().isEmpty()); assertEquals(0, detectReadOnlyChunks(startTimeSecs)); assertEquals(0, detectReadOnlyChunks(startTimeSecs + 1)); assertEquals(0, detectReadOnlyChunks(startTimeSecs + 3600 * 2)); assertEquals(0, detectReadOnl... |
EtcdServiceRegistry implements ServiceRegistry<EtcdRegistration> { @Override public void register(EtcdRegistration registration) { String etcdKey = registration.etcdKey(properties.getPrefix()); try { long leaseId = lease.getLeaseId(); PutOption putOption = PutOption.newBuilder() .withLeaseId(leaseId) .build(); etcdClie... | @Test public void testRegister() throws ExecutionException, InterruptedException, JsonProcessingException { Client client = Client.builder() .endpoints(container.clientEndpoint()) .build(); HeartbeatProperties heartbeatProperties = new HeartbeatProperties(); heartbeatProperties.setInterval(5); EtcdHeartbeatLease heartb... |
EtcdServiceRegistry implements ServiceRegistry<EtcdRegistration> { @Override public void deregister(EtcdRegistration registration) { String etcdKey = registration.etcdKey(properties.getPrefix()); try { etcdClient.getKVClient() .delete(fromString(etcdKey)) .get(); lease.revoke(); } catch (InterruptedException | Executio... | @Test public void testDeregister() throws ExecutionException, InterruptedException, JsonProcessingException { Client client = Client.builder() .endpoints(container.clientEndpoint()) .build(); HeartbeatProperties heartbeatProperties = new HeartbeatProperties(); heartbeatProperties.setInterval(5); EtcdHeartbeatLease hear... |
EtcdHeartbeatLease implements AutoCloseable { public Long getLeaseId() { initLease(); return leaseId; } EtcdHeartbeatLease(Client etcdClient, HeartbeatProperties properties); void initLease(); Long getLeaseId(); void revoke(); @Override void close(); } | @Test public void testEtcdLeaseIsAvailable() throws ExecutionException, InterruptedException { Client client = Client.builder() .endpoints(container.clientEndpoint()) .build(); HeartbeatProperties heartbeatProperties = new HeartbeatProperties(); heartbeatProperties.setInterval(5); EtcdHeartbeatLease heartbeatLease = ne... |
Counter extends Applet { private void getBalance(APDU apdu, byte[] buffer) { Util.setShort(buffer, (byte) 0, balance); apdu.setOutgoingAndSend((byte) 0, (byte) 2); } private Counter(); static void install(byte[] buffer, short offset, byte length); void process(APDU apdu); static final byte INS_GET_BALANCE; static fina... | @Test public void balanceTest() throws CardException { assertArrayEquals(new byte[]{0x00, 0x00}, getBalance().getData()); }
@Test public void creditOverflowTest() throws CardException { sendCredit(OVERFLOW_CREDIT, ISO7816.SW_WRONG_DATA, new byte[]{}); sendCredit(MAX_CREDIT, 0x9000, MAX_CREDIT); assertArrayEquals(MAX_CR... |
Counter extends Applet { private void credit(APDU apdu, byte[] buffer) { short credit; if (apdu.setIncomingAndReceive() != 2) ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); credit = Util.getShort(buffer, ISO7816.OFFSET_CDATA); if (((short) (credit + balance) > MAX_BALANCE) || (credit <= 0) || (credit > MAX_CREDIT)) ISO... | @Test public void creditTest() throws CardException { sendCredit(new byte[]{0x00, 0x05}, 0x9000, new byte[]{0x00, 0x05}); assertArrayEquals(new byte[]{0x00, 0x05}, getBalance().getData()); } |
Counter extends Applet { private void debit(APDU apdu, byte[] buffer) { short debit; if (apdu.setIncomingAndReceive() != 2) ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); debit = Util.getShort(buffer, ISO7816.OFFSET_CDATA); if ((debit > balance) || (debit <= 0) || (debit > MAX_DEBIT)) ISOException.throwIt(ISO7816.SW_WR... | @Test public void debitTest() throws CardException { sendCredit(new byte[]{0x00, 0x05}, 0x9000, new byte[]{0x00, 0x05}); assertArrayEquals(new byte[]{0x00, 0x05}, getBalance().getData()); sendDebit(new byte[]{0x00, 0x05}, 0x9000, new byte[]{0x00, 0x00}); assertArrayEquals(new byte[]{0x00, 0x00}, getBalance().getData())... |
PasswordEntry { static void delete(byte[] buf, short ofs, byte len) { PasswordEntry pe = search(buf, ofs, len); if (pe != null) { JCSystem.beginTransaction(); pe.remove(); pe.recycle(); JCSystem.commitTransaction(); } } private PasswordEntry(); static PasswordEntry getFirst(); byte getIdLength(); PasswordEntry getNext... | @Test public void deleteTest() throws NoSuchFieldException, IllegalAccessException { assertEquals("init length", 0, getLength()); addItem(ID_BASIC, USERNAME_BASIC, PASSWORD_BASIC); assertEquals("length after addition", 1, getLength()); deleteItem(ID_BASIC); assertEquals("length after deletion", 0, getLength()); } |
MapValueReader implements ValueReader<Map<String, Object>> { @Override public Object get(Map<String, Object> source, String memberName) { return source.get(memberName); } @Override Object get(Map<String, Object> source, String memberName); @SuppressWarnings("unchecked") @Override Member<Map<String, Object>> getMember(... | @Test(enabled = false) public void shouldMapBeanToMap() { Order order = new Order(); order.customer = new Customer(); order.customer.address = new Address(); order.customer.address.city = "Seattle"; order.customer.address.street = "1234 Main Street"; @SuppressWarnings("unchecked") Map<String, Map<String, Map<String, St... |
NumberConverter implements ConditionalConverter<Object, Number> { public Number convert(MappingContext<Object, Number> context) { Object source = context.getSource(); if (source == null) return null; Class<?> destinationType = Primitives.wrapperFor(context.getDestinationType()); if (source instanceof Number) return num... | @Test(expectedExceptions = MappingException.class, dataProvider = "numbersProvider") public void testStringToNumber(Number number) { Object[][] types = provideTypes(); for (int i = 0; i < types.length; i++) { Number result = (Number) convert(number.toString(), (Class<?>) types[i][0]); assertEquals(result.longValue(), n... |
ProxyFactory { static <T> T proxyFor(Class<T> type, InvocationHandler interceptor, Errors errors) throws ErrorsException { return proxyFor(type, interceptor, errors, Boolean.FALSE); } } | @Test public void shouldProxyTypesWithNonDefaultConstructor() { InvocationHandler interceptor = mock(InvocationHandler.class); A1 a1 = ProxyFactory.proxyFor(A1.class, interceptor, null); assertNotNull(a1); A2 a2 = ProxyFactory.proxyFor(A2.class, interceptor, null); assertNotNull(a2); } |
BooleanConverter implements ConditionalConverter<Object, Boolean> { public Boolean convert(MappingContext<Object, Boolean> context) { Object source = context.getSource(); if (source == null) return null; String stringValue = source.toString().toLowerCase(); if (stringValue.length() == 0) return null; for (int i = 0; i ... | @Test(expectedExceptions = MappingException.class) public void shouldThrowOnInvalidString() { convert("abc"); } |
MapObjs { synchronized static Object[] toArray(Object now) { if (now instanceof MapObjs) { return ((MapObjs) now).all.toArray(); } final Fn.Presenter p = getOnlyPresenter(); if (p == null) { return new Object[0]; } return new Object[] { p, now }; } private MapObjs(Fn.Ref id1, Object js); private MapObjs(Fn.Ref id1, O... | @Test public void testToArrayNoPresenterYet() { Object[] arr = MapObjs.toArray(null); assertEquals(arr.length, 0, "Empty array: " + Arrays.toString(arr)); } |
JSON { public static Character charValue(Object val) { if (val instanceof Number) { return Character.toChars(numberValue(val).intValue())[0]; } if (val instanceof Boolean) { return (Boolean)val ? (char)1 : (char)0; } if (val instanceof String) { String s = (String)val; return s.isEmpty() ? (char)0 : s.charAt(0); } retu... | @Test public void booleanToChar() { assertEquals(JSON.charValue(false), Character.valueOf((char)0)); assertEquals(JSON.charValue(true), Character.valueOf((char)1)); }
@Test public void stringToChar() { assertEquals(JSON.charValue("Ahoj"), Character.valueOf('A')); }
@Test public void numberToChar() { assertEquals(JSON.c... |
JSON { public static Boolean boolValue(Object val) { if (val instanceof String) { return Boolean.parseBoolean((String)val); } if (val instanceof Number) { return numberValue(val).doubleValue() != 0.0; } return Boolean.TRUE.equals(val); } private JSON(); static Transfer findTransfer(BrwsrCtx c); static WSTransfer<?> fi... | @Test public void stringToBoolean() { assertEquals(JSON.boolValue("false"), Boolean.FALSE); assertEquals(JSON.boolValue("True"), Boolean.TRUE); }
@Test public void numberToBoolean() { assertEquals(JSON.boolValue(0), Boolean.FALSE); assertEquals(JSON.boolValue(1), Boolean.TRUE); } |
SimpleList implements List<E> { @Override public ListIterator<E> listIterator() { return new LI(0, size); } SimpleList(); private SimpleList(Object[] data); static List<T> asList(T... arr); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<E> iterator(); @Overr... | @Test(dataProvider = "lists") public void testListIterator(List<String> list) { list.add("Hi"); list.add("Ahoj"); list.add("Ciao"); Collections.sort(list); ListIterator<String> it = list.listIterator(3); assertEquals(it.previous(), "Hi"); assertEquals(it.previous(), "Ciao"); it.remove(); assertEquals(it.next(), "Hi"); ... |
SimpleList implements List<E> { @Override public boolean retainAll(Collection<?> c) { return retainImpl(this, c); } SimpleList(); private SimpleList(Object[] data); static List<T> asList(T... arr); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<E> iterator()... | @Test(dataProvider = "lists") public void retainAll(List<Number> list) { list.add(3); list.add(3.3f); list.add(4L); list.add(4.4); list.retainAll(Collections.singleton(4L)); assertEquals(list.size(), 1); assertEquals(list.get(0), 4L); } |
Proto { public void applyBindings() { initBindings(null).applyBindings(null); } Proto(Object obj, Type type, BrwsrCtx context); BrwsrCtx getContext(); void acquireLock(); void acquireLock(String propName); void accessProperty(String propName); void verifyUnlocked(); void releaseLock(); void valueHasMutated(final String... | @Test public void registerFunctionsIncrementally() { BrwsrCtx ctx = Contexts.newBuilder().register(Technology.class, this, 100).build(); MyType type = new MyType(); MyObj obj = new MyObj(type, ctx); type.registerFunction("fifth", 5); obj.proto.applyBindings(); assertEquals(6, functions.length); assertNull(functions[0])... |
Models { public static boolean isModel(Class<?> clazz) { return JSON.isModel(clazz); } private Models(); static boolean isModel(Class<?> clazz); static Model bind(Model model, BrwsrCtx context); static M parse(BrwsrCtx c, Class<M> model, InputStream is); static void parse(
BrwsrCtx c, Class<M> model,
... | @Test public void peopleAreModel() { assertTrue(Models.isModel(People.class), "People are generated class"); }
@Test public void personIsModel() { assertTrue(Models.isModel(Person.class), "Person is generated class"); }
@Test public void implClassIsNotModel() { assertFalse(Models.isModel(PersonImpl.class), "Impl is not... |
CoordImpl extends Position.Coordinates { @Override public double getLatitude() { return provider.latitude(data); } CoordImpl(Coords data, GLProvider<Coords, ?> p); @Override double getLatitude(); @Override double getLongitude(); @Override double getAccuracy(); @Override Double getAltitude(); @Override Double getAltitud... | @Test public void testGetLatitude() { CoordImpl<Double> c = new CoordImpl<Double>(50.5, this); assertEquals(c.getLatitude(), 50.5, 0.1, "Latitude returned as provided"); } |
Scripts { public static Scripts newPresenter() { return new Scripts(); } private Scripts(); @Deprecated static Presenter createPresenter(); @Deprecated static Presenter createPresenter(Executor exc); static Scripts newPresenter(); Scripts executor(Executor exc); Scripts engine(ScriptEngine engine); Scripts sanitize(bo... | @Test public void isSanitizationOnByDefault() throws Exception { assertSanitized(Scripts.newPresenter()); } |
FXBrwsr extends Application { static String findCalleeClassName() { StackTraceElement[] frames = new Exception().getStackTrace(); for (StackTraceElement e : frames) { String cn = e.getClassName(); if (cn.startsWith("org.netbeans.html.")) { continue; } if (cn.startsWith("net.java.html.")) { continue; } if (cn.startsWith... | @Test public void testFindCalleeClassName() throws InterruptedException { String callee = invokeMain(); assertEquals(callee, SampleApp.class.getName(), "Callee is found correctly"); } |
FXBrowsers { public static void runInBrowser(WebView webView, Runnable code) { Object ud = webView.getUserData(); if (ud instanceof Fn.Ref<?>) { ud = ((Fn.Ref<?>)ud).presenter(); } if (!(ud instanceof InitializeWebView)) { throw new IllegalArgumentException(); } ((InitializeWebView)ud).runInContext(code); } private FX... | @Test public void brwsrCtxExecute() throws Throwable { assertFalse(inJS(), "We aren't in JS now"); final CountDownLatch init = new CountDownLatch(1); final BrwsrCtx[] ctx = { null }; FXBrowsers.runInBrowser(App.getV1(), new Runnable() { @Override public void run() { assertTrue(inJS(), "We are in JS context now"); ctx[0... |
JsCallback { final String parse(String body) { StringBuilder sb = new StringBuilder(); int pos = 0; for (;;) { int next = body.indexOf(".@", pos); if (next == -1) { sb.append(body.substring(pos)); body = sb.toString(); break; } int ident = next; while (ident > 0) { if (!Character.isJavaIdentifierPart(body.charAt(--iden... | @Test public void missingTypeSpecification() { String body = "console[attr] = function(msg) {\n" + " @org.netbeans.html.charts.Main::log(msg);\n" + "};\n"; JsCallback instance = new JsCallbackImpl(); try { String result = instance.parse(body); fail("The parsing should fail!"); } catch (IllegalStateException ex) { } } |
FallbackIdentity extends WeakReference<Fn.Presenter> implements Fn.Ref { @Override public int hashCode() { return hashCode; } FallbackIdentity(Fn.Presenter p); @Override Fn.Ref reference(); @Override Fn.Presenter presenter(); @Override int hashCode(); @Override boolean equals(Object obj); } | @Test public void testIdAndWeak() { Fn.Presenter p = new Fn.Presenter() { @Override public Fn defineFn(String arg0, String... arg1) { return null; } @Override public void displayPage(URL arg0, Runnable arg1) { } @Override public void loadScript(Reader arg0) throws Exception { } }; Fn.Ref<?> id1 = Fn.ref(p); Fn.Ref<?> i... |
BrowserBuilder { static URL findLocalizedResourceURL(String resource, Locale l, IOException[] mal, Class<?> relativeTo) { URL url = null; if (l != null) { url = findResourceURL(resource, "_" + l.getLanguage() + "_" + l.getCountry(), mal, relativeTo); if (url != null) { return url; } url = findResourceURL(resource, "_" ... | @Test public void findsZhCN() throws IOException { File zh = new File(dir, "index_zh.html"); zh.createNewFile(); File zhCN = new File(dir, "index_zh_CN.html"); zhCN.createNewFile(); IOException[] mal = { null }; URL url = BrowserBuilder.findLocalizedResourceURL("index.html", Locale.SIMPLIFIED_CHINESE, mal, BrowserBuild... |
JSONList extends SimpleList<T> { @Override public String toString() { Iterator<T> it = iterator(); if (!it.hasNext()) { return "[]"; } String sep = ""; StringBuilder sb = new StringBuilder(); sb.append('['); while (it.hasNext()) { T t = it.next(); sb.append(sep); sb.append(JSON.toJSON(t)); sep = ","; } sb.append(']'); ... | @Test public void testConvertorOnAnArray() { BrwsrCtx c = Contexts.newBuilder().register(Technology.class, this, 1).build(); Person p = Models.bind(new Person(), c); p.setFirstName("1"); p.setLastName("2"); p.setSex(Sex.MALE); People people = Models.bind(new People(p), c).applyBindings(); assertEquals(people.getInfo().... |
JSONList extends SimpleList<T> { @Override public boolean add(T e) { prepareChange(); boolean ret = super.add(e); notifyChange(); return ret; } JSONList(Proto proto, String name, int changeIndex, String... deps); void init(Object values); static void init(Collection<T> to, Object values); @Override boolean add(T e); @O... | @Test public void testNicknames() { BrwsrCtx c = Contexts.newBuilder().register(Technology.class, this, 1).build(); People people = Models.bind(new People(), c).applyBindings(); people.getNicknames().add("One"); people.getNicknames().add("Two"); PropertyBinding pb = bindings.get("nicknames"); assertNotNull(pb, "Binding... |
JSON { public static String stringValue(Object val) { if (val instanceof Boolean) { return ((Boolean)val ? "true" : "false"); } if (isNumeric(val)) { return Long.toString(((Number)val).longValue()); } if (val instanceof Float) { return Float.toString((Float)val); } if (val instanceof Double) { return Double.toString((D... | @Test public void longToStringValue() { assertEquals(JSON.stringValue(Long.valueOf(1)), "1"); } |
JSON { public static Number numberValue(Object val) { if (val instanceof String) { try { return Double.valueOf((String)val); } catch (NumberFormatException ex) { return Double.NaN; } } if (val instanceof Boolean) { return (Boolean)val ? 1 : 0; } return (Number)val; } private JSON(); static Transfer findTransfer(BrwsrC... | @Test public void booleanIsSortOfNumber() { assertEquals(JSON.numberValue(Boolean.TRUE), Integer.valueOf(1)); assertEquals(JSON.numberValue(Boolean.FALSE), Integer.valueOf(0)); } |
TableXMLFormatter { public String getSchemaXml() { String result= "<schema>"; Map<String, TableSchema> tableSchemas = schemaExtractor.getTablesFromQuery(query); for (TableSchema tableSchema : tableSchemas.values()) { result += getTableSchemaXml(tableSchema); } result += "</schema>"; return result; } TableXMLFormatter(I... | @Test public void queryTest() { tableXMLFormatter = new TableXMLFormatter(schemaExtractor, QUERY); String expected = "<schema>" + "<table name=\"users\">" + "<column name=\"username\" type=\"varchar\" notnull=\"true\"/>" + "<column name=\"email\" type=\"varchar\" notnull=\"true\"/>" + "</table>" + "</schema>"; String a... |
QueryStripper { public String getStrippedSql() { String secureQuery = new SqlSecurer(sql).getSecureSql(); Select stmt = null; try { stmt = (Select) CCJSqlParserUtil.parse(secureQuery); } catch (JSQLParserException e) { throw new RuntimeException(e); } stmt.getSelectBody().accept(new QueryStripperVisitor()); return stmt... | @Test public void stripDouble() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = 50.1234").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = 0"); }
@Test public void stripDate() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = '1999-03-04'").getStr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.