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<?> arg0); @Override T unwrap(Class<T> arg0); @Override void abort(Executor arg0); @Override void clearWarnings(); @Override void close(); @Override void commit(); @Override Array createArrayOf(String arg0, Object[] arg1); @Override Blob createBlob(); @Override Clob createClob(); @Override NClob createNClob(); @Override SQLXML createSQLXML(); @Override Statement createStatement(); @Override Statement createStatement(int resultSetType, int resultSetConcurrency); @Override Statement createStatement(int arg0, int arg1, int arg2); @Override Struct createStruct(String arg0, Object[] arg1); @Override boolean getAutoCommit(); @Override void setAutoCommit(boolean arg0); @Override String getCatalog(); @Override void setCatalog(String arg0); @Override Properties getClientInfo(); @Override void setClientInfo(Properties arg0); @Override String getClientInfo(String arg0); @Override int getHoldability(); @Override void setHoldability(int arg0); @Override DatabaseMetaData getMetaData(); @Override int getNetworkTimeout(); @Override String getSchema(); @Override void setSchema(String arg0); @Override int getTransactionIsolation(); @Override void setTransactionIsolation(int arg0); @Override Map<String, Class<?>> getTypeMap(); @Override void setTypeMap(Map<String, Class<?>> arg0); @Override SQLWarning getWarnings(); @Override boolean isClosed(); @Override boolean isReadOnly(); @Override void setReadOnly(boolean arg0); @Override boolean isValid(int arg0); @Override String nativeSQL(String arg0); @Override CallableStatement prepareCall(String arg0); @Override CallableStatement prepareCall(String arg0, int arg1, int arg2); @Override CallableStatement prepareCall(String arg0, int arg1, int arg2, int arg3); @Override PreparedStatement prepareStatement(String sql); @Override PreparedStatement prepareStatement(String sql, int autoGeneratedKeys); @Override PreparedStatement prepareStatement(String sql, int[] columnIndexes); @Override PreparedStatement prepareStatement(String sql, String[] columnNames); @Override PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency); @Override PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability); @Override void releaseSavepoint(Savepoint arg0); @Override void rollback(); @Override void rollback(Savepoint arg0); @Override void setClientInfo(String arg0, String arg1); @Override void setNetworkTimeout(Executor arg0, int arg1); @Override Savepoint setSavepoint(); @Override Savepoint setSavepoint(String arg0); boolean reconnect(); String getTimeZone(); void setTimeZone(String zoneId); ServerProperties getServerProperties(); TSProtocolVersion getProtocol(); void setProtocol(TSProtocolVersion protocol); public TSIService.Iface client; public TS_SessionHandle sessionHandle; } | @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(version, supportedAggregationTime)); connection.client = client; assertEquals(connection.getServerProperties().getVersion(), version); for (int i = 0; i < supportedAggregationTime.size(); i++) { assertEquals(connection.getServerProperties().getSupportedTimeAggregationOperations().get(i), supportedAggregationTime.get(i)); } } |
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 = pattern.matcher(url.substring(Config.IOTDB_URL_PREFIX.length())); boolean isUrlLegal = false; while (matcher.find()) { params.setHost(matcher.group(1)); params.setPort(Integer.parseInt((matcher.group(2)))); isUrlLegal = true; } if (!isUrlLegal) { throw new IoTDBURLException("Error url format, url should be jdbc:iotdb: } if (info.containsKey(Config.AUTH_USER)) { params.setUsername(info.getProperty(Config.AUTH_USER)); } if (info.containsKey(Config.AUTH_PASSWORD)) { params.setPassword(info.getProperty(Config.AUTH_PASSWORD)); } return params; } static IoTDBConnectionParams parseUrl(String url, Properties info); static void verifySuccess(TS_Status status); static List<RowRecord> convertRowRecords(TSQueryDataSet tsQueryDataSet); } | @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); IoTDBConnectionParams params = Utils .parseUrl(String.format(Config.IOTDB_URL_PREFIX + "%s:%s/", host, port), properties); assertEquals(params.getHost(), host); assertEquals(params.getPort(), port); assertEquals(params.getUsername(), userName); assertEquals(params.getPassword(), userPwd); } |
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); static List<RowRecord> convertRowRecords(TSQueryDataSet tsQueryDataSet); } | @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.getValues().get(i); if (value.is_empty) { Field field = new Field(null); field.setNull(); r.getFields().add(field); } else { TSDataType dataType = TSDataType.valueOf(value.getType()); Field field = new Field(dataType); switch (dataType) { case BOOLEAN: field.setBoolV(value.isBool_val()); break; case INT32: field.setIntV(value.getInt_val()); break; case INT64: field.setLongV(value.getLong_val()); break; case FLOAT: field.setFloatV((float) value.getFloat_val()); break; case DOUBLE: field.setDoubleV(value.getDouble_val()); break; case TEXT: field.setBinaryV(new Binary(value.getBinary_val())); ; break; default: throw new UnSupportedDataTypeException( String.format("data type %s is not supported when convert data at client", dataType)); } r.getFields().add(field); } } records.add(r); } return records; } static IoTDBConnectionParams parseUrl(String url, Properties info); static void verifySuccess(TS_Status status); static List<RowRecord> convertRowRecords(TSQueryDataSet tsQueryDataSet); } | @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, 1004234.435d, "sensor1_text", TSDataType.TEXT, "iotdb-jdbc",}, {200L, "sensor2_boolean", TSDataType.BOOLEAN, true, "sensor2_int32", TSDataType.INT32, null, "sensor2_int64", TSDataType.INT64, -9999999999L, "sensor2_float", TSDataType.FLOAT, null, "sensor2_double", TSDataType.DOUBLE, -1004234.435d, "sensor2_text", TSDataType.TEXT, null,}, {300L, "sensor3_boolean", TSDataType.BOOLEAN, null, "sensor3_int32", TSDataType.INT32, -100, "sensor3_int64", TSDataType.INT64, null, "sensor3_float", TSDataType.FLOAT, -1.23f, "sensor3_double", TSDataType.DOUBLE, null, "sensor3_text", TSDataType.TEXT, "jdbc-iotdb",},}; TSQueryDataSet tsQueryDataSet = new TSQueryDataSet(new ArrayList<>()); for (Object[] item : input) { TSRowRecord record = new TSRowRecord(); record.setTimestamp((long) item[0]); List<String> keys = new ArrayList<>(); List<TSDataValue> values = new ArrayList<>(); for (int i = 0; i < DATA_TYPE_NUM; i++) { keys.add((String) item[3 * i + 1]); TSDataValue value = new TSDataValue(false); if (item[3 * i + 3] == null) { value.setIs_empty(true); } else { if (i == 0) { value.setBool_val((boolean) item[3 * i + 3]); value.setType(((TSDataType) item[3 * i + 2]).toString()); } else if (i == 1) { value.setInt_val((int) item[3 * i + 3]); value.setType(((TSDataType) item[3 * i + 2]).toString()); } else if (i == 2) { value.setLong_val((long) item[3 * i + 3]); value.setType(((TSDataType) item[3 * i + 2]).toString()); } else if (i == 3) { value.setFloat_val((float) item[3 * i + 3]); value.setType(((TSDataType) item[3 * i + 2]).toString()); } else if (i == 4) { value.setDouble_val((double) item[3 * i + 3]); value.setType(((TSDataType) item[3 * i + 2]).toString()); } else { value.setBinary_val(ByteBuffer.wrap(((String) item[3 * i + 3]).getBytes())); value.setType(((TSDataType) item[3 * i + 2]).toString()); } } values.add(value); } record.setValues(values); tsQueryDataSet.getRecords().add(record); } List<RowRecord> convertlist = Utils.convertRowRecords(tsQueryDataSet); int index = 0; for (RowRecord r : convertlist) { assertEquals(input[index][0], r.getTimestamp()); List<Field> fields = r.getFields(); int j = 0; for (Field f : fields) { if (j == 0) { if (input[index][3 * j + 3] == null) { assertTrue(f.isNull()); } else { assertEquals(input[index][3 * j + 3], f.getBoolV()); } } else if (j == 1) { if (input[index][3 * j + 3] == null) { assertTrue(f.isNull()); } else { assertEquals(input[index][3 * j + 3], f.getIntV()); } } else if (j == 2) { if (input[index][3 * j + 3] == null) { assertTrue(f.isNull()); } else { assertEquals(input[index][3 * j + 3], f.getLongV()); } } else if (j == 3) { if (input[index][3 * j + 3] == null) { assertTrue(f.isNull()); } else { assertEquals(input[index][3 * j + 3], f.getFloatV()); } } else if (j == 4) { if (input[index][3 * j + 3] == null) { assertTrue(f.isNull()); } else { assertEquals(input[index][3 * j + 3], f.getDoubleV()); } } else { if (input[index][3 * j + 3] == null) { assertTrue(f.isNull()); } else { assertEquals(input[index][3 * j + 3], f.getStringValue()); } } j++; } index++; } } |
PriorityMergeReaderByTimestamp extends PriorityMergeReader implements
EngineReaderByTimeStamp { @Override public TsPrimitiveType getValueInTimestamp(long timestamp) throws IOException { if (hasCachedTimeValuePair) { if (cachedTimeValuePair.getTimestamp() == timestamp) { hasCachedTimeValuePair = false; return cachedTimeValuePair.getValue(); } else if (cachedTimeValuePair.getTimestamp() > timestamp) { return null; } } while (hasNext()) { cachedTimeValuePair = next(); if (cachedTimeValuePair.getTimestamp() == timestamp) { hasCachedTimeValuePair = false; return cachedTimeValuePair.getValue(); } else if (cachedTimeValuePair.getTimestamp() > timestamp) { hasCachedTimeValuePair = true; return null; } } return null; } @Override TsPrimitiveType getValueInTimestamp(long timestamp); } | @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 FakedPrioritySeriesReaderByTimestamp(1080, 200, 13, 31); PriorityMergeReaderByTimestamp priorityReader = new PriorityMergeReaderByTimestamp(); priorityReader.addReaderWithPriority(reader1, 1); priorityReader.addReaderWithPriority(reader2, 2); priorityReader.addReaderWithPriority(reader3, 3); int cnt = 0; Random random = new Random(); for (long time = 4; time < 1080 + 200 * 13 + 600; ) { TsPrimitiveType value = priorityReader.getValueInTimestamp(time); if (time < 100) { Assert.assertNull(value); } else if (time < 850) { if ((time - 100) % 5 == 0) { Assert.assertEquals(time % 11, value.getLong()); } } else if (time < 1080) { if (time >= 850 && (time - 850) % 7 == 0) { Assert.assertEquals(time % 19, value.getLong()); } else if (time < 1100 && (time - 100) % 5 == 0) { Assert.assertEquals(time % 11, value.getLong()); } else { Assert.assertNull(value); } } else if (time < 1080 + 200 * 13) { if (time >= 1080 && (time - 1080) % 13 == 0) { Assert.assertEquals(time % 31, value.getLong()); } else if (time < 850 + 200 * 7 && (time - 850) % 7 == 0) { Assert.assertEquals(time % 19, value.getLong()); } else if (time < 1100 && (time - 100) % 5 == 0) { Assert.assertEquals(time % 11, value.getLong()); } else { Assert.assertNull(value); } } else { Assert.assertNull(value); } time += random.nextInt(50) + 1; } while (priorityReader.hasNext()) { TimeValuePair timeValuePair = priorityReader.next(); long time = timeValuePair.getTimestamp(); long value = timeValuePair.getValue().getLong(); if (time < 850) { Assert.assertEquals(time % 11, value); } else if (time < 1080) { Assert.assertEquals(time % 19, value); } else { Assert.assertEquals(time % 31, value); } cnt++; } } |
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(String.format("Timeseries %s is not right.", timeseriesPath)); } int i = 1; MNode cur = root; String levelPath = null; while (i < nodeNames.length) { String nodeName = nodeNames[i]; if (i == nodeNames.length - 1) { cur.setDataFileName(levelPath); break; } if (cur.isStorageLevel()) { levelPath = cur.getDataFileName(); } if (!cur.hasChild(nodeName)) { if (cur.isLeaf()) { throw new PathErrorException( String.format("The Node [%s] is left node, the timeseries %s can't be created", cur.getName(), timeseriesPath)); } cur.addChild(nodeName, new MNode(nodeName, cur, false)); } cur.setDataFileName(levelPath); cur = cur.getChild(nodeName); if (levelPath == null) { levelPath = cur.getDataFileName(); } i++; } TSDataType dt = TSDataType.valueOf(dataType); TSEncoding ed = TSEncoding.valueOf(encoding); MNode leaf = new MNode(nodeNames[nodeNames.length - 1], cur, dt, ed); if (args.length > 0) { for (int k = 0; k < args.length; k++) { String[] arg = args[k].split("="); leaf.getSchema().putKeyValueToArgs(arg[0], arg[1]); } } levelPath = cur.getDataFileName(); leaf.setDataFileName(levelPath); if (cur.isLeaf()) { throw new PathErrorException( String.format("The Node [%s] is left node, the timeseries %s can't be created", cur.getName(), timeseriesPath)); } cur.addChild(nodeNames[nodeNames.length - 1], leaf); } MTree(String rootName); MTree(MNode root); void addTimeseriesPath(String timeseriesPath, String dataType, String encoding,
String[] args); boolean isPathExist(String path); boolean isPathExist(MNode node, String path); void setStorageGroup(String path); String deletePath(String path); boolean hasPath(String path); ColumnSchema getSchemaForOnePath(String path); ColumnSchema getSchemaForOnePath(MNode node, String path); ColumnSchema getSchemaForOnePathWithCheck(MNode node, String path); ColumnSchema getSchemaForOnePathWithCheck(String path); MNode getNodeByPath(String path); MNode getNodeByPathWithFileLevelCheck(String path); String getDeviceTypeByPath(String path); String getFileNameByPath(String path); String getFileNameByPath(MNode node, String path); String getFileNameByPathWithCheck(MNode node, String path); boolean checkFileNameByPath(String path); HashMap<String, ArrayList<String>> getAllPath(String pathReg); List<List<String>> getShowTimeseriesPath(String pathReg); List<String> getLeafNodePathInNextLevel(String path); ArrayList<String> getAllPathInList(String path); int getFileCountForOneType(String path); ArrayList<String> getAllType(); HashSet<String> getAllStorageGroup(); ArrayList<String> getDeviceForOneType(String type); ArrayList<ColumnSchema> getSchemaForOneType(String path); ArrayList<ColumnSchema> getSchemaForOneFileNode(String path); Map<String, ColumnSchema> getSchemaMapForOneFileNode(String path); Map<String, Integer> getNumSchemaMapForOneFileNode(String path); String toString(); MNode getRoot(); } | @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]); } catch (PathErrorException e) { Assert.assertEquals( String.format("The Node [%s] is left node, the timeseries %s can't be created", "s1", "root.laptop.d1.s1.b"), e.getMessage()); } } |
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 node", path)); } int i = 1; while (i < nodeNames.length - 1) { MNode temp = cur.getChild(nodeNames[i]); if (temp == null) { cur.addChild(nodeNames[i], new MNode(nodeNames[i], cur, false)); } else if (temp.isStorageLevel()) { throw new PathErrorException( String.format("The prefix of %s has been set to the storage group.", path)); } cur = cur.getChild(nodeNames[i]); i++; } MNode temp = cur.getChild(nodeNames[i]); if (temp == null) { cur.addChild(nodeNames[i], new MNode(nodeNames[i], cur, false)); } else { throw new PathErrorException( String.format("The seriesPath of %s already exist, it can't be set to the storage group", path)); } cur = cur.getChild(nodeNames[i]); cur.setStorageLevel(true); setDataFileName(path, cur); } MTree(String rootName); MTree(MNode root); void addTimeseriesPath(String timeseriesPath, String dataType, String encoding,
String[] args); boolean isPathExist(String path); boolean isPathExist(MNode node, String path); void setStorageGroup(String path); String deletePath(String path); boolean hasPath(String path); ColumnSchema getSchemaForOnePath(String path); ColumnSchema getSchemaForOnePath(MNode node, String path); ColumnSchema getSchemaForOnePathWithCheck(MNode node, String path); ColumnSchema getSchemaForOnePathWithCheck(String path); MNode getNodeByPath(String path); MNode getNodeByPathWithFileLevelCheck(String path); String getDeviceTypeByPath(String path); String getFileNameByPath(String path); String getFileNameByPath(MNode node, String path); String getFileNameByPathWithCheck(MNode node, String path); boolean checkFileNameByPath(String path); HashMap<String, ArrayList<String>> getAllPath(String pathReg); List<List<String>> getShowTimeseriesPath(String pathReg); List<String> getLeafNodePathInNextLevel(String path); ArrayList<String> getAllPathInList(String path); int getFileCountForOneType(String path); ArrayList<String> getAllType(); HashSet<String> getAllStorageGroup(); ArrayList<String> getDeviceForOneType(String type); ArrayList<ColumnSchema> getSchemaForOneType(String path); ArrayList<ColumnSchema> getSchemaForOneFileNode(String path); Map<String, ColumnSchema> getSchemaMapForOneFileNode(String path); Map<String, Integer> getNumSchemaMapForOneFileNode(String path); String toString(); MNode getRoot(); } | @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")); assertEquals(false, root.isPathExist("root.laptop.d1.s1")); assertEquals(true, root.checkFileNameByPath("root.laptop.d1.s1")); assertEquals("root.laptop.d1", root.getFileNameByPath("root.laptop.d1.s1")); } catch (PathErrorException e) { e.printStackTrace(); fail(e.getMessage()); } try { root.setStorageGroup("root.laptop.d2"); } catch (PathErrorException e) { fail(e.getMessage()); } try { root.setStorageGroup("root.laptop"); } catch (PathErrorException e) { Assert.assertEquals( "The seriesPath of root.laptop already exist, it can't be set to the storage group", e.getMessage()); } assertEquals(root.isPathExist("root.laptop.d1.s0"), false); assertEquals(root.isPathExist("root.laptop.d1.s1"), false); assertEquals(root.isPathExist("root.laptop.d2.s0"), false); assertEquals(root.isPathExist("root.laptop.d2.s1"), false); try { assertEquals("root.laptop.d1", root.getFileNameByPath("root.laptop.d1.s0")); root.addTimeseriesPath("root.laptop.d1.s0", "INT32", "RLE", new String[0]); assertEquals("root.laptop.d1", root.getFileNameByPath("root.laptop.d1.s1")); root.addTimeseriesPath("root.laptop.d1.s1", "INT32", "RLE", new String[0]); assertEquals("root.laptop.d2", root.getFileNameByPath("root.laptop.d2.s0")); root.addTimeseriesPath("root.laptop.d2.s0", "INT32", "RLE", new String[0]); assertEquals("root.laptop.d2", root.getFileNameByPath("root.laptop.d2.s1")); root.addTimeseriesPath("root.laptop.d2.s1", "INT32", "RLE", new String[0]); } catch (PathErrorException e) { e.printStackTrace(); fail(e.getMessage()); } try { root.deletePath("root.laptop.d1.s0"); } catch (PathErrorException e) { e.printStackTrace(); fail(e.getMessage()); } assertEquals(root.isPathExist("root.laptop.d1.s0"), false); try { root.deletePath("root.laptop.d1"); } catch (PathErrorException e) { e.printStackTrace(); fail(e.getMessage()); } assertEquals(root.isPathExist("root.laptop.d1.s1"), false); assertEquals(root.isPathExist("root.laptop.d1"), false); assertEquals(root.isPathExist("root.laptop"), true); assertEquals(root.isPathExist("root.laptop.d2"), true); assertEquals(root.isPathExist("root.laptop.d2.s0"), true); } |
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.equals(other.processorName)) { return false; } return true; } Processor(String processorName); void readUnlock(); void readLock(); void writeLock(); void writeUnlock(); void lock(boolean isWriteLock); boolean tryLock(boolean isWriteLock); void unlock(boolean isWriteUnlock); String getProcessorName(); boolean tryWriteLock(); boolean tryReadLock(); @Override int hashCode(); @Override boolean equals(Object obj); abstract boolean canBeClosed(); abstract boolean flush(); abstract void close(); abstract long memoryUsage(); } | @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(value, baos); encoder.encode(value - 2, baos); encoder.encode(value - 4, baos); encoder.flush(baos); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); for (int i = 0; i < 2; i++) { Decoder decoder = new SinglePrecisionDecoder(); if (decoder.hasNext(buffer)) { assertEquals(value, decoder.readFloat(buffer), delta); } if (decoder.hasNext(buffer)) { assertEquals(value - 2, decoder.readFloat(buffer), delta); } if (decoder.hasNext(buffer)) { assertEquals(value - 4, decoder.readFloat(buffer), delta); } } }
@Test public void testZeroNumber() throws IOException { Encoder encoder = new DoublePrecisionEncoder(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); double value = 0f; encoder.encode(value, baos); encoder.encode(value, baos); encoder.encode(value, baos); encoder.flush(baos); encoder.encode(value, baos); encoder.encode(value, baos); encoder.encode(value, baos); encoder.flush(baos); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); for (int i = 0; i < 2; i++) { Decoder decoder = new DoublePrecisionDecoder(); if (decoder.hasNext(buffer)) { assertEquals(value, decoder.readDouble(buffer), delta); } if (decoder.hasNext(buffer)) { assertEquals(value, decoder.readDouble(buffer), delta); } if (decoder.hasNext(buffer)) { assertEquals(value, decoder.readDouble(buffer), delta); } } }
@Test public void testFloat() throws IOException { Encoder encoder = new SinglePrecisionEncoder(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); float value = 7.101f; int num = 10000; for (int i = 0; i < num; i++) { encoder.encode(value + 2 * i, baos); } encoder.flush(baos); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); Decoder decoder = new SinglePrecisionDecoder(); for (int i = 0; i < num; i++) { if (decoder.hasNext(buffer)) { assertEquals(value + 2 * i, decoder.readFloat(buffer), delta); continue; } fail(); } }
@Test public void testDouble() throws IOException { Encoder encoder = new DoublePrecisionEncoder(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); double value = 7.101f; int num = 1000; for (int i = 0; i < num; i++) { encoder.encode(value + 2 * i, baos); } encoder.flush(baos); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); Decoder decoder = new DoublePrecisionDecoder(); for (int i = 0; i < num; i++) { if (decoder.hasNext(buffer)) { assertEquals(value + 2 * i, decoder.readDouble(buffer), delta); continue; } fail(); } } |
OFFileMetadata { public OFFileMetadata() { } OFFileMetadata(); OFFileMetadata(long lastFooterOffset, List<OFRowGroupListMetadata> rowGroupLists); static OFFileMetadata deserializeFrom(InputStream inputStream); static OFFileMetadata deserializeFrom(ByteBuffer buffer); void addRowGroupListMetaData(OFRowGroupListMetadata rowGroupListMetadata); List<OFRowGroupListMetadata> getRowGroupLists(); long getLastFooterOffset(); void setLastFooterOffset(long lastFooterOffset); @Override String toString(); int serializeTo(OutputStream outputStream); int serializeTo(ByteBuffer buffer); } | @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(OFSeriesListMetadata timeSeries); List<OFSeriesListMetadata> getSeriesList(); @Override String toString(); String getdeviceId(); int serializeTo(OutputStream outputStream); int serializeTo(ByteBuffer buffer); } | @Test public void testOFRowGroupListMetadata() throws Exception { OFRowGroupListMetadata ofRowGroupListMetadata = OverflowTestHelper .createOFRowGroupListMetadata(); serialize(ofRowGroupListMetadata); OFRowGroupListMetadata deOfRowGroupListMetadata = deSerialized(); OverflowUtils.isOFRowGroupListMetadataEqual(ofRowGroupListMetadata, deOfRowGroupListMetadata); } |
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 == 1) { long count = Long.valueOf(subFilePaths[0]); dataPahtCount.addAndGet(count + 1); workResource = new OverflowResource(parentPath, String.valueOf(count)); LOGGER.info("The overflow processor {} recover from work status.", getProcessorName()); } else { long count1 = Long.valueOf(subFilePaths[0]); long count2 = Long.valueOf(subFilePaths[1]); if (count1 > count2) { long temp = count1; count1 = count2; count2 = temp; } dataPahtCount.addAndGet(count2 + 1); workResource = new OverflowResource(parentPath, String.valueOf(count2)); mergeResource = new OverflowResource(parentPath, String.valueOf(count1)); LOGGER.info("The overflow processor {} recover from merge status.", getProcessorName()); } } OverflowProcessor(String processorName, Map<String, Action> parameters,
FileSchema fileSchema); void insert(TSRecord tsRecord); @Deprecated void update(String deviceId, String measurementId, long startTime, long endTime,
TSDataType type,
byte[] value); @Deprecated void update(String deviceId, String measurementId, long startTime, long endTime,
TSDataType type,
String value); @Deprecated void delete(String deviceId, String measurementId, long timestamp, TSDataType type); OverflowSeriesDataSource query(String deviceId, String measurementId, Filter filter,
TSDataType dataType); MergeSeriesDataSource queryMerge(String deviceId, String measurementId,
TSDataType dataType); OverflowSeriesDataSource queryMerge(String deviceId, String measurementId,
TSDataType dataType,
boolean isMerge); void switchWorkToMerge(); void switchMergeToWork(); boolean isMerge(); boolean isFlush(); @Override boolean flush(); @Override void close(); void clear(); @Override boolean canBeClosed(); @Override long memoryUsage(); String getOverflowRestoreFile(); long getMetaSize(); long getFileSize(); WriteLogNode getLogNode(); OverflowResource getWorkResource(); } | @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 overflowProcessor = new OverflowProcessor(processorName, parameters, OverflowTestUtils.getFileSchema()); assertEquals(false, overflowProcessor.isMerge()); overflowProcessor.switchWorkToMerge(); OverflowSeriesDataSource overflowSeriesDataSource = overflowProcessor .query(OverflowTestUtils.deviceId1, OverflowTestUtils.measurementId1, null, OverflowTestUtils.dataType1); Assert.assertEquals(true, overflowSeriesDataSource.getReadableMemChunk().isEmpty()); assertEquals(2, overflowSeriesDataSource.getOverflowInsertFileList().size()); overflowProcessor.switchMergeToWork(); overflowProcessor.close(); overflowProcessor.clear(); } |
OverflowIO extends TsFileIOWriter { public void close() throws IOException { overflowReadWriter.close(); } OverflowIO(OverflowReadWriter overflowReadWriter); @Deprecated static InputStream readOneTimeSeriesChunk(ChunkMetaData chunkMetaData,
TsFileInput fileReader); @Deprecated ChunkMetaData flush(OverflowSeriesImpl index); void clearRowGroupMetadatas(); @Deprecated List<OFRowGroupListMetadata> flush(
Map<String, Map<String, OverflowSeriesImpl>> overflowTrees); void toTail(); long getPos(); void close(); void flush(); OverflowReadWriter getReader(); OverflowReadWriter getWriter(); } | @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(new OverflowIO.OverflowReadWriter(file.getPath())); assertEquals(20, file.length()); overflowIO.close(); file.delete(); } |
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 update(String deviceId, String measurementId, long startTime, long endTime,
TSDataType dataType,
byte[] value); @Deprecated void delete(String deviceId, String measurementId, long timestamp, TSDataType dataType); TimeValuePairSorter queryOverflowInsertInMemory(String deviceId, String measurementId,
TSDataType dataType); BatchData queryOverflowUpdateInMemory(String deviceId, String measurementId,
TSDataType dataType,
BatchData data); boolean isEmptyOfOverflowSeriesMap(); Map<String, Map<String, OverflowSeriesImpl>> getOverflowSeriesMap(); boolean isEmptyOfMemTable(); IMemTable getMemTabale(); long getSize(); void clear(); } | @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) .getSortedTimeValuePairList()) { assertEquals(num, pair.getTimestamp()); assertEquals(num, pair.getValue().getInt()); num++; } num = 1; for (TimeValuePair pair : support .queryOverflowInsertInMemory(deviceId2, measurementId2, dataType2) .getSortedTimeValuePairList()) { assertEquals(num, pair.getTimestamp()); if (num == 2) { assertEquals(10.5, pair.getValue().getFloat(), error); } else { assertEquals(5.5, pair.getValue().getFloat(), error); } num++; } } |
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, String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService newSingleThreadExecutor(String poolName); static ExecutorService newSingleThreadExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService newCachedThreadPool(String poolName); static ExecutorService newCachedThreadPool(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService createJDBCClientThreadPool(Args args, String poolName); static ExecutorService createJDBCClientThreadPool(Args args, String poolName,
Thread.UncaughtExceptionHandler handler); } | @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 .newFixedThreadPool(threadCount, POOL_NAME, handler); for (int i = 0; i < threadCount; i++) { Runnable task = new TestThread(reason); exec.execute(task); } try { latch.await(); assertEquals(count.get(), threadCount); } catch (InterruptedException E) { fail(); } } |
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,
Thread.UncaughtExceptionHandler handler); static ExecutorService newSingleThreadExecutor(String poolName); static ExecutorService newSingleThreadExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService newCachedThreadPool(String poolName); static ExecutorService newCachedThreadPool(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService createJDBCClientThreadPool(Args args, String poolName); static ExecutorService createJDBCClientThreadPool(Args args, String poolName,
Thread.UncaughtExceptionHandler handler); } | @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.newSingleThreadExecutor(POOL_NAME, handler); for (int i = 0; i < threadCount; i++) { Runnable task = new TestThread(reason); exec.execute(task); } try { latch.await(); assertEquals(count.get(), threadCount); } catch (InterruptedException E) { fail(); } } |
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,
Thread.UncaughtExceptionHandler handler); static ExecutorService newSingleThreadExecutor(String poolName); static ExecutorService newSingleThreadExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService newCachedThreadPool(String poolName); static ExecutorService newCachedThreadPool(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService createJDBCClientThreadPool(Args args, String poolName); static ExecutorService createJDBCClientThreadPool(Args args, String poolName,
Thread.UncaughtExceptionHandler handler); } | @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(POOL_NAME, handler); for (int i = 0; i < threadCount; i++) { Runnable task = new TestThread(reason); exec.execute(task); } try { latch.await(); assertEquals(count.get(), threadCount); } catch (InterruptedException E) { fail(); } } |
IoTDBThreadPoolFactory { public static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName) { return Executors.newSingleThreadScheduledExecutor(new IoTThreadFactory(poolName)); } static ExecutorService newFixedThreadPool(int nthreads, String poolName); static ExecutorService newFixedThreadPool(int nthreads, String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService newSingleThreadExecutor(String poolName); static ExecutorService newSingleThreadExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService newCachedThreadPool(String poolName); static ExecutorService newCachedThreadPool(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService createJDBCClientThreadPool(Args args, String poolName); static ExecutorService createJDBCClientThreadPool(Args args, String poolName,
Thread.UncaughtExceptionHandler handler); } | @Test public void testNewSingleThreadScheduledExecutor() throws InterruptedException { String reason = "NewSingleThreadScheduledExecutor"; Thread.UncaughtExceptionHandler handler = new TestExceptionHandler(reason); int threadCount = 1; latch = new CountDownLatch(threadCount); ScheduledExecutorService exec = IoTDBThreadPoolFactory .newSingleThreadScheduledExecutor(POOL_NAME, handler); for (int i = 0; i < threadCount; i++) { Runnable task = new TestThread(reason); ScheduledFuture<?> future = exec.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS); try { future.get(); } catch (ExecutionException e) { assertEquals(reason, e.getCause().getMessage()); count.addAndGet(1); latch.countDown(); } } try { latch.await(); assertEquals(count.get(), threadCount); } catch (InterruptedException E) { fail(); } } |
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 newFixedThreadPool(int nthreads, String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService newSingleThreadExecutor(String poolName); static ExecutorService newSingleThreadExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService newCachedThreadPool(String poolName); static ExecutorService newCachedThreadPool(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService createJDBCClientThreadPool(Args args, String poolName); static ExecutorService createJDBCClientThreadPool(Args args, String poolName,
Thread.UncaughtExceptionHandler handler); } | @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 .newScheduledThreadPool(threadCount, POOL_NAME, handler); for (int i = 0; i < threadCount; i++) { Runnable task = new TestThread(reason); ScheduledFuture<?> future = exec.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS); try { future.get(); } catch (ExecutionException e) { assertEquals(reason, e.getCause().getMessage()); count.addAndGet(1); latch.countDown(); } } try { latch.await(); assertEquals(count.get(), threadCount); } catch (InterruptedException E) { fail(); } } |
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, executorQueue, new IoTThreadFactory(poolName)); } static ExecutorService newFixedThreadPool(int nthreads, String poolName); static ExecutorService newFixedThreadPool(int nthreads, String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService newSingleThreadExecutor(String poolName); static ExecutorService newSingleThreadExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService newCachedThreadPool(String poolName); static ExecutorService newCachedThreadPool(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService createJDBCClientThreadPool(Args args, String poolName); static ExecutorService createJDBCClientThreadPool(Args args, String poolName,
Thread.UncaughtExceptionHandler handler); } | @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.UncaughtExceptionHandler handler = new TestExceptionHandler(reason); int threadCount = 50; latch = new CountDownLatch(threadCount); ExecutorService exec = IoTDBThreadPoolFactory .createJDBCClientThreadPool(args, POOL_NAME, handler); for (int i = 0; i < threadCount; i++) { Runnable task = new TestThread(reason); exec.execute(task); } try { latch.await(); assertEquals(count.get(), threadCount); } catch (InterruptedException E) { fail(); } } |
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 statistics); } | @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)); } totalOpenFileNumAfter = openFileNumUtil .get(OpenFileNumUtil.OpenFileNumStatistics.DATA_OPEN_FILE_NUM); totalOpenFileNumChange = totalOpenFileNumAfter - totalOpenFileNumBefore; assertEquals(0, totalOpenFileNumChange); } else { assertEquals(-2, openFileNumUtil.get(OpenFileNumUtil.OpenFileNumStatistics.DATA_OPEN_FILE_NUM)); } }
@Test public void testDataOpenFileNumWhenCreateFileWriter() { if (os.startsWith(MAC_OS_NAME) || os.startsWith(LINUX_OS_NAME)) { for (int i = 0; i < testFileNum; i++) { fileList.add(new File(currDir + testFileName + i)); } totalOpenFileNumBefore = openFileNumUtil .get(OpenFileNumUtil.OpenFileNumStatistics.DATA_OPEN_FILE_NUM); for (File file : fileList) { if (file.exists()) { try { fileWriterList.add(new FileWriter(file)); } catch (IOException e) { LOGGER.error(e.getMessage()); } } else { try { boolean flag = file.createNewFile(); if (!flag) { LOGGER.error( "create test file {} failed when execute testTotalOpenFileNumWhenCreateFileWriter().", file.getPath()); } } catch (IOException e) { LOGGER.error(e.getMessage()); } try { fileWriterList.add(new FileWriter(file)); } catch (IOException e) { LOGGER.error(e.getMessage()); } } } totalOpenFileNumAfter = openFileNumUtil .get(OpenFileNumUtil.OpenFileNumStatistics.DATA_OPEN_FILE_NUM); totalOpenFileNumChange = totalOpenFileNumAfter - totalOpenFileNumBefore; assertEquals(testFileNum, totalOpenFileNumChange); } else { assertEquals(-2, openFileNumUtil.get(OpenFileNumUtil.OpenFileNumStatistics.DATA_OPEN_FILE_NUM)); } }
@Test public void testDataOpenFileNumWhenFileWriterWriting() { if (os.startsWith(MAC_OS_NAME) || os.startsWith(LINUX_OS_NAME)) { for (int i = 0; i < testFileNum; i++) { fileList.add(new File(currDir + testFileName + i)); } for (File file : fileList) { if (file.exists()) { try { fileWriterList.add(new FileWriter(file)); } catch (IOException e) { LOGGER.error(e.getMessage()); } } else { try { if (!file.createNewFile()) { LOGGER.error("create test file {} failed.", file.getPath()); } } catch (IOException e) { LOGGER.error(e.getMessage()); } try { fileWriterList.add(new FileWriter(file)); } catch (IOException e) { LOGGER.error(e.getMessage()); } } } totalOpenFileNumBefore = openFileNumUtil .get(OpenFileNumUtil.OpenFileNumStatistics.DATA_OPEN_FILE_NUM); for (FileWriter fw : fileWriterList) { try { fw.write("this is a test file for open file number counting."); } catch (IOException e) { LOGGER.error(e.getMessage()); } } totalOpenFileNumAfter = openFileNumUtil .get(OpenFileNumUtil.OpenFileNumStatistics.DATA_OPEN_FILE_NUM); totalOpenFileNumChange = totalOpenFileNumAfter - totalOpenFileNumBefore; assertEquals(0, totalOpenFileNumChange); } else { assertEquals(-2, openFileNumUtil.get(OpenFileNumUtil.OpenFileNumStatistics.DATA_OPEN_FILE_NUM)); } }
@Test public void testDataOpenFileNumWhenFileWriterClose() { if (os.startsWith(MAC_OS_NAME) || os.startsWith(LINUX_OS_NAME)) { for (int i = 0; i < testFileNum; i++) { fileList.add(new File(currDir + testFileName + i)); } for (File file : fileList) { if (file.exists()) { try { fileWriterList.add(new FileWriter(file)); } catch (IOException e) { LOGGER.error(e.getMessage()); } } else { try { if (!file.createNewFile()) { LOGGER.error( "create test file {} failed when execute testTotalOpenFileNumWhenFileWriterClose().", file.getPath()); } } catch (IOException e) { LOGGER.error(e.getMessage()); } try { fileWriterList.add(new FileWriter(file)); } catch (IOException e) { LOGGER.error(e.getMessage()); } } } for (FileWriter fw : fileWriterList) { try { fw.write("this is a test file for open file number counting."); } catch (IOException e) { LOGGER.error(e.getMessage()); } } totalOpenFileNumBefore = openFileNumUtil .get(OpenFileNumUtil.OpenFileNumStatistics.DATA_OPEN_FILE_NUM); for (FileWriter fw : fileWriterList) { try { fw.close(); } catch (IOException e) { LOGGER.error(e.getMessage()); } } totalOpenFileNumAfter = openFileNumUtil .get(OpenFileNumUtil.OpenFileNumStatistics.DATA_OPEN_FILE_NUM); totalOpenFileNumChange = totalOpenFileNumAfter - totalOpenFileNumBefore; assertEquals(-testFileNum, totalOpenFileNumChange); } else { assertEquals(-2, openFileNumUtil.get(OpenFileNumUtil.OpenFileNumStatistics.DATA_OPEN_FILE_NUM)); } } |
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.currentTimeMillis(); } try { return DatetimeUtils.convertDatetimeStrToMillisecond(timestampStr, zoneId); } catch (Exception e) { throw new LogicalOperatorException(String .format("Input time format %s error. " + "Input like yyyy-MM-dd HH:mm:ss, yyyy-MM-ddTHH:mm:ss or " + "refer to user document for more info.", timestampStr)); } } LogicalGenerator(ZoneId zoneId); RootOperator getLogicalPlan(AstNode astNode); long parseTimeFormat(String timestampStr); } | @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 = ZoneOffset.of("+" + i + ":00"); offset2 = ZoneOffset.of("-" + i + ":00"); } ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(now), ZoneId.of(offset1.toString())); assertEquals(now, zonedDateTime.toInstant().toEpochMilli()); zonedDateTime = ZonedDateTime .ofInstant(Instant.ofEpochMilli(now), ZoneId.of(offset2.toString())); assertEquals(now, zonedDateTime.toInstant().toEpochMilli()); } }
@Test(expected = LogicalOperatorException.class) public void testParseTimeFormatFail1() throws LogicalOperatorException { generator.parseTimeFormat(null); }
@Test(expected = LogicalOperatorException.class) public void testParseTimeFormatFail2() throws LogicalOperatorException { generator.parseTimeFormat(""); } |
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"); } } } catch (IOException e) { LOGGER.error("IoTDB post back sender: cannot back up now local file info because {}", e); } finally { if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (IOException e) { LOGGER.error( "IoTDB post back sender: cannot close stream after backing up now local file info " + "because {}", e); } } } } private FileManager(); static final FileManager getInstance(); void init(); void getSendingFileList(); void getLastLocalFileList(String path); void getNowLocalFileList(String[] paths); void backupNowLocalFileInfo(String backupFile); Map<String, Set<String>> getSendingFiles(); Set<String> getLastLocalFiles(); Map<String, Set<String>> getNowLocalFiles(); void setNowLocalFiles(Map<String, Set<String>> newNowLocalFiles); } | @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<>()); } String rand = String.valueOf(r.nextInt(10000)); String fileName = SENDER_FILE_PATH_TEST + File.separator + String.valueOf(i) + File.separator + rand; File file = new File(fileName); allFileList.get(String.valueOf(i)).add(file.getAbsolutePath()); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } if (!file.exists()) { file.createNewFile(); } } } Set<String> lastFileList = new HashSet<>(); manager.getLastLocalFileList(LAST_FILE_INFO_TEST); lastFileList = manager.getLastLocalFiles(); assert (lastFileList.isEmpty()); manager.getNowLocalFileList(new String[]{SENDER_FILE_PATH_TEST}); manager.backupNowLocalFileInfo(LAST_FILE_INFO_TEST); manager.getLastLocalFileList(LAST_FILE_INFO_TEST); lastFileList = manager.getLastLocalFiles(); for (Entry<String, Set<String>> entry : allFileList.entrySet()) { assert (lastFileList.containsAll(entry.getValue())); } r = new Random(1); 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<>()); } String rand = String.valueOf(r.nextInt(10000)); String fileName = SENDER_FILE_PATH_TEST + File.separator + String.valueOf(i) + File.separator + rand; File file = new File(fileName); allFileList.get(String.valueOf(i)).add(file.getAbsolutePath()); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } if (!file.exists()) { file.createNewFile(); } } } int count = 0; Map<String, Set<String>> deleteFile = new HashMap<>(); for (Entry<String, Set<String>> entry : allFileList.entrySet()) { deleteFile.put(entry.getKey(), new HashSet<>()); for (String path : entry.getValue()) { count++; if (count % 3 == 0) { deleteFile.get(entry.getKey()).add(path); } } } for (Entry<String, Set<String>> entry : deleteFile.entrySet()) { for (String path : entry.getValue()) { new File(path).delete(); allFileList.get(entry.getKey()).remove(path); } } manager.getNowLocalFileList(new String[]{SENDER_FILE_PATH_TEST}); manager.backupNowLocalFileInfo(LAST_FILE_INFO_TEST); manager.getLastLocalFileList(LAST_FILE_INFO_TEST); lastFileList = manager.getLastLocalFiles(); for (Entry<String, Set<String>> entry : allFileList.entrySet()) { assert (lastFileList.containsAll(entry.getValue())); } } |
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.containsKey(storageGroup.getName())) { nowLocalFiles.put(storageGroup.getName(), new HashSet<String>()); } if (!sendingFiles.containsKey(storageGroup.getName())) { sendingFiles.put(storageGroup.getName(), new HashSet<String>()); } File[] files = storageGroup.listFiles(); for (File file : files) { if (!file.getAbsolutePath().endsWith(".restore")) { if (!new File(file.getAbsolutePath() + ".restore").exists()) { nowLocalFiles.get(storageGroup.getName()).add(file.getAbsolutePath()); } } } } } } } private FileManager(); static final FileManager getInstance(); void init(); void getSendingFileList(); void getLastLocalFileList(String path); void getNowLocalFileList(String[] paths); void backupNowLocalFileInfo(String backupFile); Map<String, Set<String>> getSendingFiles(); Set<String> getLastLocalFiles(); Map<String, Set<String>> getNowLocalFiles(); void setNowLocalFiles(Map<String, Set<String>> newNowLocalFiles); } | @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 = 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<>()); } String rand = String.valueOf(r.nextInt(10000)); String fileName = SENDER_FILE_PATH_TEST + File.separator + String.valueOf(i) + File.separator + rand; File file = new File(fileName); allFileList.get(String.valueOf(i)).add(file.getAbsolutePath()); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } if (!file.exists()) { file.createNewFile(); } } } manager.getNowLocalFileList(new String[]{SENDER_FILE_PATH_TEST}); fileList = manager.getNowLocalFiles(); assert (allFileList.size() == fileList.size()); for (Entry<String, Set<String>> entry : fileList.entrySet()) { assert (allFileList.containsKey(entry.getKey())); assert (allFileList.get(entry.getKey()).containsAll(entry.getValue())); } int count = 0; Map<String, Set<String>> deleteFile = new HashMap<>(); for (Entry<String, Set<String>> entry : allFileList.entrySet()) { deleteFile.put(entry.getKey(), new HashSet<>()); for (String path : entry.getValue()) { count++; if (count % 3 == 0) { deleteFile.get(entry.getKey()).add(path); } } } for (Entry<String, Set<String>> entry : deleteFile.entrySet()) { for (String path : entry.getValue()) { new File(path).delete(); allFileList.get(entry.getKey()).remove(path); } } r = new Random(1); 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<>()); } String rand = String.valueOf(r.nextInt(10000)); String fileName = SENDER_FILE_PATH_TEST + File.separator + String.valueOf(i) + File.separator + rand; File file = new File(fileName); allFileList.get(String.valueOf(i)).add(file.getAbsolutePath()); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } if (!file.exists()) { file.createNewFile(); } } } manager.setNowLocalFiles(new HashMap<>()); manager.getNowLocalFileList(new String[]{SENDER_FILE_PATH_TEST}); fileList = manager.getNowLocalFiles(); assert (allFileList.size() == fileList.size()); for (Entry<String, Set<String>> entry : fileList.entrySet()) { assert (allFileList.containsKey(entry.getKey())); System.out.println("allFileList"); for (String a : allFileList.get(entry.getKey())) { System.out.println(a); } System.out.println("FileList"); for (String a : entry.getValue()) { System.out.println(a); } assert (allFileList.get(entry.getKey()).containsAll(entry.getValue())); } } |
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 (Entry<String, Set<String>> entry : sendingFiles.entrySet()) { for (String path : entry.getValue()) { LOGGER.info(path); nowLocalFiles.get(entry.getKey()).remove(path); } } } private FileManager(); static final FileManager getInstance(); void init(); void getSendingFileList(); void getLastLocalFileList(String path); void getNowLocalFileList(String[] paths); void backupNowLocalFileInfo(String backupFile); Map<String, Set<String>> getSendingFiles(); Set<String> getLastLocalFiles(); Map<String, Set<String>> getNowLocalFiles(); void setNowLocalFiles(Map<String, Set<String>> newNowLocalFiles); } | @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<>()); manager.getNowLocalFileList(new String[]{SENDER_FILE_PATH_TEST}); allFileList = manager.getNowLocalFiles(); manager.getLastLocalFileList(LAST_FILE_INFO_TEST); lastlocalList = manager.getLastLocalFiles(); manager.getSendingFileList(); sendingFileList = manager.getSendingFiles(); assert (lastlocalList.size() == 0); assert (isEmpty(allFileList)); assert (isEmpty(sendingFileList)); newFileList.clear(); manager.backupNowLocalFileInfo(LAST_FILE_INFO_TEST); 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<>()); } if (!newFileList.containsKey(String.valueOf(i))) { newFileList.put(String.valueOf(i), new HashSet<>()); } String rand = String.valueOf(r.nextInt(10000)); String fileName = SENDER_FILE_PATH_TEST + File.separator + String.valueOf(i) + File.separator + rand; File file = new File(fileName); allFileList.get(String.valueOf(i)).add(file.getAbsolutePath()); newFileList.get(String.valueOf(i)).add(file.getAbsolutePath()); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } if (!file.exists()) { file.createNewFile(); } } } manager.getNowLocalFileList(new String[]{SENDER_FILE_PATH_TEST}); allFileList = manager.getNowLocalFiles(); manager.backupNowLocalFileInfo(LAST_FILE_INFO_TEST); manager.getLastLocalFileList(LAST_FILE_INFO_TEST); lastlocalList = manager.getLastLocalFiles(); manager.getSendingFileList(); sendingFileList = manager.getSendingFiles(); assert (sendingFileList.size() == newFileList.size()); for (Entry<String, Set<String>> entry : sendingFileList.entrySet()) { assert (newFileList.containsKey(entry.getKey())); assert (newFileList.get(entry.getKey()).containsAll(entry.getValue())); } int count = 0; Map<String, Set<String>> deleteFile = new HashMap<>(); for (Entry<String, Set<String>> entry : allFileList.entrySet()) { deleteFile.put(entry.getKey(), new HashSet<>()); for (String path : entry.getValue()) { count++; if (count % 3 == 0) { deleteFile.get(entry.getKey()).add(path); } } } for (Entry<String, Set<String>> entry : deleteFile.entrySet()) { for (String path : entry.getValue()) { new File(path).delete(); allFileList.get(entry.getKey()).remove(path); } } newFileList.clear(); r = new Random(1); 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<>()); } if (!newFileList.containsKey(String.valueOf(i))) { newFileList.put(String.valueOf(i), new HashSet<>()); } String rand = String.valueOf(r.nextInt(10000)); String fileName = SENDER_FILE_PATH_TEST + File.separator + String.valueOf(i) + File.separator + rand; File file = new File(fileName); allFileList.get(String.valueOf(i)).add(file.getAbsolutePath()); newFileList.get(String.valueOf(i)).add(file.getAbsolutePath()); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } if (!file.exists()) { file.createNewFile(); } } } manager.getNowLocalFileList(new String[]{SENDER_FILE_PATH_TEST}); allFileList = manager.getNowLocalFiles(); manager.getLastLocalFileList(LAST_FILE_INFO_TEST); lastlocalList = manager.getLastLocalFiles(); manager.getSendingFileList(); sendingFileList = manager.getSendingFiles(); assert (sendingFileList.size() == newFileList.size()); for (Entry<String, Set<String>> entry : sendingFileList.entrySet()) { assert (newFileList.containsKey(entry.getKey())); assert (newFileList.get(entry.getKey()).containsAll(entry.getValue())); } } |
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 false; } if (right == null) { if (other.right != null) { return false; } } else if (!right.equals(other.right)) { return false; } return true; } Pair(L l, R r); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); public L left; public R right; } | @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 = new Pair<String, Integer>("a", 123123); p2 = new Pair<String, Integer>("a", null); assertFalse(p1.equals(p2)); p1 = new Pair<String, Integer>(null, 123123); p2 = new Pair<String, Integer>("a", 123123); assertFalse(p1.equals(p2)); p1 = new Pair<String, Integer>("a", 123123); p2 = new Pair<String, Integer>(null, 123123); assertFalse(p1.equals(p2)); p1 = new Pair<String, Integer>(null, 123123); p2 = null; assertFalse(p1.equals(p2)); p1 = new Pair<String, Integer>(null, 123123); p2 = new Pair<String, Integer>(null, 123123); Map<Pair<String, Integer>, Integer> map = new HashMap<Pair<String, Integer>, Integer>(); map.put(p1, 1); assertTrue(map.containsKey(p2)); assertTrue(p1.equals(p2)); p1 = new Pair<String, Integer>("a", null); p2 = new Pair<String, Integer>("a", null); assertTrue(p1.equals(p2)); assertTrue(p1.equals(p1)); assertFalse(p1.equals(new Integer(1))); } |
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 createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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.getWidth(); float scalerHeight = ((float) StreamDeck.ICON_SIZE) / originalImage.getWidth(); if (scalerWidth < scaledHeight) scaledHeight = Math.round(scalerWidth * originalImage.getHeight()); else scaledWidth = Math.round(scalerHeight * originalImage.getWidth()); } int imageType = preserveType ? originalImage.getType() : BufferedImage.TYPE_INT_ARGB; BufferedImage scaledBI = new BufferedImage(StreamDeck.ICON_SIZE, StreamDeck.ICON_SIZE, imageType); Graphics2D g = scaledBI.createGraphics(); if (true) { g.setComposite(AlphaComposite.Src); } g.drawImage(originalImage, (StreamDeck.ICON_SIZE - scaledWidth) / 2, (StreamDeck.ICON_SIZE - scaledHeight) / 2, scaledWidth, scaledHeight, null); g.dispose(); return scaledBI; } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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.dispose(); return nImg; } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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.dispose(); return newImage; } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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 setRollingTextPadding(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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 exist: " + fileName); return null; } } catch (IOException e) { logger.error("Couldn't load image as resource: " + fileName, e); return null; } return buff; } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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<>(); env.put("create", "true"); try (FileSystem fileSystem = FileSystems.newFileSystem(uri, env)) { Path iconPath = fileSystem.getPath("icon.png"); SDImage icon = IconHelper.loadImage(iconPath); Path animFile = fileSystem.getPath("animation.json"); AnimationStack animation = null; if (Files.exists(animFile)) { String text = new String(Files.readAllBytes(animFile), StandardCharsets.UTF_8); Gson g = new Gson(); animation = g.fromJson(text, AnimationStack.class); int frameIndex = 0; Path frameFile = fileSystem.getPath((frameIndex++) + ".png"); List<SDImage> frameList = new LinkedList<>(); List<BufferedImage> rawFrameList = new LinkedList<>(); while (Files.exists(frameFile)) { SDImage frame = IconHelper.loadImage(frameFile); frameList.add(frame); rawFrameList.add(loadRawImage(frameFile)); frameFile = fileSystem.getPath((frameIndex++) + ".png"); } SDImage[] frames = new SDImage[frameList.size()]; for (int i = 0; i < frames.length; i++) { frames[i] = frameList.get(i); } animation.setFrames(frames); } IconPackage iconPackage = new IconPackage(icon, animation); packageCache.put(pathToZip, iconPackage); return iconPackage; } } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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_ICON); } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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.createImageInputStream(new File(pathToGif)); reader.setInput(ciis, false); int noi = reader.getNumImages(true); BufferedImage master = null; SDImage[] images = new SDImage[noi]; for (int i = 0; i < noi; i++) { BufferedImage image = reader.read(i); IIOMetadata metadata = reader.getImageMetadata(i); Node tree = metadata.getAsTree("javax_imageio_gif_image_1.0"); NodeList children = tree.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node nodeItem = children.item(j); if (nodeItem.getNodeName().equals("ImageDescriptor")) { Map<String, Integer> imageAttr = new HashMap<>(); for (int k = 0; k < imageatt.length; k++) { NamedNodeMap attr = nodeItem.getAttributes(); Node attnode = attr.getNamedItem(imageatt[k]); imageAttr.put(imageatt[k], Integer.valueOf(attnode.getNodeValue())); } if (i == 0) { master = new BufferedImage(imageAttr.get("imageWidth"), imageAttr.get("imageHeight"), BufferedImage.TYPE_INT_ARGB); } master.getGraphics().drawImage(image, imageAttr.get("imageLeftPosition"), imageAttr.get("imageTopPosition"), null); } } SDImage imgData = convertImage(master); images[i] = imgData; } return images; } catch (IOException e) { logger.error("Error loeading gif", e); throw e; } } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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 rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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 - x - 1; int nY = height - (width - y - 1) - 1; returnImage.setRGB(nX, nY, inputImage.getRGB(x, y)); } } return returnImage; } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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 createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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); BufferedImage img = new BufferedImage(StreamDeck.ICON_SIZE, StreamDeck.ICON_SIZE, BufferedImage.TYPE_INT_ARGB); Graphics2D g = img.createGraphics(); g.setColor(background); g.fillRect(0, 0, StreamDeck.ICON_SIZE, StreamDeck.ICON_SIZE); g.setColor(new Color(132, 132, 132)); g.drawRect(15, 23, 42, 29); g.drawRect(16, 24, 40, 27); g.drawLine(53, 22, 40, 22); g.drawLine(52, 21, 41, 21); g.drawLine(51, 20, 42, 20); g.drawLine(50, 19, 43, 19); g.dispose(); if(applyFrame) img = applyFrame(img, frameColor); return cacheImage(folderKey, img); } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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 BufferedImage(StreamDeck.ICON_SIZE, StreamDeck.ICON_SIZE, BufferedImage.TYPE_INT_ARGB); Graphics2D g = img.createGraphics(); g.setColor(borderColor); g.fillRect(0, 0, StreamDeck.ICON_SIZE, StreamDeck.ICON_SIZE); g.dispose(); applyAlpha(img, FRAME); return cacheImage(frameKey, img); } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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.length; i++) { int color = imagePixels[i] & 0x00ffffff; int alpha = maskPixels[i] & 0xff000000; imagePixels[i] = color | alpha; } image.setRGB(0, 0, width, height, imagePixels, 0, width); } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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++) { imgData[imgDataCount++] = (byte) ((pixels[i] >> 16) & 0xFF); imgData[imgDataCount++] = (byte) (pixels[i] & 0xFF); imgData[imgDataCount++] = (byte) ((pixels[i] >> 8) & 0xFF); } SDImage sdImage = new SDImage(imgData, img); cache(path, sdImage); return sdImage; } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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_ON); g2d.drawImage(imgData.image, null, 0, 0); g2d.drawImage(apply, null, 0, 0); g2d.dispose(); return convertImage(img); } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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.createGraphics(); g.drawImage(img, 0, 0, null); g.drawImage(createColoredFrame(frameColor).image, 0, 0, null); g.dispose(); return nImg; } private IconHelper(); static int getTextBoxAlphaValue(); static void setTextBoxAlphaValue(int textBoxAlphaValue); static int getRollingTextPadding(); static void setRollingTextPadding(int rollingTextPadding); static SDImage createFolderImage(Color background, boolean applyFrame, Color frameColor); static SDImage createColoredFrame(Color borderColor); static void applyAlpha(BufferedImage image, BufferedImage mask); static SDImage addText(SDImage imgData, String text, int pos); static SDImage addText(BufferedImage imgData, String text, int pos); static SDImage addText(SDImage imgData, String text, int pos, float fontSize); static SDImage addText(BufferedImage imgData, String text, int pos, float fontSize); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos); static AnimationStack createRollingTextAnimation(SDImage imgData, String text, int pos, float fontSize); static SDImage cacheImage(String path, BufferedImage img); static SDImage convertImage(BufferedImage img); static SDImage convertImageAndApplyFrame(BufferedImage src, Color frameColor); static SDImage applyImage(SDImage imgData, BufferedImage apply); static BufferedImage applyFrame(BufferedImage img, Color frameColor); static void createIconPackage(String pathToArchive, String pathToIcon, String pathToGif,
AnimationStack stack); static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
AnimationStack stack); static BufferedImage createResizedCopy(BufferedImage originalImage, boolean preserveType); static BufferedImage fillBackground(BufferedImage img, Color color); static BufferedImage flipHoriz(BufferedImage image); static SDImage getImage(String string); static BufferedImage getImageFromResource(String fileName); static IconPackage loadIconPackage(String pathToZip); static SDImage loadImageSafe(String path); static SDImage loadImageSafe(Path path); static SDImage loadImageSafe(String path, boolean applyFrame, Color frameColor); static SDImage loadImageSafe(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(Path path); static SDImage loadImage(String path); static SDImage loadImage(Path path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, boolean applyFrame, Color frameColor); static SDImage loadImage(String path, InputStream inputStream, boolean disableCache, boolean applyFrame, Color frameColor); static BufferedImage loadRawImage(Path path); static BufferedImage loadRawImage(InputStream inputStream); static SDImage loadImageFromResource(String path); static SDImage loadImageFromResourceSafe(String path); static SDImage[] loadImagesFromGif(String pathToGif); static BufferedImage rotate180(BufferedImage inputImage); static final String TEMP_BLACK_ICON; static final BufferedImage FRAME; static final Font DEFAULT_FONT; static final int TEXT_TOP; static final int TEXT_CENTER; static final int TEXT_BOTTOM; static final SDImage BLACK_ICON; static final SDImage FOLDER_ICON; } | @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) { long v2 = v << 64 - shift; data[index] = data[index] | v2; } } } BitStream(); BitStream(int initialCapacity); BitStream(long[] data, int len, int index, byte shift); void write(int n, long v); Map<String, Double> getStats(); BitStreamIterator read(); static BitStream deserialize(ByteBuffer buffer); void serialize(ByteBuffer buffer); int getSerializedByteSize(); } | @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(IllegalArgumentException.class); new BitStream( 2).write(65, 10); } |
OffHeapChunkManagerTask implements Runnable { @VisibleForTesting void runAt(Instant instant) { LOG.info("Starting offHeapChunkManagerTask."); deleteStaleData(instant); detectReadOnlyChunks(instant); LOG.info("Finished offHeapChunkManagerTask."); } OffHeapChunkManagerTask(ChunkManager chunkManager); OffHeapChunkManagerTask(ChunkManager chunkManager,
int metricsDelaySecs,
int staleDataDelaySecs); @Override void run(); static final int DEFAULT_METRICS_DELAY_SECS; static final int DEFAULT_STALE_DATA_DELAY_SECS; } | @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(chunkManager.getChunkMap().isEmpty()); assertEquals(0, getReadOnlyChunkCount(chunkManager)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimeSecs + 1, testValue)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimePlusTwoHoursSecs, testValue)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimePlusFourHoursSecs, testValue)); assertEquals(3, chunkManager.getChunkMap().size()); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimeSecs)); assertEquals(3, chunkManager.getChunkMap().size()); assertEquals(0, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusTwoHoursSecs)); assertEquals(3, chunkManager.getChunkMap().size()); assertEquals(1, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusFourHoursSecs)); assertEquals(3, chunkManager.getChunkMap().size()); assertEquals(2, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusSixHoursSecs)); assertEquals(2, chunkManager.getChunkMap().size()); assertEquals(2, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusSixHoursSecs + 10 * 60)); assertEquals(2, chunkManager.getChunkMap().size()); assertEquals(2, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusEightHoursSecs)); assertEquals(1, chunkManager.getChunkMap().size()); assertEquals(1, getReadOnlyChunkCount(chunkManager)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimeSecs, testValue)); assertEquals(2, chunkManager.getChunkMap().size()); assertEquals(1, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusEightHoursSecs + 2 * 3600)); assertTrue(chunkManager.getChunkMap().isEmpty()); assertEquals(0, getReadOnlyChunkCount(chunkManager)); }
@Test public void testRunAtWithOneChunk() { assertTrue(chunkManager.getChunkMap().isEmpty()); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimeSecs)); assertTrue(chunkManager.getChunkMap().isEmpty()); assertEquals(0, getReadOnlyChunkCount(chunkManager)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimeSecs + 1, testValue)); assertEquals(1, chunkManager.getChunkMap().size()); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimeSecs)); assertEquals(1, chunkManager.getChunkMap().size()); assertEquals(0, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusTwoHoursSecs)); assertEquals(1, chunkManager.getChunkMap().size()); assertEquals(0, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusTwoHoursSecs + DEFAULT_METRICS_DELAY_SECS)); assertEquals(1, chunkManager.getChunkMap().size()); assertEquals(1, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusFourHoursSecs)); assertEquals(1, chunkManager.getChunkMap().size()); assertEquals(1, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusEightHoursSecs)); assertTrue(chunkManager.getChunkMap().isEmpty()); assertEquals(0, getReadOnlyChunkCount(chunkManager)); }
@Test public void testRunAtWithMultipleChunks() { assertTrue(chunkManager.getChunkMap().isEmpty()); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimeSecs)); assertTrue(chunkManager.getChunkMap().isEmpty()); assertEquals(0, getReadOnlyChunkCount(chunkManager)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimeSecs + 1, testValue)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimePlusTwoHoursSecs, testValue)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimePlusFourHoursSecs, testValue)); assertEquals(3, chunkManager.getChunkMap().size()); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimeSecs)); assertEquals(3, chunkManager.getChunkMap().size()); assertEquals(0, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusTwoHoursSecs)); assertEquals(3, chunkManager.getChunkMap().size()); assertEquals(0, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusTwoHoursSecs + DEFAULT_METRICS_DELAY_SECS)); assertEquals(3, chunkManager.getChunkMap().size()); assertEquals(1, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusFourHoursSecs)); assertEquals(3, chunkManager.getChunkMap().size()); assertEquals(1, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusFourHoursSecs + DEFAULT_METRICS_DELAY_SECS)); assertEquals(3, chunkManager.getChunkMap().size()); assertEquals(2, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusSixHoursSecs)); assertEquals(3, chunkManager.getChunkMap().size()); assertEquals(2, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusSixHoursSecs + DEFAULT_METRICS_DELAY_SECS)); assertEquals(3, chunkManager.getChunkMap().size()); assertEquals(3, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusEightHoursSecs)); assertEquals(2, chunkManager.getChunkMap().size()); assertEquals(2, getReadOnlyChunkCount(chunkManager)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimeSecs, testValue)); assertEquals(3, chunkManager.getChunkMap().size()); assertEquals(2, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusEightHoursSecs + 2 * 3600)); assertEquals(1, chunkManager.getChunkMap().size()); assertEquals(1, getReadOnlyChunkCount(chunkManager)); offHeapChunkManagerTask.runAt(Instant.ofEpochSecond(startTimePlusEightHoursSecs + 4 * 3600)); assertTrue(chunkManager.getChunkMap().isEmpty()); assertEquals(0, getReadOnlyChunkCount(chunkManager)); } |
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>> readOnlyChunks = new ArrayList<>(); for (Map.Entry<Long, Chunk> chunkEntry: chunkManager.getChunkMap().entrySet()) { Chunk chunk = chunkEntry.getValue(); if (!chunk.isReadOnly() && offHeapCutoffSecs >= chunk.info().endTimeSecs) { readOnlyChunks.add(chunkEntry); } } LOG.info("Number of chunks past cut off: {}.", readOnlyChunks.size()); chunkManager.toReadOnlyChunks(readOnlyChunks); return readOnlyChunks.size(); } OffHeapChunkManagerTask(ChunkManager chunkManager); OffHeapChunkManagerTask(ChunkManager chunkManager,
int metricsDelaySecs,
int staleDataDelaySecs); @Override void run(); static final int DEFAULT_METRICS_DELAY_SECS; static final int DEFAULT_STALE_DATA_DELAY_SECS; } | @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()); assertEquals(1, offHeapChunkManagerTask.detectChunksPastCutOff(startTimeSecs + 3600 * 2)); assertEquals(1, chunkManager.getChunkMap().size()); assertEquals(1, getReadOnlyChunkCount(chunkManager)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimeSecs + 2, testValue * 2)); }
@Test(expected = IllegalArgumentException.class) public void testNegativeOffset() { offHeapChunkManagerTask.detectChunksPastCutOff(-1); }
@Test(expected = IllegalArgumentException.class) public void testZeroOffset() { offHeapChunkManagerTask.detectChunksPastCutOff(0); }
@Test public void testDetectChunksPastCutOff() { assertTrue(chunkManager.getChunkMap().isEmpty()); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff(startTimeSecs)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff(startTimeSecs + 1)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff(startTimeSecs + 3600 * 2)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff(startTimeSecs + 3600 * 3)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimeSecs + 1, testValue)); assertEquals(1, chunkManager.getChunkMap().size()); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff(startTimeSecs)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff(startTimeSecs + 1)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff(startTimeSecs + 3600 * 2 - 1)); assertEquals(1, offHeapChunkManagerTask.detectChunksPastCutOff(startTimeSecs + 3600 * 2)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff(startTimeSecs + 3600 * 2)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff(startTimeSecs + 3600 * 2 + 1)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimePlusTwoHoursSecs + 1, testValue)); assertEquals(2, chunkManager.getChunkMap().size()); assertEquals(1, getReadOnlyChunkCount(chunkManager)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff(startTimeSecs + 3600 * 3)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff(startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff( startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS + DEFAULT_METRICS_DELAY_SECS - 2)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff( startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS + DEFAULT_METRICS_DELAY_SECS - 1)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff( startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS + DEFAULT_METRICS_DELAY_SECS)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff( startTimeSecs + (2 * DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS) - 2)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff( startTimeSecs + (2 * DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS) - 1)); assertEquals(1, offHeapChunkManagerTask.detectChunksPastCutOff( startTimeSecs + (2 * DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS))); assertEquals(2, chunkManager.getChunkMap().size()); assertEquals(2, getReadOnlyChunkCount(chunkManager)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimePlusFourHoursSecs + 1, testValue)); assertEquals(3, chunkManager.getChunkMap().size()); assertEquals(2, getReadOnlyChunkCount(chunkManager)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff(startTimeSecs + 3600 * 3)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff(startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff( startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS + DEFAULT_METRICS_DELAY_SECS - 2)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff( startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS + DEFAULT_METRICS_DELAY_SECS - 1)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff( startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS + DEFAULT_METRICS_DELAY_SECS)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff( startTimeSecs + (2 * DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS) - 2)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff( startTimeSecs + (2 * DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS) - 1)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff( startTimeSecs + (2 * DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS))); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff( startTimeSecs + 5 * 3600)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff( startTimeSecs + (3 * DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS) - 2)); assertEquals(0, offHeapChunkManagerTask.detectChunksPastCutOff( startTimeSecs + (3 * DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS) - 1)); assertEquals(1, offHeapChunkManagerTask.detectChunksPastCutOff( startTimeSecs + (3 * DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS))); assertEquals(3, chunkManager.getChunkMap().size()); assertEquals(3, getReadOnlyChunkCount(chunkManager)); } |
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 ArrayList<>(); for (Map.Entry<Long, Chunk> chunkEntry: chunkManager.getChunkMap().entrySet()) { Chunk chunk = chunkEntry.getValue(); if (chunk.info().endTimeSecs <= staleDataCutoffSecs) { staleChunks.add(chunkEntry); } } LOG.info("Number of stale chunks is: {}.", staleChunks.size()); chunkManager.removeStaleChunks(staleChunks); return staleChunks.size(); } OffHeapChunkManagerTask(ChunkManager chunkManager); OffHeapChunkManagerTask(ChunkManager chunkManager,
int metricsDelaySecs,
int staleDataDelaySecs); @Override void run(); static final int DEFAULT_METRICS_DELAY_SECS; static final int DEFAULT_STALE_DATA_DELAY_SECS; } | @Test public void testDeleteStaleChunks() { assertTrue(chunkManager.getChunkMap().isEmpty()); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 1)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 * 2)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 * 3)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimeSecs + 1, testValue)); final List<TimeSeries> timeSeries = queryChunkManager(startTimeSecs, startTimeSecs + 3600 * 3); assertEquals(1, timeSeries.size()); assertEquals(1, chunkManager.getChunkMap().size()); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 1)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 - 1)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 + 1)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 * 2 - 1)); assertEquals(1, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 * 2)); assertTrue(chunkManager.getChunkMap().isEmpty()); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 1)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 * 2)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 * 3)); final List<TimeSeries> timeSeries2 = queryChunkManager(startTimeSecs, startTimeSecs + 3600 * 3); assertTrue(timeSeries2.isEmpty()); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimeSecs + 1, testValue)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimePlusTwoHoursSecs + 1, testValue)); assertEquals(2, chunkManager.getChunkMap().size()); final List<TimeSeries> timeSeries3 = queryChunkManager(startTimeSecs, startTimeSecs + 3600 * 3); assertEquals(1, timeSeries3.size()); assertEquals(2, chunkManager.getChunkMap().size()); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 1)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 - 1)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 + 1)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 * 2 - 1)); assertEquals(1, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 * 2)); assertEquals(1, chunkManager.getChunkMap().size()); chunkManager.getChunkMap() .forEach((k, v) -> assertEquals(startTimePlusTwoHoursSecs, k.longValue())); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 * 2 + 1)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 * 3 - 1)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 * 3)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 * 3 + 1)); assertEquals(0, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 * 4 - 1)); assertEquals(1, offHeapChunkManagerTask.deleteStaleChunks(startTimeSecs + 3600 * 4 + 1)); assertTrue(chunkManager.getChunkMap().isEmpty()); testDeleteMultipleChunks(0); testDeleteMultipleChunks(1); testDeleteMultipleChunks(2); testDeleteMultipleChunks(3); testDeleteMultipleChunks(4); } |
OffHeapChunkManagerTask implements Runnable { int deleteStaleData(Instant startInstant) { final long staleCutoffSecs = startInstant.minusSeconds(this.staleDataDelaySecs).getEpochSecond(); return deleteStaleChunks(staleCutoffSecs); } OffHeapChunkManagerTask(ChunkManager chunkManager); OffHeapChunkManagerTask(ChunkManager chunkManager,
int metricsDelaySecs,
int staleDataDelaySecs); @Override void run(); static final int DEFAULT_METRICS_DELAY_SECS; static final int DEFAULT_STALE_DATA_DELAY_SECS; } | @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)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimeSecs + 1, testValue)); final List<TimeSeries> timeSeries = queryChunkManager(startTimeSecs, startTimeSecs + 3600 * 3); assertEquals(1, timeSeries.size()); assertEquals(1, chunkManager.getChunkMap().size()); assertEquals(0, deleteStaleData(startTimeSecs)); assertEquals(0, deleteStaleData(startTimeSecs + 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 - 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 + 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 2 - 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 2)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 3)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 4)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 5)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 6)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 7)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 8 - 1)); assertEquals(1, deleteStaleData(startTimeSecs + 3600 * 8)); assertTrue(chunkManager.getChunkMap().isEmpty()); assertEquals(0, deleteStaleData(startTimeSecs)); assertEquals(0, deleteStaleData(startTimeSecs + 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 2)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 8)); final List<TimeSeries> timeSeries2 = queryChunkManager(startTimeSecs, startTimeSecs + 3600 * 3); assertTrue(timeSeries2.isEmpty()); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimeSecs + 1, testValue)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimePlusTwoHoursSecs + 1, testValue)); assertEquals(2, chunkManager.getChunkMap().size()); final List<TimeSeries> timeSeries3 = queryChunkManager(startTimeSecs, startTimeSecs + 3600 * 3); assertEquals(1, timeSeries3.size()); assertEquals(2, chunkManager.getChunkMap().size()); assertEquals(0, deleteStaleData(startTimeSecs)); assertEquals(0, deleteStaleData(startTimeSecs + 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 - 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 + 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 2 - 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 2)); assertEquals(1, deleteStaleData(startTimeSecs + 3600 * 8)); assertEquals(1, chunkManager.getChunkMap().size()); chunkManager.getChunkMap() .forEach((k, v) -> assertEquals(startTimePlusTwoHoursSecs, k.longValue())); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 2 + 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 3 - 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 3)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 3 + 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 4 - 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 4 + 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 6 - 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 6)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 8 - 1)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 8)); assertEquals(0, deleteStaleData(startTimeSecs + 3600 * 10 - 1)); assertEquals(1, deleteStaleData(startTimeSecs + 3600 * 10)); assertTrue(chunkManager.getChunkMap().isEmpty()); } |
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 expectedTagStoreSize, String dataDirectory); Chunk getChunk(long timestamp); void addMetric(final String metricString); List<TimeSeries> queryAroundChunkBoundaries(Query query, long startTsSecs,
long endTsSecs,
QueryAggregation queryAggregation); List<TimeSeries> query(Query query, long startTsSecs, long endTsSecs,
QueryAggregation queryAggregation); void toReadOnlyChunks(List<Map.Entry<Long, Chunk>> expiredChunks); void removeStaleChunks(List<Map.Entry<Long, Chunk>> staleChunks); static Duration DEFAULT_CHUNK_DURATION; } | @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, QueryAggregation.NONE).isEmpty()); } |
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 = new Metric(metricName, rawTags); long ts = Long.parseLong(metricParts[2].trim()); double value = Double.parseDouble(metricParts[3].trim()); Chunk chunk = getChunk(ts); if (!chunk.isReadOnly()) { chunk.addPoint(metric, ts, value); } else { throw new ReadOnlyChunkInsertionException("Inserting metric into a read only store:" + metricString); } } else { throw new IllegalArgumentException("Metric doesn't start with a put: " + metricString); } } catch (ReadOnlyChunkInsertionException re) { throw re; } catch (Exception e) { LOG.error("metric failed with exception: ", e); throw new IllegalArgumentException("Invalid metric string " + metricString, e); } } ChunkManager(String chunkDataPrefix, int expectedTagStoreSize); ChunkManager(String chunkDataPrefix, int expectedTagStoreSize, String dataDirectory); Chunk getChunk(long timestamp); void addMetric(final String metricString); List<TimeSeries> queryAroundChunkBoundaries(Query query, long startTsSecs,
long endTsSecs,
QueryAggregation queryAggregation); List<TimeSeries> query(Query query, long startTsSecs, long endTsSecs,
QueryAggregation queryAggregation); void toReadOnlyChunks(List<Map.Entry<Long, Chunk>> expiredChunks); void removeStaleChunks(List<Map.Entry<Long, Chunk>> staleChunks); static Duration DEFAULT_CHUNK_DURATION; } | @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 testMetricInvalidTs() { String metric = "put a.b.c.d-e 1465530393a 0"; chunkManager.addMetric(metric); }
@Test(expected = IllegalArgumentException.class) public void testMetricInvalidValue() { String metric = "put a.b.c.d-e 1465530393 a0"; chunkManager.addMetric(metric); }
@Test(expected = IllegalArgumentException.class) public void testMetricInvalidTag() { String metric = "put a.b.c.d-e 1465530393 0 a"; chunkManager.addMetric(metric); }
@Test(expected = IllegalArgumentException.class) public void testMissingMetricName() { String metric = "put 1465530393 0"; chunkManager.addMetric(metric); }
@Test(expected = IllegalArgumentException.class) public void testMissingValue() { String metric = "put a.b 1465530393 c=d"; chunkManager.addMetric(metric); }
@Test(expected = IllegalArgumentException.class) public void testMissingTs() { String metric = "put a.b 5.1 c=d"; chunkManager.addMetric(metric); } |
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(entry.getKey())) { final Chunk chunk = entry.getValue(); String chunkInfo = chunk.info().toString(); LOG.info("Deleting chunk {}.", chunkInfo); synchronized (chunkMapSync) { chunkMap.remove(entry.getKey()); } chunk.close(); LOG.info("Deleted chunk {}.", chunkInfo); } else { LOG.warn("Possible bug or race condition! Chunk {} doesn't exist in chunk map {}.", entry, chunkMap); } } catch (Exception e) { LOG.error("Exception when deleting chunk.", e); } }); } ChunkManager(String chunkDataPrefix, int expectedTagStoreSize); ChunkManager(String chunkDataPrefix, int expectedTagStoreSize, String dataDirectory); Chunk getChunk(long timestamp); void addMetric(final String metricString); List<TimeSeries> queryAroundChunkBoundaries(Query query, long startTsSecs,
long endTsSecs,
QueryAggregation queryAggregation); List<TimeSeries> query(Query query, long startTsSecs, long endTsSecs,
QueryAggregation queryAggregation); void toReadOnlyChunks(List<Map.Entry<Long, Chunk>> expiredChunks); void removeStaleChunks(List<Map.Entry<Long, Chunk>> staleChunks); static Duration DEFAULT_CHUNK_DURATION; } | @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().isEmpty()); chunkManager.removeStaleChunks(Collections.emptyList()); chunkManager.removeStaleChunks(Collections.singletonList(fakeMapEntry)); assertTrue(chunkManager.getChunkMap().isEmpty()); chunkManager.addMetric(MetricUtils .makeMetricString(testMetricName, inputTagString, startTime + 1, testValue)); assertEquals(1, chunkManager.getChunkMap().size()); ArrayList<Map.Entry<Long, Chunk>> chunks = new ArrayList<>(chunkManager.getChunkMap().entrySet()); chunkManager.removeStaleChunks(chunks); assertTrue(chunkManager.getChunkMap().isEmpty()); chunkManager.addMetric(MetricUtils .makeMetricString(testMetricName, inputTagString, startTime + 1, testValue)); chunkManager.addMetric(MetricUtils .makeMetricString(testMetricName, inputTagString, startTimePlusTwoHours + 1, testValue)); assertEquals(2, chunkManager.getChunkMap().size()); ArrayList<Map.Entry<Long, Chunk>> chunks2 = new ArrayList<>(chunkManager.getChunkMap().entrySet()); chunkManager.removeStaleChunks(chunks2); assertTrue(chunkManager.getChunkMap().isEmpty()); chunkManager.addMetric(MetricUtils .makeMetricString(testMetricName, inputTagString, startTime + 1, testValue)); chunkManager.addMetric(MetricUtils .makeMetricString(testMetricName, inputTagString, startTimePlusTwoHours, testValue)); chunkManager.addMetric(MetricUtils .makeMetricString(testMetricName, inputTagString, startTimePlusFourHours, testValue)); assertEquals(3, chunkManager.getChunkMap().size()); ArrayList<Map.Entry<Long, Chunk>> chunks3 = new ArrayList<>(); for (Map.Entry<Long, Chunk> entry : chunkManager.getChunkMap().entrySet()) { if (entry.getKey() < startTimePlusFourHours) { chunks3.add(entry); } } chunkManager.removeStaleChunks(chunks3); assertEquals(1, chunkManager.getChunkMap().size()); assertEquals(startTimePlusFourHours, chunkManager.getChunkMap().get(startTimePlusFourHours).info().startTimeSecs); chunkManager.removeStaleChunks(Collections.singletonList(fakeMapEntry)); assertEquals(1, chunkManager.getChunkMap().size()); assertEquals(startTimePlusFourHours, chunkManager.getChunkMap().get(startTimePlusFourHours).info().startTimeSecs); chunkManager.removeStaleChunks(Collections.emptyList()); assertEquals(1, chunkManager.getChunkMap().size()); assertEquals(startTimePlusFourHours, chunkManager.getChunkMap().get(startTimePlusFourHours).info().startTimeSecs); } |
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 metricIdMapCapacity, int initialIndexSize); InvertedIndexTagStore(int metricIdMapCapacity, int initialIndexSize,
String dataDirectory); InvertedIndexTagStore(int metricIdMapCapacity, int initialIndexSize,
String dataDirectory, boolean useOffHeapIdStore,
boolean useOffHeapIndexStore); @Override Optional<Integer> get(Metric m); @Override List<Integer> lookup(Query q); RoaringBitmap lookupMetricIndex(String key); @VisibleForTesting Map<Integer, String> getValuesForMetricKey(String metricName, String key); @Override int getOrCreate(final Metric m); @Override String getMetricName(final int metricId); @Override Map<String, Object> getStats(); @Override void close(); @Override boolean isReadOnly(); String getMetricNameFromId(final int id); } | @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 Metric(METRIC2, Collections.singletonList("k1=v2")))); ids.add(store.getOrCreate(new Metric(METRIC2, Arrays.asList("k1=v1", "k2=v1")))); ids.add(store.getOrCreate(new Metric(METRIC3, emptyList()))); assertEquals(6, ids.size()); Set<Integer> deduped = new HashSet<>(ids); assertEquals(deduped.size(), ids.size()); assertEquals(ids.get(0), store.get(new Metric(METRIC1, Collections.singletonList("k1=v1"))).get()); assertEquals(ids.get(1), store.get(new Metric(METRIC2, Collections.singletonList("k1=v1"))).get()); assertEquals(ids.get(2), store.get(new Metric(METRIC1, Collections.singletonList("k1=v2"))).get()); assertEquals(ids.get(3), store.get(new Metric(METRIC2, Collections.singletonList("k1=v2"))).get()); assertEquals(ids.get(4), store.get(new Metric(METRIC2, Arrays.asList("k1=v1", "k2=v1"))).get()); assertEquals(ids.get(4), store.get(new Metric(METRIC2, Arrays.asList("k2=v1", "k1=v1"))).get()); assertEquals(ids.get(5), store.get(new Metric(METRIC3, emptyList())).get()); } |
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); InvertedIndexTagStore(int metricIdMapCapacity, int initialIndexSize,
String dataDirectory); InvertedIndexTagStore(int metricIdMapCapacity, int initialIndexSize,
String dataDirectory, boolean useOffHeapIdStore,
boolean useOffHeapIndexStore); @Override Optional<Integer> get(Metric m); @Override List<Integer> lookup(Query q); RoaringBitmap lookupMetricIndex(String key); @VisibleForTesting Map<Integer, String> getValuesForMetricKey(String metricName, String key); @Override int getOrCreate(final Metric m); @Override String getMetricName(final int metricId); @Override Map<String, Object> getStats(); @Override void close(); @Override boolean isReadOnly(); String getMetricNameFromId(final int id); } | @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 wildcardMatch(String key, String wildcardString); static TagMatcher iwildcardMatch(String key, String wildcardString); static TagMatcher literalOrMatch(String key, String orLiteralString,
boolean caseInsensitive); static TagMatcher notLiteralOrMatch(String key, String orLiteralString,
boolean caseInsensitive); static TagMatcher regExMatch(String key, String regExString); @Override String toString(); static final String WILDCARD; final MatchType type; final Tag tag; } | @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.type); } |
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(key, value, rawTag); } Tag(String key, String value, String rawTag); Tag(String key, String value); @Override int compareTo(Tag o); @Override boolean equals(Object o); @Override int hashCode(); static Tag parseTag(String rawTag); final String rawTag; final String key; final String value; } | @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); assertEquals("v=1", t1.value); assertEquals("k=v=1", t1.rawTag); } |
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 -> new SimpleEntry<>(t.tag.key, t)) .collect(groupingBy(Entry::getKey, mapping(Entry::getValue, toList()))); tagNameMap.entrySet().forEach(tagKeyEntry -> { if (tagKeyEntry.getValue().size() != 1) { throw new IllegalArgumentException("Only one tagFilter is allowed per tagKey: " + tagKeyEntry.getKey() + " .But we found " + tagKeyEntry.getValue().toString()); } }); this.metricName = metricName; this.tagMatchers = tagMatchers; } Query(final String metricName, final List<TagMatcher> tagMatchers); static Query parse(String s); @Override String toString(); final String metricName; final List<TagMatcher> tagMatchers; } | @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 q2 = Query.parse("metric k1=v1"); assertEquals(metric, q2.metricName); assertEquals(1, q2.tagMatchers.size()); assertEquals(new TagMatcher(MatchType.EXACT, new Tag("k1", "v1", "k1=v1")), q2.tagMatchers.get(0)); Query q3 = Query.parse("metric k1=v1 k2=v2"); assertEquals(metric, q3.metricName); assertEquals(2, q3.tagMatchers.size()); assertEquals(new TagMatcher(MatchType.EXACT, new Tag("k1", "v1", "k1=v1")), q3.tagMatchers.get(0)); assertEquals(new TagMatcher(MatchType.EXACT, new Tag("k2", "v2", "k2=v2")), q3.tagMatchers.get(1)); Query q4 = Query.parse("metric k1=*"); assertEquals(metric, q4.metricName); assertEquals(1, q4.tagMatchers.size()); assertEquals(new TagMatcher(MatchType.WILDCARD, new Tag("k1", "*")), q4.tagMatchers.get(0)); Query q5 = Query.parse("metric k1=* k2=v1"); assertEquals(metric, q5.metricName); assertEquals(2, q5.tagMatchers.size()); assertEquals(new TagMatcher(MatchType.WILDCARD, new Tag("k1", "*")), q5.tagMatchers.get(0)); assertEquals(new TagMatcher(MatchType.EXACT, new Tag("k2", "v1", "k2=v1")), q5.tagMatchers.get(1)); } |
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.wildcardMatch(tag.key, "*")); } else { matchers.add(TagMatcher.exactMatch(tag)); } } return new Query(metricName, matchers); } Query(final String metricName, final List<TagMatcher> tagMatchers); static Query parse(String s); @Override String toString(); final String metricName; final List<TagMatcher> tagMatchers; } | @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.deserialize(serializedValues); return iterator.getPoints(); } else { return Collections.emptyList(); } } OffHeapVarBitMetricStore(long size, String chunkInfo); OffHeapVarBitMetricStore(long size, int valueSize, String chunkInfo); OffHeapVarBitMetricStore(long size, int valueSize, String chunkInfo, String dir); @Override List<Point> getSeries(long uuid); static OffHeapVarBitMetricStore toOffHeapStore(Map<Long, VarBitTimeSeries> timeSeriesMap,
String chunkInfo, String dataDirectory); void addPoint(long uuid, ByteBuffer series); @Override void addPoint(long uuid, long ts, double val); @Override Map<String, Object> getStats(); @Override Map getSeriesMap(); @Override void close(); @Override boolean isReadOnly(); @Override void setReadOnly(boolean readOnly); } | @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, String chunkInfo); OffHeapVarBitMetricStore(long size, int valueSize, String chunkInfo, String dir); @Override List<Point> getSeries(long uuid); static OffHeapVarBitMetricStore toOffHeapStore(Map<Long, VarBitTimeSeries> timeSeriesMap,
String chunkInfo, String dataDirectory); void addPoint(long uuid, ByteBuffer series); @Override void addPoint(long uuid, long ts, double val); @Override Map<String, Object> getStats(); @Override Map getSeriesMap(); @Override void close(); @Override boolean isReadOnly(); @Override void setReadOnly(boolean readOnly); } | @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, value); } size++; } VarBitTimeSeries(); synchronized void append(long timestamp, double value); synchronized TimeSeriesIterator read(); Map<String, Double> getStats(); int getSerializedByteSize(); void serialize(ByteBuffer buffer); static TimeSeriesIterator deserialize(final ByteBuffer buffer); static final long MAX_UNIX_TIMESTAMP; static final int BLOCK_HEADER_OFFSET_SECS; static final short DEFAULT_TIMESTAMP_BITSTREAM_SIZE; static final short DEFAULT_VALUE_BITSTREAM_SIZE; } | @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); }
@Test(expected = IllegalArgumentException.class) public void testTimestampEncodingOverflow() { VarBitTimeSeries series = new VarBitTimeSeries(); int i = 10; long ts1 = 1477678600L; long ts2 = 14776780L; long ts3 = 1477678580L; series.append(ts1, i); series.append(ts2, i); series.append(ts3, i); } |
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 getSerializedByteSize(); void serialize(ByteBuffer buffer); static TimeSeriesIterator deserialize(final ByteBuffer buffer); static final long MAX_UNIX_TIMESTAMP; static final int BLOCK_HEADER_OFFSET_SECS; static final short DEFAULT_TIMESTAMP_BITSTREAM_SIZE; static final short DEFAULT_VALUE_BITSTREAM_SIZE; } | @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(); VarBitMetricStore(int initialSize); @Override List<Point> getSeries(long uuid); @Override void addPoint(long uuid, long ts, double val); @Override Map<String, Object> getStats(); @Override Map getSeriesMap(); @Override void close(); void setReadOnly(boolean readOnly); @Override boolean isReadOnly(); } | @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.endTimeSecs <= endTs); } ChunkImpl(MetricAndTagStore store, ChunkInfo chunkInfo); @Override List<TimeSeries> query(Query query); @Override void addPoint(Metric metric, long ts, double value); @Override ChunkInfo info(); @Override boolean isReadOnly(); @Override boolean containsDataInTimeRange(long startTs, long endTs); @Override Map<String, Object> getStats(); @Override void close(); @Override void setReadOnly(boolean readOnly); MetricAndTagStore getStore(); @Override String toString(); } | @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 - 1)); assertTrue(chunk.containsDataInTimeRange(startTime, endTime)); assertTrue(chunk.containsDataInTimeRange(startTime, endTime - 1)); assertTrue(chunk.containsDataInTimeRange(startTime, endTime + 1)); assertTrue(chunk.containsDataInTimeRange(startTime + 1, endTime)); assertTrue(chunk.containsDataInTimeRange(startTime - 1, endTime)); assertFalse(chunk.containsDataInTimeRange(startTime - 10000, endTime - 10000)); assertFalse(chunk.containsDataInTimeRange(startTime + 10000, endTime + 10000)); } |
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(); @Override boolean isReadOnly(); @Override boolean containsDataInTimeRange(long startTs, long endTs); @Override Map<String, Object> getStats(); @Override void close(); @Override void setReadOnly(boolean readOnly); MetricAndTagStore getStore(); @Override String toString(); } | @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, inputTagString, testTs, testValue), chunk); assertTrue(chunk.query(Query.parse("test")).isEmpty()); assertTrue(chunk.query(Query.parse("test host=h1")).isEmpty()); assertTrue(chunk.query(Query.parse("test host=h1 dc=dc1")).isEmpty()); final List<TimeSeries> series1 = chunk.query(Query.parse(testMetricName1 + queryTagString)); assertEquals(1, series1.size()); assertEquals(expectedMetricName1, series1.get(0).getMetric()); assertEquals(1, series1.get(0).getPoints().size()); Assert.assertThat(series1.get(0).getPoints(), IsIterableContainingInOrder.contains(new Point(testTs, testValue))); parseAndAddOpenTSDBMetric( makeMetricString(testMetricName1, inputTagString, testTs * 2, testValue * 2), chunk); assertTrue(chunk.query(Query.parse("test")).isEmpty()); assertTrue(chunk.query(Query.parse("test host=h1")).isEmpty()); assertTrue(chunk.query(Query.parse("test host=h1 dc=dc1")).isEmpty()); final List<TimeSeries> series2 = chunk.query(Query.parse(testMetricName1 + queryTagString)); assertEquals(1, series2.size()); assertEquals(expectedMetricName1, series2.get(0).getMetric()); assertEquals(2, series2.get(0).getPoints().size()); List<Point> expectedPoints2 = Arrays.asList(new Point(testTs, testValue), new Point(testTs * 2, testValue * 2)); final TimeSeries timeseries12 = new TimeSeries(expectedMetricName1, expectedPoints2); Assert.assertThat(series2, IsIterableContainingInOrder.contains(timeseries12)); final String testMetricName2 = "testMetric2"; final String expectedMetricName2 = testMetricName2 + " dc=dc1 host=h1"; parseAndAddOpenTSDBMetric( makeMetricString(testMetricName2, inputTagString, testTs * 3, testValue * 3), chunk); assertTrue(chunk.query(Query.parse("test")).isEmpty()); assertTrue(chunk.query(Query.parse("test host=h1")).isEmpty()); assertTrue(chunk.query(Query.parse("test host=h1 dc=dc1")).isEmpty()); final Point point21 = new Point(testTs * 3, testValue * 3); Assert.assertThat(chunk.query(Query.parse(testMetricName2 + queryTagString)), IsIterableContainingInOrder.contains(new TimeSeries(expectedMetricName2, Collections.singletonList(point21)))); Assert.assertThat(chunk.query(Query.parse(testMetricName1 + queryTagString)), IsIterableContainingInOrder.contains(timeseries12)); parseAndAddOpenTSDBMetric( makeMetricString(testMetricName2, inputTagString, testTs * 3, testValue * 3), chunk); List<Point> expectedPoints4 = Arrays.asList(point21, point21); Assert.assertThat(chunk.query(Query.parse(testMetricName2 + queryTagString)), IsIterableContainingInOrder.contains(new TimeSeries(expectedMetricName2, expectedPoints4))); Assert.assertThat(chunk.query(Query.parse(testMetricName1 + queryTagString)), IsIterableContainingInOrder.contains(timeseries12)); parseAndAddOpenTSDBMetric( makeMetricString(testMetricName2, inputTagString, testTs * 4, testValue * 4), chunk); List<Point> expectedPoints5 = Arrays.asList(point21, point21, new Point(testTs * 4, testValue * 4)); Assert.assertThat(chunk.query(Query.parse(testMetricName2 + queryTagString)), IsIterableContainingInOrder.contains(new TimeSeries(expectedMetricName2, expectedPoints5))); Assert.assertThat(chunk.query(Query.parse(testMetricName1 + queryTagString)), IsIterableContainingInOrder.contains(timeseries12)); assertTrue(chunk.query(Query.parse("test")).isEmpty()); assertTrue(chunk.query(Query.parse("test host=h1")).isEmpty()); assertTrue(chunk.query(Query.parse("test host=h1 dc=dc1")).isEmpty()); }
@Test public void testMultipleTimeSeriesResponse() { setUp(); final String testMetricName1 = "testMetric1"; final List<String> testTags1 = Arrays.asList("host=h1", "dc=dc1"); final List<String> testTags2 = Arrays.asList("host=h2", "dc=dc1"); assertTrue(chunk.query(new Query("test", Collections.emptyList())).isEmpty()); parseAndAddOpenTSDBMetric( makeMetricString(testMetricName1, "host=h1 dc=dc1", testTs, testValue), chunk); parseAndAddOpenTSDBMetric( makeMetricString(testMetricName1, "host=h2 dc=dc1", testTs, testValue), chunk); Point p1 = new Point(testTs, testValue); Assert.assertThat(chunk.query(Query.parse(testMetricName1 + " dc=dc1")), IsIterableContainingInOrder.contains( new TimeSeries(testMetricName1 + " dc=dc1 host=h1", Collections.singletonList(p1)), new TimeSeries(testMetricName1 + " dc=dc1 host=h2", Collections.singletonList(p1)))); } |
OffHeapChunkManagerTask implements Runnable { @VisibleForTesting int detectReadOnlyChunks(Instant startInstant) { int secondsToSubtract = this.metricsDelay; final long offHeapCutoffSecs = startInstant.minusSeconds(secondsToSubtract).getEpochSecond(); return detectChunksPastCutOff(offHeapCutoffSecs); } OffHeapChunkManagerTask(ChunkManager chunkManager); OffHeapChunkManagerTask(ChunkManager chunkManager,
int metricsDelaySecs,
int staleDataDelaySecs); @Override void run(); static final int DEFAULT_METRICS_DELAY_SECS; static final int DEFAULT_STALE_DATA_DELAY_SECS; } | @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, detectReadOnlyChunks(startTimeSecs + 3600 * 3)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimeSecs + 1, testValue)); assertEquals(1, chunkManager.getChunkMap().size()); assertEquals(0, detectReadOnlyChunks(startTimeSecs)); assertEquals(0, detectReadOnlyChunks(startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS - 1)); assertEquals(0, detectReadOnlyChunks(startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS)); assertEquals(0, detectReadOnlyChunks(startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS + 1)); assertEquals(0, detectReadOnlyChunks(startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS + DEFAULT_METRICS_DELAY_SECS - 1)); assertEquals(1, detectReadOnlyChunks(startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS + DEFAULT_METRICS_DELAY_SECS)); assertEquals(1, chunkManager.getChunkMap().size()); assertEquals(1, getReadOnlyChunkCount(chunkManager)); assertEquals(0, detectReadOnlyChunks(startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS + DEFAULT_METRICS_DELAY_SECS + 1)); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimePlusTwoHoursSecs + 1, testValue)); assertEquals(2, chunkManager.getChunkMap().size()); assertEquals(0, detectReadOnlyChunks(startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS + DEFAULT_METRICS_DELAY_SECS)); assertEquals(0, detectReadOnlyChunks(startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS + DEFAULT_METRICS_DELAY_SECS + 3600)); assertEquals(1, detectReadOnlyChunks(startTimeSecs + 2 * DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS + DEFAULT_METRICS_DELAY_SECS)); assertEquals(2, getReadOnlyChunkCount(chunkManager)); assertEquals(2, chunkManager.getChunkMap().size()); chunkManager.addMetric(MetricUtils.makeMetricString( testMetricName, inputTagString1, startTimePlusFourHoursSecs + 1, testValue)); assertEquals(3, chunkManager.getChunkMap().size()); assertEquals(0, detectReadOnlyChunks(startTimeSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS + DEFAULT_METRICS_DELAY_SECS)); assertEquals(0, detectReadOnlyChunks(startTimePlusTwoHoursSecs + DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS + DEFAULT_METRICS_DELAY_SECS)); assertEquals(0, detectReadOnlyChunks(startTimeSecs + (2 * DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS) + DEFAULT_METRICS_DELAY_SECS)); assertEquals(1, detectReadOnlyChunks(startTimeSecs + (3 * DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS) + DEFAULT_METRICS_DELAY_SECS)); assertEquals(3, getReadOnlyChunkCount(chunkManager)); assertEquals(3, chunkManager.getChunkMap().size()); assertEquals(0, detectReadOnlyChunks(startTimeSecs + (3 * DEFAULT_CHUNK_READ_ONLY_THRESHOLD_SECS) + DEFAULT_METRICS_DELAY_SECS)); } |
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(); etcdClient.getKVClient() .put(fromString(etcdKey), fromString(objectMapper.writeValueAsString(registration)), putOption) .get(); } catch (JsonProcessingException | InterruptedException | ExecutionException e) { throw new EtcdOperationException(e); } } @Override void register(EtcdRegistration registration); @Override void deregister(EtcdRegistration registration); @Override void close(); @Override void setStatus(EtcdRegistration registration, String status); @Override Object getStatus(EtcdRegistration registration); } | @Test public void testRegister() throws ExecutionException, InterruptedException, JsonProcessingException { Client client = Client.builder() .endpoints(container.clientEndpoint()) .build(); HeartbeatProperties heartbeatProperties = new HeartbeatProperties(); heartbeatProperties.setInterval(5); EtcdHeartbeatLease heartbeatLease = new EtcdHeartbeatLease(client, heartbeatProperties); EtcdDiscoveryProperties discoveryProperties = new EtcdDiscoveryProperties(); EtcdServiceRegistry registry = new EtcdServiceRegistry(client, discoveryProperties, heartbeatLease); EtcdRegistration registration = new EtcdRegistration( "test-app", "127.0.0.1", 8080 ); String key = registration.etcdKey(discoveryProperties.getPrefix()); registry.register(registration); Long leaseId = heartbeatLease.getLeaseId(); assertNotNull(leaseId); LeaseTimeToLiveResponse leaseTimeToLiveResponse = client.getLeaseClient().timeToLive(leaseId, LeaseOption.newBuilder().withAttachedKeys().build()).get(); Thread.sleep(10); assertEquals(leaseTimeToLiveResponse.getGrantedTTL(), heartbeatProperties.getInterval()); assertTrue(leaseTimeToLiveResponse.getTTl() > 0); assertTrue(leaseTimeToLiveResponse.getTTl() < heartbeatProperties.getInterval()); List<ByteSequence> keys = leaseTimeToLiveResponse.getKeys(); assertEquals(keys.size(), 1); assertEquals(keys.get(0).toStringUtf8(), key); GetResponse getResponse = client.getKVClient().get(fromString(key)).get(); assertEquals(getResponse.getCount(), 1); assertEquals(getResponse.getKvs().get(0).getValue().toStringUtf8(), objectMapper.writeValueAsString(registration)); } |
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 | ExecutionException e) { throw new EtcdOperationException(e); } } @Override void register(EtcdRegistration registration); @Override void deregister(EtcdRegistration registration); @Override void close(); @Override void setStatus(EtcdRegistration registration, String status); @Override Object getStatus(EtcdRegistration registration); } | @Test public void testDeregister() throws ExecutionException, InterruptedException, JsonProcessingException { Client client = Client.builder() .endpoints(container.clientEndpoint()) .build(); HeartbeatProperties heartbeatProperties = new HeartbeatProperties(); heartbeatProperties.setInterval(5); EtcdHeartbeatLease heartbeatLease = new EtcdHeartbeatLease(client, heartbeatProperties); EtcdDiscoveryProperties discoveryProperties = new EtcdDiscoveryProperties(); EtcdServiceRegistry registry = new EtcdServiceRegistry(client, discoveryProperties, heartbeatLease); EtcdRegistration registration = new EtcdRegistration( "test-app", "127.0.0.1", 8080 ); String key = registration.etcdKey(discoveryProperties.getPrefix()); registry.register(registration); Long leaseId = heartbeatLease.getLeaseId(); assertNotNull(leaseId); LeaseTimeToLiveResponse leaseTimeToLiveResponse = client.getLeaseClient().timeToLive(leaseId, LeaseOption.newBuilder().withAttachedKeys().build()).get(); Thread.sleep(10); assertEquals(leaseTimeToLiveResponse.getGrantedTTL(), heartbeatProperties.getInterval()); assertTrue(leaseTimeToLiveResponse.getTTl() > 0); assertTrue(leaseTimeToLiveResponse.getTTl() < heartbeatProperties.getInterval()); List<ByteSequence> keys = leaseTimeToLiveResponse.getKeys(); assertEquals(keys.size(), 1); assertEquals(keys.get(0).toStringUtf8(), key); GetResponse getResponse = client.getKVClient().get(fromString(key)).get(); assertEquals(getResponse.getCount(), 1); assertEquals(getResponse.getKvs().get(0).getValue().toStringUtf8(), objectMapper.writeValueAsString(registration)); registry.deregister(registration); leaseTimeToLiveResponse = client.getLeaseClient().timeToLive(leaseId, LeaseOption.newBuilder().withAttachedKeys().build()).get(); assertEquals(leaseTimeToLiveResponse.getGrantedTTL(), 0); assertEquals(leaseTimeToLiveResponse.getTTl(), -1); getResponse = client.getKVClient().get(fromString(key)).get(); assertEquals(getResponse.getCount(), 0); } |
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 = new EtcdHeartbeatLease(client, heartbeatProperties); Long leaseId = heartbeatLease.getLeaseId(); assertNotNull(leaseId); LeaseTimeToLiveResponse leaseTimeToLiveResponse = client.getLeaseClient().timeToLive(leaseId, LeaseOption.DEFAULT).get(); Thread.sleep(10); assertEquals(leaseTimeToLiveResponse.getGrantedTTL(), heartbeatProperties.getInterval()); assertTrue(leaseTimeToLiveResponse.getTTl() > 0); assertTrue(leaseTimeToLiveResponse.getTTl() < heartbeatProperties.getInterval()); } |
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 final byte INS_CREDIT; static final byte INS_DEBIT; static final short MAX_BALANCE; static final short MAX_CREDIT; static final short MAX_DEBIT; } | @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_CREDIT, getBalance().getData()); }
@Test public void balanceOverflowTest() throws CardException { sendCredit(MAX_CREDIT, 0x9000, MAX_CREDIT); sendCredit(MAX_CREDIT, 0x9000, TestUtils.getByte(TestUtils.getInt(MAX_CREDIT) * 2)); sendCredit(new byte[]{0x00, 0x01}, ISO7816.SW_WRONG_DATA, new byte[]{}); assertArrayEquals(MAX_BALANCE, getBalance().getData()); }
@Test public void debitNegativeTest() throws CardException { sendCredit(new byte[]{0x00, 0x05}, 0x9000, new byte[]{0x00, 0x05}); assertArrayEquals(new byte[]{0x00, 0x05}, getBalance().getData()); sendDebit(new byte[]{0x00, 0x06}, ISO7816.SW_WRONG_DATA, new byte[]{}); assertArrayEquals(new byte[]{0x00, 0x05}, getBalance().getData()); }
@Test public void debitOverflowTest() throws CardException { sendDebit(new byte[]{0x00, 0x01}, ISO7816.SW_WRONG_DATA, new byte[]{}); assertArrayEquals(new byte[]{0x00, 0x00}, getBalance().getData()); } |
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)) ISOException.throwIt(ISO7816.SW_WRONG_DATA); balance += credit; getBalance(apdu, buffer); } private Counter(); static void install(byte[] buffer, short offset, byte length); void process(APDU apdu); static final byte INS_GET_BALANCE; static final byte INS_CREDIT; static final byte INS_DEBIT; static final short MAX_BALANCE; static final short MAX_CREDIT; static final short MAX_DEBIT; } | @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_WRONG_DATA); balance -= debit; getBalance(apdu, buffer); } private Counter(); static void install(byte[] buffer, short offset, byte length); void process(APDU apdu); static final byte INS_GET_BALANCE; static final byte INS_CREDIT; static final byte INS_DEBIT; static final short MAX_BALANCE; static final short MAX_CREDIT; static final short MAX_DEBIT; } | @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(); void setId(byte[] buf, short ofs, byte len); void setUserName(byte[] buf, short ofs, byte len); void setPassword(byte[] buf, short ofs, byte len); static short SIZE_ID; static short SIZE_USERNAME; static short SIZE_PASSWORD; } | @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(Map<String, Object> source, String memberName); @Override Collection<String> memberNames(Map<String, Object> source); } | @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, String>>> map = modelMapper.map(order, LinkedHashMap.class); modelMapper.validate(); assertEquals(map.get("customer").get("address").get("city"), order.customer.address.city); assertEquals(map.get("customer").get("address").get("street"), order.customer.address.street); } |
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 numberFor((Number) source, destinationType); if (source instanceof Boolean) return numberFor(((Boolean) source).booleanValue() ? 1 : 0, destinationType); if (source instanceof Date && Long.class.equals(destinationType)) return Long.valueOf(((Date) source).getTime()); if (source instanceof Calendar && Long.class.equals(destinationType)) return Long.valueOf(((Calendar) source).getTime().getTime()); if (source instanceof XMLGregorianCalendar && Long.class.equals(destinationType)) return ((XMLGregorianCalendar) source).toGregorianCalendar().getTimeInMillis(); return numberFor(source.toString(), destinationType); } Number convert(MappingContext<Object, Number> context); MatchResult match(Class<?> sourceType, Class<?> destinationType); } | @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(), number.longValue()); } for (int i = 0; i < types.length; i++) convert("12x", (Class<?>) types[i][0]); }
@Test(expectedExceptions = MappingException.class, dataProvider = "numbersProvider") public void shouldFailOnInvalidDestinationType(Number number) { convert(number, Object.class); }
@Test public void shouldConvertDateToLong() { Date dateValue = new Date(); assertEquals(new Long(dateValue.getTime()), convert(dateValue, Long.class)); }
@Test public void shouldConvertXmlGregorianCalendarToLong() throws DatatypeConfigurationException { XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar()); assertEquals(xmlGregorianCalendar.toGregorianCalendar().getTimeInMillis(), convert(xmlGregorianCalendar, Long.class)); }
@Test(expectedExceptions = MappingException.class) public void shouldThrowOnMapCalendarToInteger() { convert(Calendar.getInstance(), Integer.class); }
@Test(expectedExceptions = MappingException.class) public void shouldThrowOnMapDateToInteger() { convert(new Date(), Integer.class); }
@Test(expectedExceptions = MappingException.class) public void shouldThrowOnNotANumber() { convert("XXXX", Integer.class); }
@Test(dataProvider = "typesProvider") public void testBooleanToNumber(Class<?> type) { assertEquals(0, ((Number) convert(Boolean.FALSE, type)).intValue()); assertEquals(1, ((Number) convert(Boolean.TRUE, type)).intValue()); }
@Test(dataProvider = "typesProvider") public void testConvertNumber(Class<?> type) { Object[] number = { new Byte((byte) 7), new Short((short) 8), new Integer(9), new Long(10), new Float(11.1), new Double(12.2), new BigDecimal("17.2"), new BigInteger("33") }; for (int i = 0; i < number.length; i++) { Object val = convert(number[i], type); assertNotNull(val); assertTrue(type.isInstance(val)); } } |
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 < TRUE_STRINGS.length; i++) if (TRUE_STRINGS[i].equals(stringValue)) return Boolean.TRUE; for (int i = 0; i < FALSE_STRINGSS.length; i++) if (FALSE_STRINGSS[i].equals(stringValue)) return Boolean.FALSE; throw new Errors().errorMapping(context.getSource(), context.getDestinationType()) .toMappingException(); } Boolean convert(MappingContext<Object, Boolean> context); MatchResult match(Class<?> sourceType, Class<?> destinationType); } | @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, Object js1, Fn.Ref id2, Object js2); } | @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); } return (Character)val; } private JSON(); static Transfer findTransfer(BrwsrCtx c); static WSTransfer<?> findWSTransfer(BrwsrCtx c); static void readBindings(BrwsrCtx c, M model, Object value); static void extract(BrwsrCtx c, Object value, String[] props, Object[] values); static String toJSON(Object value); static String toString(BrwsrCtx c, Object obj, String prop); static Number toNumber(BrwsrCtx c, Object obj, String prop); static M toModel(BrwsrCtx c, Class<M> aClass, Object data, Object object); static boolean isSame(int a, int b); static boolean isSame(double a, double b); static boolean isSame(Object a, Object b); static int hashPlus(Object o, int h); static T extractValue(Class<T> type, Object val); static String stringValue(Object val); static Number numberValue(Object val); static Character charValue(Object val); static Boolean boolValue(Object val); static Object find(Object object, Bindings model); static Object find(Object object); static void applyBindings(Object object, String id); static void register(Class c, Proto.Type<?> type); static boolean isModel(Class<?> clazz); static Model bindTo(Model model, BrwsrCtx c); static T readStream(BrwsrCtx c, Class<T> modelClazz, InputStream data, Collection<? super T> collectTo); static T read(BrwsrCtx c, Class<T> modelClazz, Object data); } | @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.charValue(65), Character.valueOf('A')); } |
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<?> findWSTransfer(BrwsrCtx c); static void readBindings(BrwsrCtx c, M model, Object value); static void extract(BrwsrCtx c, Object value, String[] props, Object[] values); static String toJSON(Object value); static String toString(BrwsrCtx c, Object obj, String prop); static Number toNumber(BrwsrCtx c, Object obj, String prop); static M toModel(BrwsrCtx c, Class<M> aClass, Object data, Object object); static boolean isSame(int a, int b); static boolean isSame(double a, double b); static boolean isSame(Object a, Object b); static int hashPlus(Object o, int h); static T extractValue(Class<T> type, Object val); static String stringValue(Object val); static Number numberValue(Object val); static Character charValue(Object val); static Boolean boolValue(Object val); static Object find(Object object, Bindings model); static Object find(Object object); static void applyBindings(Object object, String id); static void register(Class c, Proto.Type<?> type); static boolean isModel(Class<?> clazz); static Model bindTo(Model model, BrwsrCtx c); static T readStream(BrwsrCtx c, Class<T> modelClazz, InputStream data, Collection<? super T> collectTo); static T read(BrwsrCtx c, Class<T> modelClazz, Object data); } | @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(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(E e); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends E> c); @Override boolean addAll(int index, Collection<? extends E> c); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); void sort(Comparator<? super E> c); @Override void clear(); @Override E get(int index); @Override E set(int index, E element); @Override void add(int index, E element); @Override E remove(int index); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); int lastIndexOfImpl(Object o, int from, int to); @Override ListIterator<E> listIterator(); @Override ListIterator<E> listIterator(int index); @Override List<E> subList(int fromIndex, int toIndex); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static void ensureSize(List<?> list, int size); } | @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"); assertEquals(it.previous(), "Hi"); assertEquals(it.previous(), "Ahoj"); assertEquals(list.size(), 2); } |
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(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(E e); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends E> c); @Override boolean addAll(int index, Collection<? extends E> c); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); void sort(Comparator<? super E> c); @Override void clear(); @Override E get(int index); @Override E set(int index, E element); @Override void add(int index, E element); @Override E remove(int index); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); int lastIndexOfImpl(Object o, int from, int to); @Override ListIterator<E> listIterator(); @Override ListIterator<E> listIterator(int index); @Override List<E> subList(int fromIndex, int toIndex); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static void ensureSize(List<?> list, int size); } | @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 propName); void valueHasMutated(
final String propName, final Object oldValue, final Object newValue
); void applyBindings(); void applyBindings(String id); void runInBrowser(Runnable run); void runInBrowser(final int index, final Object... args); void initTo(Collection<?> to, Object array); void extract(Object json, String[] props, Object[] values); T read(Class<T> modelClass, Object data); void loadJSON(final int index,
String urlBefore, String urlAfter, String method,
final Object data
); void loadJSON(final int index,
String urlBefore, String urlAfter, String method,
final Object data, final Object... params
); void loadJSONWithHeaders(final int index,
String headers,
String urlBefore, String urlAfter, String method,
final Object data, final Object... params
); Object wsOpen(final int index, String url, Object data); void wsSend(Object webSocket, String url, Object data); String toString(Object data, String propName); Number toNumber(Object data, String propName); T toModel(Class<T> type, Object data); List<T> createList(String propName, int onChange, String... dependingProps); void cloneList(Collection<T> to, BrwsrCtx ctx, Collection<T> from); } | @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]); assertNull(functions[1]); assertNull(functions[2]); assertNull(functions[3]); assertNull(functions[4]); assertNotNull(functions[5]); } |
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,
InputStream is, Collection<? super M> collectTo
); static M fromRaw(BrwsrCtx ctx, Class<M> model, Object jsonObject); static Object toRaw(Object model); static void applyBindings(Object model); static void applyBindings(Object model, String targetId); static List<T> asList(T... values); } | @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 model"); }
@Test public void randomClassIsNotModel() { assertFalse(Models.isModel(StringBuilder.class), "JDK classes are not model"); } |
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 getAltitudeAccuracy(); @Override Double getHeading(); @Override Double getSpeed(); } | @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(boolean yesOrNo); Presenter build(); } | @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("java.")) { continue; } if (cn.startsWith("javafx.")) { continue; } if (cn.startsWith("com.sun.")) { continue; } return cn; } return "org.netbeans.html"; } static synchronized WebView findWebView(final URL url, final AbstractFXPresenter onLoad); @Override void start(Stage primaryStage); } | @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 FXBrowsers(); static void load(
final WebView webView, final URL url,
Class<?> onPageLoad, String methodName,
String... args
); static void load(
WebView webView, final URL url, Runnable onPageLoad
); static void load(
WebView webView, final URL url, Runnable onPageLoad, ClassLoader loader
); static void load(
WebView webView, final URL url, Runnable onPageLoad, ClassLoader loader,
Object... context
); static void runInBrowser(WebView webView, Runnable code); } | @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] = BrwsrCtx.findDefault(FXBrowsersTest.class); init.countDown(); } }); init.await(); final CountDownLatch cdl = new CountDownLatch(1); class R implements Runnable { @Override public void run() { if (Platform.isFxApplicationThread()) { assertTrue(inJS()); cdl.countDown(); } else { ctx[0].execute(this); } } } new Thread(new R(), "Background thread").start(); cdl.await(); } |
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(--ident))) { ident++; break; } } String refId = body.substring(ident, next); sb.append(body.substring(pos, ident)); int sigBeg = body.indexOf('(', next); int sigEnd = body.indexOf(')', sigBeg); int colon4 = body.indexOf("::", next); if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) { throw new IllegalStateException( "Wrong format of instance callback. " + "Should be: '[email protected]::method(Ljava/lang/Object;)(param)':\n" + body ); } String fqn = body.substring(next + 2, colon4); String method = body.substring(colon4 + 2, sigBeg); String params = body.substring(sigBeg, sigEnd + 1); int paramBeg = body.indexOf('(', sigEnd + 1); if (paramBeg == -1) { throw new IllegalStateException( "Wrong format of instance callback. " + "Should be: '[email protected]::method(Ljava/lang/Object;)(param)':\n" + body ); } sb.append(callMethod(refId, fqn, method, params)); if (body.charAt(paramBeg + 1) != (')')) { sb.append(","); } pos = paramBeg + 1; } pos = 0; sb = null; for (;;) { int next = body.indexOf("@", pos); if (next == -1) { if (sb == null) { return body; } sb.append(body.substring(pos)); return sb.toString(); } if (sb == null) { sb = new StringBuilder(); } sb.append(body.substring(pos, next)); int sigBeg = body.indexOf('(', next); int sigEnd = body.indexOf(')', sigBeg); int colon4 = body.indexOf("::", next); int paramBeg = body.indexOf('(', sigEnd + 1); if (sigBeg == -1 || sigEnd == -1 || colon4 == -1 || paramBeg == -1) { throw new IllegalStateException( "Wrong format of static callback. " + "Should be: '@pkg.Class::staticMethod(Ljava/lang/Object;)(param)':\n" + body ); } String fqn = body.substring(next + 1, colon4); String method = body.substring(colon4 + 2, sigBeg); String params = body.substring(sigBeg, sigEnd + 1); sb.append(callMethod(null, fqn, method, params)); pos = paramBeg + 1; } } } | @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<?> id2 = Fn.ref(p); assertNotSame(id1, id2); assertEquals(id1, id2); assertEquals(id1.hashCode(), id2.hashCode()); Reference<Fn.Presenter> ref = new WeakReference<>(p); p = null; NbTestCase.assertGC("Presenter is held weakly", ref); } |
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, "_" + l.getLanguage(), mal, relativeTo); } if (url != null) { return url; } return findResourceURL(resource, null, mal, relativeTo); } private BrowserBuilder(Object[] context); static BrowserBuilder newBrowser(Object... context); BrowserBuilder loadClass(Class<?> mainClass); BrowserBuilder loadFinished(Runnable r); BrowserBuilder loadPage(String page); BrowserBuilder locale(Locale locale); BrowserBuilder invoke(String methodName, String... args); BrowserBuilder classloader(ClassLoader l); void showAndWait(); } | @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, BrowserBuilder.class); assertEquals(url, zhCN.toURI().toURL(), "Found both suffixes"); }
@Test public void findsZh() throws IOException { File zh = new File(dir, "index_zh.html"); zh.createNewFile(); IOException[] mal = { null }; URL url = BrowserBuilder.findLocalizedResourceURL("index.html", Locale.SIMPLIFIED_CHINESE, mal, BrowserBuilder.class); assertEquals(url, zh.toURI().toURL(), "Found one suffix"); }
@Test public void findsIndex() throws IOException { IOException[] mal = { null }; URL url = BrowserBuilder.findLocalizedResourceURL("index.html", Locale.SIMPLIFIED_CHINESE, mal, BrowserBuilder.class); assertEquals(url, index.toURI().toURL(), "Found root file"); } |
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(']'); return sb.toString(); } 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); @Override boolean addAll(Collection<? extends T> c); @Override boolean addAll(int index, Collection<? extends T> c); void fastReplace(Collection<? extends T> c); @Override boolean remove(Object o); @Override void clear(); @Override boolean removeAll(Collection<?> c); void sort(Comparator<? super T> c); @Override boolean retainAll(Collection<?> c); @Override T set(int index, T element); @Override void add(int index, T element); @Override T remove(int index); @Override String toString(); @Override JSONList clone(); } | @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().toString(), "[{\"firstName\":\"1\",\"lastName\":\"2\",\"sex\":\"MALE\"}]", "Converted to real JSON"); PropertyBinding pb = bindings.get("info"); assertNotNull(pb, "Binding for info found"); Object real = pb.getValue(); assertTrue(real instanceof Object[], "It is an array: " + real); Object[] arr = (Object[])real; assertEquals(arr.length, 1, "Size is one"); assertEquals(this, arr[0], "I am the right model"); }
@Test public void toStringOnArrayOfStrings() { JSNLst l = new JSNLst("Jarda", "Jirka", "Parda"); assertEquals(l.toString(), "{\"names\":[\"Jarda\",\"Jirka\",\"Parda\"]}", "Properly quoted"); } |
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); @Override boolean addAll(Collection<? extends T> c); @Override boolean addAll(int index, Collection<? extends T> c); void fastReplace(Collection<? extends T> c); @Override boolean remove(Object o); @Override void clear(); @Override boolean removeAll(Collection<?> c); void sort(Comparator<? super T> c); @Override boolean retainAll(Collection<?> c); @Override T set(int index, T element); @Override void add(int index, T element); @Override T remove(int index); @Override String toString(); @Override JSONList clone(); } | @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 for info found"); Object real = pb.getValue(); assertTrue(real instanceof Object[], "It is an array: " + real); Object[] arr = (Object[])real; assertEquals(arr.length, 2, "Length two"); assertEquals(arr[0], "One", "Text should be in the model"); assertEquals(arr[1], "Two", "2nd text in the model"); }
@Test public void testConvertorOnAnArrayWithWrapper() { this.replaceArray = true; 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(), c).applyBindings(); people.getInfo().add(p); Object real = JSON.find(people.getInfo()); assertEquals(real, this, "I am the model of the array"); }
@Test public void bindingsOnArray() { this.replaceArray = true; BrwsrCtx c = Contexts.newBuilder().register(Technology.class, this, 1).build(); People p = Models.bind(new People(), c).applyBindings(); p.getAge().add(30); PropertyBinding pb = bindings.get("age"); assertNotNull(pb, "There is a binding for age list"); assertEquals(pb.getValue(), this, "I am the model of the array"); } |
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((Double)val); } return (String)val; } private JSON(); static Transfer findTransfer(BrwsrCtx c); static WSTransfer<?> findWSTransfer(BrwsrCtx c); static void readBindings(BrwsrCtx c, M model, Object value); static void extract(BrwsrCtx c, Object value, String[] props, Object[] values); static String toJSON(Object value); static String toString(BrwsrCtx c, Object obj, String prop); static Number toNumber(BrwsrCtx c, Object obj, String prop); static M toModel(BrwsrCtx c, Class<M> aClass, Object data, Object object); static boolean isSame(int a, int b); static boolean isSame(double a, double b); static boolean isSame(Object a, Object b); static int hashPlus(Object o, int h); static T extractValue(Class<T> type, Object val); static String stringValue(Object val); static Number numberValue(Object val); static Character charValue(Object val); static Boolean boolValue(Object val); static Object find(Object object, Bindings model); static Object find(Object object); static void applyBindings(Object object, String id); static void register(Class c, Proto.Type<?> type); static boolean isModel(Class<?> clazz); static Model bindTo(Model model, BrwsrCtx c); static T readStream(BrwsrCtx c, Class<T> modelClazz, InputStream data, Collection<? super T> collectTo); static T read(BrwsrCtx c, Class<T> modelClazz, Object data); } | @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(BrwsrCtx c); static WSTransfer<?> findWSTransfer(BrwsrCtx c); static void readBindings(BrwsrCtx c, M model, Object value); static void extract(BrwsrCtx c, Object value, String[] props, Object[] values); static String toJSON(Object value); static String toString(BrwsrCtx c, Object obj, String prop); static Number toNumber(BrwsrCtx c, Object obj, String prop); static M toModel(BrwsrCtx c, Class<M> aClass, Object data, Object object); static boolean isSame(int a, int b); static boolean isSame(double a, double b); static boolean isSame(Object a, Object b); static int hashPlus(Object o, int h); static T extractValue(Class<T> type, Object val); static String stringValue(Object val); static Number numberValue(Object val); static Character charValue(Object val); static Boolean boolValue(Object val); static Object find(Object object, Bindings model); static Object find(Object object); static void applyBindings(Object object, String id); static void register(Class c, Proto.Type<?> type); static boolean isModel(Class<?> clazz); static Model bindTo(Model model, BrwsrCtx c); static T readStream(BrwsrCtx c, Class<T> modelClazz, InputStream data, Collection<? super T> collectTo); static T read(BrwsrCtx c, Class<T> modelClazz, Object data); } | @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(ISchemaExtractor schemaExtractor, String query); String getSchemaXml(); } | @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 actual = tableXMLFormatter.getSchemaXml(); Assert.assertEquals(expected, actual); } |
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.toString(); } QueryStripper(String sql); String getStrippedSql(); } | @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'").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = '2000-01-01'"); }
@Test public void stripDate2() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = '1999-3-4'").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = '2000-01-01'"); }
@Test public void stripTime() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = '1:13:56'").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = '12:00:00'"); }
@Test public void stripTime2() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = '14:13:56'").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = '12:00:00'"); }
@Test public void stripTimestamp() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = '1999-03-04 01:13:56'").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = '2000-01-01 12:00:00'"); }
@Test public void stripTimestamp2() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = '1999-3-4 13:13:56.100'").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = '2000-01-01 12:00:00'"); }
@Test public void stripSelectAllQuery() { String sql = new QueryStripper("SELECT * FROM Table").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\""); }
@Test public void stripInteger() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = 10").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = 0"); }
@Test public void stripString() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = 'test'").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = ''"); } |
Subsets and Splits