method2testcases
stringlengths 118
6.63k
|
---|
### Question:
BytesUtils { public static byte[] concatByteArray(byte[] a, byte[] b) { byte[] c = new byte[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void testConcatByteArray() { List<byte[]> list = new ArrayList<byte[]>(); float f1 = 12.4f; boolean b1 = true; list.add(BytesUtils.floatToBytes(f1)); list.add(BytesUtils.boolToBytes(b1)); byte[] ret = BytesUtils.concatByteArray(list.get(0), list.get(1)); float rf1 = BytesUtils.bytesToFloat(ret, 0); boolean rb1 = BytesUtils.bytesToBool(ret, 4); assertEquals(f1, rf1, CommonTestConstant.float_min_delta); assertEquals(b1, rb1); } |
### Question:
BytesUtils { public static byte[] concatByteArrayList(List<byte[]> list) { int size = list.size(); int len = 0; for (byte[] cs : list) { len += cs.length; } byte[] result = new byte[len]; int pos = 0; for (int i = 0; i < size; i++) { int l = list.get(i).length; System.arraycopy(list.get(i), 0, result, pos, l); pos += l; } return result; } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void testConcatByteArrayList() { List<byte[]> list = new ArrayList<byte[]>(); float f1 = 12.4f; boolean b1 = true; int i1 = 12; list.add(BytesUtils.floatToBytes(f1)); list.add(BytesUtils.boolToBytes(b1)); list.add(BytesUtils.intToBytes(i1)); byte[] ret = BytesUtils.concatByteArrayList(list); float rf1 = BytesUtils.bytesToFloat(ret, 0); boolean rb1 = BytesUtils.bytesToBool(ret, 4); int ri1 = BytesUtils.bytesToInt(ret, 5); assertEquals(f1, rf1, CommonTestConstant.float_min_delta); assertEquals(b1, rb1); assertEquals(i1, ri1); } |
### Question:
AbstractClient { protected static String checkRequiredArg(String arg, String name, CommandLine commandLine, boolean isRequired, String defaultValue) throws ArgsErrorException { String str = commandLine.getOptionValue(arg); if (str == null) { if (isRequired) { String msg = String .format("%s: Required values for option '%s' not provided", IOTDB_CLI_PREFIX, name); System.out.println(msg); System.out.println("Use -help for more information"); throw new ArgsErrorException(msg); } else if (defaultValue == null) { String msg = String .format("%s: Required values for option '%s' is null.", IOTDB_CLI_PREFIX, name); throw new ArgsErrorException(msg); } else { return defaultValue; } } return str; } static void output(ResultSet res, boolean printToConsole, String statement, ZoneId zoneId); }### Answer:
@Test public void testCheckRequiredArg() throws ParseException, ArgsErrorException { Options options = AbstractClient.createOptions(); CommandLineParser parser = new DefaultParser(); String[] args = new String[]{"-u", "user1"}; CommandLine commandLine = parser.parse(options, args); String str = AbstractClient .checkRequiredArg(AbstractClient.USERNAME_ARGS, AbstractClient.USERNAME_NAME, commandLine, true, "root"); assertEquals(str, "user1"); args = new String[]{"-u", "root",}; commandLine = parser.parse(options, args); str = AbstractClient .checkRequiredArg(AbstractClient.HOST_ARGS, AbstractClient.HOST_NAME, commandLine, false, "127.0.0.1"); assertEquals(str, "127.0.0.1"); try { str = AbstractClient .checkRequiredArg(AbstractClient.HOST_ARGS, AbstractClient.HOST_NAME, commandLine, true, "127.0.0.1"); } catch (ArgsErrorException e) { assertEquals(e.getMessage(), "IoTDB: Required values for option 'host' not provided"); } try { str = AbstractClient .checkRequiredArg(AbstractClient.HOST_ARGS, AbstractClient.HOST_NAME, commandLine, false, null); } catch (ArgsErrorException e) { assertEquals(e.getMessage(), "IoTDB: Required values for option 'host' is null."); } } |
### Question:
BytesUtils { public static byte[] subBytes(byte[] src, int start, int length) { if ((start + length) > src.length) { return null; } if (length <= 0) { return null; } byte[] result = new byte[length]; for (int i = 0; i < length; i++) { result[i] = src[start + i]; } return result; } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void testSubBytes() throws IOException { List<byte[]> list = new ArrayList<byte[]>(); float f1 = 12.4f; boolean b1 = true; int i1 = 12; list.add(BytesUtils.floatToBytes(f1)); list.add(BytesUtils.boolToBytes(b1)); list.add(BytesUtils.intToBytes(i1)); byte[] ret = BytesUtils.concatByteArrayList(list); boolean rb1 = BytesUtils.bytesToBool(BytesUtils.subBytes(ret, 4, 1)); int ri1 = BytesUtils.bytesToInt(BytesUtils.subBytes(ret, 5, 4)); assertEquals(b1, rb1); assertEquals(i1, ri1); } |
### Question:
BytesUtils { public static int getByteN(byte data, int offset) { offset %= 8; if ((data & (1 << (7 - offset))) != 0) { return 1; } else { return 0; } } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void testGetByteN() { byte src = 120; byte dest = 0; for (int i = 0; i < 64; i++) { int a = BytesUtils.getByteN(src, i); dest = BytesUtils.setByteN(dest, i, a); } assertEquals(src, dest); } |
### Question:
BytesUtils { public static int getLongN(long data, int offset) { offset %= 64; if ((data & (1L << (offset))) != 0) { return 1; } else { return 0; } } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void testGetLongN() { long src = (long) Math.pow(2, 33); long dest = 0; for (int i = 0; i < 64; i++) { int a = BytesUtils.getLongN(src, i); dest = BytesUtils.setLongN(dest, i, a); } assertEquals(src, dest); } |
### Question:
BytesUtils { public static int getIntN(int data, int offset) { offset %= 32; if ((data & (1 << (offset))) != 0) { return 1; } else { return 0; } } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void testGetIntN() { int src = 54243342; int dest = 0; for (int i = 0; i < 32; i++) { int a = BytesUtils.getIntN(src, i); dest = BytesUtils.setIntN(dest, i, a); } assertEquals(src, dest); } |
### Question:
BytesUtils { public static int readInt(InputStream in) throws IOException { byte[] b = safeReadInputStreamToBytes(4, in); return BytesUtils.bytesToInt(b); } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void testReadInt() throws IOException { int l = r.nextInt(); byte[] bs = BytesUtils.intToBytes(l); InputStream in = new ByteArrayInputStream(bs); assertEquals(l, BytesUtils.readInt(in)); } |
### Question:
BytesUtils { public static float readFloat(InputStream in) throws IOException { byte[] b = safeReadInputStreamToBytes(4, in); return BytesUtils.bytesToFloat(b); } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void testReadFloat() throws IOException { float l = r.nextFloat(); byte[] bs = BytesUtils.floatToBytes(l); InputStream in = new ByteArrayInputStream(bs); assertEquals(l, BytesUtils.readFloat(in), CommonTestConstant.float_min_delta); } |
### Question:
BytesUtils { public static double readDouble(InputStream in) throws IOException { byte[] b = safeReadInputStreamToBytes(8, in); return BytesUtils.bytesToDouble(b); } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void testReadDouble() throws IOException { double l = r.nextDouble(); byte[] bs = BytesUtils.doubleToBytes(l); InputStream in = new ByteArrayInputStream(bs); assertEquals(l, BytesUtils.readDouble(in), CommonTestConstant.double_min_delta); } |
### Question:
BytesUtils { public static boolean readBool(InputStream in) throws IOException { byte[] b = safeReadInputStreamToBytes(1, in); return BytesUtils.bytesToBool(b); } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); }### Answer:
@Test public void testReadBool() throws IOException { boolean l = r.nextBoolean(); byte[] bs = BytesUtils.boolToBytes(l); InputStream in = new ByteArrayInputStream(bs); assertEquals(l, BytesUtils.readBool(in)); } |
### Question:
StringContainer { public String getSubString(int index) { int realIndex = index >= 0 ? index : count + index; if (realIndex < 0 || realIndex >= count) { throw new IndexOutOfBoundsException( "Index: " + index + ", Real Index: " + realIndex + ", Size: " + count); } if (realIndex < reverseList.size()) { return reverseList.get(reverseList.size() - 1 - realIndex); } else { return sequenceList.get(realIndex - reverseList.size()); } } StringContainer(); StringContainer(String joinSeparator); StringContainer(String[] strings); StringContainer(String[] strings, String joinSeparator); int size(); int length(); ArrayList<String> getSequenceList(); ArrayList<String> getReverseList(); StringContainer addTail(Object... objs); StringContainer addTail(String... strings); StringContainer addTail(StringContainer myContainer); StringContainer addHead(String... strings); StringContainer addHead(StringContainer myContainer); @Override String toString(); String join(String separator); String getSubString(int index); StringContainer getSubStringContainer(int start, int end); @Override int hashCode(); @Override boolean equals(Object sc); boolean equals(StringContainer sc); @Override StringContainer clone(); }### Answer:
@Test public void testGetSubString() { StringContainer a = new StringContainer(); try { a.getSubString(0); } catch (Exception e) { assertTrue(e instanceof IndexOutOfBoundsException); } a.addHead("a", "bbb", "cc"); assertEquals("a", a.getSubString(0)); assertEquals("cc", a.getSubString(-1)); assertEquals("bbb", a.getSubString(-2)); try { a.getSubString(4); } catch (Exception e) { assertTrue(e instanceof IndexOutOfBoundsException); } a.addTail("dd", "eeee"); assertEquals("a", a.getSubString(0)); assertEquals("cc", a.getSubString(-3)); assertEquals("dd", a.getSubString(3)); assertEquals("eeee", a.getSubString(-1)); try { a.getSubString(9); } catch (Exception e) { assertTrue(e instanceof IndexOutOfBoundsException); } } |
### Question:
AbstractClient { protected static String[] removePasswordArgs(String[] args) { int index = -1; for (int i = 0; i < args.length; i++) { if (args[i].equals("-" + PASSWORD_ARGS)) { index = i; break; } } if (index >= 0) { if ((index + 1 >= args.length) || (index + 1 < args.length && keywordSet .contains(args[index + 1]))) { return ArrayUtils.remove(args, index); } } return args; } static void output(ResultSet res, boolean printToConsole, String statement, ZoneId zoneId); }### Answer:
@Test public void testRemovePasswordArgs() { AbstractClient.init(); String[] input = new String[]{"-h", "127.0.0.1", "-p", "6667", "-u", "root", "-pw", "root"}; String[] res = new String[]{"-h", "127.0.0.1", "-p", "6667", "-u", "root", "-pw", "root"}; isTwoStringArrayEqual(res, AbstractClient.removePasswordArgs(input)); input = new String[]{"-h", "127.0.0.1", "-p", "6667", "-pw", "root", "-u", "root"}; res = new String[]{"-h", "127.0.0.1", "-p", "6667", "-pw", "root", "-u", "root"}; isTwoStringArrayEqual(res, AbstractClient.removePasswordArgs(input)); input = new String[]{"-h", "127.0.0.1", "-p", "6667", "root", "-u", "root", "-pw"}; res = new String[]{"-h", "127.0.0.1", "-p", "6667", "root", "-u", "root"}; isTwoStringArrayEqual(res, AbstractClient.removePasswordArgs(input)); input = new String[]{"-h", "127.0.0.1", "-p", "6667", "-pw", "-u", "root"}; res = new String[]{"-h", "127.0.0.1", "-p", "6667", "-u", "root"}; isTwoStringArrayEqual(res, AbstractClient.removePasswordArgs(input)); input = new String[]{"-pw", "-h", "127.0.0.1", "-p", "6667", "root", "-u", "root"}; res = new String[]{"-h", "127.0.0.1", "-p", "6667", "root", "-u", "root"}; isTwoStringArrayEqual(res, AbstractClient.removePasswordArgs(input)); input = new String[]{}; res = new String[]{}; isTwoStringArrayEqual(res, AbstractClient.removePasswordArgs(input)); } |
### Question:
StringContainer { public StringContainer getSubStringContainer(int start, int end) { int realStartIndex = start >= 0 ? start : count + start; int realEndIndex = end >= 0 ? end : count + end; if (realStartIndex < 0 || realStartIndex >= count) { throw new IndexOutOfBoundsException( "start Index: " + start + ", Real start Index: " + realStartIndex + ", Size: " + count); } if (realEndIndex < 0 || realEndIndex >= count) { throw new IndexOutOfBoundsException( "end Index: " + end + ", Real end Index: " + realEndIndex + ", Size: " + count); } StringContainer ret = new StringContainer(joinSeparator); if (realStartIndex < reverseList.size()) { for (int i = reverseList.size() - 1 - realStartIndex; i >= Math.max(0, reverseList.size() - 1 - realEndIndex); i--) { ret.addTail(this.reverseList.get(i)); } } if (realEndIndex >= reverseList.size()) { for (int i = Math.max(0, realStartIndex - reverseList.size()); i <= realEndIndex - reverseList.size(); i++) { ret.addTail(this.sequenceList.get(i)); } } return ret; } StringContainer(); StringContainer(String joinSeparator); StringContainer(String[] strings); StringContainer(String[] strings, String joinSeparator); int size(); int length(); ArrayList<String> getSequenceList(); ArrayList<String> getReverseList(); StringContainer addTail(Object... objs); StringContainer addTail(String... strings); StringContainer addTail(StringContainer myContainer); StringContainer addHead(String... strings); StringContainer addHead(StringContainer myContainer); @Override String toString(); String join(String separator); String getSubString(int index); StringContainer getSubStringContainer(int start, int end); @Override int hashCode(); @Override boolean equals(Object sc); boolean equals(StringContainer sc); @Override StringContainer clone(); }### Answer:
@Test public void testGetSubStringContainer() { StringContainer a = new StringContainer(); try { a.getSubStringContainer(0, 1); } catch (Exception e) { assertTrue(e instanceof IndexOutOfBoundsException); } a.addTail("a", "bbb", "cc"); assertEquals("", a.getSubStringContainer(1, 0).toString()); assertEquals("a", a.getSubStringContainer(0, 0).toString()); assertEquals("bbbcc", a.getSubStringContainer(1, -1).toString()); assertEquals("bbb", a.getSubStringContainer(-2, -2).toString()); try { a.getSubStringContainer(1, 4); } catch (Exception e) { assertTrue(e instanceof IndexOutOfBoundsException); } a.addHead("dd", "eeee"); assertEquals("eeeea", a.getSubStringContainer(1, 2).toString()); assertEquals("eeeea", a.getSubStringContainer(1, -3).toString()); assertEquals("dd", a.getSubStringContainer(0, 0).toString()); assertEquals("cc", a.getSubStringContainer(-1, -1).toString()); assertEquals("ddeeeeabbbcc", a.getSubStringContainer(-5, -1).toString()); try { a.getSubString(9); } catch (Exception e) { assertTrue(e instanceof IndexOutOfBoundsException); } } |
### Question:
StringContainer { @Override public int hashCode() { final int prime = 31; int result = 1; if (joinSeparator != null) { result = prime * result + joinSeparator.hashCode(); } for (String string : reverseList) { result = prime * result + ((string == null) ? 0 : string.hashCode()); } for (String string : sequenceList) { result = prime * result + ((string == null) ? 0 : string.hashCode()); } return result; } StringContainer(); StringContainer(String joinSeparator); StringContainer(String[] strings); StringContainer(String[] strings, String joinSeparator); int size(); int length(); ArrayList<String> getSequenceList(); ArrayList<String> getReverseList(); StringContainer addTail(Object... objs); StringContainer addTail(String... strings); StringContainer addTail(StringContainer myContainer); StringContainer addHead(String... strings); StringContainer addHead(StringContainer myContainer); @Override String toString(); String join(String separator); String getSubString(int index); StringContainer getSubStringContainer(int start, int end); @Override int hashCode(); @Override boolean equals(Object sc); boolean equals(StringContainer sc); @Override StringContainer clone(); }### Answer:
@Test public void testHashCode() { StringContainer c1 = new StringContainer(","); c1.addHead("a", "b", "c123"); c1.addTail("a", "12", "c"); c1.addTail("1284736", "b", "c"); StringContainer c2 = new StringContainer("."); c2.addHead("a", "b", "c123"); c2.addTail("a", "12", "c"); c2.addTail("1284736", "b", "c"); StringContainer copyC = c1.clone(); assertEquals(c1.hashCode(), copyC.hashCode()); assertNotEquals(c1.hashCode(), c2.hashCode()); StringContainer c3 = new StringContainer(","); c3.addHead("a", "b", "c123"); assertNotEquals(c1.hashCode(), c3.hashCode()); StringContainer c4 = new StringContainer(","); c4.addTail("a", "b", "c123"); assertNotEquals(c1.hashCode(), c4.hashCode()); } |
### Question:
MetadataQuerierByFileImpl implements MetadataQuerier { @Override public List<ChunkMetaData> getChunkMetaDataList(Path path) throws IOException { return chunkMetaDataCache.get(path); } MetadataQuerierByFileImpl(TsFileSequenceReader tsFileReader); @Override List<ChunkMetaData> getChunkMetaDataList(Path path); @Override TsFileMetaData getWholeFileMetadata(); @Override void loadChunkMetaDatas(List<Path> paths); }### Answer:
@Test public void test() throws IOException { fileReader = new TsFileSequenceReader(FILE_PATH); MetadataQuerierByFileImpl metadataQuerierByFile = new MetadataQuerierByFileImpl(fileReader); List<ChunkMetaData> chunkMetaDataList = metadataQuerierByFile .getChunkMetaDataList(new Path("d2.s1")); for (ChunkMetaData chunkMetaData : chunkMetaDataList) { Assert.assertEquals(chunkMetaData.getMeasurementUid(), "s1"); } } |
### Question:
Path { public boolean startWith(String prefix) { return prefix != null && fullPath.startsWith(prefix); } Path(StringContainer pathSc); Path(String pathSc); Path(String[] pathSc); Path(String device, String measurement); static Path mergePath(Path prefix, Path suffix); static Path addPrefixPath(Path src, String prefix); static Path addPrefixPath(Path src, Path prefix); static Path replace(String srcPrefix, Path descPrefix); static Path replace(Path srcPrefix, Path descPrefix); String getFullPath(); String getDevice(); String getMeasurement(); @Override int hashCode(); @Override boolean equals(Object obj); boolean equals(String obj); @Override String toString(); @Override Path clone(); boolean startWith(String prefix); boolean startWith(Path prefix); }### Answer:
@Test public void startWith() throws Exception { Path path = new Path("a.b.c"); assertTrue(path.startWith(new Path(""))); assertTrue(path.startWith(new Path("a"))); assertTrue(path.startWith(new Path("a.b.c"))); } |
### Question:
Path { public static Path mergePath(Path prefix, Path suffix) { StringContainer sc = new StringContainer(SystemConstant.PATH_SEPARATOR); sc.addTail(prefix); sc.addTail(suffix); return new Path(sc); } Path(StringContainer pathSc); Path(String pathSc); Path(String[] pathSc); Path(String device, String measurement); static Path mergePath(Path prefix, Path suffix); static Path addPrefixPath(Path src, String prefix); static Path addPrefixPath(Path src, Path prefix); static Path replace(String srcPrefix, Path descPrefix); static Path replace(Path srcPrefix, Path descPrefix); String getFullPath(); String getDevice(); String getMeasurement(); @Override int hashCode(); @Override boolean equals(Object obj); boolean equals(String obj); @Override String toString(); @Override Path clone(); boolean startWith(String prefix); boolean startWith(Path prefix); }### Answer:
@Test public void mergePath() throws Exception { Path prefix = new Path("a.b.c"); Path suffix = new Path("d.e"); Path suffix1 = new Path(""); testPath(Path.mergePath(prefix, suffix), "a.b.c.d", "e", "a.b.c.d.e"); testPath(Path.mergePath(prefix, suffix1), "a.b", "c", "a.b.c"); } |
### Question:
Path { public static Path replace(String srcPrefix, Path descPrefix) { if ("".equals(srcPrefix) || descPrefix.startWith(srcPrefix)) { return descPrefix; } int prefixSize = srcPrefix.split(SystemConstant.PATH_SEPARATER_NO_REGEX).length; String[] descArray = descPrefix.fullPath.split(SystemConstant.PATH_SEPARATER_NO_REGEX); if (descArray.length <= prefixSize) { return new Path(srcPrefix); } StringContainer sc = new StringContainer(SystemConstant.PATH_SEPARATOR); sc.addTail(srcPrefix); for (int i = prefixSize; i < descArray.length; i++) { sc.addTail(descArray[i]); } return new Path(sc); } Path(StringContainer pathSc); Path(String pathSc); Path(String[] pathSc); Path(String device, String measurement); static Path mergePath(Path prefix, Path suffix); static Path addPrefixPath(Path src, String prefix); static Path addPrefixPath(Path src, Path prefix); static Path replace(String srcPrefix, Path descPrefix); static Path replace(Path srcPrefix, Path descPrefix); String getFullPath(); String getDevice(); String getMeasurement(); @Override int hashCode(); @Override boolean equals(Object obj); boolean equals(String obj); @Override String toString(); @Override Path clone(); boolean startWith(String prefix); boolean startWith(Path prefix); }### Answer:
@Test public void replace() throws Exception { Path src = new Path("a.b.c"); Path rep1 = new Path(""); Path rep2 = new Path("d"); Path rep3 = new Path("d.e.f"); Path rep4 = new Path("d.e.f.g"); testPath(Path.replace(rep1, src), "a.b", "c", "a.b.c"); testPath(Path.replace(rep2, src), "d.b", "c", "d.b.c"); testPath(Path.replace(rep3, src), "d.e", "f", "d.e.f"); testPath(Path.replace(rep4, src), "d.e.f", "g", "d.e.f.g"); } |
### Question:
ReadOnlyTsFile { public QueryDataSet query(QueryExpression queryExpression) throws IOException { return tsFileExecutor.execute(queryExpression); } ReadOnlyTsFile(TsFileSequenceReader fileReader); QueryDataSet query(QueryExpression queryExpression); void close(); }### Answer:
@Test public void queryTest() throws IOException { Filter filter = TimeFilter.lt(1480562618100L); Filter filter2 = ValueFilter.gt(new Binary("dog")); Filter filter3 = FilterFactory .and(TimeFilter.gtEq(1480562618000L), TimeFilter.ltEq(1480562618100L)); IExpression IExpression = BinaryExpression .or(BinaryExpression.and(new SingleSeriesExpression(new Path("d1.s1"), filter), new SingleSeriesExpression(new Path("d1.s4"), filter2)), new GlobalTimeExpression(filter3)); QueryExpression queryExpression = QueryExpression.create().addSelectedPath(new Path("d1.s1")) .addSelectedPath(new Path("d1.s4")).setExpression(IExpression); QueryDataSet queryDataSet = tsFile.query(queryExpression); long aimedTimestamp = 1480562618000L; while (queryDataSet.hasNext()) { RowRecord rowRecord = queryDataSet.next(); Assert.assertEquals(aimedTimestamp, rowRecord.getTimestamp()); aimedTimestamp++; } queryExpression = QueryExpression.create().addSelectedPath(new Path("d1.s1")) .addSelectedPath(new Path("d1.s4")); queryDataSet = tsFile.query(queryExpression); aimedTimestamp = 1480562618000L; int count = 0; while (queryDataSet.hasNext()) { RowRecord rowRecord = queryDataSet.next(); Assert.assertEquals(aimedTimestamp, rowRecord.getTimestamp()); aimedTimestamp++; count++; } Assert.assertEquals(rowCount, count); queryExpression = QueryExpression.create().addSelectedPath(new Path("d1.s1")) .addSelectedPath(new Path("d1.s4")) .setExpression(new GlobalTimeExpression(filter3)); queryDataSet = tsFile.query(queryExpression); aimedTimestamp = 1480562618000L; count = 0; while (queryDataSet.hasNext()) { RowRecord rowRecord = queryDataSet.next(); Assert.assertEquals(aimedTimestamp, rowRecord.getTimestamp()); aimedTimestamp++; count++; } Assert.assertEquals(101, count); } |
### Question:
IoTDBStatement implements Statement { @Override public boolean execute(String sql) throws SQLException { checkConnection("execute"); isClosed = false; try { return executeSQL(sql); } catch (TException e) { boolean flag = connection.reconnect(); reInit(); if (flag) { try { return executeSQL(sql); } catch (TException e2) { throw new SQLException( String.format("Fail to execute %s after reconnecting. please check server status", sql)); } } else { throw new SQLException(String .format("Fail to reconnect to server when executing %s. please check server status", sql)); } } } IoTDBStatement(IoTDBConnection connection, TSIService.Iface client,
TS_SessionHandle sessionHandle,
int fetchSize, ZoneId zoneId); IoTDBStatement(IoTDBConnection connection, TSIService.Iface client,
TS_SessionHandle sessionHandle,
ZoneId zoneId); @Override boolean isWrapperFor(Class<?> iface); @Override T unwrap(Class<T> iface); @Override void addBatch(String sql); @Override void cancel(); @Override void clearBatch(); @Override void clearWarnings(); @Override void close(); @Override void closeOnCompletion(); @Override boolean execute(String sql); @Override boolean execute(String arg0, int arg1); @Override boolean execute(String arg0, int[] arg1); @Override boolean execute(String arg0, String[] arg1); @Override int[] executeBatch(); @Override ResultSet executeQuery(String sql); @Override int executeUpdate(String sql); @Override int executeUpdate(String arg0, int arg1); @Override int executeUpdate(String arg0, int[] arg1); @Override int executeUpdate(String arg0, String[] arg1); @Override Connection getConnection(); @Override int getFetchDirection(); @Override void setFetchDirection(int direction); @Override int getFetchSize(); @Override void setFetchSize(int fetchSize); @Override ResultSet getGeneratedKeys(); @Override int getMaxFieldSize(); @Override void setMaxFieldSize(int arg0); @Override int getMaxRows(); @Override void setMaxRows(int num); @Override boolean getMoreResults(); @Override boolean getMoreResults(int arg0); @Override int getQueryTimeout(); @Override void setQueryTimeout(int seconds); @Override ResultSet getResultSet(); @Override int getResultSetConcurrency(); @Override int getResultSetHoldability(); @Override int getResultSetType(); @Override int getUpdateCount(); @Override SQLWarning getWarnings(); @Override boolean isCloseOnCompletion(); @Override boolean isClosed(); @Override boolean isPoolable(); @Override void setPoolable(boolean arg0); @Override void setCursorName(String arg0); @Override void setEscapeProcessing(boolean enable); }### Answer:
@SuppressWarnings("resource") @Test(expected = SQLException.class) public void testExecuteSQL1() throws SQLException { IoTDBStatement stmt = new IoTDBStatement(connection, client, sessHandle, zoneID); stmt.execute("show timeseries"); } |
### Question:
IoTDBStatement implements Statement { @Override public int getFetchSize() throws SQLException { checkConnection("getFetchSize"); return fetchSize; } IoTDBStatement(IoTDBConnection connection, TSIService.Iface client,
TS_SessionHandle sessionHandle,
int fetchSize, ZoneId zoneId); IoTDBStatement(IoTDBConnection connection, TSIService.Iface client,
TS_SessionHandle sessionHandle,
ZoneId zoneId); @Override boolean isWrapperFor(Class<?> iface); @Override T unwrap(Class<T> iface); @Override void addBatch(String sql); @Override void cancel(); @Override void clearBatch(); @Override void clearWarnings(); @Override void close(); @Override void closeOnCompletion(); @Override boolean execute(String sql); @Override boolean execute(String arg0, int arg1); @Override boolean execute(String arg0, int[] arg1); @Override boolean execute(String arg0, String[] arg1); @Override int[] executeBatch(); @Override ResultSet executeQuery(String sql); @Override int executeUpdate(String sql); @Override int executeUpdate(String arg0, int arg1); @Override int executeUpdate(String arg0, int[] arg1); @Override int executeUpdate(String arg0, String[] arg1); @Override Connection getConnection(); @Override int getFetchDirection(); @Override void setFetchDirection(int direction); @Override int getFetchSize(); @Override void setFetchSize(int fetchSize); @Override ResultSet getGeneratedKeys(); @Override int getMaxFieldSize(); @Override void setMaxFieldSize(int arg0); @Override int getMaxRows(); @Override void setMaxRows(int num); @Override boolean getMoreResults(); @Override boolean getMoreResults(int arg0); @Override int getQueryTimeout(); @Override void setQueryTimeout(int seconds); @Override ResultSet getResultSet(); @Override int getResultSetConcurrency(); @Override int getResultSetHoldability(); @Override int getResultSetType(); @Override int getUpdateCount(); @Override SQLWarning getWarnings(); @Override boolean isCloseOnCompletion(); @Override boolean isClosed(); @Override boolean isPoolable(); @Override void setPoolable(boolean arg0); @Override void setCursorName(String arg0); @Override void setEscapeProcessing(boolean enable); }### Answer:
@SuppressWarnings("resource") @Test public void testSetFetchSize3() throws SQLException { final int fetchSize = 10000; IoTDBStatement stmt = new IoTDBStatement(connection, client, sessHandle, fetchSize, zoneID); assertEquals(fetchSize, stmt.getFetchSize()); } |
### Question:
IoTDBStatement implements Statement { @Override public void setFetchSize(int fetchSize) throws SQLException { checkConnection("setFetchSize"); if (fetchSize < 0) { throw new SQLException(String.format("fetchSize %d must be >= 0!", fetchSize)); } this.fetchSize = fetchSize == 0 ? Config.fetchSize : fetchSize; } IoTDBStatement(IoTDBConnection connection, TSIService.Iface client,
TS_SessionHandle sessionHandle,
int fetchSize, ZoneId zoneId); IoTDBStatement(IoTDBConnection connection, TSIService.Iface client,
TS_SessionHandle sessionHandle,
ZoneId zoneId); @Override boolean isWrapperFor(Class<?> iface); @Override T unwrap(Class<T> iface); @Override void addBatch(String sql); @Override void cancel(); @Override void clearBatch(); @Override void clearWarnings(); @Override void close(); @Override void closeOnCompletion(); @Override boolean execute(String sql); @Override boolean execute(String arg0, int arg1); @Override boolean execute(String arg0, int[] arg1); @Override boolean execute(String arg0, String[] arg1); @Override int[] executeBatch(); @Override ResultSet executeQuery(String sql); @Override int executeUpdate(String sql); @Override int executeUpdate(String arg0, int arg1); @Override int executeUpdate(String arg0, int[] arg1); @Override int executeUpdate(String arg0, String[] arg1); @Override Connection getConnection(); @Override int getFetchDirection(); @Override void setFetchDirection(int direction); @Override int getFetchSize(); @Override void setFetchSize(int fetchSize); @Override ResultSet getGeneratedKeys(); @Override int getMaxFieldSize(); @Override void setMaxFieldSize(int arg0); @Override int getMaxRows(); @Override void setMaxRows(int num); @Override boolean getMoreResults(); @Override boolean getMoreResults(int arg0); @Override int getQueryTimeout(); @Override void setQueryTimeout(int seconds); @Override ResultSet getResultSet(); @Override int getResultSetConcurrency(); @Override int getResultSetHoldability(); @Override int getResultSetType(); @Override int getUpdateCount(); @Override SQLWarning getWarnings(); @Override boolean isCloseOnCompletion(); @Override boolean isClosed(); @Override boolean isPoolable(); @Override void setPoolable(boolean arg0); @Override void setCursorName(String arg0); @Override void setEscapeProcessing(boolean enable); }### Answer:
@SuppressWarnings("resource") @Test(expected = SQLException.class) public void testSetFetchSize4() throws SQLException { IoTDBStatement stmt = new IoTDBStatement(connection, client, sessHandle, zoneID); stmt.setFetchSize(-1); } |
### Question:
IoTDBStatement implements Statement { @Override public void setMaxRows(int num) throws SQLException { checkConnection("setMaxRows"); if (num < 0) { throw new SQLException(String.format("maxRows %d must be >= 0!", num)); } this.maxRows = num; } IoTDBStatement(IoTDBConnection connection, TSIService.Iface client,
TS_SessionHandle sessionHandle,
int fetchSize, ZoneId zoneId); IoTDBStatement(IoTDBConnection connection, TSIService.Iface client,
TS_SessionHandle sessionHandle,
ZoneId zoneId); @Override boolean isWrapperFor(Class<?> iface); @Override T unwrap(Class<T> iface); @Override void addBatch(String sql); @Override void cancel(); @Override void clearBatch(); @Override void clearWarnings(); @Override void close(); @Override void closeOnCompletion(); @Override boolean execute(String sql); @Override boolean execute(String arg0, int arg1); @Override boolean execute(String arg0, int[] arg1); @Override boolean execute(String arg0, String[] arg1); @Override int[] executeBatch(); @Override ResultSet executeQuery(String sql); @Override int executeUpdate(String sql); @Override int executeUpdate(String arg0, int arg1); @Override int executeUpdate(String arg0, int[] arg1); @Override int executeUpdate(String arg0, String[] arg1); @Override Connection getConnection(); @Override int getFetchDirection(); @Override void setFetchDirection(int direction); @Override int getFetchSize(); @Override void setFetchSize(int fetchSize); @Override ResultSet getGeneratedKeys(); @Override int getMaxFieldSize(); @Override void setMaxFieldSize(int arg0); @Override int getMaxRows(); @Override void setMaxRows(int num); @Override boolean getMoreResults(); @Override boolean getMoreResults(int arg0); @Override int getQueryTimeout(); @Override void setQueryTimeout(int seconds); @Override ResultSet getResultSet(); @Override int getResultSetConcurrency(); @Override int getResultSetHoldability(); @Override int getResultSetType(); @Override int getUpdateCount(); @Override SQLWarning getWarnings(); @Override boolean isCloseOnCompletion(); @Override boolean isClosed(); @Override boolean isPoolable(); @Override void setPoolable(boolean arg0); @Override void setCursorName(String arg0); @Override void setEscapeProcessing(boolean enable); }### Answer:
@SuppressWarnings("resource") @Test(expected = SQLException.class) public void testSetMaxRows2() throws SQLException { IoTDBStatement stmt = new IoTDBStatement(connection, client, sessHandle, zoneID); stmt.setMaxRows(-1); } |
### Question:
IoTDBMetadataResultMetadata implements ResultSetMetaData { @Override public int getColumnCount() throws SQLException { if (showLabels == null || showLabels.length == 0) { throw new SQLException("No column exists"); } return showLabels.length; } IoTDBMetadataResultMetadata(String[] showLabels); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override String getCatalogName(int arg0); @Override String getColumnClassName(int arg0); @Override int getColumnCount(); @Override int getColumnDisplaySize(int arg0); @Override String getColumnLabel(int column); @Override String getColumnName(int column); @Override int getColumnType(int column); @Override String getColumnTypeName(int arg0); @Override int getPrecision(int arg0); @Override int getScale(int arg0); @Override String getSchemaName(int arg0); @Override String getTableName(int arg0); @Override boolean isAutoIncrement(int arg0); @Override boolean isCaseSensitive(int arg0); @Override boolean isCurrency(int arg0); @Override boolean isDefinitelyWritable(int arg0); @Override int isNullable(int arg0); @Override boolean isReadOnly(int arg0); @Override boolean isSearchable(int arg0); @Override boolean isSigned(int arg0); @Override boolean isWritable(int arg0); }### Answer:
@Test public void testGetColumnCount() throws SQLException { boolean flag = false; try { metadata = new IoTDBMetadataResultMetadata(null); assertEquals((long) metadata.getColumnCount(), 0); } catch (Exception e) { flag = true; } assertEquals(flag, true); flag = false; try { String[] nullArray = {}; metadata = new IoTDBMetadataResultMetadata(nullArray); assertEquals((long) metadata.getColumnCount(), 0); } catch (Exception e) { flag = true; } assertEquals(flag, true); metadata = new IoTDBMetadataResultMetadata(cols); assertEquals((long) metadata.getColumnCount(), cols.length); } |
### Question:
IoTDBMetadataResultMetadata implements ResultSetMetaData { @Override public String getColumnName(int column) throws SQLException { return getColumnLabel(column); } IoTDBMetadataResultMetadata(String[] showLabels); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override String getCatalogName(int arg0); @Override String getColumnClassName(int arg0); @Override int getColumnCount(); @Override int getColumnDisplaySize(int arg0); @Override String getColumnLabel(int column); @Override String getColumnName(int column); @Override int getColumnType(int column); @Override String getColumnTypeName(int arg0); @Override int getPrecision(int arg0); @Override int getScale(int arg0); @Override String getSchemaName(int arg0); @Override String getTableName(int arg0); @Override boolean isAutoIncrement(int arg0); @Override boolean isCaseSensitive(int arg0); @Override boolean isCurrency(int arg0); @Override boolean isDefinitelyWritable(int arg0); @Override int isNullable(int arg0); @Override boolean isReadOnly(int arg0); @Override boolean isSearchable(int arg0); @Override boolean isSigned(int arg0); @Override boolean isWritable(int arg0); }### Answer:
@Test public void testGetColumnName() throws SQLException { boolean flag = false; metadata = new IoTDBMetadataResultMetadata(null); try { metadata.getColumnName(1); } catch (Exception e) { flag = true; } assertEquals(flag, true); try { String[] nullArray = {}; metadata = new IoTDBMetadataResultMetadata(nullArray); metadata.getColumnName(1); } catch (Exception e) { flag = true; } assertEquals(flag, true); metadata = new IoTDBMetadataResultMetadata(cols); try { metadata.getColumnName(0); } catch (Exception e) { flag = true; } assertEquals(flag, true); flag = false; try { metadata.getColumnName(cols.length + 1); } catch (Exception e) { flag = true; } assertEquals(flag, true); for (int i = 1; i <= cols.length; i++) { assertEquals(metadata.getColumnName(i), cols[i - 1]); } } |
### Question:
IoTDBResultMetadata implements ResultSetMetaData { @Override public int getColumnCount() throws SQLException { if (columnInfoList == null || columnInfoList.size() == 0) { throw new SQLException("No column exists"); } return columnInfoList.size(); } IoTDBResultMetadata(List<String> columnInfoList, String operationType,
List<String> columnTypeList); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override String getCatalogName(int arg0); @Override String getColumnClassName(int arg0); @Override int getColumnCount(); @Override int getColumnDisplaySize(int arg0); @Override String getColumnLabel(int column); @Override String getColumnName(int column); @Override int getColumnType(int column); @Override String getColumnTypeName(int arg0); @Override int getPrecision(int arg0); @Override int getScale(int arg0); @Override String getSchemaName(int arg0); @Override String getTableName(int arg0); @Override boolean isAutoIncrement(int arg0); @Override boolean isCaseSensitive(int arg0); @Override boolean isCurrency(int arg0); @Override boolean isDefinitelyWritable(int arg0); @Override int isNullable(int arg0); @Override boolean isReadOnly(int arg0); @Override boolean isSearchable(int arg0); @Override boolean isSigned(int arg0); @Override boolean isWritable(int arg0); }### Answer:
@Test public void testGetColumnCount() throws SQLException { metadata = new IoTDBResultMetadata(null, null, null); boolean flag = false; try { metadata.getColumnCount(); } catch (Exception e) { flag = true; } assertEquals(flag, true); List<String> columnInfoList = new ArrayList<>(); flag = false; try { metadata = new IoTDBResultMetadata(columnInfoList, null, null); metadata.getColumnCount(); } catch (Exception e) { flag = true; } assertEquals(flag, true); columnInfoList.add("root.a.b.c"); assertEquals(metadata.getColumnCount(), 1); } |
### Question:
IoTDBResultMetadata implements ResultSetMetaData { @Override public String getColumnName(int column) throws SQLException { return getColumnLabel(column); } IoTDBResultMetadata(List<String> columnInfoList, String operationType,
List<String> columnTypeList); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override String getCatalogName(int arg0); @Override String getColumnClassName(int arg0); @Override int getColumnCount(); @Override int getColumnDisplaySize(int arg0); @Override String getColumnLabel(int column); @Override String getColumnName(int column); @Override int getColumnType(int column); @Override String getColumnTypeName(int arg0); @Override int getPrecision(int arg0); @Override int getScale(int arg0); @Override String getSchemaName(int arg0); @Override String getTableName(int arg0); @Override boolean isAutoIncrement(int arg0); @Override boolean isCaseSensitive(int arg0); @Override boolean isCurrency(int arg0); @Override boolean isDefinitelyWritable(int arg0); @Override int isNullable(int arg0); @Override boolean isReadOnly(int arg0); @Override boolean isSearchable(int arg0); @Override boolean isSigned(int arg0); @Override boolean isWritable(int arg0); }### Answer:
@Test public void testGetColumnName() throws SQLException { metadata = new IoTDBResultMetadata(null, null, null); boolean flag = false; try { metadata.getColumnName(1); } catch (Exception e) { flag = true; } assertEquals(flag, true); List<String> columnInfoList = new ArrayList<>(); metadata = new IoTDBResultMetadata(columnInfoList, null, null); flag = false; try { metadata.getColumnName(1); } catch (Exception e) { flag = true; } assertEquals(flag, true); String[] colums = {"root.a.b.c1", "root.a.b.c2", "root.a.b.c3"}; metadata = new IoTDBResultMetadata(Arrays.asList(colums), null, null); flag = false; try { metadata.getColumnName(colums.length + 1); } catch (Exception e) { flag = true; } assertEquals(flag, true); flag = false; try { metadata.getColumnName(0); } catch (Exception e) { flag = true; } assertEquals(flag, true); for (int i = 1; i <= colums.length; i++) { assertEquals(metadata.getColumnLabel(i), colums[i - 1]); } } |
### Question:
IoTDBResultMetadata implements ResultSetMetaData { @Override public int getColumnType(int column) throws SQLException { if (columnInfoList == null || columnInfoList.size() == 0) { throw new SQLException("No column exists"); } if (column > columnInfoList.size()) { throw new SQLException(String.format("column %d does not exist", column)); } if (column <= 0) { throw new SQLException(String.format("column index should start from 1", column)); } if (column == 1) { return Types.TIMESTAMP; } String columnType = columnTypeList.get(column - 2); switch (columnType.toUpperCase()) { case "BOOLEAN": return Types.BOOLEAN; case "INT32": return Types.INTEGER; case "INT64": return Types.BIGINT; case "FLOAT": return Types.FLOAT; case "DOUBLE": return Types.DOUBLE; case "TEXT": return Types.VARCHAR; default: break; } return 0; } IoTDBResultMetadata(List<String> columnInfoList, String operationType,
List<String> columnTypeList); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override String getCatalogName(int arg0); @Override String getColumnClassName(int arg0); @Override int getColumnCount(); @Override int getColumnDisplaySize(int arg0); @Override String getColumnLabel(int column); @Override String getColumnName(int column); @Override int getColumnType(int column); @Override String getColumnTypeName(int arg0); @Override int getPrecision(int arg0); @Override int getScale(int arg0); @Override String getSchemaName(int arg0); @Override String getTableName(int arg0); @Override boolean isAutoIncrement(int arg0); @Override boolean isCaseSensitive(int arg0); @Override boolean isCurrency(int arg0); @Override boolean isDefinitelyWritable(int arg0); @Override int isNullable(int arg0); @Override boolean isReadOnly(int arg0); @Override boolean isSearchable(int arg0); @Override boolean isSigned(int arg0); @Override boolean isWritable(int arg0); }### Answer:
@Test public void testGetColumnType() throws SQLException { metadata = new IoTDBResultMetadata(null, null, null); boolean flag = false; try { metadata.getColumnType(1); } catch (Exception e) { flag = true; } assertEquals(flag, true); List<String> columnInfoList = new ArrayList<>(); metadata = new IoTDBResultMetadata(columnInfoList, null, null); flag = false; try { metadata.getColumnType(1); } catch (Exception e) { flag = true; } assertEquals(flag, true); String[] columns = {"timestamp", "root.a.b.boolean", "root.a.b.int32", "root.a.b.int64", "root.a.b.float", "root.a.b.double", "root.a.b.text"}; String[] typesString = {"BOOLEAN", "INT32", "INT64", "FLOAT", "DOUBLE", "TEXT"}; int[] types = {Types.BOOLEAN, Types.INTEGER, Types.BIGINT, Types.FLOAT, Types.DOUBLE, Types.VARCHAR}; metadata = new IoTDBResultMetadata(Arrays.asList(columns), null, Arrays.asList(typesString)); flag = false; try { metadata.getColumnType(columns.length + 1); } catch (Exception e) { flag = true; } assertEquals(flag, true); flag = false; try { metadata.getColumnType(0); } catch (Exception e) { flag = true; } assertEquals(flag, true); assertEquals(metadata.getColumnType(1), Types.TIMESTAMP); for (int i = 1; i <= types.length; i++) { assertEquals(metadata.getColumnType(i + 1), types[i - 1]); } } |
### Question:
IoTDBResultMetadata implements ResultSetMetaData { @Override public String getColumnTypeName(int arg0) throws SQLException { return operationType; } IoTDBResultMetadata(List<String> columnInfoList, String operationType,
List<String> columnTypeList); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override String getCatalogName(int arg0); @Override String getColumnClassName(int arg0); @Override int getColumnCount(); @Override int getColumnDisplaySize(int arg0); @Override String getColumnLabel(int column); @Override String getColumnName(int column); @Override int getColumnType(int column); @Override String getColumnTypeName(int arg0); @Override int getPrecision(int arg0); @Override int getScale(int arg0); @Override String getSchemaName(int arg0); @Override String getTableName(int arg0); @Override boolean isAutoIncrement(int arg0); @Override boolean isCaseSensitive(int arg0); @Override boolean isCurrency(int arg0); @Override boolean isDefinitelyWritable(int arg0); @Override int isNullable(int arg0); @Override boolean isReadOnly(int arg0); @Override boolean isSearchable(int arg0); @Override boolean isSigned(int arg0); @Override boolean isWritable(int arg0); }### Answer:
@Test public void testGetColumnTypeName() throws SQLException { String operationType = "sum"; metadata = new IoTDBResultMetadata(null, operationType, null); assertEquals(metadata.getColumnTypeName(1), operationType); } |
### Question:
FloatDecoder extends Decoder { @Override public float readFloat(ByteBuffer buffer) { readMaxPointValue(buffer); int value = decoder.readInt(buffer); double result = value / maxPointValue; return (float) result; } FloatDecoder(TSEncoding encodingType, TSDataType dataType); @Override float readFloat(ByteBuffer buffer); @Override double readDouble(ByteBuffer buffer); @Override boolean hasNext(ByteBuffer buffer); @Override Binary readBinary(ByteBuffer buffer); @Override boolean readBoolean(ByteBuffer buffer); @Override short readShort(ByteBuffer buffer); @Override int readInt(ByteBuffer buffer); @Override long readLong(ByteBuffer buffer); @Override void reset(); }### Answer:
@Test public void test() throws Exception { float value = 7.101f; Encoder encoder = new FloatEncoder(TSEncoding.RLE, TSDataType.FLOAT, 3); ByteArrayOutputStream baos = new ByteArrayOutputStream(); encoder.encode(value, baos); encoder.flush(baos); encoder.encode(value + 2, baos); encoder.flush(baos); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); Decoder decoder1 = new FloatDecoder(TSEncoding.RLE, TSDataType.FLOAT); Decoder decoder2 = new FloatDecoder(TSEncoding.RLE, TSDataType.FLOAT); float value1_ = decoder1.readFloat(buffer); float value2_ = decoder2.readFloat(buffer); assertEquals(value, value1_, delta); assertEquals(value + 2, value2_, delta); LOGGER.debug("{} LOGGER.debug("{} } |
### Question:
IoTDBConnection implements Connection { public void setTimeZone(String zoneId) throws TException, IoTDBSQLException { TSSetTimeZoneReq req = new TSSetTimeZoneReq(zoneId); TSSetTimeZoneResp resp = client.setTimeZone(req); Utils.verifySuccess(resp.getStatus()); this.zoneId = ZoneId.of(zoneId); } 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; }### Answer:
@Test public void testSetTimeZone() throws TException, IoTDBSQLException { String timeZone = "Asia/Shanghai"; when(client.setTimeZone(any(TSSetTimeZoneReq.class))) .thenReturn(new TSSetTimeZoneResp(Status_SUCCESS)); connection.client = client; connection.setTimeZone(timeZone); assertEquals(connection.getTimeZone(), timeZone); } |
### Question:
IoTDBConnection implements Connection { public String getTimeZone() throws TException, IoTDBSQLException { if (zoneId != null) { return zoneId.toString(); } TSGetTimeZoneResp resp = client.getTimeZone(); Utils.verifySuccess(resp.getStatus()); return resp.getTimeZone(); } 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; }### Answer:
@Test public void testGetTimeZone() throws IoTDBSQLException, TException { String timeZone = "GMT+:08:00"; when(client.getTimeZone()).thenReturn(new TSGetTimeZoneResp(Status_SUCCESS, timeZone)); connection.client = client; assertEquals(connection.getTimeZone(), timeZone); } |
### Question:
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; }### Answer:
@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)); } } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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++; } } |
### Question:
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(); }### Answer:
@Test public void testEquals() { assertEquals(processor1, processor3); assertFalse(processor1.equals(processor2)); } |
### Question:
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); }### Answer:
@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(); } } |
### Question:
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); }### Answer:
@Test public void testOFFileMetadata() throws Exception { OFFileMetadata ofFileMetadata = OverflowTestHelper.createOFFileMetadata(); serialize(ofFileMetadata); OFFileMetadata deOFFileMetadata = deSerialize(); OverflowUtils.isOFFileMetadataEqual(ofFileMetadata, deOFFileMetadata); } |
### Question:
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); }### Answer:
@Test public void testOFRowGroupListMetadata() throws Exception { OFRowGroupListMetadata ofRowGroupListMetadata = OverflowTestHelper .createOFRowGroupListMetadata(); serialize(ofRowGroupListMetadata); OFRowGroupListMetadata deOfRowGroupListMetadata = deSerialized(); OverflowUtils.isOFRowGroupListMetadataEqual(ofRowGroupListMetadata, deOfRowGroupListMetadata); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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(); }### Answer:
@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++; } } |
### Question:
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); }### Answer:
@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(); } } |
### Question:
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); }### Answer:
@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(); } } |
### Question:
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); }### Answer:
@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(); } } |
### Question:
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); }### Answer:
@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(); } } |
### Question:
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); }### Answer:
@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(); } } |
### Question:
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); }### Answer:
@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(); } } |
### Question:
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); }### Answer:
@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(""); } |
### Question:
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; }### Answer:
@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))); } |
### Question:
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; }### Answer:
@Test void testGetTextBoxAlphaValue() { IconHelper.setTextBoxAlphaValue(200); assertEquals(IconHelper.getTextBoxAlphaValue(), 200); } |
### Question:
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; }### Answer:
@Test void testFillBackground() { assertTrue(IconHelper.fillBackground(IconHelper.createColoredFrame(Color.GREEN).image, Color.GREEN) instanceof BufferedImage); } |
### Question:
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; }### Answer:
@Test void testFlipHoriz() { assertTrue(IconHelper.flipHoriz(IconHelper.createColoredFrame(Color.GREEN).image) instanceof BufferedImage); } |
### Question:
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; }### Answer:
@Test void testGetImage() { assertTrue(IconHelper.getImage(IconHelper.TEMP_BLACK_ICON) instanceof SDImage); } |
### Question:
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; }### Answer:
@Test void testGetImageFromResource() { assertTrue(IconHelper.getImageFromResource("/resources/icons/frame.png") instanceof BufferedImage); } |
### Question:
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; }### Answer:
@Test void testLoadImageSafeString() { assertTrue(IconHelper.loadImageSafe("/resources/icons/frame.png") instanceof SDImage); } |
### Question:
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; }### Answer:
@Test void testLoadImageFromResource() { } |
### Question:
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; }### Answer:
@Test void testLoadImageFromResourceSafe() { } |
### Question:
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; }### Answer:
@Test void testSetTextBoxAlphaValue() { IconHelper.setTextBoxAlphaValue(200); assertEquals(IconHelper.getTextBoxAlphaValue(), 200); } |
### Question:
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; }### Answer:
@Test void testRotate180() { } |
### Question:
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; }### Answer:
@Test void testGetRollingTextPadding() { IconHelper.setRollingTextPadding(8); assertEquals(IconHelper.getRollingTextPadding(), 8); } |
### Question:
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; }### Answer:
@Test void testSetRollingTextPadding() { IconHelper.setRollingTextPadding(8); assertEquals(IconHelper.getRollingTextPadding(), 8); } |
### Question:
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; }### Answer:
@Test void testCreateColoredFrame() { assertTrue(IconHelper.createColoredFrame(Color.GREEN) instanceof SDImage); } |
### Question:
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; }### Answer:
@Test void testApplyAlpha() { IconHelper.applyAlpha(IconHelper.createColoredFrame(Color.GREEN).image, IconHelper.FRAME); assertTrue(true); } |
### Question:
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; }### Answer:
@Test void testCacheImage() { assertTrue(IconHelper.cacheImage("TEST-PATH", IconHelper.createFolderImage(Color.GREEN, true, Color.GREEN.darker()).image) instanceof SDImage); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@Test void testApplyFrame() { assertTrue(IconHelper.applyFrame(IconHelper.createColoredFrame(Color.GREEN).image, Color.GREEN.darker()) instanceof BufferedImage); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testDuplicateTagKeysUsingParse() { Query.parse("metric k1=v1 k1=v2"); } |
### Question:
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); }### Answer:
@Test public void testEmpty() { MetricStore store = new OffHeapVarBitMetricStore(1, testFileName); assertTrue(store.getSeries(1).isEmpty()); assertTrue(store.getSeries(2).isEmpty()); } |
### Question:
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); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testReadOnlyStore() { MetricStore store = new OffHeapVarBitMetricStore(1, testFileName); store.addPoint(1, 1, 1); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@Test public void testEmptyPoints() { VarBitTimeSeries series = new VarBitTimeSeries(); TimeSeriesIterator dr = series.read(); List<Point> points = dr.getPoints(); assertTrue(points.isEmpty()); } |
### Question:
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(); }### Answer:
@Test public void testEmpty() { MetricStore store = new VarBitMetricStore(); assertTrue(store.getSeries(1).isEmpty()); assertTrue(store.getSeries(2).isEmpty()); } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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); } |
### Question:
EtcdHeartbeatLease implements AutoCloseable { public Long getLeaseId() { initLease(); return leaseId; } EtcdHeartbeatLease(Client etcdClient, HeartbeatProperties properties); void initLease(); Long getLeaseId(); void revoke(); @Override void close(); }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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; }### Answer:
@Test public void creditTest() throws CardException { sendCredit(new byte[]{0x00, 0x05}, 0x9000, new byte[]{0x00, 0x05}); assertArrayEquals(new byte[]{0x00, 0x05}, getBalance().getData()); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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)); } } |
### Question:
ProxyFactory { static <T> T proxyFor(Class<T> type, InvocationHandler interceptor, Errors errors) throws ErrorsException { return proxyFor(type, interceptor, errors, Boolean.FALSE); } }### Answer:
@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); } |
### Question:
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); }### Answer:
@Test(expectedExceptions = MappingException.class) public void shouldThrowOnInvalidString() { convert("abc"); } |
### Question:
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); }### Answer:
@Test public void testToArrayNoPresenterYet() { Object[] arr = MapObjs.toArray(null); assertEquals(arr.length, 0, "Empty array: " + Arrays.toString(arr)); } |
### Question:
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); }### Answer:
@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')); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.