method2testcases stringlengths 118 6.63k |
|---|
### Question:
Strings { @Contract("!null,_->!null; null,_->null") public static String lastPart(@Nullable final String string, final char delimiter) { if (string == null) return null; int pos = string.lastIndexOf(delimiter); if (pos >= 0) { return string.substring(pos+1); } else { return string; } } @SuppressWarnings({"StringEquality", "SimplifiableIfStatement"}) static boolean eq(final String str1, final String str2); @SuppressWarnings({"StringEquality", "SimplifiableIfStatement"}) static boolean eq(final String str1, final String str2, final boolean caseSensitive); @NotNull static String ensureStartsWith(@NotNull final String str, final char c); @NotNull static String ensureEndsWith(@NotNull final String str, final char c); @NotNull static String removeEnding(@NotNull final String str, @NotNull final String ending); @NotNull static String rtrim(@NotNull final String str); @NotNull static String replace(@NotNull final String where, @NotNull final String what, @NotNull final String with); @NotNull static String repeat(@NotNull final String what, @Nullable final String delimiter, int count); @Contract("null,_->false") static boolean matches(@Nullable final CharSequence string, @NotNull final Pattern pattern); @Contract("null,_,_->false") static boolean matches(@Nullable final CharSequence string, @NotNull final String pattern, boolean caseSensitive); @Contract("!null->!null; null->null") static String upper(@Nullable final String string); @Contract("!null->!null; null->null") static String lower(@Nullable final String string); @Contract("!null->!null; null->null") static String minimizeSpaces(@Nullable final String string); @Contract("!null,_->!null; null,_->null") static String lastPart(@Nullable final String string, final char delimiter); }### Answer:
@Test public void lastPart_basic() { assertThat(lastPart("aaa.bbb.ccc", '.')).isEqualTo("ccc"); assertThat(lastPart("dddd", '.')).isEqualTo("dddd"); assertThat(lastPart("", '.')).isEqualTo(""); assertThat(lastPart(null, '.')).isNull(); }
@Test public void lastPart_same() { final String s = "dddd"; assertThat(lastPart(s, '.')).isSameAs(s); }
@Test public void lastPart_delimiterAtTheEnd() { final String s = "word/"; assertThat(lastPart(s, '/')).isEqualTo(""); } |
### Question:
Numbers { public static boolean valuesAreEqual(@Nullable final Number x, @Nullable final Number y) { if (x == y) return true; if (x == null || y == null) return false; return x.getClass() == y.getClass() ? x.equals(y) : x.toString().equals(y.toString()); } static boolean valuesAreEqual(@Nullable final Number x, @Nullable final Number y); @SuppressWarnings("unchecked") @Contract(value = "_,!null -> !null; _,null -> null", pure = true) static N convertNumber(final Class<N> numberClass, final Number number); @Contract(value = "!null -> !null; null -> null", pure = true) static Number convertNumberSmartly(final BigDecimal decimal); static int parseIntSafe(@Nullable final String str); static long parseLongSafe(@Nullable final String str); static final Byte BYTE_ZERO; static final BigDecimal DECIMAL_ZERO; static final BigDecimal DECIMAL_MIN_LONG; static final BigDecimal DECIMAL_MAX_LONG; }### Answer:
@Test public void valuesAreEqual_basic() { assertThat(valuesAreEqual(123, 123L)).isTrue(); assertThat(valuesAreEqual(123, BigInteger.valueOf(123L))).isTrue(); assertThat(valuesAreEqual(123.45f, new BigDecimal("123.45"))).isTrue(); }
@Test public void valuesAreEqual_nulls() { assertThat(valuesAreEqual(null, null)).isTrue(); assertThat(valuesAreEqual(111, null)).isFalse(); assertThat(valuesAreEqual(null, 222)).isFalse(); } |
### Question:
Numbers { @SuppressWarnings("unchecked") @Contract(value = "_,!null -> !null; _,null -> null", pure = true) public static <N extends Number> N convertNumber(final Class<N> numberClass, final Number number) { if (number == null) return null; if (numberClass.isAssignableFrom(number.getClass())) return (N) number; if (numberClass == Byte.class || numberClass == byte.class) return (N) new Byte(number.byteValue()); if (numberClass == Short.class || numberClass == short.class) return (N) new Short(number.shortValue()); if (numberClass == Integer.class || numberClass == int.class) return (N) new Integer(number.intValue()); if (numberClass == Long.class || numberClass == long.class) return (N) new Long(number.longValue()); if (numberClass == Float.class || numberClass == float.class) return (N) new Float(number.floatValue()); if (numberClass == Double.class || numberClass == double.class) return (N) new Double(number.doubleValue()); if (numberClass == BigInteger.class) return (N) new BigInteger(number.toString()); if (numberClass == BigDecimal.class) return (N) new BigDecimal(number.toString()); String message = String.format("Unknown how to convert value (%s) of type %s to %s.", number.toString(), number.getClass().getCanonicalName(), numberClass.getCanonicalName()); throw new IllegalArgumentException(message); } static boolean valuesAreEqual(@Nullable final Number x, @Nullable final Number y); @SuppressWarnings("unchecked") @Contract(value = "_,!null -> !null; _,null -> null", pure = true) static N convertNumber(final Class<N> numberClass, final Number number); @Contract(value = "!null -> !null; null -> null", pure = true) static Number convertNumberSmartly(final BigDecimal decimal); static int parseIntSafe(@Nullable final String str); static long parseLongSafe(@Nullable final String str); static final Byte BYTE_ZERO; static final BigDecimal DECIMAL_ZERO; static final BigDecimal DECIMAL_MIN_LONG; static final BigDecimal DECIMAL_MAX_LONG; }### Answer:
@TestWithParams(params = "CONVERT_CASES") public void convert_basic(Number number, Class<Number> toClass) { Number convertedNumber = Numbers.convertNumber(toClass, number); assertThat(convertedNumber).isNotNull() .isExactlyInstanceOf(toClass); String originalString = removeEnding(number.toString(), ".0"); String convertedString = removeEnding(convertedNumber.toString(),".0"); assertThat(convertedString).isEqualTo(originalString); } |
### Question:
Numbers { @Contract(value = "!null -> !null; null -> null", pure = true) public static Number convertNumberSmartly(final BigDecimal decimal) { if (decimal == null) return null; if (decimal.equals(Numbers.DECIMAL_ZERO)) return BYTE_ZERO; final int precision = decimal.precision(); final int scale = decimal.scale(); Number num; if (scale == 0) { try { if (precision <= 19 && decimal.compareTo(Numbers.DECIMAL_MIN_LONG) >= 0 && decimal.compareTo(Numbers.DECIMAL_MAX_LONG) <= 0) { long v = decimal.longValueExact(); if (-128 <= v && v <= 127) num = (byte) v; else if (-32768 <= v && v <= 32767) num = (short) v; else if (Integer.MIN_VALUE <= v && v <= Integer.MAX_VALUE) num = (int) v; else num = v; } else { num = decimal.toBigIntegerExact(); } } catch (ArithmeticException ae) { num = decimal; } } else { if (precision <= 6) { num = decimal.floatValue(); } else if (precision <= 15) { num = decimal.doubleValue(); } else { num = decimal; } } return num; } static boolean valuesAreEqual(@Nullable final Number x, @Nullable final Number y); @SuppressWarnings("unchecked") @Contract(value = "_,!null -> !null; _,null -> null", pure = true) static N convertNumber(final Class<N> numberClass, final Number number); @Contract(value = "!null -> !null; null -> null", pure = true) static Number convertNumberSmartly(final BigDecimal decimal); static int parseIntSafe(@Nullable final String str); static long parseLongSafe(@Nullable final String str); static final Byte BYTE_ZERO; static final BigDecimal DECIMAL_ZERO; static final BigDecimal DECIMAL_MIN_LONG; static final BigDecimal DECIMAL_MAX_LONG; }### Answer:
@TestWithParams(params = "CONVERT_SMART_CASES") public void convertNumberSmartly_basic(Number origin) { BigDecimal d = new BigDecimal(origin.toString()); Number num = convertNumberSmartly(d); assertThat(num).isEqualTo(origin); } |
### Question:
Numbers { public static int parseIntSafe(@Nullable final String str) { if (str == null) { return 0; } try { final String s = str.trim(); if (s.isEmpty()) return 0; if (s.charAt(0) == '+') return Integer.parseInt(s.substring(1)); return Integer.parseInt(s); } catch (NumberFormatException e) { return 0; } } static boolean valuesAreEqual(@Nullable final Number x, @Nullable final Number y); @SuppressWarnings("unchecked") @Contract(value = "_,!null -> !null; _,null -> null", pure = true) static N convertNumber(final Class<N> numberClass, final Number number); @Contract(value = "!null -> !null; null -> null", pure = true) static Number convertNumberSmartly(final BigDecimal decimal); static int parseIntSafe(@Nullable final String str); static long parseLongSafe(@Nullable final String str); static final Byte BYTE_ZERO; static final BigDecimal DECIMAL_ZERO; static final BigDecimal DECIMAL_MIN_LONG; static final BigDecimal DECIMAL_MAX_LONG; }### Answer:
@TestWithParams(params = "INT_CASES") public void parseIntSafe_with(String str, int result) { final int value = parseIntSafe(str); assertThat(value).isEqualTo(result); } |
### Question:
Numbers { public static long parseLongSafe(@Nullable final String str) { if (str == null) { return 0; } try { final String s = str.trim(); if (s.isEmpty()) return 0L; if (s.charAt(0) == '+') return Long.parseLong(s.substring(1)); return Long.parseLong(s); } catch (NumberFormatException e) { return 0; } } static boolean valuesAreEqual(@Nullable final Number x, @Nullable final Number y); @SuppressWarnings("unchecked") @Contract(value = "_,!null -> !null; _,null -> null", pure = true) static N convertNumber(final Class<N> numberClass, final Number number); @Contract(value = "!null -> !null; null -> null", pure = true) static Number convertNumberSmartly(final BigDecimal decimal); static int parseIntSafe(@Nullable final String str); static long parseLongSafe(@Nullable final String str); static final Byte BYTE_ZERO; static final BigDecimal DECIMAL_ZERO; static final BigDecimal DECIMAL_MIN_LONG; static final BigDecimal DECIMAL_MAX_LONG; }### Answer:
@TestWithParams(params = "LONG_CASES") public void parseLongSafe_with(String str, long result) { final long value = parseLongSafe(str); assertThat(value).isEqualTo(result); } |
### Question:
Version implements Comparable<Version>, Serializable { @NotNull public Version truncate(final int n) { if (elements.length <= n) return this; if (n < 0) throw new IllegalArgumentException("Negative desired size: " + n); int m = n; while (m > 0 && elements[m-1] == 0) m--; if (m == 0) return ZERO; final int[] newElements = new int[m]; System.arraycopy(this.elements, 0, newElements, 0, m); return new Version(newElements); } private Version(@NotNull final int[] elements); static Version of(@NotNull final String string); static Version of(@NotNull final int... elements); static Version of(@NotNull final Integer[] elements); int get(int index); int size(); @NotNull Version truncate(final int n); @NotNull Version truncateNegatives(); int compareTo(@NotNull final Version that); int compareTo(final int... that); boolean isOrGreater(final int... than); boolean isOrGreater(@NotNull final Version than); boolean less(final int... than); boolean less(@NotNull final Version than); @Override boolean equals(final Object o); @Override int hashCode(); @NotNull String toString(); @NotNull String toString(int minimumElements, int maximumElements); @NotNull int[] toArray(); static final Version ZERO; }### Answer:
@Test public void truncate_ZERO() { Version z = Version.ZERO; Version z1 = z.truncate(1); assertThat(z1).isSameAs(z); } |
### Question:
Version implements Comparable<Version>, Serializable { @NotNull public Version truncateNegatives() { final int n = elements.length; for (int k = 0; k < n; k++) if (elements[k] < 0) return truncate(k); return this; } private Version(@NotNull final int[] elements); static Version of(@NotNull final String string); static Version of(@NotNull final int... elements); static Version of(@NotNull final Integer[] elements); int get(int index); int size(); @NotNull Version truncate(final int n); @NotNull Version truncateNegatives(); int compareTo(@NotNull final Version that); int compareTo(final int... that); boolean isOrGreater(final int... than); boolean isOrGreater(@NotNull final Version than); boolean less(final int... than); boolean less(@NotNull final Version than); @Override boolean equals(final Object o); @Override int hashCode(); @NotNull String toString(); @NotNull String toString(int minimumElements, int maximumElements); @NotNull int[] toArray(); static final Version ZERO; }### Answer:
@Test public void truncateNegatives_ZERO() { assertThat(Version.ZERO.truncateNegatives()).isSameAs(Version.ZERO); } |
### Question:
Version implements Comparable<Version>, Serializable { public static Version of(@NotNull final String string) { ArrayList<Integer> b = new ArrayList<Integer>(5); final String[] substrings = string.split("[.,\\-_ ]|(?<=\\d)(?!\\d)|(?<!\\d)(?=\\d)"); for (String ss : substrings) { String ss2 = ss.trim().toLowerCase(Locale.ENGLISH); if (ss2.isEmpty()) continue; Integer special = SPECIAL_VALUES.get(ss2); if (special != null) b.add(special); else { try { Integer v = new Integer(ss2); b.add(v); } catch (NumberFormatException e) { break; } } } if (b.isEmpty()) throw new IllegalArgumentException("Failed to parse version \""+string+"\""); if (b.size() == 1 && b.get(0) == 0) return ZERO; return of(b.toArray(new Integer[b.size()])); } private Version(@NotNull final int[] elements); static Version of(@NotNull final String string); static Version of(@NotNull final int... elements); static Version of(@NotNull final Integer[] elements); int get(int index); int size(); @NotNull Version truncate(final int n); @NotNull Version truncateNegatives(); int compareTo(@NotNull final Version that); int compareTo(final int... that); boolean isOrGreater(final int... than); boolean isOrGreater(@NotNull final Version than); boolean less(final int... than); boolean less(@NotNull final Version than); @Override boolean equals(final Object o); @Override int hashCode(); @NotNull String toString(); @NotNull String toString(int minimumElements, int maximumElements); @NotNull int[] toArray(); static final Version ZERO; }### Answer:
@Test public void parse_currentJavaVersion() { Version.of(System.getProperty("java.runtime.version")); }
@Test public void equal_zeros() { Version v1 = Version.of(1,2,3), v2 = Version.of(1,2,3,0,0); assertThat(v2).isEqualTo(v1); assertThat(v1).isEqualTo(v2); }
@Test public void equal_zeros_and_empty() { Version v1 = Version.of(), v2 = Version.of(0,0,0); assertThat(v2).isEqualTo(v1); assertThat(v1).isEqualTo(v2); } |
### Question:
Rewriters { public static StringOperator replace(@NotNull final String what, @NotNull final String with) { return new StringOperator() { @Override public String apply(final String arg) { return Strings.replace(arg, what, with); } }; } static StringOperator replace(@NotNull final String what, @NotNull final String with); static StringOperator replace(@NotNull final Map<String,String> map); }### Answer:
@Test public void replace_1_basic() { assertThat(Rewriters.replace("YYY","TTT").apply("XXX YYY ZZZ")).isEqualTo("XXX TTT ZZZ"); }
@Test public void replace_1_same() { String str = "ABCDE"; assertThat(Rewriters.replace("YYY","TTT").apply(str)).isSameAs(str); }
@Test public void replace_map_1() { assertThat(Rewriters.replace(Collections.singletonMap("YYY", "TTT")).apply("XXX YYY ZZZ")) .isEqualTo("XXX TTT ZZZ"); }
@Test public void replace_map_2x2() { Map<String,String> map = new HashMap<String, String>(); map.put("AAA", "X"); map.put("BBB", "YYYYY"); String original = "AAAAAABBBBBB"; String expected = "XXYYYYYYYYYY"; assertThat(Rewriters.replace(map).apply(original)).isEqualTo(expected); }
@Test public void replace_map_same() { String original = "1234567890"; assertThat(Rewriters.replace(Collections.singletonMap("YYY", "TTT")).apply(original)) .isSameAs(original); } |
### Question:
SqlScriptBuilder { @NotNull public SqlScript build() { return new SqlScript(myStatements); } void add(@NotNull String... commands); void add(@NotNull SqlCommand... commands); void add(@NotNull SqlScript... scripts); void parse(@NotNull final String text); @NotNull SqlScript build(); }### Answer:
@Test public void parse_1() { String commandText = "select * from dual"; final SqlScript script = build(commandText); assertThat(script.hasStatements()).isTrue(); assertThat(script.getStatements()).hasSize(1); SqlStatement statement = script.getStatements().get(0); assertThat(statement.getSourceText()).isEqualTo(commandText); assertThat(statement.getRow()).isEqualTo(1); }
@Test public void parse_2_in_2_lines() { String text = "create table X;\n drop table X"; final SqlScript script = build(text); assertThat(script.count()).isEqualTo(2); assertThat(script.getStatements().get(0).getSourceText()).isEqualTo("create table X"); assertThat(script.getStatements().get(1).getSourceText()).isEqualTo("drop table X"); }
@Test public void parse_singleLineComment() { String text = "-- a single line comment \n" + "do something"; final SqlScript script = build(text); assertThat(script.count()).isEqualTo(1); assertThat(script.getStatements().get(0).getSourceText()).isEqualTo("do something"); }
@Test public void parse_singleLineComment_preserveOracleHint() { String text = "select --+index(i) \n" + " all fields \n" + "from my_table \n"; final SqlScript script = build(text); assertThat(script.hasStatements()).isTrue(); assertThat(script.count()).isEqualTo(1); final String queryText = script.getStatements().get(0).getSourceText(); assertThat(queryText).contains("--+index(i)"); }
@Test public void parse_multiLineComment_1() { String text = "\n" + "do something"; final SqlScript script = build(text); assertThat(script.count()).isEqualTo(1); assertThat(script.getStatements().get(0).getSourceText()).isEqualTo("do something"); }
@Test public void parse_multiLineComment_3() { String text = " \n" + "do something \n"; final SqlScript script = build(text); assertThat(script.count()).isEqualTo(1); assertThat(script.getStatements().get(0).getSourceText()).isEqualTo("do something"); }
@Test public void parse_multiLineComment_preserveOracleHint() { String text = "select * \n" + "from table \n"; final SqlScript script = build(text); assertThat(script.count()).isEqualTo(1); final String queryText = script.getStatements().get(0).getSourceText(); assertThat(queryText).contains(""); }
@Test public void parse_OraclePackage() { final SqlScript script = build(ORACLE_PKG1); assertThat(script.getStatements()).hasSize(2); assertThat(script.getStatements().get(0).getSourceText()).startsWith("create package pkg1") .endsWith("end pkg1;"); assertThat(script.getStatements().get(1).getSourceText()).startsWith("create package body") .endsWith("end;"); }
@Test public void parse_OraclePackage_lines() { final SqlScript script = build(ORACLE_PKG1); assertThat(script.getStatements()).hasSize(2) .extracting("row") .containsSequence(1, 9); } |
### Question:
SqlScript { @NotNull public List<? extends SqlStatement> getStatements() { return Collections.unmodifiableList(Arrays.asList(myStatements)); } SqlScript(@NotNull final String... statements); SqlScript(@NotNull final SqlStatement... statements); SqlScript(@NotNull final SqlScript... scripts); SqlScript(@NotNull final Collection<? extends SqlStatement> statements); private SqlScript(@NotNull final SqlStatement[] statements, boolean copy); @NotNull List<? extends SqlStatement> getStatements(); boolean hasStatements(); int count(); @Override @NotNull String toString(); }### Answer:
@Test public void construct_2() { SqlScript script1 = new SqlScript("command1"), script2 = new SqlScript("command2"); SqlScript script = new SqlScript(script1, script2); assertThat((Integer)script.getStatements().size()).isEqualTo((Integer)2); assertThat(script.getStatements().get(0).getSourceText()).isEqualTo("command1"); assertThat(script.getStatements().get(1).getSourceText()).isEqualTo("command2"); } |
### Question:
SqlScript { @Override @NotNull public String toString() { switch (myCount) { case 0: return ""; case 1: return myStatements[0].getSourceText(); default: final StringBuilder b = new StringBuilder(); final String delimiterString = getScriptDelimiterString(); b.append(myStatements[0].getSourceText()); for (int i = 1; i < myCount; i++) { if (b.charAt(b.length()-1) != '\n') b.append('\n'); b.append(delimiterString).append('\n'); b.append(myStatements[i].getSourceText()); } return b.toString(); } } SqlScript(@NotNull final String... statements); SqlScript(@NotNull final SqlStatement... statements); SqlScript(@NotNull final SqlScript... scripts); SqlScript(@NotNull final Collection<? extends SqlStatement> statements); private SqlScript(@NotNull final SqlStatement[] statements, boolean copy); @NotNull List<? extends SqlStatement> getStatements(); boolean hasStatements(); int count(); @Override @NotNull String toString(); }### Answer:
@Test public void toString_contains_all_commands() { SqlScript script = new SqlScript("command 1", "command 2"); final String text = script.toString(); assertThat(text).contains("command 1") .contains("command 2"); } |
### Question:
SqlCommand extends SqlStatement { @NotNull @Override public SqlCommand rewrite(@NotNull final StringOperator operator) { String transformedSourceTex = operator.apply(mySourceText); return new SqlCommand(myRow, transformedSourceTex, myName, myDescription); } SqlCommand(@NotNull final TextFragment sourceFragment); SqlCommand(@NotNull final String sourceText, final int row, @Nullable final String commandName); SqlCommand(@NotNull final String sourceText); private SqlCommand(final int row,
@NotNull final String sourceText,
@Nullable final String name,
@NotNull final String description); @NotNull @Override SqlCommand rewrite(@NotNull final StringOperator operator); }### Answer:
@Test public void rewrite_basic() { SqlCommand cmd1 = new SqlCommand("AAA BBB CCC", 33, "name"); SqlCommand cmd2 = cmd1.rewrite(Rewriters.replace("BBB", "XXX")); assertThat(cmd2.getSourceText()).isEqualTo("AAA XXX CCC"); assertThat(cmd2.getRow()).isEqualTo(33); assertThat(cmd2.getName()).isEqualTo("name"); } |
### Question:
BaseRdbmsProvider implements DBRdbmsProvider { @NotNull @Override public BaseFacade openFacade(@NotNull final String connectionString, @Nullable final Properties connectionProperties, final int connectionsLimit, final boolean connect) { boolean ok = false; final IntegralIntermediateFacade intermediateFacade = myIntermediateProvider.openFacade(connectionString, connectionProperties, connectionsLimit); try { final BaseFacade facade = new BaseFacade(intermediateFacade); if (connect) { facade.connect(); } ok = true; return facade; } finally { if (!ok) { intermediateFacade.disconnect(); } } } BaseRdbmsProvider(@NotNull final PrimeIntermediateRdbmsProvider primeIntermediateProvider); BaseRdbmsProvider(@NotNull final IntegralIntermediateRdbmsProvider integralIntermediateProvider); @NotNull @Override Rdbms rdbms(); @NotNull @Override Pattern connectionStringPattern(); @NotNull @Override BaseFacade openFacade(@NotNull final String connectionString,
@Nullable final Properties connectionProperties,
final int connectionsLimit,
final boolean connect); @Nullable @Override I getSpecificService(@NotNull final Class<I> serviceClass,
@NotNull final String serviceName); }### Answer:
@Test public void connect_directly() { final BaseRdbmsProvider provider = new BaseRdbmsProvider(ourUnknownDatabaseProvider); final BaseFacade facade = provider.openFacade(H2_CONNECTION_STRING, null, 1, true); assertThat(facade.isConnected()).isTrue(); facade.disconnect(); assertThat(facade.isConnected()).isFalse(); }
@Test public void connect_remotely() { final BaseRdbmsProvider provider = new BaseRdbmsProvider(ourUnknownDatabaseProvider); final BaseFacade facade = provider.openFacade(H2_CONNECTION_STRING, null, 1, true); assertThat(facade.isConnected()).isTrue(); facade.disconnect(); assertThat(facade.isConnected()).isFalse(); } |
### Question:
BaseRdbmsProvider implements DBRdbmsProvider { @Nullable @Override public <I> I getSpecificService(@NotNull final Class<I> serviceClass, @NotNull final String serviceName) throws ClassCastException { return myIntermediateProvider.getSpecificService(serviceClass, serviceName); } BaseRdbmsProvider(@NotNull final PrimeIntermediateRdbmsProvider primeIntermediateProvider); BaseRdbmsProvider(@NotNull final IntegralIntermediateRdbmsProvider integralIntermediateProvider); @NotNull @Override Rdbms rdbms(); @NotNull @Override Pattern connectionStringPattern(); @NotNull @Override BaseFacade openFacade(@NotNull final String connectionString,
@Nullable final Properties connectionProperties,
final int connectionsLimit,
final boolean connect); @Nullable @Override I getSpecificService(@NotNull final Class<I> serviceClass,
@NotNull final String serviceName); }### Answer:
@Test public void get_intermediate_service() { final BaseRdbmsProvider provider = new BaseRdbmsProvider(ourUnknownDatabaseProvider); final IntegralIntermediateRdbmsProvider intermediateRdbmsProvider = provider.getSpecificService( IntegralIntermediateRdbmsProvider.class, ImplementationAccessibleService.Names.INTERMEDIATE_SERVICE); assertThat(intermediateRdbmsProvider).isSameAs(ourUnknownDatabaseProvider); } |
### Question:
BaseFacade implements DBFacade { @Override public synchronized DBLeasedSession leaseSession() { final IntegralIntermediateSession interSession = instantiateIntermediateSession(); final BaseSession baseSession = new BaseSession(interSession); return new DBLeasedSessionWrapper(baseSession); } BaseFacade(@NotNull final IntegralIntermediateFacade interFacade); @NotNull @Override Rdbms rdbms(); @Override synchronized void connect(); @Override synchronized void reconnect(); @Override synchronized void disconnect(); @Override boolean isConnected(); @Override ConnectionInfo getConnectionInfo(); @Override R inTransaction(final InTransaction<R> operation); @Override void inTransaction(final InTransactionNoResult operation); @Override R inSession(final InSession<R> operation); @Override void inSession(final InSessionNoResult operation); @Override synchronized DBLeasedSession leaseSession(); @Nullable @Override I getSpecificService(@NotNull final Class<I> serviceClass,
@NotNull final String serviceName); }### Answer:
@Test public void leaseSession_basic() { final DBLeasedSession session = myFacade.leaseSession(); assertThat(session.isClosed()).isFalse(); session.ping(); session.close(); assertThat(session.isClosed()).isTrue(); } |
### Question:
BaseFacade implements DBFacade { @Nullable @Override public <I> I getSpecificService(@NotNull final Class<I> serviceClass, @NotNull final String serviceName) throws ClassCastException { return myInterFacade.getSpecificService(serviceClass, serviceName); } BaseFacade(@NotNull final IntegralIntermediateFacade interFacade); @NotNull @Override Rdbms rdbms(); @Override synchronized void connect(); @Override synchronized void reconnect(); @Override synchronized void disconnect(); @Override boolean isConnected(); @Override ConnectionInfo getConnectionInfo(); @Override R inTransaction(final InTransaction<R> operation); @Override void inTransaction(final InTransactionNoResult operation); @Override R inSession(final InSession<R> operation); @Override void inSession(final InSessionNoResult operation); @Override synchronized DBLeasedSession leaseSession(); @Nullable @Override I getSpecificService(@NotNull final Class<I> serviceClass,
@NotNull final String serviceName); }### Answer:
@Test public void get_intermediate_service() { IntegralIntermediateFacade intermediateSession = myFacade.getSpecificService( IntegralIntermediateFacade.class, ImplementationAccessibleService.Names.INTERMEDIATE_SERVICE); assertThat(intermediateSession).isInstanceOf(JdbcIntermediateFacade.class); } |
### Question:
BaseScriptRunner implements DBScriptRunner { @Override public DBScriptRunner run() { List<? extends SqlStatement> statements = myScript.getStatements(); for (SqlStatement statement : statements) { if (statement instanceof SqlCommand) { runCommand((SqlCommand)statement); } if (statement instanceof SqlQuery) { runQuery((SqlQuery) statement); } } return this; } BaseScriptRunner(@NotNull final DBTransaction transaction,
@NotNull final SqlScript script); @Override DBScriptRunner run(); }### Answer:
@Test public void basic_2() { final SqlScript script = new SqlScript("create table TT2(X1 integer)", "drop table TT2"); myFacade.inSession(new InSessionNoResult() { @Override public void run(@NotNull final DBSession session) { session.script(script).run(); } }); }
@Test public void basic_4() { final SqlScript script = new SqlScript("create table TT4(X1 integer)", "insert into TT4 values (44)", "select * from TT4", "drop table TT4"); myFacade.inSession(new InSessionNoResult() { @Override public void run(@NotNull final DBSession session) { session.script(script).run(); } }); }
@Test public void basic_4_with_query() { final SqlScript script = new SqlScript(new SqlCommand("create table TT4a(X1 integer)"), new SqlCommand("insert into TT4a values (44)"), new SqlQuery<Boolean>("select * from TT4a", Layouts.existence()), new SqlCommand("drop table TT4a")); myFacade.inSession(new InSessionNoResult() { @Override public void run(@NotNull final DBSession session) { session.script(script).run(); } }); } |
### Question:
BaseSession implements DBSession, DBLeasedSession, DBTransaction { @SuppressWarnings("unchecked") @Nullable public synchronized <I> I getSpecificService(@NotNull final Class<I> serviceClass, @NotNull final String serviceName) throws ClassCastException { if (serviceName.equalsIgnoreCase(Names.INTERMEDIATE_SERVICE)) { return Objects.castTo(serviceClass, myInterSession); } else { return myInterSession.getSpecificService(serviceClass, serviceName); } } protected BaseSession(@NotNull final IntegralIntermediateSession interSession); @Override void beginTransaction(); @Override boolean isInTransaction(); @Override void commit(); @Override void rollback(); @Override synchronized R inTransaction(final InTransaction<R> operation); @Override synchronized void inTransaction(final InTransactionNoResult operation); @NotNull @Override synchronized DBCommandRunner command(@NotNull final SqlCommand command); @NotNull @Override synchronized DBCommandRunner command(@NotNull final String commandText); @NotNull @Override synchronized BaseQueryRunner<S> query(@NotNull final SqlQuery<S> query); @NotNull @Override synchronized BaseQueryRunner<S> query(@NotNull final String queryText,
@NotNull final ResultLayout<S> layout); @NotNull @Override synchronized DBScriptRunner script(@NotNull final SqlScript script); @SuppressWarnings("unchecked") @Nullable synchronized I getSpecificService(@NotNull final Class<I> serviceClass,
@NotNull final String serviceName); @Override long ping(); synchronized boolean isClosed(); synchronized void close(); }### Answer:
@Test public void get_intermediate_service() { myFacade.inSession(new InSessionNoResult() { @Override public void run(@NotNull final DBSession session) { final IntegralIntermediateSession intermediateSession = session.getSpecificService( IntegralIntermediateSession.class, ImplementationAccessibleService.Names.INTERMEDIATE_SERVICE); assertThat(intermediateSession).isInstanceOf(JdbcIntermediateSession.class); } }); }
@Test public void get_jdbc_connection() { myFacade.inSession(new InSessionNoResult() { @Override public void run(@NotNull final DBSession session) { java.sql.Connection connection = session.getSpecificService(java.sql.Connection.class, ImplementationAccessibleService.Names.JDBC_CONNECTION); assertThat(connection).isNotNull() .isInstanceOf(java.sql.Connection.class); } }); } |
### Question:
Strings { @NotNull public static String ensureStartsWith(@NotNull final String str, final char c) { if (str.length() == 0) { return Character.toString(c); } else { char c1 = str.charAt(0); if (c1 == c) return str; else return c + str; } } @SuppressWarnings({"StringEquality", "SimplifiableIfStatement"}) static boolean eq(final String str1, final String str2); @SuppressWarnings({"StringEquality", "SimplifiableIfStatement"}) static boolean eq(final String str1, final String str2, final boolean caseSensitive); @NotNull static String ensureStartsWith(@NotNull final String str, final char c); @NotNull static String ensureEndsWith(@NotNull final String str, final char c); @NotNull static String removeEnding(@NotNull final String str, @NotNull final String ending); @NotNull static String rtrim(@NotNull final String str); @NotNull static String replace(@NotNull final String where, @NotNull final String what, @NotNull final String with); @NotNull static String repeat(@NotNull final String what, @Nullable final String delimiter, int count); @Contract("null,_->false") static boolean matches(@Nullable final CharSequence string, @NotNull final Pattern pattern); @Contract("null,_,_->false") static boolean matches(@Nullable final CharSequence string, @NotNull final String pattern, boolean caseSensitive); @Contract("!null->!null; null->null") static String upper(@Nullable final String string); @Contract("!null->!null; null->null") static String lower(@Nullable final String string); @Contract("!null->!null; null->null") static String minimizeSpaces(@Nullable final String string); @Contract("!null,_->!null; null,_->null") static String lastPart(@Nullable final String string, final char delimiter); }### Answer:
@Test public void ensureStartsWith_basic() { assertThat(ensureStartsWith("AAAA", 'C')).isEqualTo("CAAAA"); assertThat(ensureStartsWith("CAAAA", 'C')).isEqualTo("CAAAA"); assertThat(ensureStartsWith("", 'C')).isEqualTo("C"); }
@Test public void ensureStartsWith_dontMakeNewInstanceIfAlreadyStarts() { final String str = "CAAA"; final String ensured = ensureStartsWith(str, 'C'); assertThat(ensured).isSameAs(str); } |
### Question:
Rdbms implements Serializable { public static Rdbms of(@NotNull final String code) { String theCode = code.intern(); Rdbms newRdbms = new Rdbms(theCode); Rdbms oldRdbms = RdbmsMarkersCache.cache.putIfAbsent(theCode, newRdbms); return notNull(oldRdbms, newRdbms); } private Rdbms(@NotNull final String code); static Rdbms of(@NotNull final String code); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @NotNull
final String code; }### Answer:
@SuppressWarnings("RedundantStringConstructorCall") @Test public void dedulplicate_on_create() { String str1 = new String("FantasticDB"); String str2 = new String("FantasticDB"); assertThat(str2).isNotSameAs(str1); Rdbms rdbms1 = Rdbms.of(str1); Rdbms rdbms2 = Rdbms.of(str2); assertThat(rdbms2).isSameAs(rdbms1); }
@Test public void serialization() throws IOException, ClassNotFoundException { JustAClass c1 = new JustAClass(Rdbms.of("MicroDB")); ByteArrayOutputStream os = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(os); oos.writeObject(c1); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); ObjectInputStream ois = new ObjectInputStream(is); Object gotObject = ois.readObject(); assertThat(gotObject).isInstanceOf(JustAClass.class); JustAClass c2 = (JustAClass) gotObject; assertThat(c2.rdbms).isSameAs(c1.rdbms); } |
### Question:
JdbcSessions extends DBSessions { @NotNull public static DBLeasedSession wrap(@NotNull final Connection connection, @NotNull final JdbcIntermediateRdbmsProvider rdbmsProvider, final boolean takeOwnership) { final JdbcIntermediateSession intermediateSession = rdbmsProvider.wrapConnection(connection, takeOwnership); return wrap(intermediateSession); } @NotNull static DBLeasedSession wrap(@NotNull final Connection connection,
@NotNull final JdbcIntermediateRdbmsProvider rdbmsProvider,
final boolean takeOwnership); @NotNull static DBLeasedSession wrap(@NotNull final Connection connection,
@NotNull final JdbcIntermediateFederatedProvider federatedProvider,
@NotNull final Rdbms rdbms,
final boolean takeOwnership); }### Answer:
@Test public void wrap_connection_not_own() throws SQLException { final Connection connection = obtainConnection(); assertThat(connection.isClosed()).isFalse(); final DBLeasedSession session = JdbcSessions.wrap(connection, provider, false); assertThat(session.isClosed()).isFalse(); session.close(); assertThat(session.isClosed()).isTrue(); assertThat(connection.isClosed()).isFalse(); connection.close(); assertThat(connection.isClosed()).isTrue(); }
@Test public void wrap_connection_ownership() throws SQLException { final Connection connection = obtainConnection(); assertThat(connection.isClosed()).isFalse(); final DBLeasedSession session = JdbcSessions.wrap(connection, provider, true); assertThat(session.isClosed()).isFalse(); session.close(); assertThat(session.isClosed()).isTrue(); assertThat(connection.isClosed()).isTrue(); } |
### Question:
JdbcIntermediateFederatedProvider implements IntegralIntermediateFederatedProvider { @Nullable @Override public IntegralIntermediateRdbmsProvider getSpecificServiceProvider(@NotNull final Rdbms rdbms) { final SpecificProvider sp = myBestProviders.get(rdbms); return sp != null ? sp.provider : null; } JdbcIntermediateFederatedProvider(); void registerProvider(@NotNull final IntegralIntermediateRdbmsProvider provider); void deregisterProvider(@NotNull final PrimeIntermediateRdbmsProvider provider); @NotNull @Override Set<Rdbms> supportedRdbms(); @NotNull @Override IntegralIntermediateFacade openFacade(@NotNull final String connectionString,
@Nullable final Properties connectionProperties,
final int connectionsLimit); @Nullable @Override IntegralIntermediateRdbmsProvider getSpecificServiceProvider(@NotNull final Rdbms rdbms); }### Answer:
@Test public void the_UnknownDatabaseServiceProvider_is_registered() { PrimeIntermediateRdbmsProvider provider = myFederatedProvider.getSpecificServiceProvider(UnknownDatabase.RDBMS); assertThat(provider).isNotNull() .isInstanceOf(UnknownDatabaseProvider.class); } |
### Question:
JdbcIntermediateFederatedProvider implements IntegralIntermediateFederatedProvider { @NotNull @Override public IntegralIntermediateFacade openFacade(@NotNull final String connectionString, @Nullable final Properties connectionProperties, final int connectionsLimit) { IntegralIntermediateRdbmsProvider provider = findTheBestFor(connectionString); return provider.openFacade(connectionString, connectionProperties, connectionsLimit); } JdbcIntermediateFederatedProvider(); void registerProvider(@NotNull final IntegralIntermediateRdbmsProvider provider); void deregisterProvider(@NotNull final PrimeIntermediateRdbmsProvider provider); @NotNull @Override Set<Rdbms> supportedRdbms(); @NotNull @Override IntegralIntermediateFacade openFacade(@NotNull final String connectionString,
@Nullable final Properties connectionProperties,
final int connectionsLimit); @Nullable @Override IntegralIntermediateRdbmsProvider getSpecificServiceProvider(@NotNull final Rdbms rdbms); }### Answer:
@Test public void the_UnknownDatabaseServiceProvider_is_accepted_by_connectionString() { myFederatedProvider.openFacade(UnknownDatabaseProviderTest.H2_CONNECTION_STRING, null, 1); } |
### Question:
UnknownDatabaseProvider extends JdbcIntermediateRdbmsProvider { @NotNull @Override public Pattern connectionStringPattern() { return CONNECTION_STRING_PATTERN; } @NotNull @Override Rdbms rdbms(); @NotNull @Override Pattern connectionStringPattern(); @Override byte specificity(); @NotNull @Override BaseExceptionRecognizer getExceptionRecognizer(); }### Answer:
@Test public void accepts_connectionString_H2() { PatternAssert.assertThat(myProvider.connectionStringPattern()).fits(H2_CONNECTION_STRING); } |
### Question:
JdbcIntermediateCursor implements IntegralIntermediateCursor<R> { @Override public R fetch() { if (!myHasRows) { if (myResultLayout.kind == ResultLayout.Kind.EXISTENCE) { return (R) Boolean.FALSE; } else { return null; } } if (!myOpened) throw new IllegalStateException("The cursor is not opened or is yet closed."); final R result; try { result = myRowsCollector.collectRows(myResultSet, myCollectLimit); } catch (SQLException sqle) { close(); throw mySeance.mySession.recognizeException(sqle, mySeance.myStatementText); } myHasRows = myRowsCollector.hasMoreRows; if (!myHasRows) close(); return result; } protected JdbcIntermediateCursor(@NotNull final JdbcIntermediateSeance seance,
@NotNull final ResultSet resultSet,
@NotNull final ResultLayout<R> resultLayout,
final boolean isDefault,
@Nullable final Boolean hasRows); @Override boolean hasRows(); @NotNull @Override String[] getColumnNames(); synchronized void setCollectLimit(final int limit); @Override R fetch(); @Override synchronized void close(); }### Answer:
@Test public void query_hash_map() { JdbcIntermediateSession session = openSession(); performStatements(session, "create table if not exists map_1 (K integer, V bigint)", "insert into map_1 values (11,10000001), (22,20000002), (33,30000003)" ); JdbcIntermediateSeance seance = session.openSeance("select * from map_1", null); seance.execute(); JdbcIntermediateCursor<Map<Integer, Long>> cursor = seance.openDefaultCursor(Layouts.hashMapOf(Integer.class, Long.class)); Map<Integer, Long> map = cursor.fetch(); assertThat(map).containsEntry(11, 10000001L) .containsEntry(22, 20000002L) .containsEntry(33, 30000003L) .hasSize(3); } |
### Question:
AdaptIntermediateRdbmsProvider implements IntegralIntermediateRdbmsProvider { @NotNull @Override public IntegralIntermediateFacade openFacade(@NotNull final String connectionString, @Nullable final Properties connectionProperties, final int connectionsLimit) { final PrimeIntermediateFacade remoteFacade = myRemoteProvider.openFacade(connectionString, connectionProperties, connectionsLimit); return new AdaptIntermediateFacade(remoteFacade); } AdaptIntermediateRdbmsProvider(@NotNull final PrimeIntermediateRdbmsProvider remoteProvider); @NotNull @Override Rdbms rdbms(); @NotNull @Override Pattern connectionStringPattern(); @Override byte specificity(); @NotNull @Override IntegralIntermediateFacade openFacade(@NotNull final String connectionString,
@Nullable final Properties connectionProperties,
final int connectionsLimit); @NotNull @Override Class<? extends DBExceptionRecognizer> getExceptionRecognizerClass(); @NotNull @Override DBExceptionRecognizer getExceptionRecognizer(); @Nullable @Override I getSpecificService(@NotNull final Class<I> serviceClass,
@NotNull final String serviceName); }### Answer:
@Test public void remote_ping() throws Exception { UnknownDatabaseProvider remoteProvider = ourUnknownDatabaseProvider; AdaptIntermediateRdbmsProvider provider = new AdaptIntermediateRdbmsProvider(remoteProvider); IntegralIntermediateFacade facade = provider.openFacade(BaseInMemoryDBCase.H2_CONNECTION_STRING, null, 1); facade.connect(); IntegralIntermediateSession session = facade.openSession(); long duration = session.ping(); assertThat(duration).isGreaterThan(0); session.close(); facade.disconnect(); }
@Test public void remote_scenario() throws Exception { UnknownDatabaseProvider remoteProvider = ourUnknownDatabaseProvider; AdaptIntermediateRdbmsProvider provider = new AdaptIntermediateRdbmsProvider(remoteProvider); IntegralIntermediateFacade facade = provider.openFacade(BaseInMemoryDBCase.H2_CONNECTION_STRING, null, 1); facade.connect(); IntegralIntermediateSession session = facade.openSession(); IntegralIntermediateSeance seance = session.openSeance("select 44", null); seance.execute(); IntegralIntermediateCursor<Integer> cursor = seance.openCursor(0, Layouts.singleOf(Integer.class)); cursor.fetch(); cursor.close(); seance.close(); session.close(); facade.disconnect(); } |
### Question:
AdaptIntermediateRdbmsProvider implements IntegralIntermediateRdbmsProvider { @NotNull @Override public DBExceptionRecognizer getExceptionRecognizer() { Class<? extends DBExceptionRecognizer> erClass = myRemoteProvider.getExceptionRecognizerClass(); try { Field instanceField = erClass.getDeclaredField("INSTANCE"); if (instanceField != null && Modifier.isStatic(instanceField.getModifiers())) { return (DBExceptionRecognizer) instanceField.get(null); } return erClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } throw new IllegalStateException("Unknown how to get an instance of class "+erClass.getName()); } AdaptIntermediateRdbmsProvider(@NotNull final PrimeIntermediateRdbmsProvider remoteProvider); @NotNull @Override Rdbms rdbms(); @NotNull @Override Pattern connectionStringPattern(); @Override byte specificity(); @NotNull @Override IntegralIntermediateFacade openFacade(@NotNull final String connectionString,
@Nullable final Properties connectionProperties,
final int connectionsLimit); @NotNull @Override Class<? extends DBExceptionRecognizer> getExceptionRecognizerClass(); @NotNull @Override DBExceptionRecognizer getExceptionRecognizer(); @Nullable @Override I getSpecificService(@NotNull final Class<I> serviceClass,
@NotNull final String serviceName); }### Answer:
@Test public void getExceptionRecognizer_same() { AdaptIntermediateRdbmsProvider adaptProvider = new AdaptIntermediateRdbmsProvider(ourUnknownDatabaseProvider); assertThat(adaptProvider.getExceptionRecognizer()).isSameAs(ourUnknownDatabaseProvider.getExceptionRecognizer()); } |
### Question:
Strings { @NotNull public static String ensureEndsWith(@NotNull final String str, final char c) { final int n = str.length(); if (n > 0 && str.charAt(n - 1) == c) { return str; } else { return str + c; } } @SuppressWarnings({"StringEquality", "SimplifiableIfStatement"}) static boolean eq(final String str1, final String str2); @SuppressWarnings({"StringEquality", "SimplifiableIfStatement"}) static boolean eq(final String str1, final String str2, final boolean caseSensitive); @NotNull static String ensureStartsWith(@NotNull final String str, final char c); @NotNull static String ensureEndsWith(@NotNull final String str, final char c); @NotNull static String removeEnding(@NotNull final String str, @NotNull final String ending); @NotNull static String rtrim(@NotNull final String str); @NotNull static String replace(@NotNull final String where, @NotNull final String what, @NotNull final String with); @NotNull static String repeat(@NotNull final String what, @Nullable final String delimiter, int count); @Contract("null,_->false") static boolean matches(@Nullable final CharSequence string, @NotNull final Pattern pattern); @Contract("null,_,_->false") static boolean matches(@Nullable final CharSequence string, @NotNull final String pattern, boolean caseSensitive); @Contract("!null->!null; null->null") static String upper(@Nullable final String string); @Contract("!null->!null; null->null") static String lower(@Nullable final String string); @Contract("!null->!null; null->null") static String minimizeSpaces(@Nullable final String string); @Contract("!null,_->!null; null,_->null") static String lastPart(@Nullable final String string, final char delimiter); }### Answer:
@Test public void ensureEndsWith_basic() { assertThat(ensureEndsWith("AAAA", 'C')).isEqualTo("AAAAC"); assertThat(ensureEndsWith("AAAAC", 'C')).isEqualTo("AAAAC"); assertThat(ensureEndsWith("", 'C')).isEqualTo("C"); }
@Test public void ensureEndsWith_dontMakeNewInstanceIfAlreadyEnds() { final String str = "AAAC"; final String ensured = ensureEndsWith(str, 'C'); assertThat(ensured).isSameAs(str); } |
### Question:
Sorting { public static void parallelSort(double[] dValues, int[] iValues) { quickSort(new DoubleIntIndexedSortable(dValues, iValues)); } private Sorting(); static int selectPivotIndex(final int[] indices,
int left,
int right,
final IntComparator comp); static int partitionIndices(
final int[] indices,
final int k0,
final int left0,
final int right0,
final IntComparator comp); static void quickSort(final IndexedSortable sortable); static void quickSort(final IndexedSortable sortable, final int offset, final int len); static void quickSort(final int[] arr, final IntComparator comp); static void quickSort(final int[] arr, final int offset, final int len, final IntComparator comp); static int medianOf3(final int[] a, final int x, final int y, final int z, final IntComparator c); static int medianOf3(IndexedSortable sortable, int x, int y, int z); static void parallelSort(double[] dValues, int[] iValues); }### Answer:
@Test public void testParallelSort() { final int numValues = 1000; double[] dValues = new double[numValues]; int[] iValues = new int[numValues]; Map<Double, Integer> checkMap = new HashMap<Double, Integer>(); Random random = new Random(); for (int i = 0; i < numValues; i++) { double d = random.nextDouble(); dValues[i] = d; iValues[i] = i; checkMap.put(d, i); } double[] dValuesCopy = (double[]) dValues.clone(); Sorting.parallelSort(dValues, iValues); Arrays.sort(dValuesCopy); for (int i = 0; i < numValues; i++) { assertTrue(dValuesCopy[i] == dValues[i]); assertTrue(checkMap.get(dValues[i]).intValue() == iValues[i]); } } |
### Question:
AbstractTask implements Task<V> { @Override public void setProgressEndpoints(double begin, double end) { if (Double.isNaN(begin) || Double.isNaN(end) || begin < 0.0 || (begin > end)) { throw new IllegalArgumentException( "invalid progress endpoints (begin == " + begin + ", end == " + end + ")"); } if (hasBegun.get()) { throw new IllegalStateException( "endpoints must be set before running the AbstractTask" ); } else { beginProgress = begin; endProgress = end; } } @Override void addTaskListener(TaskListener l); @Override void removeTaskListener(TaskListener l); @Override void setProgressEndpoints(double begin, double end); double getBeginProgress(); double getEndProgress(); @Override V get(); @Override V get(long timeout, TimeUnit unit); boolean isPaused(); synchronized void pause(); synchronized void play(); void reset(); final void run(); boolean cancel(boolean mayInterruptIfRunning); @Override /** * This version is mandated by the Future<V> interface. */ boolean isCancelled(); boolean isDone(); String getErrorMessage(); Throwable getError(); double getProgress(); boolean isBegun(); boolean isEnded(); final TaskOutcome getTaskOutcome(); }### Answer:
@Test public void testSetProgressEndpoints() throws InterruptedException { System.out.println("setProgressEndpoints"); TestTaskListener l = new TestTaskListener(); AbstractTask instance = new CapitalizeStringTask("a string to capitalize"); instance.setProgressEndpoints(0.25, 0.75); instance.addTaskListener(l); Thread t = new Thread(instance); t.start(); t.join(); assertThat(l.minProgress(), is(0.25)); assertThat(l.maxProgress(), is(0.75)); }
@Test(expected = IllegalArgumentException.class) public void testSetProgressEndpointBeginLessThanZero() { AbstractTask instance = new CapitalizeStringTask("a string to capitalize"); instance.setProgressEndpoints(-0.25, 1.0); }
@Test(expected = IllegalArgumentException.class) public void testSetProgressEndpointEndLessThanBegin() { AbstractTask instance = new CapitalizeStringTask("a string to capitalize"); instance.setProgressEndpoints(0.75, 0.5); }
@Test(expected = IllegalArgumentException.class) public void testSetProgressEndpointsWithNaNs() { AbstractTask instance = new CapitalizeStringTask("a string to capitalize"); instance.setProgressEndpoints(Double.NaN, Double.NaN); } |
### Question:
AbstractTask implements Task<V> { @Override public V get() throws InterruptedException, ExecutionException { while(!hasEnded.get()) { synchronized (this) { wait(); } } return getResultAfterHasEnded(); } @Override void addTaskListener(TaskListener l); @Override void removeTaskListener(TaskListener l); @Override void setProgressEndpoints(double begin, double end); double getBeginProgress(); double getEndProgress(); @Override V get(); @Override V get(long timeout, TimeUnit unit); boolean isPaused(); synchronized void pause(); synchronized void play(); void reset(); final void run(); boolean cancel(boolean mayInterruptIfRunning); @Override /** * This version is mandated by the Future<V> interface. */ boolean isCancelled(); boolean isDone(); String getErrorMessage(); Throwable getError(); double getProgress(); boolean isBegun(); boolean isEnded(); final TaskOutcome getTaskOutcome(); }### Answer:
@Test(expected=TimeoutException.class) public void testGetWithNoStartOfTask() throws InterruptedException, ExecutionException, TimeoutException { AbstractTask<String> instance = new CapitalizeStringTask("a string to capitalize"); String result = instance.get(1L, TimeUnit.MILLISECONDS); } |
### Question:
TupleKDTree { public static TupleKDTree forTupleList(final TupleList tuples, final DistanceMetric distanceMetric) { TupleKDTree kd = new TupleKDTree(tuples, distanceMetric); int tupleCount = tuples.getTupleCount(); for (int i = 0; i < tupleCount; i++) { kd.insert(i); } return kd; } TupleKDTree(final TupleList tuples, final DistanceMetric distanceMetric); KDNode getRoot(); TupleList getTupleList(); DistanceMetric getDistanceMetric(); int getDimensions(); static TupleKDTree forTupleList(final TupleList tuples,
final DistanceMetric distanceMetric); static TupleKDTree forTupleListBalanced(final TupleList tuples,
final DistanceMetric distanceMetric); void insert(final int ndx); boolean contains(final int ndx); int search(final double[] coords); int nearestNeighbor(final int ndx); int nearest(final double[] coords); int[] nearest(final int ndx, final int num); int[] nearest(final double[] coords, final int num); int[] closeTo(final int ndx, final double maxDistance); int[] closeTo(final double[] coords, final double maxDistance); int[] inside(final HyperRect rect); }### Answer:
@Test public void testForTupleList() { int tupleCount = 100; int numClusters = 10; int tupleLength = 10; int nnCount = 5; TupleList tuples = generateTestTuples(tupleCount, tupleLength, numClusters, 123L); DistanceMetric distMetric = new EuclideanDistanceMetric(); TupleKDTree kdTree = TupleKDTree.forTupleList(tuples, distMetric); Random random = new Random(123L); int ndx = random.nextInt(tupleCount); List<TupleKDTree.DistanceEntry> distEntries = sortedDistanceEntries(ndx, tuples, distMetric); System.out.printf("Using dumb searching, the %d nearest neighbors are:\n", nnCount); final int lim = Math.min(nnCount, distEntries.size()); int[] dumbNns = new int[lim]; for (int i=0; i<lim; i++) { TupleKDTree.DistanceEntry entry = distEntries.get(i); dumbNns[i] = entry.getIndex(); } int[] nns = kdTree.nearest(ndx, nnCount); for (int i=0; i<lim; i++) { assertTrue(dumbNns[i] == nns[i]); } double[] buf1 = new double[tupleLength]; double[] buf2 = new double[tupleLength]; tuples.getTuple(ndx, buf1); tuples.getTuple(nns[nns.length - 1], buf2); double md = distMetric.distance(buf1, buf2); int[] closeto = kdTree.closeTo(ndx, md); System.out.println(" md = " + md); System.out.println(" ndx = " + ndx); System.out.println(" nns = " + toStr(nns)); System.out.println("closeTo = " + toStr(closeto)); TupleKDTree.KDNode node = kdTree.getRoot(); System.out.println("root balance factor = " + node.balanceFactor()); } |
### Question:
TupleKDTree { public static TupleKDTree forTupleListBalanced(final TupleList tuples, final DistanceMetric distanceMetric) { final TupleKDTree kd = new TupleKDTree(tuples, distanceMetric); final int tupleCount = tuples.getTupleCount(); final int tupleLen = tuples.getTupleLength(); final int[] tupleIndices = new int[tupleCount]; for (int i = 0; i < tupleCount; i++) { tupleIndices[i] = i; } final IntComparator[] comparators = new IntComparator[tupleLen]; for (int dim = 0; dim < tupleLen; dim++) { comparators[dim] = new TupleIndexComparator(tuples, dim); } generateBalanced(kd, tupleIndices, 0, tupleIndices.length - 1, 0, comparators); return kd; } TupleKDTree(final TupleList tuples, final DistanceMetric distanceMetric); KDNode getRoot(); TupleList getTupleList(); DistanceMetric getDistanceMetric(); int getDimensions(); static TupleKDTree forTupleList(final TupleList tuples,
final DistanceMetric distanceMetric); static TupleKDTree forTupleListBalanced(final TupleList tuples,
final DistanceMetric distanceMetric); void insert(final int ndx); boolean contains(final int ndx); int search(final double[] coords); int nearestNeighbor(final int ndx); int nearest(final double[] coords); int[] nearest(final int ndx, final int num); int[] nearest(final double[] coords, final int num); int[] closeTo(final int ndx, final double maxDistance); int[] closeTo(final double[] coords, final double maxDistance); int[] inside(final HyperRect rect); }### Answer:
@Test public void testForTupleListBalanced() { int tupleCount = 100; int numClusters = 10; int tupleLength = 10; int nnCount = 5; TupleList tuples = generateTestTuples(tupleCount, tupleLength, numClusters, 123L); DistanceMetric distMetric = new EuclideanDistanceMetric(); TupleKDTree kdTree = TupleKDTree.forTupleListBalanced(tuples, distMetric); Random random = new Random(123L); int ndx = random.nextInt(tupleCount); List<TupleKDTree.DistanceEntry> distEntries = sortedDistanceEntries(ndx, tuples, distMetric); System.out.printf("Using dumb searching, the %d nearest neighbors are:\n", nnCount); final int lim = Math.min(nnCount, distEntries.size()); int[] dumbNns = new int[lim]; for (int i=0; i<lim; i++) { TupleKDTree.DistanceEntry entry = distEntries.get(i); dumbNns[i] = entry.getIndex(); } int[] nns = kdTree.nearest(ndx, nnCount); for (int i=0; i<lim; i++) { assertTrue(dumbNns[i] == nns[i]); } double[] buf1 = new double[tupleLength]; double[] buf2 = new double[tupleLength]; tuples.getTuple(ndx, buf1); tuples.getTuple(nns[nns.length - 1], buf2); double md = distMetric.distance(buf1, buf2); int[] closeto = kdTree.closeTo(ndx, md); System.out.println(" md = " + md); System.out.println(" ndx = " + ndx); System.out.println(" nns = " + toStr(nns)); System.out.println("closeTo = " + toStr(closeto)); TupleKDTree.KDNode node = kdTree.getRoot(); System.out.println("root balance factor = " + node.balanceFactor()); } |
### Question:
Sorting { public static int medianOf3(final int[] a, final int x, final int y, final int z, final IntComparator c) { if (c.compare(a[x], a[y]) < 0) { if (c.compare(a[y], a[z]) < 0) { return y; } if (c.compare(a[x], a[z]) < 0) { return z; } return x; } if (c.compare(a[y], a[z]) > 0) { return y; } if (c.compare(a[x], a[z]) > 0) { return z; } return x; } private Sorting(); static int selectPivotIndex(final int[] indices,
int left,
int right,
final IntComparator comp); static int partitionIndices(
final int[] indices,
final int k0,
final int left0,
final int right0,
final IntComparator comp); static void quickSort(final IndexedSortable sortable); static void quickSort(final IndexedSortable sortable, final int offset, final int len); static void quickSort(final int[] arr, final IntComparator comp); static void quickSort(final int[] arr, final int offset, final int len, final IntComparator comp); static int medianOf3(final int[] a, final int x, final int y, final int z, final IntComparator c); static int medianOf3(IndexedSortable sortable, int x, int y, int z); static void parallelSort(double[] dValues, int[] iValues); }### Answer:
@Test public void testMedianOf3() { final int loops = 100; Random random = new Random(); for (int i = 0; i < loops; i++) { int len = 10 + random.nextInt(50); int[] values = new int[len]; for (int j = 0; j < len; j++) { values[j] = random.nextInt(); } IntComparator comp = new SimpleIntComparator(); final int x = 0; final int m = len>>1; final int y = len-1; int med = Sorting.medianOf3(values, x, m, y, comp); int[] otherTwo; if (med == x) { otherTwo = new int[] { m, y }; } else if (med == m) { otherTwo = new int[] { x, y }; } else { otherTwo = new int[] { x, m }; } boolean foundLE = false; boolean foundGE = false; for (int j=0; j<otherTwo.length; j++) { if (!foundLE && values[otherTwo[j]] <= values[med]) { foundLE = true; } if (!foundGE && values[otherTwo[j]] >= values[med]) { foundGE = true; } } assertTrue(foundLE && foundGE); } } |
### Question:
Sorting { public static int partitionIndices( final int[] indices, final int k0, final int left0, final int right0, final IntComparator comp) { int k = k0; int left = left0; int right = right0; for (;;) { int idx = selectPivotIndex(indices, left, right, comp); int pivotIndex = partition(indices, left, right, idx, comp); if (left + k - 1 == pivotIndex) { int i = right0; while (i > pivotIndex) { if (comp.compare(indices[i], indices[pivotIndex]) == 0) { pivotIndex++; if (i > pivotIndex) { swap(indices, i, pivotIndex); } } else { i--; } } return pivotIndex; } if (left + k - 1 < pivotIndex) { right = pivotIndex - 1; } else { k -= (pivotIndex - left + 1); left = pivotIndex + 1; } } } private Sorting(); static int selectPivotIndex(final int[] indices,
int left,
int right,
final IntComparator comp); static int partitionIndices(
final int[] indices,
final int k0,
final int left0,
final int right0,
final IntComparator comp); static void quickSort(final IndexedSortable sortable); static void quickSort(final IndexedSortable sortable, final int offset, final int len); static void quickSort(final int[] arr, final IntComparator comp); static void quickSort(final int[] arr, final int offset, final int len, final IntComparator comp); static int medianOf3(final int[] a, final int x, final int y, final int z, final IntComparator c); static int medianOf3(IndexedSortable sortable, int x, int y, int z); static void parallelSort(double[] dValues, int[] iValues); }### Answer:
@Test public void testPartitionIndices() { Random random = new Random(); final int count = 50 + random.nextInt(100); final int[] values = new int[count]; for (int i = 0; i < count; i++) { values[i] = random.nextInt(10); } int m = 1 + (count - 1 + 0) / 2; int pi = Sorting.partitionIndices(values, m, 0, count - 1, new SimpleIntComparator()); checkPartitionIndex(values, pi); } |
### Question:
ProgressHandler { public void setMinTimeIncrement(final long ms) { minTimeInc = ms; } ProgressHandler(AbstractTask<?> t,
double begin,
double end,
int steps); ProgressHandler(AbstractTask<?> t, int steps); ProgressHandler(final AbstractTask<?> task,
final double begin,
final double end); ProgressHandler(AbstractTask<?> t); void setMinProgressIncrement(final double minInc); void setMinTimeIncrement(final long ms); void postMessage(final String msg); void postFraction(final double fraction); void postStep(); void postSteps(final int steps); void postEnd(); void postIndeterminate(); void subsection(final double fraction); void subsection(final double fraction, final int steps); void subsection(final int steps); void subsection(); void postBegin(); double getCurrentProgress(); static final double DEFAULT_START_VALUE; static final double DEFAULT_END_VALUE; static final double DEFAULT_MIN_PROGRESS_INC; static final long DEFAULT_MIN_TIME_INC; }### Answer:
@Test public void testSetMinTimeIncrement() throws InterruptedException { TestTask testTask = new TestTask(0.0, 1.0, 10); testTask.setTotalTimeToDoTask(100L, TimeUnit.MILLISECONDS); testTask.getProgressHandler().setMinTimeIncrement(25L); testTask.getProgressHandler().setMinProgressIncrement(5.0); final AtomicReference<Long> lastProgressReceived = new AtomicReference<>(); final List<Long> timeBetweenPosts = new ArrayList<>(); testTask.addTaskListener(new TaskAdapter() { @Override public void taskProgress(TaskEvent evt) { long now = System.currentTimeMillis(); Long lastTimeReceived = lastProgressReceived.getAndSet(now); if (lastTimeReceived != null) { Long timeBetween = now - lastTimeReceived; timeBetweenPosts.add(timeBetween); } } }); Thread t = new Thread(testTask); t.start(); t.join(); for (int i=0; i<timeBetweenPosts.size()-1; i++) { long ms = timeBetweenPosts.get(i); assertTrue("timeBetweenPosts(" + i + ") is too small: " + ms, ms >= 25L); } } |
### Question:
ProgressHandler { public void postMessage(final String msg) { if (task != null) { task.postMessage(msg); } } ProgressHandler(AbstractTask<?> t,
double begin,
double end,
int steps); ProgressHandler(AbstractTask<?> t, int steps); ProgressHandler(final AbstractTask<?> task,
final double begin,
final double end); ProgressHandler(AbstractTask<?> t); void setMinProgressIncrement(final double minInc); void setMinTimeIncrement(final long ms); void postMessage(final String msg); void postFraction(final double fraction); void postStep(); void postSteps(final int steps); void postEnd(); void postIndeterminate(); void subsection(final double fraction); void subsection(final double fraction, final int steps); void subsection(final int steps); void subsection(); void postBegin(); double getCurrentProgress(); static final double DEFAULT_START_VALUE; static final double DEFAULT_END_VALUE; static final double DEFAULT_MIN_PROGRESS_INC; static final long DEFAULT_MIN_TIME_INC; }### Answer:
@Test public void testPostMessage() throws InterruptedException { final int steps = 100; TestTask testTask = new TestTask(0.0, 1.0, steps); List<String> messages = new ArrayList<>(); testTask.addTaskListener(new TaskAdapter() { @Override public void taskMessage(TaskEvent evt) { messages.add(evt.getMessage()); } }); Thread t = new Thread(testTask); t.start(); t.join(); assertThat(messages.size(), is(equalTo(steps + 1))); } |
### Question:
ProgressHandler { public void postFraction(final double fraction) { currentStep.postFraction(fraction); } ProgressHandler(AbstractTask<?> t,
double begin,
double end,
int steps); ProgressHandler(AbstractTask<?> t, int steps); ProgressHandler(final AbstractTask<?> task,
final double begin,
final double end); ProgressHandler(AbstractTask<?> t); void setMinProgressIncrement(final double minInc); void setMinTimeIncrement(final long ms); void postMessage(final String msg); void postFraction(final double fraction); void postStep(); void postSteps(final int steps); void postEnd(); void postIndeterminate(); void subsection(final double fraction); void subsection(final double fraction, final int steps); void subsection(final int steps); void subsection(); void postBegin(); double getCurrentProgress(); static final double DEFAULT_START_VALUE; static final double DEFAULT_END_VALUE; static final double DEFAULT_MIN_PROGRESS_INC; static final long DEFAULT_MIN_TIME_INC; }### Answer:
@Test public void testPostFraction() throws InterruptedException { TestTask testTask = new TestTask(0.0, 1.0, 10); testTask.setPostFractionalProgress(true); final List<Double> progressReceived = new ArrayList<>(); testTask.addTaskListener(new TaskAdapter() { @Override public void taskProgress(TaskEvent evt) { progressReceived.add(evt.getProgress()); } }); Thread t = new Thread(testTask); t.start(); t.join(); assertTrue(progressReceived.size() >= 10); for (int i=1; i<progressReceived.size() - 1; i++) { assertEquals(0.1, progressReceived.get(i) - progressReceived.get(i-1), 1.0e-10); } } |
### Question:
ProgressHandler { public void postSteps(final int steps) { currentStep.postSteps(steps); } ProgressHandler(AbstractTask<?> t,
double begin,
double end,
int steps); ProgressHandler(AbstractTask<?> t, int steps); ProgressHandler(final AbstractTask<?> task,
final double begin,
final double end); ProgressHandler(AbstractTask<?> t); void setMinProgressIncrement(final double minInc); void setMinTimeIncrement(final long ms); void postMessage(final String msg); void postFraction(final double fraction); void postStep(); void postSteps(final int steps); void postEnd(); void postIndeterminate(); void subsection(final double fraction); void subsection(final double fraction, final int steps); void subsection(final int steps); void subsection(); void postBegin(); double getCurrentProgress(); static final double DEFAULT_START_VALUE; static final double DEFAULT_END_VALUE; static final double DEFAULT_MIN_PROGRESS_INC; static final long DEFAULT_MIN_TIME_INC; }### Answer:
@Test public void testPostSteps() throws InterruptedException { final List<Integer> stepsToPost = Arrays.asList(2, 4, 5, 7, 3, 2, 6); final Integer totalSteps = stepsToPost.stream().mapToInt(n -> n.intValue()).sum(); final List<Double> expectedProgress = new ArrayList<>(); stepsToPost.forEach(n -> { double d = ((double) n.intValue())/totalSteps; if (expectedProgress.size() > 0) { d += expectedProgress.get(expectedProgress.size() - 1); } expectedProgress.add(d); }); Task<Void> task = new AbstractTask<Void> () { @Override protected Void doTask() throws Exception { ProgressHandler ph = new ProgressHandler(this, 0.0, 1.0, totalSteps); ph.postBegin(); stepsToPost.forEach(ph::postSteps); ph.postEnd(); return null; } @Override public String taskName() { return "testPostSteps() task"; } }; final List<Double> progressReceived = new ArrayList<>(); task.addTaskListener(new TaskAdapter() { @Override public void taskProgress(TaskEvent evt) { progressReceived.add(evt.getProgress()); } }); Thread t = new Thread(task); t.start(); t.join(); assertThat(progressReceived.size(), is(equalTo(expectedProgress.size() + 2))); for (int i=0; i<expectedProgress.size(); i++) { assertEquals(expectedProgress.get(i), progressReceived.get(i+1), 1.0e-10); } } |
### Question:
ProgressHandler { public void postIndeterminate() { postValue(-1.0); } ProgressHandler(AbstractTask<?> t,
double begin,
double end,
int steps); ProgressHandler(AbstractTask<?> t, int steps); ProgressHandler(final AbstractTask<?> task,
final double begin,
final double end); ProgressHandler(AbstractTask<?> t); void setMinProgressIncrement(final double minInc); void setMinTimeIncrement(final long ms); void postMessage(final String msg); void postFraction(final double fraction); void postStep(); void postSteps(final int steps); void postEnd(); void postIndeterminate(); void subsection(final double fraction); void subsection(final double fraction, final int steps); void subsection(final int steps); void subsection(); void postBegin(); double getCurrentProgress(); static final double DEFAULT_START_VALUE; static final double DEFAULT_END_VALUE; static final double DEFAULT_MIN_PROGRESS_INC; static final long DEFAULT_MIN_TIME_INC; }### Answer:
@Test public void testPostIndeterminate() throws InterruptedException { final int loops = 10; Task<Void> task = new AbstractTask<Void> () { @Override protected Void doTask() throws Exception { ProgressHandler ph = new ProgressHandler(this, 0.0, 1.0); ph.postBegin(); for (int i=0; i<loops; i++) { ph.postIndeterminate(); } ph.postEnd(); return null; } @Override public String taskName() { return "testPostIndeterminate() task"; } }; final AtomicInteger numIndeterminates = new AtomicInteger(); task.addTaskListener(new TaskAdapter() { @Override public void taskProgress(TaskEvent evt) { if (evt.getProgress() == -1.0) { numIndeterminates.incrementAndGet(); } } }); Thread t = new Thread(task); t.start(); t.join(); assertThat(numIndeterminates.get(), is(equalTo(1))); } |
### Question:
AbstractTask implements Task<V> { @Override public void addTaskListener(TaskListener l) { eventSupport.addTaskListener(l); } @Override void addTaskListener(TaskListener l); @Override void removeTaskListener(TaskListener l); @Override void setProgressEndpoints(double begin, double end); double getBeginProgress(); double getEndProgress(); @Override V get(); @Override V get(long timeout, TimeUnit unit); boolean isPaused(); synchronized void pause(); synchronized void play(); void reset(); final void run(); boolean cancel(boolean mayInterruptIfRunning); @Override /** * This version is mandated by the Future<V> interface. */ boolean isCancelled(); boolean isDone(); String getErrorMessage(); Throwable getError(); double getProgress(); boolean isBegun(); boolean isEnded(); final TaskOutcome getTaskOutcome(); }### Answer:
@Test public void testAddTaskListener() throws InterruptedException, ExecutionException { System.out.println("addTaskListener"); TestTaskListener l = new TestTaskListener(); final String s = "a string to capitalize"; AbstractTask<String> instance = new CapitalizeStringTask(s); instance.addTaskListener(l); Thread t = new Thread(instance); t.start(); t.join(); assertThat(l.taskBegunCount(), is(1)); assertThat(l.taskEndedCount(), is(1)); assertThat(instance.get(), is(s.toUpperCase())); } |
### Question:
AbstractTask implements Task<V> { @Override public void removeTaskListener(TaskListener l) { eventSupport.removeTaskListener(l); } @Override void addTaskListener(TaskListener l); @Override void removeTaskListener(TaskListener l); @Override void setProgressEndpoints(double begin, double end); double getBeginProgress(); double getEndProgress(); @Override V get(); @Override V get(long timeout, TimeUnit unit); boolean isPaused(); synchronized void pause(); synchronized void play(); void reset(); final void run(); boolean cancel(boolean mayInterruptIfRunning); @Override /** * This version is mandated by the Future<V> interface. */ boolean isCancelled(); boolean isDone(); String getErrorMessage(); Throwable getError(); double getProgress(); boolean isBegun(); boolean isEnded(); final TaskOutcome getTaskOutcome(); }### Answer:
@Test public void testRemoveTaskListener() throws InterruptedException { System.out.println("removeTaskListener"); TestTaskListener l = new TestTaskListener(); AbstractTask instance = new CapitalizeStringTask("a string to capitalize"); instance.addTaskListener(l); instance.removeTaskListener(l); Thread t = new Thread(instance); t.start(); t.join(); assertThat(l.taskBegunCount(), is(0)); assertThat(l.taskEndedCount(), is(0)); } |
### Question:
HostManager { synchronized String getNextHostForRequest() { if (participantHosts.isEmpty()) { return null; } checkNextHostIndex(); String host = participantHosts.get(currentIndex); if (LOG.isDebugEnabled()) { LOG.debug("hosts size: " + participantHosts.size()); } if (LOG.isInfoEnabled()) { LOG.info("Next host retrieved for signing: " + host); } return host; } HostManager(List<String> hosts, boolean useLoadBalancing); }### Answer:
@Test public void test01GetNextHostNoLoadBalancing() throws Exception { List<String> participantHosts = new ArrayList<>(); participantHosts.add("host1"); participantHosts.add("host2"); participantHosts.add("host3"); MockHostManager hostManager = new MockHostManager(participantHosts, false); assertEquals("host1", hostManager.getNextHostForRequest()); assertEquals("host1", hostManager.getNextHostForRequest()); assertEquals("host1", hostManager.getNextHostForRequest()); assertEquals("host1", hostManager.getNextHostForRequest()); assertEquals("host1", hostManager.getNextHostForRequest()); assertEquals("host1", hostManager.getNextHostForRequest()); }
@Test public void test03GetNextHostWithLoadBalancing() throws Exception { List<String> participantHosts = new ArrayList<>(); participantHosts.add("host1"); participantHosts.add("host2"); participantHosts.add("host3"); participantHosts.add("host4"); MockHostManager hostManager = new MockHostManager(participantHosts, true); assertEquals("host2", hostManager.getNextHostForRequest()); assertEquals("host3", hostManager.getNextHostForRequest()); assertEquals("host4", hostManager.getNextHostForRequest()); assertEquals("host1", hostManager.getNextHostForRequest()); assertEquals("host2", hostManager.getNextHostForRequest()); assertEquals("host3", hostManager.getNextHostForRequest()); assertEquals("host4", hostManager.getNextHostForRequest()); } |
### Question:
PdfVersionCompatibilityChecker { public int getMinimumCompatiblePdfVersion() { switch (signatureDigestAlgorithm) { case PdfSignatureDigestAlgorithms.SHA1: return 0; case PdfSignatureDigestAlgorithms.SHA256: case PdfSignatureDigestAlgorithms.SHA_256: return 6; case PdfSignatureDigestAlgorithms.SHA384: case PdfSignatureDigestAlgorithms.SHA_384: case PdfSignatureDigestAlgorithms.SHA512: case PdfSignatureDigestAlgorithms.SHA_512: case PdfSignatureDigestAlgorithms.RIPEMD160: return 7; default: throw new IllegalArgumentException("Unknown digest algorithm: " + signatureDigestAlgorithm); } } PdfVersionCompatibilityChecker(String pPdfVersionOfDocumentToBeSigned, String pSignatureDigestAlgorithm); int getPdfVersionOfDocumentToBeSigned(); boolean isVersionUpgradeRequired(); int getMinimumCompatiblePdfVersion(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void minimumVersionCannotBeRetrievedForUnknownDigestAlgorithm() { PdfVersionCompatibilityChecker checker = new PdfVersionCompatibilityChecker("0", "HSA 223"); checker.getMinimumCompatiblePdfVersion(); }
@Test public void minimumVersionForSHA1Is0() { PdfVersionCompatibilityChecker checker = new PdfVersionCompatibilityChecker("0", "SHA1"); int minVer = checker.getMinimumCompatiblePdfVersion(); assertEquals(0, minVer); }
@Test public void minimumVersionForSHA256Is6() { PdfVersionCompatibilityChecker checker = new PdfVersionCompatibilityChecker("0", "SHA-256"); int minVer = checker.getMinimumCompatiblePdfVersion(); assertEquals(6, minVer); }
@Test public void minimumVersionForSHA512Is7() { PdfVersionCompatibilityChecker checker = new PdfVersionCompatibilityChecker("0", "SHA512"); int minVer = checker.getMinimumCompatiblePdfVersion(); assertEquals(7, minVer); } |
### Question:
PdfSignatureDigestAlgorithms { public static boolean isSupported(String digestAlgorithm) { return ALL_SUPPORTED_DIGEST_ALGORITHMS.contains(digestAlgorithm); } private PdfSignatureDigestAlgorithms(); static boolean isSupported(String digestAlgorithm); static final String SHA1; static final String SHA256; static final String SHA_256; static final String SHA384; static final String SHA_384; static final String SHA512; static final String SHA_512; static final String RIPEMD160; static final List<String> ALL_SUPPORTED_DIGEST_ALGORITHMS; }### Answer:
@Test public void shouldNotSupportFictitiousDigestAlgorithm() { boolean supported = PdfSignatureDigestAlgorithms.isSupported("HSA 256"); assertFalse("We support fictitious Digest Algorithms ??", supported); } |
### Question:
BaseProcessable extends BaseWorker implements IProcessable { @Override public void importCertificateChain(final List<Certificate> certChain, final String alias, final char[] authenticationCode, Map<String, Object> params, final IServices services) throws CryptoTokenOfflineException, NoSuchAliasException, InvalidAlgorithmParameterException, UnsupportedCryptoTokenParameter, OperationUnsupportedException { try { final ICryptoTokenV4 token = getCryptoToken(services); if (token == null) { throw new CryptoTokenOfflineException("Crypto token offline"); } else { token.importCertificateChain(certChain, alias, authenticationCode, params, services); } } catch (SignServerException e) { log.error(FAILED_TO_GET_CRYPTO_TOKEN_ + e.getMessage()); throw new CryptoTokenOfflineException(e); } } protected BaseProcessable(); @Override void init(int workerId, WorkerConfig config,
WorkerContext workerContext, EntityManager workerEM); @Override void activateSigner(String authenticationCode, IServices services); @Override boolean deactivateSigner(IServices services); @Override String getAuthenticationType(); ICryptoTokenV4 getCryptoToken(final IServices services); @Override int getCryptoTokenStatus(IServices services); Certificate getSigningCertificate(ICryptoInstance crypto); Certificate getSigningCertificate(IServices services); Certificate getSigningCertificate(String alias, IServices services); List<Certificate> getSigningCertificateChain(final ICryptoInstance crypto); List<Certificate> getSigningCertificateChain(final IServices services); List<Certificate> getSigningCertificateChain(final String alias, final IServices services); @Override ICertReqData genCertificateRequest(ISignerCertReqInfo certReqInfo, boolean explicitEccParameters, String keyAlias, IServices services); @Override ICertReqData genCertificateRequest(ISignerCertReqInfo certReqInfo, boolean explicitEccParameters, boolean defaultKey, IServices services); @Override ICertReqData genCertificateRequest(ISignerCertReqInfo info,
final boolean explicitEccParameters, final boolean defaultKey); @Override boolean removeKey(String alias, IServices services); @Override void generateKey(final String keyAlgorithm, final String keySpec, final String alias, final char[] authCode, Map<String, Object> params, final IServices services); @Override Collection<org.signserver.common.KeyTestResult> testKey(String alias, char[] authCode); @Override Collection<org.signserver.common.KeyTestResult> testKey(String alias,
char[] authCode, IServices services); @Override void importCertificateChain(final List<Certificate> certChain, final String alias, final char[] authenticationCode, Map<String, Object> params, final IServices services); @Override TokenSearchResults searchTokenEntries(int startIndex, int max, final QueryCriteria qc, final boolean includeData, final Map<String, Object> params, final IServices services); @Override List<String> getCertificateIssues(List<Certificate> certificateChain); static final String PROPERTY_CACHE_PRIVATEKEY; }### Answer:
@Test public void testImportCertificateChain() throws Exception { LOG.info("testGetCryptoToken_noDefaults"); Properties globalConfig = new Properties(); WorkerConfig workerConfig = new WorkerConfig(); MockServices services = new MockServices(globalConfig); workerConfig.setProperty(WorkerConfig.IMPLEMENTATION_CLASS, TestSigner.class.getName()); workerConfig.setProperty(WorkerConfig.CRYPTOTOKEN_IMPLEMENTATION_CLASS, MockedCryptoToken.class.getName()); workerConfig.setProperty("NAME", "TestSigner100"); TestSigner instance = new TestSigner(globalConfig); instance.init(workerId, workerConfig, anyContext, null); final List<Certificate> chain = Arrays.asList(CertTools.getCertfromByteArray(Base64.decode(CERT2))); instance.importCertificateChain(chain, "alias2", null, Collections.<String, Object>emptyMap(), services); final List<Certificate> importedChain = instance.getSigningCertificateChain("alias2", null); System.out.println("CERT2: " + chain.get(0).toString()); System.out.println("ACTUAL: " + importedChain.get(0)); assertTrue("Matching certificate", Arrays.equals(chain.get(0).getEncoded(), importedChain.get(0).getEncoded())); } |
### Question:
AllowedMechanisms { public static AllowedMechanisms parse(final String allowedMechanismsProperty) throws IllegalArgumentException { final String[] parts = allowedMechanismsProperty.split("[,;\\s]"); final List<Long> mechs = new ArrayList<>(parts.length); for (String part : parts) { part = part.trim(); if (!part.isEmpty()) { try { if (part.startsWith("0x") && part.length() > 2) { mechs.add(Long.parseLong(part.substring(2), 16)); } else { if (part.startsWith("CKM_")) { part = part.substring("CKM_".length()); } Long l = MechanismNames.longFromName(part); if (l == null) { l = Long.parseLong(part); } mechs.add(l); } } catch (NumberFormatException ex) { throw new IllegalArgumentException("Mechanism could not be parsed as number: " + ex.getMessage()); } } } return new AllowedMechanisms(mechs); } AllowedMechanisms(List<Long> mechs); static AllowedMechanisms parse(final String allowedMechanismsProperty); static AllowedMechanisms fromBinaryEncoding(final byte[] binary); byte[] toBinaryEncoding(); Long[] toLongArray(); String toPropertyValue(); @Override String toString(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testParseHexAndDecimal_incorrectValue1() { LOG.info(">testParseHexAndDecimal_incorrectValue1"); String allowedMechanismsProperty = " 0x00000040, 0x00000000 0xnotANumber;0x252 ,624"; AllowedMechanisms.parse(allowedMechanismsProperty); }
@Test(expected = IllegalArgumentException.class) public void testParseHexAndDecimal_incorrectValue2() { LOG.info(">testParseHexAndDecimal_incorrectValue2"); String allowedMechanismsProperty = " 0x00000040, 0x00000000 notANumberNorConstant;0x252 ,624"; AllowedMechanisms.parse(allowedMechanismsProperty); } |
### Question:
AllowedMechanisms { public byte[] toBinaryEncoding() { final int num = mechs.size(); final ByteBuffer bb = ByteBuffer.allocate(8 * num); bb.order(ByteOrder.LITTLE_ENDIAN); for (long mech : mechs) { bb.putLong(mech); } return bb.array(); } AllowedMechanisms(List<Long> mechs); static AllowedMechanisms parse(final String allowedMechanismsProperty); static AllowedMechanisms fromBinaryEncoding(final byte[] binary); byte[] toBinaryEncoding(); Long[] toLongArray(); String toPropertyValue(); @Override String toString(); }### Answer:
@Test public void testToBinaryEncoding() { LOG.info(">testToBinaryEncoding"); String allowedMechanismsProperty = " 0x00000040, 0x00000000, 0x00000250, 0x252, 624, 0x81234567"; AllowedMechanisms instance = AllowedMechanisms.parse(allowedMechanismsProperty); final String expected = "4000000000000000" + "0000000000000000" + "5002000000000000" + "5202000000000000" + "7002000000000000" + "6745238100000000"; assertEquals(expected, Hex.toHexString(instance.toBinaryEncoding())); } |
### Question:
AllowedMechanisms { public static AllowedMechanisms fromBinaryEncoding(final byte[] binary) throws IllegalArgumentException { final ArrayList<Long> mechs = new ArrayList<>(); try { final LongBuffer lb = ByteBuffer.wrap(binary).order(ByteOrder.LITTLE_ENDIAN).asLongBuffer(); while (lb.hasRemaining()) { mechs.add(lb.get()); } } catch (BufferUnderflowException ex) { throw new IllegalArgumentException("Unable to parse allowed mechanisms value: " + ex.getMessage()); } return new AllowedMechanisms(mechs); } AllowedMechanisms(List<Long> mechs); static AllowedMechanisms parse(final String allowedMechanismsProperty); static AllowedMechanisms fromBinaryEncoding(final byte[] binary); byte[] toBinaryEncoding(); Long[] toLongArray(); String toPropertyValue(); @Override String toString(); }### Answer:
@Test public void testFromBinaryEncoding() { LOG.info(">testFromBinaryEncoding"); final Long[] expected = new Long[] { 0x00000040l, 0x00000000l, 0x00000250l, 0x252l, 624l, 0x81234567l }; final String binary = "4000000000000000" + "0000000000000000" + "5002000000000000" + "5202000000000000" + "7002000000000000" + "6745238100000000"; assertArrayEquals(expected, AllowedMechanisms.fromBinaryEncoding(Hex.decode(binary)).toLongArray()); } |
### Question:
AllowedMechanisms { @Override public String toString() { return "AllowedMechanisms{" + toPropertyValue() + "}"; } AllowedMechanisms(List<Long> mechs); static AllowedMechanisms parse(final String allowedMechanismsProperty); static AllowedMechanisms fromBinaryEncoding(final byte[] binary); byte[] toBinaryEncoding(); Long[] toLongArray(); String toPropertyValue(); @Override String toString(); }### Answer:
@Test public void testToString() { LOG.info(">testToString"); String allowedMechanismsProperty = " 0x00000040, 0x00000000 0x00000250;0x252 ,624 0x81234567"; String expected = "AllowedMechanisms{CKM_SHA256_RSA_PKCS, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_SHA256, CKM_SHA256_HMAC_GENERAL, CKM_SHA512, 0x81234567}"; AllowedMechanisms result = AllowedMechanisms.parse(allowedMechanismsProperty); assertEquals(expected, result.toString()); } |
### Question:
AttributeProperties { public static AttributeProperties fromWorkerProperties(Properties properties) throws IllegalArgumentException { final Map<String, List<Attribute>> publicTemplateMap = new HashMap<>(); final Map<String, List<Attribute>> privateTemplateMap = new HashMap<>(); for (String attributeObjectKeyAttribute : properties.stringPropertyNames()) { attributeObjectKeyAttribute = attributeObjectKeyAttribute.trim(); if (attributeObjectKeyAttribute.startsWith(ATTRIBUTE_DOT)) { final String objectKeyAttribute = attributeObjectKeyAttribute.substring(ATTRIBUTE_DOT.length()); int nextDot = objectKeyAttribute.indexOf("."); if (nextDot == -1 || objectKeyAttribute.length() < nextDot + 1) { throw new IllegalArgumentException("Incorrect attribute property name: " + attributeObjectKeyAttribute); } else { final String object = objectKeyAttribute.substring(0, nextDot); final String keyAttribute = objectKeyAttribute.substring(object.length() + 1); nextDot = keyAttribute.indexOf("."); if (nextDot == -1 || keyAttribute.length() < nextDot + 1) { throw new IllegalArgumentException("Incorrect attribute property name: " + attributeObjectKeyAttribute); } else { final String keyType = keyAttribute.substring(0, nextDot); List<Attribute> publicTemplate = publicTemplateMap.get(keyType); if (publicTemplate == null) { publicTemplate = new ArrayList<>(); publicTemplateMap.put(keyType, publicTemplate); } List<Attribute> privateTemplate = privateTemplateMap.get(keyType); if (privateTemplate == null) { privateTemplate = new ArrayList<>(); privateTemplateMap.put(keyType, privateTemplate); } final String attribute = keyAttribute.substring(keyType.length() + 1); final long attributeId; if (attribute.startsWith("0x") || attribute.startsWith("0X")) { attributeId = Long.parseLong(attribute.substring("0x".length()), 16); } else if (attribute.startsWith("CKA_")) { Long id = AttributeNames.longFromName(attribute.substring("CKA_".length())); if (id == null) { throw new IllegalArgumentException("Incorrect attribute property name: " + attributeObjectKeyAttribute + ". Unknown attribute: " + attribute); } attributeId = id; } else { attributeId = Long.parseLong(attribute); } final String value = properties.getProperty(attributeObjectKeyAttribute); final Attribute attributeObject = new Attribute(attributeId, getObjectValue(attribute, value)); switch (object) { case OBJECT_PUBLIC: publicTemplate.add(attributeObject); break; case OBJECT_PRIVATE: privateTemplate.add(attributeObject); break; default: } } } } } return new AttributeProperties(publicTemplateMap, privateTemplateMap); } AttributeProperties(Map<String, List<Attribute>> publicTemplate, Map<String, List<Attribute>> privateTemplate); static AttributeProperties fromWorkerProperties(Properties properties); List<Attribute> getPublicTemplate(final String keyType); List<Attribute> getPrivateTemplate(final String keyType); Properties toWorkerProperties(); @Override String toString(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testFromWorkerProperties_booleanIllegal() { LOG.info(">testFromWorkerProperties_booleanIllegal"); Properties properties = new Properties(); properties.setProperty("ATTRIBUTE.PRIVATE.RSA.CKA_VERIFY", "not-boolean"); AttributeProperties.fromWorkerProperties(properties); } |
### Question:
AttributeProperties { public Properties toWorkerProperties() { Properties properties = new Properties(); fill(properties, OBJECT_PRIVATE, privateTemplateMap); fill(properties, OBJECT_PUBLIC, publicTemplateMap); return properties; } AttributeProperties(Map<String, List<Attribute>> publicTemplate, Map<String, List<Attribute>> privateTemplate); static AttributeProperties fromWorkerProperties(Properties properties); List<Attribute> getPublicTemplate(final String keyType); List<Attribute> getPrivateTemplate(final String keyType); Properties toWorkerProperties(); @Override String toString(); }### Answer:
@Test public void testToWorkerProperties() { LOG.info(">testToWorkerProperties"); Properties properties = new Properties(); properties.setProperty("ATTRIBUTE.PRIVATE.RSA.CKA_VERIFY", "True"); properties.setProperty("OTHER", "true"); properties.setProperty("ATTRIBUTE.PRIVATE.RSA.CKA_ALLOWED_MECHANISMS", "SHA256_RSA_PKCS, RSA_PKCS_KEY_PAIR_GEN"); properties.setProperty("ATTRIBUTES", "Attributes value"); properties.setProperty("ATTRIBUTE.PRIVATE.ECDSA.0x162", "false"); properties.setProperty("ATTRIBUTE", "Attribute value"); Properties actual = AttributeProperties.fromWorkerProperties(properties).toWorkerProperties(); assertEquals("ATTRIBUTE.PRIVATE.RSA.CKA_VERIFY", "true", actual.get("ATTRIBUTE.PRIVATE.RSA.CKA_VERIFY")); assertEquals("ATTRIBUTE.PRIVATE.RSA.CKA_ALLOWED_MECHANISMS", "CKM_SHA256_RSA_PKCS, CKM_RSA_PKCS_KEY_PAIR_GEN", actual.get("ATTRIBUTE.PRIVATE.RSA.CKA_ALLOWED_MECHANISMS")); assertEquals("ATTRIBUTE.PRIVATE.ECDSA.CKA_EXTRACTABLE", "false", actual.get("ATTRIBUTE.PRIVATE.ECDSA.CKA_EXTRACTABLE")); } |
### Question:
MSAuthCodeTimeStampSigner extends BaseSigner { @Override public List<String> getCertificateIssues(List<Certificate> certificateChain) { final List<String> results = super.getCertificateIssues(certificateChain); if (!certificateChain.isEmpty()) { results.addAll(checkTimeStampCertificate(certificateChain.get(0))); } return results; } @Override void init(final int signerId, final WorkerConfig config,
final WorkerContext workerContext,
final EntityManager workerEntityManager); @Override Response processData(final Request signRequest,
final RequestContext requestContext); BigInteger getSerno(); @Override List<String> getCertificateIssues(List<Certificate> certificateChain); static final String TIMESOURCE; static final String SIGNATUREALGORITHM; static final String ACCEPTEDALGORITHMS; static final String ACCEPTEDPOLICIES; static final String ACCEPTEDEXTENSIONS; static final String DEFAULTTSAPOLICYOID; static final String ACCURACYMICROS; static final String ACCURACYMILLIS; static final String ACCURACYSECONDS; static final String ORDERING; static final String TSA; static final String REQUIREVALIDCHAIN; static final String INCLUDE_SIGNING_CERTIFICATE_ATTRIBUTE; }### Answer:
@Test public void testCertificateIssues() throws Exception { LOG.info(">testCertificateIssues"); MSAuthCodeTimeStampSigner instance = new MSAuthCodeTimeStampSigner(); final Certificate certNoEku = new JcaX509CertificateConverter().getCertificate(new CertBuilder().setSubject("CN=Without EKU").build()); assertEquals(Arrays.asList("Missing extended key usage timeStamping", "The extended key usage extension must be present and marked as critical"), instance.getCertificateIssues(Arrays.asList(certNoEku))); boolean critical = false; final Certificate certEku = new JcaX509CertificateConverter().getCertificate(new CertBuilder().setSubject("CN=With non-critical EKU").addExtension(new CertExt(Extension.extendedKeyUsage, critical, new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping))).build()); assertEquals(Arrays.asList("The extended key usage extension must be present and marked as critical"), instance.getCertificateIssues(Arrays.asList(certEku))); critical = true; final Certificate certCritEkuButAlsoOther = new JcaX509CertificateConverter().getCertificate(new CertBuilder().setSubject("CN=With critical EKU and other").addExtension(new CertExt(Extension.extendedKeyUsage, critical, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_timeStamping, KeyPurposeId.id_kp_codeSigning }))).build()); assertEquals(Arrays.asList("No other extended key usages than timeStamping is allowed"), instance.getCertificateIssues(Arrays.asList(certCritEkuButAlsoOther))); critical = true; final Certificate certCritEku = new JcaX509CertificateConverter().getCertificate(new CertBuilder().setSubject("CN=With critical EKU").addExtension(new CertExt(Extension.extendedKeyUsage, critical, new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping))).build()); assertEquals(Collections.<String>emptyList(), instance.getCertificateIssues(Arrays.asList(certCritEku))); } |
### Question:
PdfVersionCompatibilityChecker { public boolean isVersionUpgradeRequired() { return pdfVersionOfDocumentToBeSigned < getMinimumCompatiblePdfVersion(); } PdfVersionCompatibilityChecker(String pPdfVersionOfDocumentToBeSigned, String pSignatureDigestAlgorithm); int getPdfVersionOfDocumentToBeSigned(); boolean isVersionUpgradeRequired(); int getMinimumCompatiblePdfVersion(); }### Answer:
@Test public void versionUpgradeRequiredForSha256_PdfVersionIs_0() { PdfVersionCompatibilityChecker checker = new PdfVersionCompatibilityChecker("0", "SHA-256"); boolean upgradeRequired = checker.isVersionUpgradeRequired(); assertTrue(upgradeRequired); }
@Test public void versionUpgradeNotRequiredForSha256_PdfVersionIs_6() { PdfVersionCompatibilityChecker checker = new PdfVersionCompatibilityChecker("6", "SHA-256"); boolean upgradeRequired = checker.isVersionUpgradeRequired(); assertFalse(upgradeRequired); }
@Test public void versionUpgradeRequiredForSha256_PdfVersionIs_NotNumeric() { PdfVersionCompatibilityChecker checker = new PdfVersionCompatibilityChecker("XXXX", "SHA-256"); boolean upgradeRequired = checker.isVersionUpgradeRequired(); assertTrue(upgradeRequired); }
@Test public void versionUpgradeRequiredForSha384_PdfVersionIs_6() { PdfVersionCompatibilityChecker checker = new PdfVersionCompatibilityChecker("6", "SHA-384"); boolean upgradeRequired = checker.isVersionUpgradeRequired(); assertTrue(upgradeRequired); }
@Test public void versionUpgradeNotRequiredForSha384_PdfVersionIs_7() { PdfVersionCompatibilityChecker checker = new PdfVersionCompatibilityChecker("7", "SHA-384"); boolean upgradeRequired = checker.isVersionUpgradeRequired(); assertFalse(upgradeRequired); } |
### Question:
VirtualMetric extends AbstractMetric<V> { @Override public int getCardinality() { return cardinality; } VirtualMetric(
String name,
String description,
String valueDisplayName,
ImmutableSet<LabelDescriptor> labels,
Supplier<ImmutableMap<ImmutableList<String>, V>> valuesSupplier,
Class<V> valueClass); @Override ImmutableList<MetricPoint<V>> getTimestampedValues(); @Override int getCardinality(); }### Answer:
@Test public void testGetCardinality_beforeGetTimestampedValues_returnsZero() { assertThat(metric.getCardinality()).isEqualTo(0); } |
### Question:
ExponentialFitter implements DistributionFitter { public static ExponentialFitter create(int numFiniteIntervals, double base, double scale) { checkArgument(numFiniteIntervals > 0, "numFiniteIntervals must be greater than 0"); checkArgument(scale != 0, "scale must not be 0"); checkArgument(base > 1, "base must be greater than 1"); checkDouble(base); checkDouble(scale); ImmutableSortedSet.Builder<Double> boundaries = ImmutableSortedSet.naturalOrder(); for (int i = 0; i < numFiniteIntervals + 1; i++) { boundaries.add(scale * Math.pow(base, i)); } return new AutoValue_ExponentialFitter(base, scale, boundaries.build()); } static ExponentialFitter create(int numFiniteIntervals, double base, double scale); abstract double base(); abstract double scale(); @Override abstract ImmutableSortedSet<Double> boundaries(); }### Answer:
@Test public void testCreateExponentialFitter_zeroNumIntervals_throwsException() throws Exception { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> ExponentialFitter.create(0, 3.0, 1.0)); assertThat(thrown).hasMessageThat().contains("numFiniteIntervals must be greater than 0"); }
@Test public void testCreateExponentialFitter_negativeNumIntervals_throwsException() throws Exception { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> ExponentialFitter.create(-1, 3.0, 1.0)); assertThat(thrown).hasMessageThat().contains("numFiniteIntervals must be greater than 0"); }
@Test public void testCreateExponentialFitter_invalidBase_throwsException() throws Exception { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> ExponentialFitter.create(3, 0.5, 1.0)); assertThat(thrown).hasMessageThat().contains("base must be greater than 1"); }
@Test public void testCreateExponentialFitter_zeroScale_throwsException() throws Exception { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> ExponentialFitter.create(3, 2.0, 0.0)); assertThat(thrown).hasMessageThat().contains("scale must not be 0"); }
@Test public void testCreateExponentialFitter_NanScale_throwsException() throws Exception { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> ExponentialFitter.create(3, 2.0, Double.NaN)); assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0"); } |
### Question:
MetricReporter extends AbstractScheduledService { @Override protected void runOneIteration() { logger.fine("Running background metric push"); if (metricExporter.state() == State.FAILED) { startMetricExporter(); } ImmutableList.Builder<MetricPoint<?>> points = new ImmutableList.Builder<>(); for (Metric<?> metric : metricRegistry.getRegisteredMetrics()) { points.addAll(metric.getTimestampedValues()); logger.fine(String.format("Enqueued metric %s", metric)); MetricMetrics.pushedPoints.increment( metric.getMetricSchema().kind().name(), metric.getValueClass().toString()); } if (!writeQueue.offer(Optional.of(points.build()))) { logger.severe("writeQueue full, dropped a reporting interval of points"); } MetricMetrics.pushIntervals.increment(); } MetricReporter(
MetricWriter metricWriter, long writeInterval, ThreadFactory threadFactory); @VisibleForTesting MetricReporter(
MetricWriter metricWriter,
long writeInterval,
ThreadFactory threadFactory,
MetricRegistry metricRegistry,
BlockingQueue<Optional<ImmutableList<MetricPoint<?>>>> writeQueue); }### Answer:
@Test public void testRunOneIteration_enqueuesBatch() throws Exception { Metric<?> metric = new Counter("/name", "description", "vdn", ImmutableSet.<LabelDescriptor>of()); when(registry.getRegisteredMetrics()).thenReturn(ImmutableList.of(metric, metric)); MetricReporter reporter = new MetricReporter(writer, 10L, threadFactory, registry, writeQueue); reporter.runOneIteration(); verify(writeQueue).offer(Optional.of(ImmutableList.<MetricPoint<?>>of())); } |
### Question:
MetricSchema { @VisibleForTesting public static MetricSchema create( String name, String description, String valueDisplayName, Kind kind, ImmutableSet<LabelDescriptor> labels) { checkArgument(!name.isEmpty(), "Name must not be blank"); checkArgument(!description.isEmpty(), "Description must not be blank"); checkArgument(!valueDisplayName.isEmpty(), "Value Display Name must not be empty"); checkArgument(name.startsWith("/"), "Name must be URL-like and start with a '/'"); return new AutoValue_MetricSchema(name, description, valueDisplayName, kind, labels); } MetricSchema(); @VisibleForTesting static MetricSchema create(
String name,
String description,
String valueDisplayName,
Kind kind,
ImmutableSet<LabelDescriptor> labels); abstract String name(); abstract String description(); abstract String valueDisplayName(); abstract Kind kind(); abstract ImmutableSet<LabelDescriptor> labels(); }### Answer:
@Test public void testCreate_blankNameField_throwsException() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> MetricSchema.create( "", "description", "valueDisplayName", Kind.GAUGE, ImmutableSet.<LabelDescriptor>of())); assertThat(thrown).hasMessageThat().contains("Name must not be blank"); }
@Test public void testCreate_blankDescriptionField_throwsException() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> MetricSchema.create( "/name", "", "valueDisplayName", Kind.GAUGE, ImmutableSet.<LabelDescriptor>of())); assertThat(thrown).hasMessageThat().contains("Description must not be blank"); }
@Test public void testCreate_blankValueDisplayNameField_throwsException() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> MetricSchema.create( "/name", "description", "", Kind.GAUGE, ImmutableSet.<LabelDescriptor>of())); assertThat(thrown).hasMessageThat().contains("Value Display Name must not be empty"); }
@Test public void testCreate_nakedNames_throwsException() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> MetricSchema.create( "foo", "description", "valueDisplayName", Kind.GAUGE, ImmutableSet.<LabelDescriptor>of())); assertThat(thrown).hasMessageThat().contains("Name must be URL-like and start with a '/'"); } |
### Question:
VirtualMetric extends AbstractMetric<V> { @Override public ImmutableList<MetricPoint<V>> getTimestampedValues() { return getTimestampedValues(Instant.now()); } VirtualMetric(
String name,
String description,
String valueDisplayName,
ImmutableSet<LabelDescriptor> labels,
Supplier<ImmutableMap<ImmutableList<String>, V>> valuesSupplier,
Class<V> valueClass); @Override ImmutableList<MetricPoint<V>> getTimestampedValues(); @Override int getCardinality(); }### Answer:
@Test public void testGetTimestampedValues_returnsValues() { assertThat(metric.getTimestampedValues(Instant.ofEpochMilli(1337))) .containsExactly( MetricPoint.create( metric, ImmutableList.of("label_value1"), Instant.ofEpochMilli(1337), "value1"), MetricPoint.create( metric, ImmutableList.of("label_value2"), Instant.ofEpochMilli(1337), "value2")); } |
### Question:
MutableDistribution implements Distribution { public void add(double value) { add(value, 1L); } MutableDistribution(DistributionFitter distributionFitter); void add(double value); void add(double value, long numSamples); @Override double mean(); @Override double sumOfSquaredDeviation(); @Override long count(); @Override ImmutableRangeMap<Double, Long> intervalCounts(); @Override DistributionFitter distributionFitter(); }### Answer:
@Test public void testAdd_negativeZero_throwsException() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> distribution.add(Double.longBitsToDouble(0x80000000))); assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0"); }
@Test public void testAdd_NaN_throwsException() { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> distribution.add(Double.NaN)); assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0"); }
@Test public void testAdd_positiveInfinity_throwsException() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> distribution.add(Double.POSITIVE_INFINITY)); assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0"); }
@Test public void testAdd_negativeInfinity_throwsException() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> distribution.add(Double.NEGATIVE_INFINITY)); assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0"); } |
### Question:
LabelDescriptor { public static LabelDescriptor create(String name, String description) { checkArgument(!name.isEmpty(), "Name must not be empty"); checkArgument(!description.isEmpty(), "Description must not be empty"); checkArgument( ALLOWED_LABEL_PATTERN.matches(name), "Label name must match the regex %s", ALLOWED_LABEL_PATTERN); return new AutoValue_LabelDescriptor(name, description); } LabelDescriptor(); static LabelDescriptor create(String name, String description); abstract String name(); abstract String description(); }### Answer:
@Test public void testCreate_invalidLabel_throwsException() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> LabelDescriptor.create("@", "description")); assertThat(thrown).hasMessageThat().contains("Label name must match the regex"); }
@Test public void testCreate_blankNameField_throwsException() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> LabelDescriptor.create("", "description")); assertThat(thrown).hasMessageThat().contains("Name must not be empty"); }
@Test public void testCreate_blankDescriptionField_throwsException() { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> LabelDescriptor.create("name", "")); assertThat(thrown).hasMessageThat().contains("Description must not be empty"); } |
### Question:
FibonacciFitter { public static CustomFitter create(long maxBucketSize) { checkArgument(maxBucketSize > 0, "maxBucketSize must be greater than 0"); ImmutableSortedSet.Builder<Double> boundaries = ImmutableSortedSet.naturalOrder(); boundaries.add(Double.valueOf(0)); long i = 1; long j = 2; long k = 3; while (i <= maxBucketSize) { boundaries.add(Double.valueOf(i)); i = j; j = k; k = i + j; } return CustomFitter.create(boundaries.build()); } private FibonacciFitter(); static CustomFitter create(long maxBucketSize); }### Answer:
@Test public void testCreate_maxBucketSizeNegative_throwsException() { IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> FibonacciFitter.create(-1)); assertThat(e).hasMessageThat().isEqualTo("maxBucketSize must be greater than 0"); }
@Test public void testCreate_maxBucketSizeZero_throwsException() { IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> FibonacciFitter.create(0)); assertThat(e).hasMessageThat().isEqualTo("maxBucketSize must be greater than 0"); }
@Test public void testCreate_maxBucketSizeOne_createsTwoBoundaries() { assertThat(FibonacciFitter.create(1).boundaries()).containsExactly(0.0, 1.0).inOrder(); }
@Test public void testCreate_maxBucketSizeTwo_createsThreeBoundaries() { assertThat(FibonacciFitter.create(2).boundaries()).containsExactly(0.0, 1.0, 2.0).inOrder(); }
@Test public void testCreate_maxBucketSizeThree_createsFourBoundaries() { assertThat(FibonacciFitter.create(3).boundaries()) .containsExactly(0.0, 1.0, 2.0, 3.0) .inOrder(); }
@Test public void testCreate_maxBucketSizeFour_createsFourBoundaries() { assertThat(FibonacciFitter.create(4).boundaries()) .containsExactly(0.0, 1.0, 2.0, 3.0) .inOrder(); }
@Test public void testCreate_maxBucketSizeLarge_createsFibonacciSequenceBoundaries() { ImmutableList<Double> expectedBoundaries = ImmutableList.of( 0.0, 1.0, 2.0, 3.0, 5.0, 8.0, 13.0, 21.0, 34.0, 55.0, 89.0, 144.0, 233.0, 377.0, 610.0, 987.0); assertThat(FibonacciFitter.create(1000).boundaries()) .containsExactlyElementsIn(expectedBoundaries) .inOrder(); } |
### Question:
Counter extends AbstractMetric<Long> implements SettableMetric<Long>, IncrementableMetric { @Override public final void increment(String... labelValues) { MetricsUtils.checkLabelValuesLength(this, labelValues); incrementBy(1L, Instant.now(), ImmutableList.copyOf(labelValues)); } Counter(
String name,
String description,
String valueDisplayName,
ImmutableSet<LabelDescriptor> labels); @Override final void incrementBy(long offset, String... labelValues); @Override final void increment(String... labelValues); @Override final ImmutableList<MetricPoint<Long>> getTimestampedValues(); @Override final int getCardinality(); @Override final void set(Long value, String... labelValues); @Override final void reset(); @Override final void reset(String... labelValues); }### Answer:
@Test public void testIncrementBy_wrongLabelValueCount_throwsException() { Counter counter = new Counter( "/metric", "description", "vdn", ImmutableSet.of( LabelDescriptor.create("label1", "bar"), LabelDescriptor.create("label2", "bar"))); IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> counter.increment("blah")); assertThat(thrown) .hasMessageThat() .contains( "The count of labelValues must be equal to the underlying Metric's count of labels."); } |
### Question:
StoredMetric extends AbstractMetric<V> implements SettableMetric<V> { @VisibleForTesting final void set(V value, ImmutableList<String> labelValues) { this.values.put(labelValues, value); } StoredMetric(
String name,
String description,
String valueDisplayName,
ImmutableSet<LabelDescriptor> labels,
Class<V> valueClass); @Override final void set(V value, String... labelValues); @Override final ImmutableList<MetricPoint<V>> getTimestampedValues(); @Override final int getCardinality(); }### Answer:
@Test public void testSet_wrongNumberOfLabels_throwsException() { StoredMetric<Boolean> dimensionalMetric = new StoredMetric<>( "/metric", "description", "vdn", ImmutableSet.of( LabelDescriptor.create("label1", "bar"), LabelDescriptor.create("label2", "bar")), Boolean.class); IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> dimensionalMetric.set(true, "foo")); assertThat(thrown) .hasMessageThat() .contains( "The count of labelValues must be equal to the underlying Metric's count of labels."); } |
### Question:
EventMetric extends AbstractMetric<Distribution> { public void record(double sample, String... labelValues) { MetricsUtils.checkLabelValuesLength(this, labelValues); recordMultiple(sample, 1, Instant.now(), ImmutableList.copyOf(labelValues)); } EventMetric(
String name,
String description,
String valueDisplayName,
DistributionFitter distributionFitter,
ImmutableSet<LabelDescriptor> labels); @Override final int getCardinality(); @Override final ImmutableList<MetricPoint<Distribution>> getTimestampedValues(); void record(double sample, String... labelValues); void record(double sample, int count, String... labelValues); void reset(); void reset(String... labelValues); static final DistributionFitter DEFAULT_FITTER; }### Answer:
@Test public void testIncrementBy_wrongLabelValueCount_throwsException() { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> metric.record(1.0, "blah", "blah")); assertThat(thrown) .hasMessageThat() .contains( "The count of labelValues must be equal to the underlying Metric's count of labels."); } |
### Question:
CustomFitter implements DistributionFitter { public static CustomFitter create(ImmutableSet<Double> boundaries) { checkArgument(boundaries.size() > 0, "boundaries must not be empty"); checkArgument(Ordering.natural().isOrdered(boundaries), "boundaries must be sorted"); for (Double d : boundaries) { checkDouble(d); } return new AutoValue_CustomFitter(ImmutableSortedSet.copyOf(boundaries)); } static CustomFitter create(ImmutableSet<Double> boundaries); @Override abstract ImmutableSortedSet<Double> boundaries(); }### Answer:
@Test public void testCreateCustomFitter_emptyBounds_throwsException() throws Exception { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> CustomFitter.create(ImmutableSet.<Double>of())); assertThat(thrown).hasMessageThat().contains("boundaries must not be empty"); }
@Test public void testCreateCustomFitter_outOfOrderBounds_throwsException() throws Exception { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> CustomFitter.create(ImmutableSet.of(2.0, 0.0))); assertThat(thrown).hasMessageThat().contains("boundaries must be sorted"); } |
### Question:
StackdriverWriter implements MetricWriter { @Override public <V> void write(com.google.monitoring.metrics.MetricPoint<V> point) throws IOException { checkNotNull(point); TimeSeries timeSeries = getEncodedTimeSeries(point); timeSeriesBuffer.add(timeSeries); logger.fine(String.format("Enqueued metric %s for writing", timeSeries.getMetric().getType())); if (timeSeriesBuffer.size() == maxPointsPerRequest) { flush(); } } StackdriverWriter(
Monitoring monitoringClient,
String project,
MonitoredResource monitoredResource,
int maxQps,
int maxPointsPerRequest); @Override void write(com.google.monitoring.metrics.MetricPoint<V> point); @Override void flush(); }### Answer:
@Test public void testWrite_invalidMetricType_throwsException() throws Exception { when(metric.getValueClass()).thenAnswer((Answer<Class<?>>) invocation -> Object.class); StackdriverWriter writer = new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST); for (MetricPoint<?> point : metric.getTimestampedValues()) { assertThrows(IOException.class, () -> writer.write(point)); } } |
### Question:
StackdriverWriter implements MetricWriter { @VisibleForTesting MetricDescriptor registerMetric(final com.google.monitoring.metrics.Metric<?> metric) throws IOException { if (registeredDescriptors.containsKey(metric)) { logger.fine( String.format("Using existing metric descriptor %s", metric.getMetricSchema().name())); return registeredDescriptors.get(metric); } MetricDescriptor descriptor = encodeMetricDescriptor(metric); rateLimiter.acquire(); try { descriptor = monitoringClient .projects() .metricDescriptors() .create(projectResource, descriptor) .execute(); logger.info(String.format("Registered new metric descriptor %s", descriptor.getType())); } catch (GoogleJsonResponseException jsonException) { if (!"ALREADY_EXISTS".equals(jsonException.getStatusMessage())) { throw jsonException; } descriptor = monitoringClient .projects() .metricDescriptors() .get(projectResource + "/metricDescriptors/" + descriptor.getType()) .execute(); logger.info( String.format("Fetched existing metric descriptor %s", metric.getMetricSchema().name())); } registeredDescriptors.put(metric, descriptor); return descriptor; } StackdriverWriter(
Monitoring monitoringClient,
String project,
MonitoredResource monitoredResource,
int maxQps,
int maxPointsPerRequest); @Override void write(com.google.monitoring.metrics.MetricPoint<V> point); @Override void flush(); }### Answer:
@Test public void registerMetric_fetchesStackdriverDefinition() throws Exception { ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8)); HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream); HttpResponseException.Builder httpResponseExceptionBuilder = new HttpResponseException.Builder(response); httpResponseExceptionBuilder.setStatusCode(400); httpResponseExceptionBuilder.setStatusMessage("ALREADY_EXISTS"); GoogleJsonResponseException exception = new GoogleJsonResponseException(httpResponseExceptionBuilder, null); when(metricDescriptorCreate.execute()).thenThrow(exception); StackdriverWriter writer = new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST); writer.registerMetric(metric); verify(client.projects().metricDescriptors().get("metric")).execute(); }
@Test public void registerMetric_rethrowsException() throws Exception { ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8)); HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream); HttpResponseException.Builder httpResponseExceptionBuilder = new HttpResponseException.Builder(response); httpResponseExceptionBuilder.setStatusCode(404); GoogleJsonResponseException exception = new GoogleJsonResponseException(httpResponseExceptionBuilder, null); when(metricDescriptorCreate.execute()).thenThrow(exception); StackdriverWriter writer = new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST); assertThrows(GoogleJsonResponseException.class, () -> writer.registerMetric(metric)); assertThat(exception.getStatusCode()).isEqualTo(404); } |
### Question:
Counter extends AbstractMetric<Long> implements SettableMetric<Long>, IncrementableMetric { @VisibleForTesting void incrementBy(long offset, Instant startTimestamp, ImmutableList<String> labelValues) { Lock lock = valueLocks.get(labelValues); lock.lock(); try { values.addAndGet(labelValues, offset); valueStartTimestamps.putIfAbsent(labelValues, startTimestamp); } finally { lock.unlock(); } } Counter(
String name,
String description,
String valueDisplayName,
ImmutableSet<LabelDescriptor> labels); @Override final void incrementBy(long offset, String... labelValues); @Override final void increment(String... labelValues); @Override final ImmutableList<MetricPoint<Long>> getTimestampedValues(); @Override final int getCardinality(); @Override final void set(Long value, String... labelValues); @Override final void reset(); @Override final void reset(String... labelValues); }### Answer:
@Test public void testIncrementBy_negativeOffset_throwsException() { Counter counter = new Counter( "/metric", "description", "vdn", ImmutableSet.of(LabelDescriptor.create("label1", "bar"))); IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> counter.incrementBy(-1L, "foo")); assertThat(thrown).hasMessageThat().contains("The offset provided must be non-negative"); } |
### Question:
StackdriverWriter implements MetricWriter { @VisibleForTesting static MetricDescriptor encodeMetricDescriptor(com.google.monitoring.metrics.Metric<?> metric) { return new MetricDescriptor() .setType(METRIC_DOMAIN + metric.getMetricSchema().name()) .setDescription(metric.getMetricSchema().description()) .setDisplayName(metric.getMetricSchema().valueDisplayName()) .setValueType(ENCODED_METRIC_TYPES.get(metric.getValueClass())) .setLabels(encodeLabelDescriptors(metric.getMetricSchema().labels())) .setMetricKind(ENCODED_METRIC_KINDS.get(metric.getMetricSchema().kind().name())); } StackdriverWriter(
Monitoring monitoringClient,
String project,
MonitoredResource monitoredResource,
int maxQps,
int maxPointsPerRequest); @Override void write(com.google.monitoring.metrics.MetricPoint<V> point); @Override void flush(); }### Answer:
@Test public void encodeMetricDescriptor_simpleMetric_encodes() { MetricDescriptor descriptor = StackdriverWriter.encodeMetricDescriptor(metric); assertThat(descriptor.getType()).isEqualTo("custom.googleapis.com/name"); assertThat(descriptor.getValueType()).isEqualTo("INT64"); assertThat(descriptor.getDescription()).isEqualTo("desc"); assertThat(descriptor.getDisplayName()).isEqualTo("vdn"); assertThat(descriptor.getLabels()) .containsExactly( new com.google.api.services.monitoring.v3.model.LabelDescriptor() .setValueType("STRING") .setKey("label1") .setDescription("desc1")); } |
### Question:
StackdriverWriter implements MetricWriter { @VisibleForTesting static ImmutableList<LabelDescriptor> encodeLabelDescriptors( ImmutableSet<com.google.monitoring.metrics.LabelDescriptor> labelDescriptors) { List<LabelDescriptor> stackDriverLabelDescriptors = new ArrayList<>(labelDescriptors.size()); for (com.google.monitoring.metrics.LabelDescriptor labelDescriptor : labelDescriptors) { stackDriverLabelDescriptors.add( new LabelDescriptor() .setKey(labelDescriptor.name()) .setDescription(labelDescriptor.description()) .setValueType(LABEL_VALUE_TYPE)); } return ImmutableList.copyOf(stackDriverLabelDescriptors); } StackdriverWriter(
Monitoring monitoringClient,
String project,
MonitoredResource monitoredResource,
int maxQps,
int maxPointsPerRequest); @Override void write(com.google.monitoring.metrics.MetricPoint<V> point); @Override void flush(); }### Answer:
@Test public void encodeLabelDescriptors_simpleLabels_encodes() { ImmutableSet<LabelDescriptor> descriptors = ImmutableSet.of( LabelDescriptor.create("label1", "description1"), LabelDescriptor.create("label2", "description2")); ImmutableList<com.google.api.services.monitoring.v3.model.LabelDescriptor> encodedDescritors = StackdriverWriter.encodeLabelDescriptors(descriptors); assertThat(encodedDescritors) .containsExactly( new com.google.api.services.monitoring.v3.model.LabelDescriptor() .setValueType("STRING") .setKey("label1") .setDescription("description1"), new com.google.api.services.monitoring.v3.model.LabelDescriptor() .setValueType("STRING") .setKey("label2") .setDescription("description2")); } |
### Question:
DistributionMetricSubject extends AbstractMetricSubject<Distribution, DistributionMetricSubject> { public static DistributionMetricSubject assertThat(@Nullable Metric<Distribution> metric) { return assertAbout(DistributionMetricSubject::new).that(metric); } private DistributionMetricSubject(FailureMetadata metadata, Metric<Distribution> actual); static DistributionMetricSubject assertThat(@Nullable Metric<Distribution> metric); And<DistributionMetricSubject> hasDataSetForLabels(
ImmutableSet<? extends Number> dataSet, String... labels); }### Answer:
@Test public void testWrongNumberOfLabels_fails() { AssertionError e = assertThrows( AssertionError.class, () -> assertThat(metric).hasAnyValueForLabels("Domestic")); assertThat(e) .hasMessageThat() .isEqualTo( "Not true that </test/event/sheep> has a value for labels <Domestic>." + " It has labeled values <[Bighorn:Blue =>" + " {[4.0..16.0)=1}, Domestic:Green => {[1.0..4.0)=1}]>"); }
@Test public void testDoesNotHaveWrongNumberOfLabels_succeeds() { assertThat(metric).doesNotHaveAnyValueForLabels("Domestic"); }
@Test public void testHasAnyValueForLabels_success() { assertThat(metric) .hasAnyValueForLabels("Domestic", "Green") .and() .hasAnyValueForLabels("Bighorn", "Blue") .and() .hasNoOtherValues(); }
@Test public void testDoesNotHaveValueForLabels_success() { assertThat(metric).doesNotHaveAnyValueForLabels("Domestic", "Blue"); }
@Test public void testDoesNotHaveValueForLabels_failure() { AssertionError e = assertThrows( AssertionError.class, () -> assertThat(metric).doesNotHaveAnyValueForLabels("Domestic", "Green")); assertThat(e) .hasMessageThat() .isEqualTo( "Not true that </test/event/sheep> has no value for labels <Domestic:Green>." + " It has a value of <{[1.0..4.0)=1}>"); }
@Test public void testUnexpectedValue_failure() { AssertionError e = assertThrows( AssertionError.class, () -> assertThat(metric) .hasAnyValueForLabels("Domestic", "Green") .and() .hasNoOtherValues()); assertThat(e) .hasMessageThat() .isEqualTo( "Not true that </test/event/sheep> has <no other nondefault values>." + " It has labeled values <[Bighorn:Blue =>" + " {[4.0..16.0)=1}, Domestic:Green => {[1.0..4.0)=1}]>"); } |
### Question:
LinearFitter implements DistributionFitter { public static LinearFitter create(int numFiniteIntervals, double width, double offset) { checkArgument(numFiniteIntervals > 0, "numFiniteIntervals must be greater than 0"); checkArgument(width > 0, "width must be greater than 0"); checkDouble(offset); ImmutableSortedSet.Builder<Double> boundaries = ImmutableSortedSet.naturalOrder(); for (int i = 0; i < numFiniteIntervals + 1; i++) { boundaries.add(width * i + offset); } return new AutoValue_LinearFitter(width, offset, boundaries.build()); } static LinearFitter create(int numFiniteIntervals, double width, double offset); abstract double width(); abstract double offset(); @Override abstract ImmutableSortedSet<Double> boundaries(); }### Answer:
@Test public void testCreateLinearFitter_zeroNumIntervals_throwsException() throws Exception { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> LinearFitter.create(0, 3.0, 0.0)); assertThat(thrown).hasMessageThat().contains("numFiniteIntervals must be greater than 0"); }
@Test public void testCreateLinearFitter_negativeNumIntervals_throwsException() throws Exception { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> LinearFitter.create(0, 3.0, 0.0)); assertThat(thrown).hasMessageThat().contains("numFiniteIntervals must be greater than 0"); }
@Test public void testCreateLinearFitter_zeroWidth_throwsException() throws Exception { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> LinearFitter.create(3, 0.0, 0.0)); assertThat(thrown).hasMessageThat().contains("width must be greater than 0"); }
@Test public void testCreateLinearFitter_negativeWidth_throwsException() throws Exception { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> LinearFitter.create(3, 0.0, 0.0)); assertThat(thrown).hasMessageThat().contains("width must be greater than 0"); }
@Test public void testCreateLinearFitter_NaNWidth_throwsException() throws Exception { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> LinearFitter.create(3, Double.NaN, 0.0)); assertThat(thrown).hasMessageThat().contains("width must be greater than 0"); }
@Test public void testCreateLinearFitter_NaNOffset_throwsException() throws Exception { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> LinearFitter.create(3, 1.0, Double.NaN)); assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0"); } |
### Question:
LongMetricSubject extends AbstractMetricSubject<Long, LongMetricSubject> { public static LongMetricSubject assertThat(@Nullable Metric<Long> metric) { return assertAbout(LongMetricSubject::new).that(metric); } private LongMetricSubject(FailureMetadata metadata, Metric<Long> actual); static LongMetricSubject assertThat(@Nullable Metric<Long> metric); And<LongMetricSubject> hasValueForLabels(long value, String... labels); }### Answer:
@Test public void testDoesNotHaveWrongNumberOfLabels_succeeds() { assertThat(metric).doesNotHaveAnyValueForLabels("Domestic"); }
@Test public void testHasAnyValueForLabels_success() { assertThat(metric) .hasAnyValueForLabels("Domestic", "Green") .and() .hasAnyValueForLabels("Bighorn", "Blue") .and() .hasNoOtherValues(); }
@Test public void testDoesNotHaveValueForLabels_success() { assertThat(metric).doesNotHaveAnyValueForLabels("Domestic", "Blue"); }
@Test public void testDoesNotHaveValueForLabels_failure() { AssertionError e = assertThrows( AssertionError.class, () -> assertThat(metric).doesNotHaveAnyValueForLabels("Domestic", "Green")); assertThat(e) .hasMessageThat() .isEqualTo( "Not true that </test/incrementable/sheep> has no value for labels <Domestic:Green>." + " It has a value of <1>"); } |
### Question:
HiveTables extends BaseMetastoreTables { @Override public Table create(Schema schema, String tableIdentifier) { return create(schema, PartitionSpec.unpartitioned(), tableIdentifier); } HiveTables(Configuration conf); @Override Table create(Schema schema, String tableIdentifier); @Override Table create(Schema schema, PartitionSpec spec, Map<String, String> properties, String tableIdentifier); @Override Table load(String tableIdentifier); @Override BaseMetastoreTableOperations newTableOps(Configuration conf, String database, String table); }### Answer:
@Test public void testCreate() throws TException { final Table table = metastoreClient.getTable(DB_NAME, TABLE_NAME); final Map<String, String> parameters = table.getParameters(); Assert.assertNotNull(parameters); Assert.assertTrue(ICEBERG_TABLE_TYPE_VALUE.equalsIgnoreCase(parameters.get(TABLE_TYPE_PROP))); Assert.assertTrue(ICEBERG_TABLE_TYPE_VALUE.equalsIgnoreCase(table.getTableType())); Assert.assertEquals(getTableLocation(TABLE_NAME) , table.getSd().getLocation()); Assert.assertEquals(0 , table.getPartitionKeysSize()); Assert.assertEquals(1, metadataVersionFiles(TABLE_NAME).size()); Assert.assertEquals(0, manifestFiles(TABLE_NAME).size()); final com.netflix.iceberg.Table icebergTable = new HiveTables(hiveConf).load(DB_NAME, TABLE_NAME); Assert.assertEquals(schema.asStruct(), icebergTable.schema().asStruct()); } |
### Question:
HiveTables extends BaseMetastoreTables { @Override public Table load(String tableIdentifier) { List<String> parts = DOT.splitToList(tableIdentifier); if (parts.size() == 2) { return load(parts.get(0), parts.get(1)); } throw new UnsupportedOperationException("Could not parse table identifier: " + tableIdentifier); } HiveTables(Configuration conf); @Override Table create(Schema schema, String tableIdentifier); @Override Table create(Schema schema, PartitionSpec spec, Map<String, String> properties, String tableIdentifier); @Override Table load(String tableIdentifier); @Override BaseMetastoreTableOperations newTableOps(Configuration conf, String database, String table); }### Answer:
@Test public void testExistingTableUpdate() throws TException { com.netflix.iceberg.Table icebergTable = new HiveTables(hiveConf).load(DB_NAME, TABLE_NAME); icebergTable.updateSchema().addColumn("data", Types.LongType.get()).commit(); icebergTable = new HiveTables(hiveConf).load(DB_NAME, TABLE_NAME); Assert.assertEquals(2, metadataVersionFiles(TABLE_NAME).size()); Assert.assertEquals(0, manifestFiles(TABLE_NAME).size()); Assert.assertEquals(altered.asStruct(), icebergTable.schema().asStruct()); final Table table = metastoreClient.getTable(DB_NAME, TABLE_NAME); final List<String> hiveColumns = table.getSd().getCols().stream().map(f -> f.getName()).collect(Collectors.toList()); final List<String> icebergColumns = altered.columns().stream().map(f -> f.name()).collect(Collectors.toList()); Assert.assertEquals(icebergColumns, hiveColumns); }
@Test(expected = CommitFailedException.class) public void testFailure() throws TException { com.netflix.iceberg.Table icebergTable = new HiveTables(hiveConf).load(DB_NAME, TABLE_NAME); final Table table = metastoreClient.getTable(DB_NAME, TABLE_NAME); final String dummyLocation = "dummylocation"; table.getParameters().put(METADATA_LOCATION_PROP, dummyLocation); metastoreClient.alter_table(DB_NAME, TABLE_NAME, table); icebergTable.updateSchema() .addColumn("data", Types.LongType.get()) .commit(); } |
### Question:
SchemaUtil { public static ResourceSchema convert(Schema icebergSchema) throws IOException { ResourceSchema result = new ResourceSchema(); result.setFields(convertFields(icebergSchema.columns())); return result; } static ResourceSchema convert(Schema icebergSchema); static Schema project(Schema schema, List<String> requiredFields); }### Answer:
@Test public void testPrimitive() throws IOException { Schema icebergSchema = new Schema( optional(1, "b", BooleanType.get()), optional(1, "i", IntegerType.get()), optional(2, "l", LongType.get()), optional(3, "f", FloatType.get()), optional(4, "d", DoubleType.get()), optional(5, "dec", DecimalType.of(0,2)), optional(5, "s", StringType.get()), optional(6,"bi", BinaryType.get()) ); ResourceSchema pigSchema = SchemaUtil.convert(icebergSchema); assertEquals("b:boolean,i:int,l:long,f:float,d:double,dec:bigdecimal,s:chararray,bi:bytearray", pigSchema.toString()); }
@Test public void testTupleInMap() throws IOException { Schema icebergSchema = new Schema( optional( 1, "nested_list", MapType.ofOptional( 2, 3, StringType.get(), ListType.ofOptional( 4, StructType.of( required(5, "id", LongType.get()), optional(6, "data", StringType.get())))))); ResourceSchema pigSchema = SchemaUtil.convert(icebergSchema); assertEquals("nested_list:[{(id:long,data:chararray)}]", pigSchema.toString()); }
@Test public void testLongInBag() throws IOException { Schema icebergSchema = new Schema( optional( 1, "nested_list", MapType.ofOptional( 2, 3, StringType.get(), ListType.ofRequired(5, LongType.get())))); SchemaUtil.convert(icebergSchema); } |
### Question:
Listeners { @SuppressWarnings("unchecked") public static <E> void notifyAll(E event) { Preconditions.checkNotNull(event, "Cannot notify listeners for a null event."); List<Listener<?>> list = listeners.get(event.getClass()); if (list != null) { Iterator<Listener<?>> iter = list.iterator(); while (iter.hasNext()) { Listener<E> listener = (Listener<E>) iter.next(); listener.notify(event); } } } private Listeners(); static void register(Listener<E> listener, Class<E> eventType); @SuppressWarnings("unchecked") static void notifyAll(E event); }### Answer:
@Test public void testEvent1() { Event1 e1 = new Event1(); Listeners.notifyAll(e1); Assert.assertEquals(e1, TestListener.get().e1); }
@Test public void testEvent2() { Event2 e2 = new Event2(); Listeners.notifyAll(e2); Assert.assertEquals(e2, TestListener.get().e2); } |
### Question:
ScanSummary { static long toMillis(long timestamp) { if (timestamp < 10000000000L) { return timestamp * 1000; } else if (timestamp < 10000000000000L) { return timestamp; } return timestamp / 1000; } private ScanSummary(); static ScanSummary.Builder of(TableScan scan); }### Answer:
@Test public void testToMillis() { long millis = 1542750947417L; Assert.assertEquals(1542750947000L, toMillis(millis / 1000)); Assert.assertEquals(1542750947417L, toMillis(millis)); Assert.assertEquals(1542750947417L, toMillis(millis * 1000 + 918)); } |
### Question:
SchemaUpdate implements UpdateSchema { @Override public Schema apply() { return applyChanges(schema, deletes, updates, adds); } SchemaUpdate(TableOperations ops); SchemaUpdate(Schema schema, int lastColumnId); @Override UpdateSchema addColumn(String name, Type type); @Override UpdateSchema addColumn(String parent, String name, Type type); @Override UpdateSchema deleteColumn(String name); @Override UpdateSchema renameColumn(String name, String newName); @Override UpdateSchema updateColumn(String name, Type.PrimitiveType newType); @Override Schema apply(); @Override void commit(); }### Answer:
@Test public void testNoChanges() { Schema identical = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID).apply(); Assert.assertEquals("Should not include any changes", SCHEMA.asStruct(), identical.asStruct()); } |
### Question:
SchemaUpdate implements UpdateSchema { private static Types.StructType addFields(Types.StructType struct, Collection<Types.NestedField> adds) { List<Types.NestedField> newFields = Lists.newArrayList(struct.fields()); newFields.addAll(adds); return Types.StructType.of(newFields); } SchemaUpdate(TableOperations ops); SchemaUpdate(Schema schema, int lastColumnId); @Override UpdateSchema addColumn(String name, Type type); @Override UpdateSchema addColumn(String parent, String name, Type type); @Override UpdateSchema deleteColumn(String name); @Override UpdateSchema renameColumn(String name, String newName); @Override UpdateSchema updateColumn(String name, Type.PrimitiveType newType); @Override Schema apply(); @Override void commit(); }### Answer:
@Test public void testAddFields() { Schema expected = new Schema( required(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()), optional(3, "preferences", Types.StructType.of( required(8, "feature1", Types.BooleanType.get()), optional(9, "feature2", Types.BooleanType.get()) )), required(4, "locations", Types.MapType.ofRequired(10, 11, Types.StructType.of( required(20, "address", Types.StringType.get()), required(21, "city", Types.StringType.get()), required(22, "state", Types.StringType.get()), required(23, "zip", Types.IntegerType.get()) ), Types.StructType.of( required(12, "lat", Types.FloatType.get()), required(13, "long", Types.FloatType.get()), optional(25, "alt", Types.FloatType.get()) ))), optional(5, "points", Types.ListType.ofOptional(14, Types.StructType.of( required(15, "x", Types.LongType.get()), required(16, "y", Types.LongType.get()), optional(26, "z", Types.LongType.get()), optional(27, "t.t", Types.LongType.get()) ))), required(6, "doubles", Types.ListType.ofRequired(17, Types.DoubleType.get() )), optional(7, "properties", Types.MapType.ofOptional(18, 19, Types.StringType.get(), Types.StringType.get() )), optional(24, "toplevel", Types.DecimalType.of(9, 2)) ); Schema added = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID) .addColumn("toplevel", Types.DecimalType.of(9, 2)) .addColumn("locations", "alt", Types.FloatType.get()) .addColumn("points", "z", Types.LongType.get()) .addColumn("points", "t.t", Types.LongType.get()) .apply(); Assert.assertEquals("Should match with added fields", expected.asStruct(), added.asStruct()); } |
### Question:
SchemaUpdate implements UpdateSchema { @Override public UpdateSchema addColumn(String name, Type type) { Preconditions.checkArgument(!name.contains("."), "Cannot add column with ambiguous name: %s, use addColumn(parent, name, type)", name); return addColumn(null, name, type); } SchemaUpdate(TableOperations ops); SchemaUpdate(Schema schema, int lastColumnId); @Override UpdateSchema addColumn(String name, Type type); @Override UpdateSchema addColumn(String parent, String name, Type type); @Override UpdateSchema deleteColumn(String name); @Override UpdateSchema renameColumn(String name, String newName); @Override UpdateSchema updateColumn(String name, Type.PrimitiveType newType); @Override Schema apply(); @Override void commit(); }### Answer:
@Test public void testAmbiguousAdd() { AssertHelpers.assertThrows("Should reject ambiguous column name", IllegalArgumentException.class, "ambiguous name: preferences.booleans", () -> { UpdateSchema update = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID); update.addColumn("preferences.booleans", Types.BooleanType.get()); } ); }
@Test public void testAddAlreadyExists() { AssertHelpers.assertThrows("Should reject column name that already exists", IllegalArgumentException.class, "already exists: preferences.feature1", () -> { UpdateSchema update = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID); update.addColumn("preferences", "feature1", Types.BooleanType.get()); } ); AssertHelpers.assertThrows("Should reject column name that already exists", IllegalArgumentException.class, "already exists: preferences", () -> { UpdateSchema update = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID); update.addColumn("preferences", Types.BooleanType.get()); } ); } |
### Question:
SchemaUpdate implements UpdateSchema { @Override public UpdateSchema deleteColumn(String name) { Types.NestedField field = schema.findField(name); Preconditions.checkArgument(field != null, "Cannot delete missing column: %s", name); Preconditions.checkArgument(!adds.containsKey(field.fieldId()), "Cannot delete a column that has additions: %s", name); Preconditions.checkArgument(!updates.containsKey(field.fieldId()), "Cannot delete a column that has updates: %s", name); deletes.add(field.fieldId()); return this; } SchemaUpdate(TableOperations ops); SchemaUpdate(Schema schema, int lastColumnId); @Override UpdateSchema addColumn(String name, Type type); @Override UpdateSchema addColumn(String parent, String name, Type type); @Override UpdateSchema deleteColumn(String name); @Override UpdateSchema renameColumn(String name, String newName); @Override UpdateSchema updateColumn(String name, Type.PrimitiveType newType); @Override Schema apply(); @Override void commit(); }### Answer:
@Test public void testDeleteMissingColumn() { AssertHelpers.assertThrows("Should reject delete missing column", IllegalArgumentException.class, "missing column: col", () -> { UpdateSchema update = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID); update.deleteColumn("col"); } ); } |
### Question:
SchemaUpdate implements UpdateSchema { @Override public UpdateSchema renameColumn(String name, String newName) { Types.NestedField field = schema.findField(name); Preconditions.checkArgument(field != null, "Cannot rename missing column: %s", name); Preconditions.checkArgument(!deletes.contains(field.fieldId()), "Cannot rename a column that will be deleted: %s", field.name()); int fieldId = field.fieldId(); Types.NestedField update = updates.get(fieldId); if (update != null) { updates.put(fieldId, Types.NestedField.required(fieldId, newName, update.type())); } else { updates.put(fieldId, Types.NestedField.required(fieldId, newName, field.type())); } return this; } SchemaUpdate(TableOperations ops); SchemaUpdate(Schema schema, int lastColumnId); @Override UpdateSchema addColumn(String name, Type type); @Override UpdateSchema addColumn(String parent, String name, Type type); @Override UpdateSchema deleteColumn(String name); @Override UpdateSchema renameColumn(String name, String newName); @Override UpdateSchema updateColumn(String name, Type.PrimitiveType newType); @Override Schema apply(); @Override void commit(); }### Answer:
@Test public void testRenameMissingColumn() { AssertHelpers.assertThrows("Should reject rename missing column", IllegalArgumentException.class, "missing column: col", () -> { UpdateSchema update = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID); update.renameColumn("col", "fail"); } ); } |
### Question:
SchemaUpdate implements UpdateSchema { @Override public UpdateSchema updateColumn(String name, Type.PrimitiveType newType) { Types.NestedField field = schema.findField(name); Preconditions.checkArgument(field != null, "Cannot update missing column: %s", name); Preconditions.checkArgument(!deletes.contains(field.fieldId()), "Cannot update a column that will be deleted: %s", field.name()); Preconditions.checkArgument(TypeUtil.isPromotionAllowed(field.type(), newType), "Cannot change column type: %s: %s -> %s", name, field.type(), newType); int fieldId = field.fieldId(); Types.NestedField rename = updates.get(fieldId); if (rename != null) { updates.put(fieldId, Types.NestedField.required(fieldId, rename.name(), newType)); } else { updates.put(fieldId, Types.NestedField.required(fieldId, field.name(), newType)); } return this; } SchemaUpdate(TableOperations ops); SchemaUpdate(Schema schema, int lastColumnId); @Override UpdateSchema addColumn(String name, Type type); @Override UpdateSchema addColumn(String parent, String name, Type type); @Override UpdateSchema deleteColumn(String name); @Override UpdateSchema renameColumn(String name, String newName); @Override UpdateSchema updateColumn(String name, Type.PrimitiveType newType); @Override Schema apply(); @Override void commit(); }### Answer:
@Test public void testUpdateMissingColumn() { AssertHelpers.assertThrows("Should reject rename missing column", IllegalArgumentException.class, "missing column: col", () -> { UpdateSchema update = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID); update.updateColumn("col", Types.DateType.get()); } ); } |
### Question:
StringUtils { public static boolean isEmpty(String str) { return str == null || str.length() == 0; } static boolean isEmpty(String str); static String leftPad(String str, int size); static String leftPad(String str, int size, char padChar); static String leftPad(String str, int size, String padStr); static String padding(int repeat, char padChar); }### Answer:
@Test public void isEmpty() { Assert.assertTrue(StringUtils.isEmpty(null)); Assert.assertTrue(StringUtils.isEmpty("")); Assert.assertFalse(StringUtils.isEmpty(" ")); Assert.assertFalse(StringUtils.isEmpty("bob")); Assert.assertFalse(StringUtils.isEmpty(" bob ")); } |
### Question:
FlakeEncodingProvider implements EncodingProvider { @Override public long encodeAsLong(long time, int sequence) { throw new UnsupportedOperationException("Long value not supported"); } FlakeEncodingProvider(long machineId); @Override byte[] encodeAsBytes(long time, int sequence); @Override long encodeAsLong(long time, int sequence); @Override String encodeAsString(long time, int sequence); @Override int maxSequenceNumbers(); }### Answer:
@Test public void notImplemented() { try { new FlakeEncodingProvider(1).encodeAsLong(1, 1); Assert.fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException e) { Assert.assertTrue(e.getMessage().contains("Long value not supported")); } } |
### Question:
StringUtils { public static String leftPad(String str, int size) { return leftPad(str, size, ' '); } static boolean isEmpty(String str); static String leftPad(String str, int size); static String leftPad(String str, int size, char padChar); static String leftPad(String str, int size, String padStr); static String padding(int repeat, char padChar); }### Answer:
@Test public void leftPad() { Assert.assertNull(StringUtils.leftPad(null, 9)); Assert.assertEquals(" ", StringUtils.leftPad("", 3)); Assert.assertEquals("bat", StringUtils.leftPad("bat", 3)); Assert.assertEquals(" bat", StringUtils.leftPad("bat", 5)); Assert.assertEquals("bat", StringUtils.leftPad("bat", 1)); Assert.assertEquals("bat", StringUtils.leftPad("bat", -1)); Assert.assertEquals(8193, StringUtils.leftPad("", 8193).length()); Assert.assertNull(StringUtils.leftPad(null, 9, "ddd")); Assert.assertEquals("zzz", StringUtils.leftPad("", 3, "z")); Assert.assertEquals("bat", StringUtils.leftPad("bat", 3, "yz")); Assert.assertEquals("yzbat", StringUtils.leftPad("bat", 5, "yz")); Assert.assertEquals("yzyzybat", StringUtils.leftPad("bat", 8, "yz")); Assert.assertEquals("bat", StringUtils.leftPad("bat", 1, "yz")); Assert.assertEquals("bat", StringUtils.leftPad("bat", -1, "yz")); Assert.assertEquals(" bat", StringUtils.leftPad("bat", 5, null)); Assert.assertEquals(" bat", StringUtils.leftPad("bat", 5, "")); } |
### Question:
StringUtils { public static String padding(int repeat, char padChar) throws IndexOutOfBoundsException { if (repeat < 0) { throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat); } final char[] buf = new char[repeat]; for (int i = 0; i < buf.length; i++) { buf[i] = padChar; } return new String(buf); } static boolean isEmpty(String str); static String leftPad(String str, int size); static String leftPad(String str, int size, char padChar); static String leftPad(String str, int size, String padStr); static String padding(int repeat, char padChar); }### Answer:
@Test public void padding() { Assert.assertEquals("", padding(0, 'e')); Assert.assertEquals("eee", padding(3, 'e')); try { padding(-2, 'e'); Assert.fail("Expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { Assert.assertTrue(e.getMessage().contains("Cannot pad a negative amount:")); } } |
### Question:
PidUtils { public static int pid() { int localPID = 0; try { String name = ManagementFactory.getRuntimeMXBean().getName(); String[] nameSplit = name.split("@"); if(nameSplit.length > 1) { localPID = Integer.parseInt(nameSplit[0]); } return localPID; } catch(Throwable t) { throw new UnsupportedOperationException("An error occurred while getting the PID: " + t.getMessage()) ; } } static int pid(); }### Answer:
@Test public void verifyPid() { int pid = PidUtils.pid(); Assert.assertTrue("Could not retrieve PID", pid != 0); Assert.assertTrue("Negative PID", pid > 0); } |
### Question:
MacUtils { public static byte[] macAddress() { byte[] override = getOverride(); return override != null ? override : realMacAddress(); } static byte[] getOverride(); static byte[] realMacAddress(); static byte[] macAddress(); static final String OVERRIDE_MAC_PROP; }### Answer:
@Test public void verifyMac() { byte[] mac; try { mac = MacUtils.macAddress(); } catch(UnsupportedOperationException e) { e.printStackTrace(); System.setProperty(MacUtils.OVERRIDE_MAC_PROP, "00:DE:AD:BE:EF:00"); mac = MacUtils.macAddress(); } Assert.assertNotNull("Could not retrieve MAC", mac); Assert.assertTrue("Invalid MAC address", mac.length == 6); }
@Test public void verifyOverride() { System.setProperty(MacUtils.OVERRIDE_MAC_PROP, "00:DE:AD:BE:EF:11"); byte[] mac = MacUtils.macAddress(); Assert.assertNotNull("Could not retrieve MAC", mac); Assert.assertTrue("Invalid MAC address", mac.length == 6); Assert.assertEquals("Unexpected MAC address", "[0, -34, -83, -66, -17, 17]", Arrays.toString(mac)); System.clearProperty(MacUtils.OVERRIDE_MAC_PROP); } |
### Question:
MacUtils { public static byte[] getOverride() { String overrideMac = System.getProperty(OVERRIDE_MAC_PROP); byte[] macBytes = null; if (overrideMac != null) { ByteArrayOutputStream out = new ByteArrayOutputStream(); String[] rawBytes = overrideMac.split(":"); if (rawBytes.length == 6) { try { for (String b : rawBytes) { out.write(Integer.parseInt(b, 16)); } macBytes = out.toByteArray(); } catch (NumberFormatException e) { } } } return macBytes; } static byte[] getOverride(); static byte[] realMacAddress(); static byte[] macAddress(); static final String OVERRIDE_MAC_PROP; }### Answer:
@Test public void bogusOverride() { System.setProperty(MacUtils.OVERRIDE_MAC_PROP, "totally not a MAC"); byte[] mac = MacUtils.getOverride(); Assert.assertNull("Retrieved a bogus MAC", mac); System.clearProperty(MacUtils.OVERRIDE_MAC_PROP); }
@Test public void slightlyBogusOverride() { System.setProperty(MacUtils.OVERRIDE_MAC_PROP, "00:DE:AD:BE:EF:QQ"); byte[] mac = MacUtils.getOverride(); Assert.assertNull("Retrieved a bogus MAC", mac); System.clearProperty(MacUtils.OVERRIDE_MAC_PROP); } |
### Question:
MacMachineIdProvider implements MachineIdProvider { @Override public long getMachineId() { return machineId; } MacMachineIdProvider(); @Override long getMachineId(); }### Answer:
@Test public void validateProvider() { Assert.assertEquals("Machine id's are not deterministic", new MacMachineIdProvider().getMachineId(), new MacMachineIdProvider().getMachineId()); if(new MacMachineIdProvider().getMachineId() == 0L) { System.err.println("Could not detect MAC address"); } } |
### Question:
MacPidMachineIdProvider implements MachineIdProvider { @Override public long getMachineId() { return machineId; } MacPidMachineIdProvider(); @Override long getMachineId(); }### Answer:
@Test public void validateProvider() { Assert.assertEquals("Machine id's are not deterministic", new MacPidMachineIdProvider().getMachineId(), new MacPidMachineIdProvider().getMachineId()); if(new MacPidMachineIdProvider().getMachineId() == 0L) { System.err.println("Could not detect MAC address"); } } |
### Question:
SPPDecoder implements MALDecoder { @Override public UShort decodeNullableUShort() throws MALException { return isNull() ? null : decodeUShort(); } SPPDecoder(final InputStream inputStream, final Map properties); @Override Boolean decodeBoolean(); @Override Boolean decodeNullableBoolean(); @Override Float decodeFloat(); @Override Float decodeNullableFloat(); @Override Double decodeDouble(); @Override Double decodeNullableDouble(); @Override Byte decodeOctet(); @Override Byte decodeNullableOctet(); @Override UOctet decodeUOctet(); @Override UOctet decodeNullableUOctet(); @Override Short decodeShort(); @Override Short decodeNullableShort(); @Override UShort decodeUShort(); @Override UShort decodeNullableUShort(); @Override Integer decodeInteger(); @Override Integer decodeNullableInteger(); @Override UInteger decodeUInteger(); @Override UInteger decodeNullableUInteger(); @Override Long decodeLong(); @Override Long decodeNullableLong(); @Override ULong decodeULong(); @Override ULong decodeNullableULong(); @Override String decodeString(); @Override String decodeNullableString(); @Override Blob decodeBlob(); @Override Blob decodeNullableBlob(); @Override Duration decodeDuration(); @Override Duration decodeNullableDuration(); @Override FineTime decodeFineTime(); @Override FineTime decodeNullableFineTime(); @Override Identifier decodeIdentifier(); @Override Identifier decodeNullableIdentifier(); @Override Time decodeTime(); @Override Time decodeNullableTime(); @Override URI decodeURI(); @Override URI decodeNullableURI(); @Override Element decodeElement(final Element element); @Override Element decodeNullableElement(final Element element); @Override Attribute decodeAttribute(); @Override Attribute decodeNullableAttribute(); @Override MALListDecoder createListDecoder(final List list); }### Answer:
@Test public void testDecodeNullableUShort2b() throws Exception { newBuffer(new byte[]{ 1, (byte) 0b11111111, (byte) 0b11111111, 1, 0, 0, 0, 1, (byte) 0b01111010, (byte) 0b10110111, 1, (byte) 0b00000001, 0 }); setVarintSupportedProperty(false); assertEquals(new UShort(65535), decoder.decodeNullableUShort()); assertEquals(new UShort(0), decoder.decodeNullableUShort()); assertEquals(null, decoder.decodeNullableUShort()); assertEquals(new UShort(31415), decoder.decodeNullableUShort()); assertEquals(new UShort(256), decoder.decodeNullableUShort()); }
@Test public void testDecodeNullableUShort1() throws Exception { newBuffer(new byte[]{0}); assertEquals(null, decoder.decodeNullableUShort()); }
@Test public void testDecodeNullableUShort2() throws Exception { newBuffer(new byte[]{ 1, (byte) 0b11111111, (byte) 0b11111111, (byte) 0b00000011, 1, (byte) 0, 0, 1, (byte) 0b10110111, (byte) 0b11110101, (byte) 0b00000001, 1, (byte) 0b10000000, (byte) 0b00000010 }); assertEquals(new UShort(65535), decoder.decodeNullableUShort()); assertEquals(new UShort(0), decoder.decodeNullableUShort()); assertEquals(null, decoder.decodeNullableUShort()); assertEquals(new UShort(31415), decoder.decodeNullableUShort()); assertEquals(new UShort(256), decoder.decodeNullableUShort()); } |
### Question:
SPPDecoder implements MALDecoder { @Override public Integer decodeNullableInteger() throws MALException { return isNull() ? null : decodeInteger(); } SPPDecoder(final InputStream inputStream, final Map properties); @Override Boolean decodeBoolean(); @Override Boolean decodeNullableBoolean(); @Override Float decodeFloat(); @Override Float decodeNullableFloat(); @Override Double decodeDouble(); @Override Double decodeNullableDouble(); @Override Byte decodeOctet(); @Override Byte decodeNullableOctet(); @Override UOctet decodeUOctet(); @Override UOctet decodeNullableUOctet(); @Override Short decodeShort(); @Override Short decodeNullableShort(); @Override UShort decodeUShort(); @Override UShort decodeNullableUShort(); @Override Integer decodeInteger(); @Override Integer decodeNullableInteger(); @Override UInteger decodeUInteger(); @Override UInteger decodeNullableUInteger(); @Override Long decodeLong(); @Override Long decodeNullableLong(); @Override ULong decodeULong(); @Override ULong decodeNullableULong(); @Override String decodeString(); @Override String decodeNullableString(); @Override Blob decodeBlob(); @Override Blob decodeNullableBlob(); @Override Duration decodeDuration(); @Override Duration decodeNullableDuration(); @Override FineTime decodeFineTime(); @Override FineTime decodeNullableFineTime(); @Override Identifier decodeIdentifier(); @Override Identifier decodeNullableIdentifier(); @Override Time decodeTime(); @Override Time decodeNullableTime(); @Override URI decodeURI(); @Override URI decodeNullableURI(); @Override Element decodeElement(final Element element); @Override Element decodeNullableElement(final Element element); @Override Attribute decodeAttribute(); @Override Attribute decodeNullableAttribute(); @Override MALListDecoder createListDecoder(final List list); }### Answer:
@Test public void testDecodeNullableInteger1() throws Exception { newBuffer(new byte[]{0}); assertEquals(null, decoder.decodeNullableInteger()); }
@Test public void testDecodeNullableInteger2() throws Exception { newBuffer(new byte[]{ 1, (byte) 0b00000010, 0, 1, (byte) 0b00000001, 1, (byte) 0b10101100, (byte) 0b10110101, (byte) 0b11011110, (byte) 0b01110101 }); assertEquals(Integer.valueOf(1), decoder.decodeNullableInteger()); assertEquals(null, decoder.decodeNullableInteger()); assertEquals(Integer.valueOf(-1), decoder.decodeNullableInteger()); assertEquals(Integer.valueOf(123456854), decoder.decodeNullableInteger()); }
@Test public void testDecodeNullableInteger2b() throws Exception { newBuffer(new byte[]{ 1, 0, 0, 0, (byte) 0x01, 0, 1, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, 1, (byte) 0x07, (byte) 0x5B, (byte) 0xCD, (byte) 0x56 }); setVarintSupportedProperty(false); assertEquals(Integer.valueOf(1), decoder.decodeNullableInteger()); assertEquals(null, decoder.decodeNullableInteger()); assertEquals(Integer.valueOf(-1), decoder.decodeNullableInteger()); assertEquals(Integer.valueOf(123456854), decoder.decodeNullableInteger()); } |
### Question:
SPPDecoder implements MALDecoder { @Override public UInteger decodeNullableUInteger() throws MALException { return isNull() ? null : decodeUInteger(); } SPPDecoder(final InputStream inputStream, final Map properties); @Override Boolean decodeBoolean(); @Override Boolean decodeNullableBoolean(); @Override Float decodeFloat(); @Override Float decodeNullableFloat(); @Override Double decodeDouble(); @Override Double decodeNullableDouble(); @Override Byte decodeOctet(); @Override Byte decodeNullableOctet(); @Override UOctet decodeUOctet(); @Override UOctet decodeNullableUOctet(); @Override Short decodeShort(); @Override Short decodeNullableShort(); @Override UShort decodeUShort(); @Override UShort decodeNullableUShort(); @Override Integer decodeInteger(); @Override Integer decodeNullableInteger(); @Override UInteger decodeUInteger(); @Override UInteger decodeNullableUInteger(); @Override Long decodeLong(); @Override Long decodeNullableLong(); @Override ULong decodeULong(); @Override ULong decodeNullableULong(); @Override String decodeString(); @Override String decodeNullableString(); @Override Blob decodeBlob(); @Override Blob decodeNullableBlob(); @Override Duration decodeDuration(); @Override Duration decodeNullableDuration(); @Override FineTime decodeFineTime(); @Override FineTime decodeNullableFineTime(); @Override Identifier decodeIdentifier(); @Override Identifier decodeNullableIdentifier(); @Override Time decodeTime(); @Override Time decodeNullableTime(); @Override URI decodeURI(); @Override URI decodeNullableURI(); @Override Element decodeElement(final Element element); @Override Element decodeNullableElement(final Element element); @Override Attribute decodeAttribute(); @Override Attribute decodeNullableAttribute(); @Override MALListDecoder createListDecoder(final List list); }### Answer:
@Test public void testDecodeNullableUInteger1() throws Exception { newBuffer(new byte[]{0}); assertEquals(null, decoder.decodeNullableUInteger()); }
@Test public void testDecodeNullableUInteger2() throws Exception { newBuffer(new byte[]{ 1, (byte) 0b00000001, 1, (byte) 0b11101011, (byte) 0b01111111, 1, (byte) 0b11000101, (byte) 0b11010000, (byte) 0b10000100, (byte) 0b10000000, (byte) 0b00001000, 0 }); assertEquals(new UInteger(1), decoder.decodeNullableUInteger()); assertEquals(new UInteger(16363), decoder.decodeNullableUInteger()); assertEquals(new UInteger(2147559493L), decoder.decodeNullableUInteger()); assertEquals(null, decoder.decodeNullableUInteger()); }
@Test public void testDecodeNullableUInteger2b() throws Exception { newBuffer(new byte[]{ 1, 0, 0, 0, (byte) 0x01, 1, 0, 0, (byte) 0x3F, (byte) 0xEB, 1, (byte) 0x80, (byte) 0x01, (byte) 0x28, (byte) 0x45, 0 }); setVarintSupportedProperty(false); assertEquals(new UInteger(1), decoder.decodeNullableUInteger()); assertEquals(new UInteger(16363), decoder.decodeNullableUInteger()); assertEquals(new UInteger(2147559493L), decoder.decodeNullableUInteger()); assertEquals(null, decoder.decodeNullableUInteger()); } |
### Question:
SPPDecoder implements MALDecoder { @Override public Long decodeNullableLong() throws MALException { return isNull() ? null : decodeLong(); } SPPDecoder(final InputStream inputStream, final Map properties); @Override Boolean decodeBoolean(); @Override Boolean decodeNullableBoolean(); @Override Float decodeFloat(); @Override Float decodeNullableFloat(); @Override Double decodeDouble(); @Override Double decodeNullableDouble(); @Override Byte decodeOctet(); @Override Byte decodeNullableOctet(); @Override UOctet decodeUOctet(); @Override UOctet decodeNullableUOctet(); @Override Short decodeShort(); @Override Short decodeNullableShort(); @Override UShort decodeUShort(); @Override UShort decodeNullableUShort(); @Override Integer decodeInteger(); @Override Integer decodeNullableInteger(); @Override UInteger decodeUInteger(); @Override UInteger decodeNullableUInteger(); @Override Long decodeLong(); @Override Long decodeNullableLong(); @Override ULong decodeULong(); @Override ULong decodeNullableULong(); @Override String decodeString(); @Override String decodeNullableString(); @Override Blob decodeBlob(); @Override Blob decodeNullableBlob(); @Override Duration decodeDuration(); @Override Duration decodeNullableDuration(); @Override FineTime decodeFineTime(); @Override FineTime decodeNullableFineTime(); @Override Identifier decodeIdentifier(); @Override Identifier decodeNullableIdentifier(); @Override Time decodeTime(); @Override Time decodeNullableTime(); @Override URI decodeURI(); @Override URI decodeNullableURI(); @Override Element decodeElement(final Element element); @Override Element decodeNullableElement(final Element element); @Override Attribute decodeAttribute(); @Override Attribute decodeNullableAttribute(); @Override MALListDecoder createListDecoder(final List list); }### Answer:
@Test public void testDecodeNullableLong1() throws Exception { newBuffer(new byte[]{0}); assertEquals(null, decoder.decodeNullableLong()); }
@Test public void testDecodeNullableLong2() throws Exception { newBuffer(new byte[]{ 0, 1, (byte) 0b11111110, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0b00000001, 1, (byte) 0b00000001, 1, (byte) 0b10111110, (byte) 0b11001110, (byte) 0b10010111, (byte) 0b10111111, (byte) 0b11100100, (byte) 0b00000111 }); assertEquals(null, decoder.decodeNullableLong()); assertEquals(Long.valueOf(9223372036854775807L), decoder.decodeNullableLong()); assertEquals(Long.valueOf(-1), decoder.decodeNullableLong()); assertEquals(Long.valueOf(133747110815L), decoder.decodeNullableLong()); }
@Test public void testDecodeNullableLong2b() throws Exception { newBuffer(new byte[]{ 0, 1, (byte) 0x7F, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, 1, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, 1, 0, 0, 0, (byte) 0x1F, (byte) 0x23, (byte) 0xF2, (byte) 0xF3, (byte) 0x9F }); setVarintSupportedProperty(false); assertEquals(null, decoder.decodeNullableLong()); assertEquals(Long.valueOf(9223372036854775807L), decoder.decodeNullableLong()); assertEquals(Long.valueOf(-1), decoder.decodeNullableLong()); assertEquals(Long.valueOf(133747110815L), decoder.decodeNullableLong()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.