src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
Schooljaar implements IBeginEinddatumEntiteit, Comparable<Schooljaar>, Serializable { public static Schooljaar parse(String value) { Pattern[] patterns = new Pattern[] {officieel, kort}; for (Pattern pattern : patterns) { Matcher matcher = pattern.matcher(value); if (!matcher.matches()) { continue; } String startJaar = matcher.group(1); if (startJaar == null) return null; TimeUtil kalender = TimeUtil.getInstance(); Date date = kalender.parseDateString(String.format("01-08-%s", startJaar)); return Schooljaar.valueOf(date); } return null; } private Schooljaar(int jaar); private Schooljaar(Date datum); int getStartJaar(); int getEindJaar(); @Override Date getBegindatum(); @Override Date getEinddatum(); @Override boolean isActief(Date peildatum); @Override void setBegindatum(Date begindatum); @Override void setEinddatum(Date einddatum); @Exportable String getOmschrijving(); @Exportable String getAfkorting(); @Override String toString(); Schooljaar getVolgendSchooljaar(); Schooljaar getVorigSchooljaar(); boolean isAfgelopen(); static Schooljaar huidigSchooljaar(); static Schooljaar schooljaarOpPeildatum(); static Schooljaar valueOf(Date datum); static Schooljaar valueOf(int startJaar); static Schooljaar parse(String value); @Override int compareTo(Schooljaar other); @Override int hashCode(); @Override boolean equals(Object obj); @Override Date getEinddatumNotNull(); @Override boolean isActief(); Date getEenOktober(); Date getEenJanuari(); Date getEenFebruari(); List<Date> getBoPeildata(); List<Date> getBoPeildataOpOfNa(Date datum); boolean voor(Schooljaar anderSchooljaar); boolean gelijkOfVoor(Schooljaar anderSchooljaar); boolean na(Schooljaar anderSchooljaar); boolean gelijkOfNa(Schooljaar anderSchooljaar); static List<Date> allePeildataTussen(Date begindatum, Date einddatum); static List<Date> allePeildataVoorSchooljarenTussen(Date begindatum, Date einddatum); static List<Date> allePeildataTotEnMetHuidigSchooljaarVanaf(Date datum); }
@Test public void parseAAAA_2009fails() { assertThat(Schooljaar.parse("AAAA/2009"), is(nullValue())); } @Test public void parse2008_AAAAfails() { assertThat(Schooljaar.parse("2008/AAAA"), is(nullValue())); } @Test public void parse2008A2009fails() { assertThat(Schooljaar.parse("2008A2009"), is(nullValue())); }
NaturalOrderComparator implements Comparator<Object>, Serializable { @Override public int compare(Object o1, Object o2) { String a = o1.toString(); String b = o2.toString(); int ia = 0, ib = 0; int nza = 0, nzb = 0; char ca, cb; int result; while (true) { nza = nzb = 0; ca = charAt(a, ia); cb = charAt(b, ib); while (Character.isSpaceChar(ca) || ca == '0') { if (ca == '0') { nza++; } else { nza = 0; } ca = charAt(a, ++ia); } while (Character.isSpaceChar(cb) || cb == '0') { if (cb == '0') { nzb++; } else { nzb = 0; } cb = charAt(b, ++ib); } if (Character.isDigit(ca) && Character.isDigit(cb)) { if ((result = compareRight(a.substring(ia), b.substring(ib))) != 0) { return result; } } if (ca == 0 && cb == 0) { return nza - nzb; } if (ca < cb) { return -1; } else if (ca > cb) { return +1; } else if (ca == cb && nza != nzb) { return nza - nzb; } ++ia; ++ib; } } @Override int compare(Object o1, Object o2); }
@Test public void testCompare() { String[] strings = new String[] {"1-2", "1-02", "1-20", "10-20", "fred", "jane", "pic01", "pic2", "pic02", "pic02a", "pic3", "pic4", "pic 4 else", "pic 5", "pic 5 something", "pic05", "pic 6", "pic 7", "pic100", "pic100a", "pic120", "pic121", "pic02000", "tom", "x2-g8", "x2-y7", "x2-y08", "x8-y8"}; List<String> orig = Arrays.asList(strings.clone()); List<String> scrambled = Arrays.asList(strings.clone()); Collections.shuffle(scrambled); Collections.sort(scrambled, new NaturalOrderComparator()); Assert.assertEquals(StringUtil.join(orig, ", "), StringUtil.join(scrambled, ", ")); }
ExceptionUtil { public static void printStackTrace(PrintWriter pw, Throwable t) { printStackTrace(pw, t, new StackTraceElement[] {}); } static String getDescription(Exception exception); static boolean isCausedBy(Throwable exception, Class< ? extends Throwable> cause); static void printStackTrace(PrintWriter pw, Throwable t); static T getCause(Throwable exception, Class<T> exceptionType); static Throwable getRootCause(Throwable exception); }
@Test public void enkelvoudigeExceptie() { NullPointerException e = returnsNullPointerException(); ExceptionUtil.printStackTrace(pw, e); String expected = "java.lang.NullPointerException" + newLine() + "\tat nl.topicus.cobra.util.ExceptionUtilTest.returnsNullPointerException(ExceptionUtilTest.java:25)"; Assert.assertEquals(expected, sw.toString().substring(0, expected.length())); } @Test public void returnedWrappedException() { ExceptionUtil.printStackTrace(pw, wrapsAndReturnsException()); String expected = "java.lang.RuntimeException: ROOT Exception" + newLine() + "\tat nl.topicus.cobra.util.ExceptionUtilTest.returnsRuntimeException(ExceptionUtilTest.java:30)\n" + "Wrapped by java.lang.RuntimeException: WRAPPING EXCEPTION" + newLine() + "\tat nl.topicus.cobra.util.ExceptionUtilTest.wrapsAndReturnsException(ExceptionUtilTest.java:35)\n" + "\tat nl.topicus.cobra.util.ExceptionUtilTest.returnedWrappedException(ExceptionUtilTest.java:75)"; Assert.assertEquals(expected, sw.toString().substring(0, expected.length())); } @Test public void caughtAndWrappedException() { try { wrapsAndThrowsException(); } catch (RuntimeException e) { ExceptionUtil.printStackTrace(pw, e); } String expected = "java.lang.RuntimeException: ROOT Exception" + newLine() + "\tat nl.topicus.cobra.util.ExceptionUtilTest.throwsRuntimeException(ExceptionUtilTest.java:40)\n" + "\tat nl.topicus.cobra.util.ExceptionUtilTest.wrapsAndThrowsException(ExceptionUtilTest.java:47)\n" + "Wrapped by java.lang.RuntimeException: WRAPPING EXCEPTION" + newLine() + "\tat nl.topicus.cobra.util.ExceptionUtilTest.wrapsAndThrowsException(ExceptionUtilTest.java:51)\n" + "\tat nl.topicus.cobra.util.ExceptionUtilTest.caughtAndWrappedException(ExceptionUtilTest.java:93)\n"; Assert.assertEquals(expected, sw.toString().substring(0, expected.length())); }
DecimalUtil { public static final boolean nonZero(BigDecimal decimal) { return decimal != null && decimal.compareTo(BigDecimal.ZERO) != 0; } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }
@Test public void testNonZero() { Assert.assertFalse(DecimalUtil.nonZero(null)); Assert.assertFalse(DecimalUtil.nonZero(BigDecimal.ZERO)); Assert.assertTrue(DecimalUtil.nonZero(DecimalUtil.THREE)); }
DecimalUtil { public static final boolean isZero(BigDecimal decimal) { return decimal.compareTo(BigDecimal.ZERO) == 0; } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }
@Test public void testIsZero() { Assert.assertTrue(DecimalUtil.isZero(BigDecimal.ZERO)); Assert.assertFalse(DecimalUtil.isZero(DecimalUtil.THREE)); }
DecimalUtil { public static final boolean greaterThan(BigDecimal is, BigDecimal than) { return is.compareTo(than) > 0; } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }
@Test public void testGreaterThanBigDecimalBigDecimal() { Assert.assertTrue(DecimalUtil.greaterThan(DecimalUtil.SEVEN, DecimalUtil.THREE)); Assert.assertFalse(DecimalUtil.greaterThan(DecimalUtil.TWO, DecimalUtil.EIGHT)); Assert.assertFalse(DecimalUtil.greaterThan(DecimalUtil.SEVEN, DecimalUtil.SEVEN)); } @Test public void testGreaterThanBigDecimalInt() { Assert.assertTrue(DecimalUtil.greaterThan(DecimalUtil.SEVEN, 3)); Assert.assertFalse(DecimalUtil.greaterThan(DecimalUtil.TWO, 8)); Assert.assertFalse(DecimalUtil.greaterThan(DecimalUtil.SEVEN, 7)); }
DecimalUtil { public static final boolean greaterThanOrEqual(BigDecimal is, int than) { return is.compareTo(BigDecimal.valueOf(than)) >= 0; } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }
@Test public void testGreaterThanOrEqual() { Assert.assertTrue(DecimalUtil.greaterThanOrEqual(DecimalUtil.SEVEN, 3)); Assert.assertFalse(DecimalUtil.greaterThanOrEqual(DecimalUtil.TWO, 8)); Assert.assertTrue(DecimalUtil.greaterThanOrEqual(DecimalUtil.SEVEN, 7)); }
DecimalUtil { public static final int compare(BigDecimal one, BigDecimal other) { if (one == null && other == null) return 0; if (one == null) return -1; else if (other == null) return 1; return one.compareTo(other); } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }
@Test public void testCompare() { Assert.assertEquals(0, DecimalUtil.compare(null, null)); Assert.assertEquals(-1, DecimalUtil.compare(null, DecimalUtil.SEVEN)); Assert.assertEquals(1, DecimalUtil.compare(DecimalUtil.SEVEN, null)); Assert.assertEquals(0, DecimalUtil.compare(DecimalUtil.SEVEN, DecimalUtil.SEVEN)); Assert.assertEquals(-1, DecimalUtil.compare(DecimalUtil.THREE, DecimalUtil.SEVEN)); Assert.assertEquals(1, DecimalUtil.compare(DecimalUtil.FIVE, DecimalUtil.FOUR)); }
DecimalUtil { public static final BigDecimal max(BigDecimal one, BigDecimal other) { return (one.compareTo(other) > 0 ? one : other); } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }
@Test public void testMax() { Assert.assertEquals(DecimalUtil.FIVE, DecimalUtil.max(DecimalUtil.FIVE, DecimalUtil.FOUR)); Assert.assertEquals(DecimalUtil.FIVE, DecimalUtil.max(DecimalUtil.ONE, DecimalUtil.FIVE)); }
DecimalUtil { public static final BigDecimal min(BigDecimal one, BigDecimal other) { return (one.compareTo(other) < 0 ? one : other); } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }
@Test public void testMin() { Assert.assertEquals(DecimalUtil.FOUR, DecimalUtil.min(DecimalUtil.FIVE, DecimalUtil.FOUR)); Assert.assertEquals(DecimalUtil.FOUR, DecimalUtil.min(DecimalUtil.FOUR, DecimalUtil.NINE)); }
DecimalUtil { public static final boolean greaterThanZero(BigDecimal is) { return is != null && is.compareTo(BigDecimal.ZERO) > 0; } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }
@Test public void testGreaterThanZero() { Assert.assertFalse(DecimalUtil.greaterThanZero(null)); Assert.assertFalse(DecimalUtil.greaterThanZero(BigDecimal.ZERO)); Assert.assertTrue(DecimalUtil.greaterThanZero(DecimalUtil.SEVEN)); }
DecimalUtil { public static boolean zeroOrMore(BigDecimal decimal) { return decimal != null && decimal.compareTo(BigDecimal.ZERO) >= 0; } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }
@Test public void testZeroOrMore() { Assert.assertFalse(DecimalUtil.zeroOrMore(null)); Assert.assertFalse(DecimalUtil.zeroOrMore(BigDecimal.valueOf(-0.01))); Assert.assertTrue(DecimalUtil.zeroOrMore(BigDecimal.ZERO)); Assert.assertTrue(DecimalUtil.zeroOrMore(BigDecimal.valueOf(0.01))); Assert.assertTrue(DecimalUtil.zeroOrMore(DecimalUtil.SEVEN)); }
DecimalUtil { public static final boolean lessThanZero(BigDecimal decimal) { if (decimal == null) return false; return decimal.compareTo(BigDecimal.ZERO) < 0; } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }
@Test public void testLessThanZero() { Assert.assertFalse(DecimalUtil.lessThanZero(null)); Assert.assertTrue(DecimalUtil.lessThanZero(BigDecimal.valueOf(-0.01))); Assert.assertFalse(DecimalUtil.lessThanZero(BigDecimal.ZERO)); Assert.assertFalse(DecimalUtil.lessThanZero(BigDecimal.valueOf(0.01))); Assert.assertTrue(DecimalUtil.lessThanZero(BigDecimal.valueOf(-7))); }
DecimalUtil { public static final boolean lessOrEqualtoZero(BigDecimal decimal) { if (decimal == null) return false; return decimal.compareTo(BigDecimal.ZERO) <= 0; } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }
@Test public void testLessOrEqualtoZero() { Assert.assertFalse(DecimalUtil.lessOrEqualtoZero(null)); Assert.assertTrue(DecimalUtil.lessOrEqualtoZero(BigDecimal.valueOf(-0.01))); Assert.assertTrue(DecimalUtil.lessOrEqualtoZero(BigDecimal.ZERO)); Assert.assertFalse(DecimalUtil.lessOrEqualtoZero(BigDecimal.valueOf(0.01))); Assert.assertTrue(DecimalUtil.lessOrEqualtoZero(BigDecimal.valueOf(-7))); }
DecimalUtil { public static final boolean lessOrEqual(BigDecimal decimal, int other) { return decimal.compareTo(BigDecimal.valueOf(other)) <= 0; } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }
@Test public void testLessOrEqual() { Assert.assertTrue(DecimalUtil.lessOrEqual(DecimalUtil.FIVE, 11)); Assert.assertFalse(DecimalUtil.lessOrEqual(DecimalUtil.FIVE, 3)); }
DecimalUtil { public static final BigDecimal divide(BigDecimal decimal, int by) { return decimal.divide(BigDecimal.valueOf(by)); } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }
@Test public void testDivideBigDecimalInt() { Assert.assertEquals(BigDecimal.ZERO, DecimalUtil.divide(BigDecimal.ZERO, 3)); Assert.assertEquals(DecimalUtil.TWO, DecimalUtil.divide(DecimalUtil.EIGHT, 4)); } @Test public void testDivideBigDecimalMathContextInt() { MathContext mc = new MathContext(1, RoundingMode.HALF_UP); Assert.assertEquals(DecimalUtil.THREE, DecimalUtil.divide(DecimalUtil.FIVE, mc, 2)); } @Test public void testDivideBigDecimalMathContextBigDecimal() { MathContext mc = new MathContext(1, RoundingMode.HALF_UP); Assert.assertEquals(DecimalUtil.THREE, DecimalUtil.divide(DecimalUtil.FIVE, mc, DecimalUtil.TWO)); } @Test public void testDivideIntMathContextInt() { MathContext mc = new MathContext(1, RoundingMode.HALF_UP); Assert.assertEquals(DecimalUtil.THREE, DecimalUtil.divide(5, mc, 2)); }
DecimalUtil { public static final BigDecimal multiply(BigDecimal decimal, int by) { return decimal.multiply(BigDecimal.valueOf(by)); } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }
@Test public void testMultiply() { Assert.assertEquals(DecimalUtil.SIX, DecimalUtil.multiply(DecimalUtil.THREE, 2)); }
DecimalUtil { public static final BigDecimal valueOf(String string) { return new BigDecimal(localizeString(string)); } static final boolean nonZero(BigDecimal decimal); static final boolean isZero(BigDecimal decimal); static final boolean greaterThan(BigDecimal is, BigDecimal than); static final boolean greaterThan(BigDecimal is, int than); static final boolean greaterThanOrEqual(BigDecimal is, int than); static final int compare(BigDecimal one, BigDecimal other); static final BigDecimal max(BigDecimal one, BigDecimal other); static final BigDecimal min(BigDecimal one, BigDecimal other); static final boolean greaterThanZero(BigDecimal is); static boolean zeroOrMore(BigDecimal decimal); static final boolean lessThanZero(BigDecimal decimal); static final boolean lessOrEqualtoZero(BigDecimal decimal); static final boolean lessOrEqual(BigDecimal decimal, int other); static final BigDecimal divide(BigDecimal decimal, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, int by); static final BigDecimal divide(BigDecimal decimal, MathContext mc, BigDecimal by); static final BigDecimal divide(int decimal, int by); static final BigDecimal divide(int decimal, MathContext mc, int by); static final BigDecimal multiply(BigDecimal decimal, int by); static final BigDecimal multiplyRounded(BigDecimal decimal, int by); static final BigDecimal valueOf(String string); static final BigDecimal average(List<BigDecimal> bigDecimalList); static final BigDecimal ONE; static final BigDecimal TWO; static final BigDecimal THREE; static final BigDecimal FOUR; static final BigDecimal FIVE; static final BigDecimal SIX; static final BigDecimal SEVEN; static final BigDecimal EIGHT; static final BigDecimal NINE; static final BigDecimal TEN; static final BigDecimal ELEVEN; static final BigDecimal SIXTEEN; static final BigDecimal EIGHTEEN; static final BigDecimal TWENTY; static final BigDecimal THIRTYSIX; static final BigDecimal HUNDRED; static final BigDecimal FIVE_POINT_FIVE; static final MathContext RESULTAAT_MATH_CONTEXT; }
@Test public void testValueOf() { Assert.assertEquals(BigDecimal.ZERO, DecimalUtil.valueOf("0")); Assert.assertEquals(BigDecimal.valueOf(0.1), DecimalUtil.valueOf("0.1")); Assert.assertEquals(BigDecimal.valueOf(0.1), DecimalUtil.valueOf("0,1")); Assert.assertEquals(BigDecimal.valueOf(1000.1), DecimalUtil.valueOf("1.000,1")); Assert.assertEquals(BigDecimal.valueOf(1000.1), DecimalUtil.valueOf("1,000.1")); Assert.assertEquals(DecimalUtil.THREE, DecimalUtil.valueOf("3,")); Assert.assertEquals(BigDecimal.valueOf(0.2), DecimalUtil.valueOf(",2")); Assert.assertEquals(BigDecimal.valueOf(1000000000), DecimalUtil.valueOf("1.000.000.000")); } @Test(expected = IllegalArgumentException.class) public void testValueOfMeerderePuntenEnKommas() { Assert.assertEquals(BigDecimal.ZERO, DecimalUtil.valueOf("0,1,2.3.4")); } @Test(expected = IllegalArgumentException.class) public void testValueOfMeerdereKommas() { Assert.assertEquals(BigDecimal.ZERO, DecimalUtil.valueOf("0.3,4,5")); } @Test(expected = IllegalArgumentException.class) public void testValueOfMeerderePunten() { Assert.assertEquals(BigDecimal.ZERO, DecimalUtil.valueOf("0,3.4.5")); }
Asserts { public static void assertNotNull(final String parameter, final Object waarde) { if (log.isDebugEnabled()) { String waardeText = String.valueOf(waarde); waardeText = waardeText.substring(0, Math.min(waardeText.length(), 16)); log.debug("Controleer dat " + parameter + " niet null is, huidige waarde: '" + waardeText + "'"); } if (waarde == null) { IllegalArgumentException exception = new IllegalArgumentException("Parameter " + parameter + " is null"); throw exception; } } static void assertNotNull(final String parameter, final Object waarde); static void assertNull(final String parameter, final Object waarde); static void assertMaxLength(String parameter, String waarde, int length); static void assertGreaterThanZero(final String parameter, long waarde); static void assertGreaterThanZero(final String parameter, int waarde); static void assertNotEmpty(String parameter, Object waarde); static void assertNotEmpty(String parameter, Collection< ? > list); static void assertEmptyCollection(String parameter, Collection< ? > list); static void assertEquals(String parameter, Object actual, Object expected); static void assertMatchesRegExp(String parameter, String value, String regexp); static void fail(String message); static void assertTrue(String message, boolean conditie); static void assertFalse(String message, boolean conditie); }
@Test(expected = IllegalArgumentException.class) public void testAssertNotNullMetNull() { Asserts.assertNotNull("foo", null); } @Test public void testAssertNotNullMetNotNull() { Asserts.assertNotNull("foo", new Object()); }
Asserts { public static void assertNotEmpty(String parameter, Object waarde) { assertNotNull(parameter, waarde); if ("".equals(waarde.toString().trim())) { String bericht = "Parameter " + parameter + " is leeg"; throw new IllegalArgumentException(bericht); } } static void assertNotNull(final String parameter, final Object waarde); static void assertNull(final String parameter, final Object waarde); static void assertMaxLength(String parameter, String waarde, int length); static void assertGreaterThanZero(final String parameter, long waarde); static void assertGreaterThanZero(final String parameter, int waarde); static void assertNotEmpty(String parameter, Object waarde); static void assertNotEmpty(String parameter, Collection< ? > list); static void assertEmptyCollection(String parameter, Collection< ? > list); static void assertEquals(String parameter, Object actual, Object expected); static void assertMatchesRegExp(String parameter, String value, String regexp); static void fail(String message); static void assertTrue(String message, boolean conditie); static void assertFalse(String message, boolean conditie); }
@Test(expected = IllegalArgumentException.class) public void testAssertNotEmptyMetEmpty() { Asserts.assertNotEmpty("foo", ""); } @Test public void testAssertNotEmptyMetNotEmpty() { Asserts.assertNotEmpty("foo", "123"); }
Asserts { public static void assertMatchesRegExp(String parameter, String value, String regexp) { assertNotNull(parameter, value); assertNotNull("regexp", regexp); Pattern pattern = Pattern.compile(regexp); String trimmedValue = value.trim(); Matcher matcher = pattern.matcher(trimmedValue.subSequence(0, trimmedValue.length())); if (!matcher.matches()) { if (log.isDebugEnabled()) { log.debug("Matcher waarde: " + matcher.toString()); } throw new IllegalArgumentException("De waarde '" + value + "' van parameter " + parameter + " voldoet niet aan het formaat " + regexp); } } static void assertNotNull(final String parameter, final Object waarde); static void assertNull(final String parameter, final Object waarde); static void assertMaxLength(String parameter, String waarde, int length); static void assertGreaterThanZero(final String parameter, long waarde); static void assertGreaterThanZero(final String parameter, int waarde); static void assertNotEmpty(String parameter, Object waarde); static void assertNotEmpty(String parameter, Collection< ? > list); static void assertEmptyCollection(String parameter, Collection< ? > list); static void assertEquals(String parameter, Object actual, Object expected); static void assertMatchesRegExp(String parameter, String value, String regexp); static void fail(String message); static void assertTrue(String message, boolean conditie); static void assertFalse(String message, boolean conditie); }
@Test public void testAssertMatchesRegExp() { Asserts.assertMatchesRegExp("postcode", "1234 Aa", "[1-9][0-9]{3} ?[a-zA-Z]{2}"); Asserts.assertMatchesRegExp("postcode", "1234Aa", "[1-9][0-9]{3} ?[a-zA-Z]{2}"); Asserts.assertMatchesRegExp("postcode", " 1234 Aa ", "[1-9][0-9]{3} ?[a-zA-Z]{2}"); } @Test(expected = IllegalArgumentException.class) public void testAssertMatchesRegExpFail1() { Asserts.assertMatchesRegExp("foo", null, "[1-9][0-9]{3} ?[a-zA-Z]{2}"); } @Test(expected = IllegalArgumentException.class) public void testAssertMatchesRegExpFail2() { Asserts.assertMatchesRegExp("foo", "", "[1-9][0-9]{3} ?[a-zA-Z]{2}"); } @Test(expected = IllegalArgumentException.class) public void testAssertMatchesRegExpFail3() { Asserts.assertMatchesRegExp("foo", "abc", "[1-9][0-9]{3} ?[a-zA-Z]{2}"); }
Dutch implements ToWords { @SuppressWarnings("all") public String toWords(long num) { if (num == 0) return ZERO; boolean negative = (num < 0); if (negative) num = -num; String s = ""; for (int group = 0; num > 0; group++) { int remdr = (int) (num % divisor[group]); num = num / divisor[group]; if (group == 1&& 1 <= num && num <= 5) { if (remdr > 0) { remdr += num * 10; num = 0; } } String t; if (remdr == 0) continue; else if (remdr == 1) t = (group == 0 || group > 2) ? lowName[1] : ""; else if (remdr < 20) t = lowName[remdr]; else if (remdr < 100) { int units = remdr % 10; int tens = remdr / 10; t = tys[tens]; if (units > 0) { t = lowName[units] + AND + t; } } else t = toWords(remdr); boolean leftPad = group > 2; boolean rightPad = group != 1; s = t + (leftPad ? " " : "") + groupName[group] + (rightPad ? " " : "") + s; } s = s.trim(); if (negative) s = MINUS + " " + s; return s; } @SuppressWarnings("all") String toWords(long num); static final String EMBEDDED_COPYRIGHT; }
@Test public void test0() { Assert.assertEquals("nul", dutch.toWords(0)); } @Test public void testMin1() { Assert.assertEquals("min een", dutch.toWords(-1)); } @Test public void test1() { Assert.assertEquals("een", dutch.toWords(1)); } @Test public void testMin10() { Assert.assertEquals("min tien", dutch.toWords(-10)); } @Test public void test10() { Assert.assertEquals("tien", dutch.toWords(10)); } @Test public void test21() { Assert.assertEquals("eenentwintig", dutch.toWords(21)); } @Test public void testMin100() { Assert.assertEquals("min honderd", dutch.toWords(-100)); } @Test public void test100() { Assert.assertEquals("honderd", dutch.toWords(100)); } @Test public void test111() { Assert.assertEquals("honderdelf", dutch.toWords(111)); } @Test public void testPositive1113() { Assert.assertEquals("elfhonderddertien", dutch.toWords(1113)); } @Test public void testPositive1999() { Assert.assertEquals("negentienhonderdnegenennegentig", dutch.toWords(1999)); } @Test public void testPositive1miljoen() { Assert.assertEquals("een miljoen", dutch.toWords(1000000)); }
StringUtil { public static Integer getFirstNumberSequence(String tekst) { if (tekst == null) return Integer.valueOf(0); int start = Integer.MAX_VALUE; int end = Integer.MIN_VALUE; boolean inNumberSequence = false; for (int i = 0; i < tekst.length(); i++) { if (tekst.charAt(i) >= '0' && tekst.charAt(i) <= '9') { start = Math.min(i, start); end = Math.max(i, end); inNumberSequence = true; } else { if (inNumberSequence) { break; } } } if (start > tekst.length()) { return null; } return Integer.valueOf(tekst.substring(start, end + 1)); } private StringUtil(); static boolean checkMatchesRegExp(String parameter, String value, String regexp); @Deprecated() static String stripHighAscii(String tekst); static Integer getFirstNumberSequence(String tekst); static String getLastCharacter(String string); static boolean isNumeric(String string); static boolean isEmail(String string); static boolean isIpAdres(String string); static boolean isDecimal(String string); static String firstCharUppercase(String name); static String firstLetterUppercase(String name); static String onlyFirstCharUppercase(String name); static String containsSamengesteldeLetter(String value); static String firstCharUppercaseOfEachWord(String sentence); static String firstCharUppercaseOnlyIfOneWordAndStartWithLowercase(String sentence); static String puntSeperated(String sentence); static boolean isEmpty(String string); static boolean areAllEmpty(String... strings); static boolean areAllNotEmpty(String... strings); static boolean isEmpty(Object object); static boolean isNotEmpty(String string); static boolean isNotEmpty(Object string); static String truncate(String source, int maxLength, String cutoffReplacement); static String escapeString(String value); static String escapeForJavascriptString(String value); static String valueOrEmptyIfNull(Object text); static String valueOrAlternativeIfNull(Object text, String alternative); static String valueOrAlternativeIfEmpty(Object text, String alternative); static String repeatString(String src, int repeat); static String maakTekenSeparatedString(Collection< ? extends Object> list, String teken); static String maakCommaSeparatedString(Collection< ? extends Object> list); static String maakCommaSeparatedString(Collection< ? extends Object> list, String defaultByEmptyList); static String toString(Collection<T> list, String token, String defaultString); static String toString(Collection<T> list, String defaultString, StringConverter< ? super T> converter); static String maakPuntSeparatedString(Collection< ? extends Object> list); static String verwijderCijfers(String input); static String voegVoorloopnullenToe(String str, int length); static String voegVoorloopnullenToe(int i, int length); static String kapAfOfVoegSpatiesToe(String str, int length); static String kapAfOfVoegNullenToe(Integer i, int length); static String kapAfOfVoegNullenToe(String str, int length); static String verwijderVoorloopnullen(String str); static int countOccurances(String org, char character); static String join(Collection<String> strings, String separator); static boolean startsWithIgnoreCase(String string1, String string2); @Deprecated static String getClassName(Class< ? > class1); static String getFirstWord(String input); static boolean containsOracleWildcard(String string); static String wildcardToRegex(String wildcard); static String convertCamelCase(String camelCase); static String convertCamelCaseFirstCharUpperCase(String camelCase); static String stripHtmlTags(String html); static boolean equalOrBothNull(String str1, String str2); static boolean equalOrBothEmpty(String a, String b); static String genereerVoorletters(String voornamen); static String hexEncode(byte[] aInput); static boolean containsStringStartingWith(List<String> list, String prefix); static String nullOrStringValue(Object value); static String emptyOrStringValue(Object value); static String firstCharLowercase(String name); static String spaties(int aantal); static String createValidFileName(String filename); static final String[] SAMENGESTELDE_LETTERS; }
@Test public void getNumberPart1() { String test = "t.o. 12 a"; assertEquals(new Integer(12), StringUtil.getFirstNumberSequence(test)); } @Test public void getNumberPart2() { String test = ""; assertNull(StringUtil.getFirstNumberSequence(test)); } @Test public void getNumberPart3() { String test = "abcdefg"; assertNull(StringUtil.getFirstNumberSequence(test)); } @Test public void getNumberPart4() { String test = "12345678"; assertEquals(new Integer(12345678), StringUtil.getFirstNumberSequence(test)); } @Test public void getNumberPart5() { String test = "1234-a"; assertEquals(new Integer(1234), StringUtil.getFirstNumberSequence(test)); } @Test public void getNumberPart6() { String test = "123a"; assertEquals(new Integer(123), StringUtil.getFirstNumberSequence(test)); } @Test public void getNumberPart7() { String test = "a123"; assertEquals(new Integer(123), StringUtil.getFirstNumberSequence(test)); } @Test public void getNumberPart8() { String test = "a-123"; assertEquals(new Integer(123), StringUtil.getFirstNumberSequence(test)); }
StringUtil { public static String truncate(String source, int maxLength, String cutoffReplacement) { if (source == null || source.length() <= maxLength) return source; int cutoffLength = maxLength; if (cutoffReplacement != null) cutoffLength -= cutoffReplacement.length(); if (cutoffLength <= 0) { if (cutoffReplacement != null) return cutoffReplacement; return source; } if (cutoffReplacement != null) return source.substring(0, cutoffLength) + cutoffReplacement; return source.substring(0, cutoffLength); } private StringUtil(); static boolean checkMatchesRegExp(String parameter, String value, String regexp); @Deprecated() static String stripHighAscii(String tekst); static Integer getFirstNumberSequence(String tekst); static String getLastCharacter(String string); static boolean isNumeric(String string); static boolean isEmail(String string); static boolean isIpAdres(String string); static boolean isDecimal(String string); static String firstCharUppercase(String name); static String firstLetterUppercase(String name); static String onlyFirstCharUppercase(String name); static String containsSamengesteldeLetter(String value); static String firstCharUppercaseOfEachWord(String sentence); static String firstCharUppercaseOnlyIfOneWordAndStartWithLowercase(String sentence); static String puntSeperated(String sentence); static boolean isEmpty(String string); static boolean areAllEmpty(String... strings); static boolean areAllNotEmpty(String... strings); static boolean isEmpty(Object object); static boolean isNotEmpty(String string); static boolean isNotEmpty(Object string); static String truncate(String source, int maxLength, String cutoffReplacement); static String escapeString(String value); static String escapeForJavascriptString(String value); static String valueOrEmptyIfNull(Object text); static String valueOrAlternativeIfNull(Object text, String alternative); static String valueOrAlternativeIfEmpty(Object text, String alternative); static String repeatString(String src, int repeat); static String maakTekenSeparatedString(Collection< ? extends Object> list, String teken); static String maakCommaSeparatedString(Collection< ? extends Object> list); static String maakCommaSeparatedString(Collection< ? extends Object> list, String defaultByEmptyList); static String toString(Collection<T> list, String token, String defaultString); static String toString(Collection<T> list, String defaultString, StringConverter< ? super T> converter); static String maakPuntSeparatedString(Collection< ? extends Object> list); static String verwijderCijfers(String input); static String voegVoorloopnullenToe(String str, int length); static String voegVoorloopnullenToe(int i, int length); static String kapAfOfVoegSpatiesToe(String str, int length); static String kapAfOfVoegNullenToe(Integer i, int length); static String kapAfOfVoegNullenToe(String str, int length); static String verwijderVoorloopnullen(String str); static int countOccurances(String org, char character); static String join(Collection<String> strings, String separator); static boolean startsWithIgnoreCase(String string1, String string2); @Deprecated static String getClassName(Class< ? > class1); static String getFirstWord(String input); static boolean containsOracleWildcard(String string); static String wildcardToRegex(String wildcard); static String convertCamelCase(String camelCase); static String convertCamelCaseFirstCharUpperCase(String camelCase); static String stripHtmlTags(String html); static boolean equalOrBothNull(String str1, String str2); static boolean equalOrBothEmpty(String a, String b); static String genereerVoorletters(String voornamen); static String hexEncode(byte[] aInput); static boolean containsStringStartingWith(List<String> list, String prefix); static String nullOrStringValue(Object value); static String emptyOrStringValue(Object value); static String firstCharLowercase(String name); static String spaties(int aantal); static String createValidFileName(String filename); static final String[] SAMENGESTELDE_LETTERS; }
@Test public void truncate1() { String org = "test"; String replace = ".."; int max = 500; assertEquals(org, StringUtil.truncate(org, max, replace)); } @Test public void truncate2() { String org = "test"; int max = 3; assertEquals("tes", StringUtil.truncate(org, max, null)); } @Test public void truncate3() { String org = "test"; String replace = ".."; int max = 3; assertEquals("t..", StringUtil.truncate(org, max, replace)); } @Test public void truncate4() { String replace = ".."; int max = 500; assertNull(StringUtil.truncate(null, max, replace)); } @Test public void truncate5() { String org = "test"; String replace = ".."; int max = 0; assertEquals(replace, StringUtil.truncate(org, max, replace)); } @Test public void truncate6() { String org = "test"; int max = 0; assertEquals(org, StringUtil.truncate(org, max, null)); } @Test public void truncate7() { String org = "test"; int max = -10; assertEquals(org, StringUtil.truncate(org, max, null)); }
StringUtil { public static String containsSamengesteldeLetter(String value) { if (isEmpty(value)) return " "; String naam = value.toUpperCase(); for (String letter : SAMENGESTELDE_LETTERS) { if (naam.startsWith(letter)) { return letter; } } return String.valueOf(value.charAt(0)).toUpperCase(); } private StringUtil(); static boolean checkMatchesRegExp(String parameter, String value, String regexp); @Deprecated() static String stripHighAscii(String tekst); static Integer getFirstNumberSequence(String tekst); static String getLastCharacter(String string); static boolean isNumeric(String string); static boolean isEmail(String string); static boolean isIpAdres(String string); static boolean isDecimal(String string); static String firstCharUppercase(String name); static String firstLetterUppercase(String name); static String onlyFirstCharUppercase(String name); static String containsSamengesteldeLetter(String value); static String firstCharUppercaseOfEachWord(String sentence); static String firstCharUppercaseOnlyIfOneWordAndStartWithLowercase(String sentence); static String puntSeperated(String sentence); static boolean isEmpty(String string); static boolean areAllEmpty(String... strings); static boolean areAllNotEmpty(String... strings); static boolean isEmpty(Object object); static boolean isNotEmpty(String string); static boolean isNotEmpty(Object string); static String truncate(String source, int maxLength, String cutoffReplacement); static String escapeString(String value); static String escapeForJavascriptString(String value); static String valueOrEmptyIfNull(Object text); static String valueOrAlternativeIfNull(Object text, String alternative); static String valueOrAlternativeIfEmpty(Object text, String alternative); static String repeatString(String src, int repeat); static String maakTekenSeparatedString(Collection< ? extends Object> list, String teken); static String maakCommaSeparatedString(Collection< ? extends Object> list); static String maakCommaSeparatedString(Collection< ? extends Object> list, String defaultByEmptyList); static String toString(Collection<T> list, String token, String defaultString); static String toString(Collection<T> list, String defaultString, StringConverter< ? super T> converter); static String maakPuntSeparatedString(Collection< ? extends Object> list); static String verwijderCijfers(String input); static String voegVoorloopnullenToe(String str, int length); static String voegVoorloopnullenToe(int i, int length); static String kapAfOfVoegSpatiesToe(String str, int length); static String kapAfOfVoegNullenToe(Integer i, int length); static String kapAfOfVoegNullenToe(String str, int length); static String verwijderVoorloopnullen(String str); static int countOccurances(String org, char character); static String join(Collection<String> strings, String separator); static boolean startsWithIgnoreCase(String string1, String string2); @Deprecated static String getClassName(Class< ? > class1); static String getFirstWord(String input); static boolean containsOracleWildcard(String string); static String wildcardToRegex(String wildcard); static String convertCamelCase(String camelCase); static String convertCamelCaseFirstCharUpperCase(String camelCase); static String stripHtmlTags(String html); static boolean equalOrBothNull(String str1, String str2); static boolean equalOrBothEmpty(String a, String b); static String genereerVoorletters(String voornamen); static String hexEncode(byte[] aInput); static boolean containsStringStartingWith(List<String> list, String prefix); static String nullOrStringValue(Object value); static String emptyOrStringValue(Object value); static String firstCharLowercase(String name); static String spaties(int aantal); static String createValidFileName(String filename); static final String[] SAMENGESTELDE_LETTERS; }
@Test public void samenGesteldeLetter() { String naam = "IJsbrand"; String naam1 = "Pietje"; assertEquals("IJ", StringUtil.containsSamengesteldeLetter(naam)); assertEquals("P", StringUtil.containsSamengesteldeLetter(naam1)); }
StringUtil { public static String firstLetterUppercase(String name) { if (StringUtil.isEmpty(name)) return " "; Integer firstLetterPos = null; for (int i = 0; i < name.length() && firstLetterPos == null; i++) { if (Character.isLetter(name.charAt(i))) firstLetterPos = i; } if (firstLetterPos != null) return new StringBuffer(name.length()).append(name.substring(0, firstLetterPos)) .append(firstCharUppercase(name.substring(firstLetterPos))).toString(); else return name; } private StringUtil(); static boolean checkMatchesRegExp(String parameter, String value, String regexp); @Deprecated() static String stripHighAscii(String tekst); static Integer getFirstNumberSequence(String tekst); static String getLastCharacter(String string); static boolean isNumeric(String string); static boolean isEmail(String string); static boolean isIpAdres(String string); static boolean isDecimal(String string); static String firstCharUppercase(String name); static String firstLetterUppercase(String name); static String onlyFirstCharUppercase(String name); static String containsSamengesteldeLetter(String value); static String firstCharUppercaseOfEachWord(String sentence); static String firstCharUppercaseOnlyIfOneWordAndStartWithLowercase(String sentence); static String puntSeperated(String sentence); static boolean isEmpty(String string); static boolean areAllEmpty(String... strings); static boolean areAllNotEmpty(String... strings); static boolean isEmpty(Object object); static boolean isNotEmpty(String string); static boolean isNotEmpty(Object string); static String truncate(String source, int maxLength, String cutoffReplacement); static String escapeString(String value); static String escapeForJavascriptString(String value); static String valueOrEmptyIfNull(Object text); static String valueOrAlternativeIfNull(Object text, String alternative); static String valueOrAlternativeIfEmpty(Object text, String alternative); static String repeatString(String src, int repeat); static String maakTekenSeparatedString(Collection< ? extends Object> list, String teken); static String maakCommaSeparatedString(Collection< ? extends Object> list); static String maakCommaSeparatedString(Collection< ? extends Object> list, String defaultByEmptyList); static String toString(Collection<T> list, String token, String defaultString); static String toString(Collection<T> list, String defaultString, StringConverter< ? super T> converter); static String maakPuntSeparatedString(Collection< ? extends Object> list); static String verwijderCijfers(String input); static String voegVoorloopnullenToe(String str, int length); static String voegVoorloopnullenToe(int i, int length); static String kapAfOfVoegSpatiesToe(String str, int length); static String kapAfOfVoegNullenToe(Integer i, int length); static String kapAfOfVoegNullenToe(String str, int length); static String verwijderVoorloopnullen(String str); static int countOccurances(String org, char character); static String join(Collection<String> strings, String separator); static boolean startsWithIgnoreCase(String string1, String string2); @Deprecated static String getClassName(Class< ? > class1); static String getFirstWord(String input); static boolean containsOracleWildcard(String string); static String wildcardToRegex(String wildcard); static String convertCamelCase(String camelCase); static String convertCamelCaseFirstCharUpperCase(String camelCase); static String stripHtmlTags(String html); static boolean equalOrBothNull(String str1, String str2); static boolean equalOrBothEmpty(String a, String b); static String genereerVoorletters(String voornamen); static String hexEncode(byte[] aInput); static boolean containsStringStartingWith(List<String> list, String prefix); static String nullOrStringValue(Object value); static String emptyOrStringValue(Object value); static String firstCharLowercase(String name); static String spaties(int aantal); static String createValidFileName(String filename); static final String[] SAMENGESTELDE_LETTERS; }
@Test public void voorvoegselsEersteLetterHoofdletter() { assertEquals("'T", StringUtil.firstLetterUppercase("'t")); assertEquals("T", StringUtil.firstLetterUppercase("t")); assertEquals("Ten", StringUtil.firstLetterUppercase("ten")); assertEquals("10 Links", StringUtil.firstLetterUppercase("10 links")); assertEquals("******", StringUtil.firstLetterUppercase("******")); }
SpringBootExample implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(SpringBootExample.class, args); } static void main(String[] args); @Override void run(String... args); }
@Test public void shouldExecuteMainWithoutExceptions() { SpringBootExample.main(new String[0]); }
WritableMapConfigurationSource extends MapConfigurationSource implements WritableConfigurationSource { @Override public OptionalValue<String> removeValue(String key, Map<String, String> attributes) { requireNonNull(key, "key cannot be null"); return source.containsKey(key) ? present(source.remove(key)) : absent(); } WritableMapConfigurationSource(Map<String, String> source); @Override void setValue(String key, String value, Map<String, String> attributes); @Override OptionalValue<String> removeValue(String key, Map<String, String> attributes); }
@Test public void shouldRemoveValue() { Map<String, String> map = new HashMap<>(); map.put("key", "value"); WritableConfigurationSource mapConfigurationSource = new WritableMapConfigurationSource(map); mapConfigurationSource.removeValue("key", null); assertThat(mapConfigurationSource.getValue("key", null).isPresent()).isFalse(); }
PropertiesConfigurationSource implements IterableConfigurationSource { @Override public Iterable<ConfigurationEntry> getAllConfigurationEntries() { Map<String, String> map = source.entrySet().stream() .filter(e -> e.getValue() instanceof String) .collect(toMap(Object::toString, e -> (String) e.getValue())); return new MapIterable(map); } PropertiesConfigurationSource(Properties source); PropertiesConfigurationSource(String propertyFile); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override Iterable<ConfigurationEntry> getAllConfigurationEntries(); }
@Test public void shouldLoadPropertiesFromFile() { PropertiesConfigurationSource source = new PropertiesConfigurationSource(file.getAbsolutePath()); assertThat(source.getAllConfigurationEntries().iterator()).isEmpty(); }
PatternConverter implements TypeConverter<Pattern> { @Override public Pattern fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); try { return (value == null) ? null : Pattern.compile(value); } catch (PatternSyntaxException e) { throw new IllegalArgumentException("Unable to convert to a Pattern: " + value, e); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Pattern fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Pattern value, Map<String, String> attributes); }
@Test public void shouldConvertFromString() { Pattern pattern = Pattern.compile(".*"); Pattern value = converter.fromString(Pattern.class, ".*", null); assertThat(value.pattern()).isEqualTo(pattern.pattern()); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongValue() { String value = "{"; assertThatThrownBy(() -> converter.fromString(Pattern.class, value, null)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unable to convert to a Pattern:"); }
PatternConverter implements TypeConverter<Pattern> { @Override public String toString(Type type, Pattern value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return Objects.toString(value, null); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Pattern fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Pattern value, Map<String, String> attributes); }
@Test public void shouldConvertToString() { Pattern pattern = Pattern.compile("123.*"); String asString = converter.toString(Pattern.class, pattern, null); assertThat(asString).isEqualTo(pattern.toString()); }
PatternConverter implements TypeConverter<Pattern> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Pattern.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Pattern fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Pattern value, Map<String, String> attributes); }
@Test public void shouldAcceptType() { Type type = Pattern.class; boolean isApplicable = converter.isApplicable(type, null); assertThat(isApplicable).isTrue(); } @Test public void shouldNotAcceptUnknownType() { boolean isApplicable = converter.isApplicable(mock(Type.class), null); assertThat(isApplicable).isFalse(); }
ObjectBuilder { ObjectBuilder beginList() { return beginList(new ArrayList<>()); } }
@Test public void shouldFailInCaseEndingObjectWhenArrayWasBegun() { assertThatThrowExceptionOfType( new ObjectBuilder().beginList()::endMap, IllegalStateException.class); }
ObjectBuilder { ObjectBuilder beginMap() { return beginMap(new LinkedHashMap<>()); } }
@Test public void shouldFailInCaseEndingArrayWhenObjectWasBegun() { assertThatThrowExceptionOfType( new ObjectBuilder().beginMap()::endList, IllegalStateException.class); }
TypeConverterUtils { static int notEscapedIndexOf(CharSequence value, int startPos, char character) { Objects.requireNonNull(value, "value must not be null"); char prev = 0xffff; for (int i = max(startPos, 0), len = value.length(); i < len; i++) { char current = value.charAt(i); if (current == character) { if (prev == ESCAPE_CHAR) { int m = 1; int l = i - 2; while (l >= 0 && value.charAt(l) == ESCAPE_CHAR) { l--; m++; } if (m % 2 == 0) { return i; } } else { return i; } } prev = current; } return NOT_FOUND; } private TypeConverterUtils(); }
@Test public void shouldProperlyReturnNotEscapedIndexOf() { assertThat(TypeConverterUtils.notEscapedIndexOf("abcb", 0, 'b')).isEqualTo(1); assertThat(TypeConverterUtils.notEscapedIndexOf("a\\bcb", 0, 'b')).isEqualTo(4); assertThat(TypeConverterUtils.notEscapedIndexOf("a\\b\\\\bcb", 0, 'b')).isEqualTo(5); } @Test public void shouldProperlyReturnNotEscapedIndexOfMultiArgs() { assertThat(TypeConverterUtils.notEscapedIndexOf("abcb", 0, 'b', 'a')).isEqualTo(0); assertThat(TypeConverterUtils.notEscapedIndexOf("a\\bcb", 0, 'b', 'c')).isEqualTo(3); assertThat(TypeConverterUtils.notEscapedIndexOf("a\\b\\\\cb", 0, 'b', 'c')).isEqualTo(5); }
JaxbConverter implements TypeConverter<T> { @Override public T fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (isBlank(value)) { return null; } @SuppressWarnings("unchecked") Class<T> targetClazz = (Class<T>) type; JaxbPool jaxbPool = getJaxbPool(targetClazz); try (Handle<Unmarshaller> handle = jaxbPool.borrowUnmarshaller()) { return targetClazz.cast(handle.get().unmarshal(new ByteArrayInputStream(value.getBytes()))); } catch (JAXBException e) { throw new IllegalArgumentException("Unable to convert xml to " + targetClazz + " using jaxb", e); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }
@Test public void shouldReturnNullObjectForBlankXML() { String resource = " "; XmlRootConfiguration01 xmlRootConfiguration01 = (XmlRootConfiguration01) jaxbTypeConverter.fromString(XmlRootConfiguration01.class, resource, null); assertThat(xmlRootConfiguration01).isNull(); } @Test public void shouldReturnNullObjectForNullXML() { String resource = null; XmlRootConfiguration01 xmlRootConfiguration01 = (XmlRootConfiguration01) jaxbTypeConverter.fromString(XmlRootConfiguration01.class, resource, null); assertThat(xmlRootConfiguration01).isNull(); } @Test public void shouldFailValidationWhenReadingXMLNotCompliantWithTheSchema() { String resource = loadXml("/JaxbTypeAdapterTest/XmlRootConfiguration01.invalid.xml"); assertThatThrownBy(() -> jaxbTypeConverter.fromString(XmlRootConfiguration01.class, resource, null)) .isInstanceOf(IllegalArgumentException.class); } @Test public void shouldReturnProperPojoForValidXML() { String resource = loadXml("/JaxbTypeAdapterTest/XmlRootConfiguration01.xml"); XmlRootConfiguration01 config01 = (XmlRootConfiguration01) jaxbTypeConverter.fromString(XmlRootConfiguration01.class, resource, null); assertThat(config01.getConfigurationName()).isEqualTo("ROOT01"); assertThat(config01.getXmlSubConfigurations()).hasSize(2); assertThat(config01.getXmlSubConfigurations().get(0).getVersion()).isEqualTo(1); assertThat(config01.getXmlSubConfigurations().get(1).getVersion()).isEqualTo(2); } @Test public void shouldReturnProperPojoForSecondValidXML() { String resource = loadXml("/JaxbTypeAdapterTest/XmlRootConfiguration02.xml"); XmlRootConfiguration02 config01 = (XmlRootConfiguration02) jaxbTypeConverter.fromString(XmlRootConfiguration02.class, resource, null); assertThat(config01.getConfigurationName()).isEqualTo("ROOT02"); assertThat(config01.getXmlSubConfigurations()).hasSize(2); assertThat(config01.getXmlSubConfigurations().get(0).getVersion()).isEqualTo(3); assertThat(config01.getXmlSubConfigurations().get(1).getVersion()).isEqualTo(4); }
PeriodConverter implements TypeConverter<Period> { @Override public Period fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); try { return value == null ? null : Period.parse(value); } catch (DateTimeParseException e) { throw new IllegalArgumentException(format("Unable to convert to a Period: %s", value), e); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Period fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Period value, Map<String, String> attributes); }
@Test public void shouldConvertFromString() { Period period = Period.ofDays(123); Period readPeriod = converter.fromString(Period.class, "P123D", null); assertThat(readPeriod).isEqualTo(period); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongValue() { String toConvert = "XXXXX"; assertThatThrownBy(() -> converter.fromString(Period.class, toConvert, null)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage("Unable to convert to a Period: XXXXX"); }
PeriodConverter implements TypeConverter<Period> { @Override public String toString(Type type, Period value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return Objects.toString(value, null); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Period fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Period value, Map<String, String> attributes); }
@Test public void shouldConvertToString() { Period period = Period.ofDays(123); String asString = converter.toString(Period.class, period, null); assertThat(asString).isEqualTo("P123D"); }
PeriodConverter implements TypeConverter<Period> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Period.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Period fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Period value, Map<String, String> attributes); }
@Test public void shouldAcceptPeriodType() { Type type = Period.class; boolean isApplicable = converter.isApplicable(type, null); assertThat(isApplicable).isTrue(); } @Test public void shouldNotAcceptUnknownType() { boolean isApplicable = converter.isApplicable(mock(Type.class), null); assertThat(isApplicable).isFalse(); }
LongConverter extends AbstractNumberConverter<Long> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Long.class, Long.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }
@Test public void shouldBeApplicableWhenLongType() { Type type = Long.class; boolean applicable = longTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotLongType() { Type type = Boolean.class; boolean applicable = longTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> longTypeConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
OffsetDateTimeConverter extends AbstractTemporalAccessorConverter<OffsetDateTime> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && OffsetDateTime.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }
@Test public void shouldBeApplicableWhenOffsetDateTimeType() { Type type = OffsetDateTime.class; boolean applicable = offsetDateTimeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotOffsetDateTimeType() { Type type = Boolean.class; boolean applicable = offsetDateTimeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> offsetDateTimeConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
CharacterConverter implements TypeConverter<Character> { @Override public Character fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null || value.isEmpty()) { return null; } if (value.length() == 1) { return value.charAt(0); } if (value.charAt(0) == '\\') { String unescapedValue; try { unescapedValue = unescapeJava(value); } catch (RuntimeException e) { throw new IllegalArgumentException(format("Unable to convert to a Character: %s", value), e); } if (unescapedValue.length() == 1) { return unescapedValue.charAt(0); } } throw new IllegalArgumentException(format("Unable to convert to a Character: %s", value)); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Character fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Character value, Map<String, String> attributes); }
@Test public void shouldReadValuesFromStringWhenNotUnescaping() { String stringValue = "A"; Character value = converter.fromString(Character.class, stringValue, null); assertThat(value).isEqualTo('A'); } @Test public void shouldReadValuesFromStringWhenUnescaping() { String stringValue = "\\u0080"; Character value = converter.fromString(Character.class, stringValue, null); assertThat(value).isEqualTo('\u0080'); } @Test public void shouldThrowExceptionWhenReadingIllegalValuesFromString() { String stringValue = "longer then just on character string"; assertThrows(IllegalArgumentException.class, () -> converter.fromString(Character.class, stringValue, null), "Unable to convert to a Character: " + stringValue ); } @Test public void shouldConvertToNullFromEmptyString() { String stringValue = ""; Character value = converter.fromString(Character.class, stringValue, null); assertThat(value).isNull(); } @Test public void shouldEscapedString() { String invalidEncodedCharacter = "\\u001"; assertThrows(IllegalArgumentException.class, () -> converter.fromString(Character.class, invalidEncodedCharacter, null), "Unable to convert to a Character: " + invalidEncodedCharacter ); }
CharacterConverter implements TypeConverter<Character> { @Override public String toString(Type type, Character value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return value == null ? null : escapeJava(value.toString()); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Character fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Character value, Map<String, String> attributes); }
@Test public void shouldWriteValueAsString() { Character value = 'A'; String asString = converter.toString(Character.class, value, null); assertThat(asString).isEqualTo("A"); } @Test public void shouldConvertToNullFromNull() { Character value = null; String asString = converter.toString(Character.class, value, null); assertThat(asString).isNull(); } @Test public void shouldUnescapeEscapedString() { Character value = '\u0080'; String asString = converter.toString(Character.class, value, null); assertThat(asString).isEqualTo("\\u0080"); }
CharacterConverter implements TypeConverter<Character> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && (Character.class.isAssignableFrom((Class<?>) type) || Character.TYPE.isAssignableFrom((Class<?>) type)); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Character fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Character value, Map<String, String> attributes); }
@Test public void shouldBeApplicableToCharacter() { boolean applicable = converter.isApplicable(Character.class, null); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableToNonCharacter() { boolean applicable = converter.isApplicable(Object.class, null); assertThat(applicable).isFalse(); }
DurationConverter implements TypeConverter<Duration> { @Override public Duration fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); String format = (attributes == null) ? null : attributes.get(FORMAT); if (format != null) { try { SimpleDateFormat dateFormat = getDateFormat(format); LocalDateTime localDateTime = LocalDateTime.ofInstant(dateFormat.parse(value).toInstant(), ZoneId.systemDefault()); return Duration.between(Instant.EPOCH, localDateTime.toInstant(ZoneOffset.ofTotalSeconds(0))); } catch (ParseException e) { throw new IllegalArgumentException(format("Unable to convert to Duration: %s. " + "The value doesn't match specified format '%s'.", value, format), e); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(format("Unable to convert to Duration: %s. " + "Invalid format: '%s'", value, format), e); } } try { return (value == null) ? null : Duration.parse(value); } catch (DateTimeParseException e) { throw new IllegalArgumentException(format("Unable to convert to Duration: %s", value), e); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Duration fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Duration value, Map<String, String> attributes); static final String FORMAT; }
@Test public void shouldConvertFromStringWhenFormatNotSpecified() { Duration duration = Duration.ofMillis(1260535L); Duration readDuration = converter.fromString(Duration.class, "PT21M0.535S", null); assertThat(readDuration).isEqualTo(duration); } @Test public void shouldConvertFromStringWhenFormatSpecified() { Duration duration = Duration.ofMillis(600000L); String format = "HH:mm:ss"; Map<String, String> attributes = singletonMap("format", format); Duration readDuration = converter.fromString(Duration.class, "00:10:00", attributes); assertThat(readDuration).isEqualTo(duration); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongValueString() { String durationInString = "invalid value string"; assertThatThrownBy(() -> converter.fromString(Duration.class, durationInString, null)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unable to convert to Duration"); } @Test public void shouldThrowExceptionWhenConvertingFromStringWithFormatAndWrongValueString() { String durationInString = "invalid value string"; String format = "H:i:s"; Map<String, String> attributes = singletonMap("format", format); assertThatThrownBy(() -> converter.fromString(Duration.class, durationInString, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unable to convert to Duration"); } @Test public void shouldThrowExceptionWhenConvertingFromStringWithFormatAndWrongValue() { String durationInString = "a wrong duration"; String format = "HH:mm:ss"; Map<String, String> attributes = singletonMap("format", format); assertThatThrownBy(() -> converter.fromString(Duration.class, durationInString, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unable to convert to Duration"); }
DurationConverter implements TypeConverter<Duration> { @Override public String toString(Type type, Duration value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } String format = (attributes == null) ? null : attributes.get(FORMAT); if (format != null) { try { return formatDuration(value.toMillis(), format); } catch (DateTimeException e) { throw new IllegalArgumentException( "Unable to convert Duration to String. Error occurred during printing.", e); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(format( "Unable to convert Duration to String. Invalid duration value: %s", value), e); } } return value.toString(); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Duration fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Duration value, Map<String, String> attributes); static final String FORMAT; }
@Test public void shouldConvertToStringWhenFormatNotSpecified() { Duration duration = Duration.ofMillis(1260535L); String asString = converter.toString(Duration.class, duration, null); assertThat(asString).isEqualTo("PT21M0.535S"); } @Test public void shouldConvertToStringWhenFormatSpecified() { Duration duration = Duration.ofHours(1).plusMinutes(10).plusSeconds(20); String format = "HH:mm:ss"; Map<String, String> attributes = singletonMap("format", format); String asString = converter.toString(Duration.class, duration, attributes); assertThat(asString).isEqualTo("01:10:20"); } @Test public void shouldReturnNullWhenConvertingToStringAndValueToConvertIsNull() { String converted = converter.toString(Duration.class, null, null); assertThat(converted).isNull(); } @Test public void shouldThrowExceptionWhenConvertingToStringWithFormatAndWrongValue() { Duration duration = Duration.ofMillis(-600000L); String format = "HH:mm:ss"; Map<String, String> attributes = singletonMap("format", format); assertThatThrownBy(() -> converter.toString(Duration.class, duration, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unable to convert Duration to String. Invalid duration value:"); }
DurationConverter implements TypeConverter<Duration> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Duration.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Duration fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Duration value, Map<String, String> attributes); static final String FORMAT; }
@Test public void shouldAcceptReadableDurationType() { Type type = Duration.class; boolean isApplicable = converter.isApplicable(type, null); assertThat(isApplicable).isTrue(); } @Test public void shouldNotAcceptUnknownType() { boolean isApplicable = converter.isApplicable(mock(Type.class), null); assertThat(isApplicable).isFalse(); }
ByteConverter extends AbstractNumberConverter<Byte> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Byte.class, Byte.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }
@Test public void shouldBeApplicableWhenByteType() { Type type = Byte.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotByteType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
LocalDateTimeConverter extends AbstractTemporalAccessorConverter<LocalDateTime> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && LocalDateTime.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }
@Test public void shouldBeApplicableWhenLocalDateTimeType() { Type type = LocalDateTime.class; boolean applicable = localDateTimeTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotLocalDateTimeType() { Type type = Boolean.class; boolean applicable = localDateTimeTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> localDateTimeTypeConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
BigDecimalConverter extends AbstractNumberConverter<BigDecimal> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, BigDecimal.class, null); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }
@Test public void shouldBeApplicableToBigDecimal() { boolean applicable = converter.isApplicable(BigDecimal.class, null); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableToNonBigDecimal() { boolean applicable = converter.isApplicable(Object.class, null); assertThat(applicable).isFalse(); }
IntegerConverter extends AbstractNumberConverter<Integer> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Integer.class, Integer.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }
@Test public void shouldBeApplicableWhenIntegerType() { Type type = Integer.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotIntegerType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
DoubleConverter extends AbstractNumberConverter<Double> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Double.class, Double.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }
@Test public void shouldBeApplicableWhenDoubleType() { Type type = Double.class; boolean applicable = doubleTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotDoubleType() { Type type = Boolean.class; boolean applicable = doubleTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> doubleTypeConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
CurrencyConverter implements TypeConverter<Currency> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Currency.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Currency fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Currency value, Map<String, String> attributes); }
@Test public void shouldBeApplicableWhenCurrencyType() { Type type = Currency.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotCurrencyType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenIsApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
YamlConverter implements TypeConverter<T> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); String converter = (attributes == null) ? null : attributes.get(CONVERTER); return ignoreConverterAttribute || Objects.equals(converter, YAML); } YamlConverter(); YamlConverter(boolean ignoreConverterAttribute); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }
@Test void shouldThrowExceptionWhenTypeIsNullAndIsApplicable() { assertThatThrownBy(() -> typeConverter.isApplicable(null, null)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
CurrencyConverter implements TypeConverter<Currency> { @Override public String toString(Type type, Currency value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return value == null ? null : value.getCurrencyCode(); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Currency fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Currency value, Map<String, String> attributes); }
@Test public void shouldConvertToString() { Currency toConvert = Currency.getInstance("USD"); String converted = converter.toString(Currency.class, toConvert, emptyMap()); assertThat(converted).isEqualTo("USD"); } @Test public void shouldReturnNullWhenToStringAndValueIsNull() { String converted = converter.toString(Currency.class, null, emptyMap()); assertThat(converted).isNull(); } @Test public void shouldThrowExceptionWhenToStringAndTypeIsNull() { Currency toConvert = Currency.getInstance("USD"); assertThatThrownBy(() -> converter.toString(null, toConvert, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
CurrencyConverter implements TypeConverter<Currency> { @Override public Currency fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return value == null ? null : Currency.getInstance(value); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Currency fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Currency value, Map<String, String> attributes); }
@Test public void shouldConvertFromString() { String toConvert = "USD"; Currency converted = converter.fromString(Currency.class, toConvert, emptyMap()); assertThat(converted).isEqualTo(Currency.getInstance("USD")); } @Test public void shouldThrowExceptionWhenInvalidFormat() { String toConvert = "invalid"; assertThatThrownBy(() -> converter.fromString(Currency.class, toConvert, emptyMap())) .isExactlyInstanceOf(IllegalArgumentException.class); } @Test public void shouldReturnNullWhenFromStringAndValueIsNull() { Currency converted = converter.fromString(Currency.class, null, emptyMap()); assertThat(converted).isNull(); } @Test public void shouldThrowExceptionWhenFromStringAndTypeIsNull() { String toConvert = "USD"; assertThatThrownBy(() -> converter.fromString(null, toConvert, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
BooleanConverter implements TypeConverter<Boolean> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && (Boolean.class.isAssignableFrom((Class<?>) type) || Boolean.TYPE.isAssignableFrom((Class<?>) type)); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Boolean fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Boolean value, Map<String, String> attributes); static final String FORMAT; }
@Test public void shouldBeApplicableWhenBooleanType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotBooleanType() { Type type = Integer.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
YamlConverter implements TypeConverter<T> { @Override public T fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } try { JavaType javaType = TypeFactory.defaultInstance().constructType(type); ObjectReader objectReader = objectMapper.readerFor(javaType); return objectReader.readValue(value); } catch (IOException e) { throw new IllegalStateException(e); } } YamlConverter(); YamlConverter(boolean ignoreConverterAttribute); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }
@Test void shouldConvertFromString() { String toConvert = "" + "integer: 1\n" + "string: test-1\n"; TestClass converted = typeConverter.fromString(TestClass.class, toConvert, null); assertThat(converted).isEqualTo(new TestClass(1, "test-1")); } @Test void shouldConvertCollectionFromString() { String toConvert = "" + "- integer: 1\n" + " string: test-1\n" + "- integer: 2\n" + " string: test-2\n"; TypeConverter<List<TestClass>> typeConverter = new YamlConverter<>(); Collection<TestClass> converted = typeConverter.fromString(parameterize(Collection.class, TestClass.class), toConvert, null); assertThat(converted) .hasSize(2) .containsSequence( new TestClass(1, "test-1"), new TestClass(2, "test-2")); } @Test void shouldConvertMapFromString() { String toConvert = "" + "first:\n" + " integer: 1\n" + " string: test-1\n" + "second:\n" + " integer: 2\n" + " string: test-2\n"; TypeConverter<Map<String, TestClass>> typeConverter = new YamlConverter<>(); Map<String, TestClass> converted = typeConverter.fromString(parameterize(Map.class, String.class, TestClass.class), toConvert, null); assertThat(converted) .hasSize(2) .containsEntry("first", new TestClass(1, "test-1")) .containsEntry("second", new TestClass(2, "test-2")); } @Test void shouldReturnNullWhenFromStringAndValueIsNull() { TestClass converted = typeConverter.fromString(TestClass.class, null, null); assertThat(converted).isNull(); } @Test void shouldThrowExceptionWhenImproperYamlFormat() { String toConvert = "" + "<integer>1</integer>" + "<string>test-1</string>"; assertThatThrownBy(() -> typeConverter.fromString(TestClass.class, toConvert, null)); } @Test void shouldThrowExceptionWhenTypeIsNullAndFromString() { assertThatThrownBy(() -> typeConverter.fromString(null, null, null)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
BooleanConverter implements TypeConverter<Boolean> { @Override public String toString(Type type, Boolean value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (attributes != null && attributes.containsKey(FORMAT)) { String format = attributes.get(FORMAT); Pair<String, String> values = cache.computeIfAbsent(format, this::getValues); return value ? values.getLeft() : values.getRight(); } else { return Objects.toString(value, null); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Boolean fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Boolean value, Map<String, String> attributes); static final String FORMAT; }
@Test public void shouldConvertToStringWhenFormatNotSpecifiedAndTrue() { Boolean b = true; String converted = converter.toString(Boolean.class, b, emptyMap()); assertThat(converted).isEqualTo("true"); } @Test public void shouldConvertToStringWhenFormatNotSpecifiedAndFalse() { Boolean b = false; String converted = converter.toString(Boolean.class, b, emptyMap()); assertThat(converted).isEqualTo("false"); } @Test public void shouldConvertToStringWhenFormatSpecifiedAndTrue() { Boolean b = true; String format = "yes/no"; Map<String, String> attributes = singletonMap("format", format); String converted = converter.toString(Boolean.class, b, attributes); assertThat(converted).isEqualTo("yes"); } @Test public void shouldConvertToStringWhenFormatSpecifiedAndFalse() { Boolean b = false; String format = "yes/no"; Map<String, String> attributes = singletonMap("format", format); String converted = converter.toString(Boolean.class, b, attributes); assertThat(converted).isEqualTo("no"); } @Test public void shouldReturnNullWhenConvertingToStringAndValueToConvertIsNull() { String converted = converter.toString(Boolean.class, null, emptyMap()); assertThat(converted).isNull(); } @Test public void shouldThrowExceptionWhenConvertingToStringAndWrongFormat() { Boolean toConvert = true; String format = "wrong format"; Map<String, String> attributes = singletonMap("format", format); assertThatThrownBy(() -> converter.toString(Boolean.class, toConvert, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageEndingWith("Invalid 'format' meta-attribute value, it must contain '/' separator character. Provided value is 'wrong format'."); } @Test public void shouldThrowExceptionWhenConvertingToStringAndTypeIsNull() { Boolean b = true; assertThatThrownBy(() -> converter.toString(null, b, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
BooleanConverter implements TypeConverter<Boolean> { @Override public Boolean fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } String format = (attributes == null) ? null : attributes.get(FORMAT); if (format != null) { Pair<String, String> values = cache.computeIfAbsent(format, this::getValues); if (value.equals(values.getLeft())) { return Boolean.TRUE; } if (value.equals(values.getRight())) { return Boolean.FALSE; } throw new IllegalArgumentException( format("Unable to convert to Boolean, values must be either '%s' or '%s' but provided value is '%s'.", values.getLeft(), values.getRight(), value)); } else { if (TRUE.equals(value)) { return Boolean.TRUE; } if (FALSE.equals(value)) { return Boolean.FALSE; } throw new IllegalArgumentException(format("Unable to convert to Boolean. Unknown value: %s", value)); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Boolean fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Boolean value, Map<String, String> attributes); static final String FORMAT; }
@Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongValue() { String aString = "wrong value"; assertThatThrownBy(() -> converter.fromString(Boolean.class, aString, null)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unable to convert to Boolean. Unknown value:"); } @Test public void shouldConvertFromStringWhenFormatNotSpecifiedAndTrue() { String booleanInString = "true"; Boolean fromConversion = converter.fromString(Boolean.class, booleanInString, emptyMap()); assertThat(fromConversion).isEqualTo(true); } @Test public void shouldConvertFromStringWhenFormatNotSpecifiedAndFalse() { String booleanInString = "false"; Boolean fromConversion = converter.fromString(Boolean.class, booleanInString, emptyMap()); assertThat(fromConversion).isEqualTo(false); } @Test public void shouldConvertFromStringWhenFormatSpecifiedAndTrue() { String booleanInString = "on"; String format = "on/off"; Map<String, String> attributes = singletonMap("format", format); Boolean fromConversion = converter.fromString(Boolean.class, booleanInString, attributes); assertThat(fromConversion).isEqualTo(true); } @Test public void shouldConvertFromStringWhenFormatSpecifiedAndFalse() { String booleanInString = "off"; String format = "on/off"; Map<String, String> attributes = singletonMap("format", format); Boolean fromConversion = converter.fromString(Boolean.class, booleanInString, attributes); assertThat(fromConversion).isEqualTo(false); } @Test public void shouldReturnNullWhenConvertingFromStringAndValueToConvertIsNull() { Boolean fromConversion = converter.fromString(Boolean.class, null, emptyMap()); assertThat(fromConversion).isNull(); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongFormat() { String booleanInString = "on"; String format = "wrong format"; Map<String, String> attributes = singletonMap("format", format); assertThatThrownBy(() -> converter.fromString(Boolean.class, booleanInString, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageEndingWith("Invalid 'format' meta-attribute value, it must contain '/' separator character. Provided value is 'wrong format'."); } @Test public void shouldThrowExceptionWhenConvertingFromStringWithFormatAndWrongValue() { String booleanInString = "wrong value"; String format = "yes/no"; Map<String, String> attributes = singletonMap("format", format); assertThatThrownBy(() -> converter.fromString(Boolean.class, booleanInString, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageEndingWith("Unable to convert to Boolean, values must be either 'yes' or 'no' but provided value is 'wrong value'."); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndTypeIsNull() { String booleanInString = "on"; assertThatThrownBy(() -> converter.fromString(null, booleanInString, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
InstantConverter extends AbstractTemporalAccessorConverter<Instant> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Instant.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override String toString(Type type, Instant value, Map<String, String> attributes); static final String ZONE; }
@Test public void shouldBeApplicableWhenInstantType() { Type type = Instant.class; boolean applicable = instantConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotInstantType() { Type type = Boolean.class; boolean applicable = instantConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> instantConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
InstantConverter extends AbstractTemporalAccessorConverter<Instant> { @Override public String toString(Type type, Instant value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } String format = null; ZoneId zoneId = DEFAULT_ZONE; if (attributes != null) { format = attributes.get(FORMAT); String zone = attributes.get(ZONE); if (ZoneId.getAvailableZoneIds().contains(zone)) { zoneId = ZoneId.of(zone); } } try { return format == null ? value.toString() : getFormatterForPattern(format).withZone(zoneId).format(value); } catch (DateTimeException e) { throw new IllegalArgumentException(format("Unable to convert %s to String. ", getSimpleClassName(type)) + "Error occurred during printing.", e); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(format("Unable to convert %s to String. " + "Invalid format: '%s'", getSimpleClassName(type), format), e); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override String toString(Type type, Instant value, Map<String, String> attributes); static final String ZONE; }
@Test public void shouldConvertToStringWhenFormatNotSpecified() { Instant toConvert = Instant.EPOCH; String converted = instantConverter.toString(Instant.class, toConvert, emptyMap()); assertThat(converted).isEqualTo("1970-01-01T00:00:00Z"); } @Test public void shouldConvertToStringWhenFormatSpecifiedAndDefaultZone() { Instant toConvert = Instant.EPOCH; String format = "yyyy MM dd HH:mm"; Map<String, String> attributes = singletonMap("format", format); String converted = instantConverter.toString(Instant.class, toConvert, attributes); assertThat(converted).isEqualTo("1969 12 31 18:00"); } @Test public void shouldConvertToStringWhenFormatAndZoneSpecified() { Instant toConvert = Instant.EPOCH; String format = "yyyy MM dd HH:mm"; Map<String, String> attributes = new HashMap<>(); attributes.put("format", format); attributes.put("zone", "Europe/London"); String converted = instantConverter.toString(Instant.class, toConvert, attributes); assertThat(converted).isEqualTo("1970 01 01 01:00"); } @Test public void shouldConvertToStringWhenFormatSpecifiedAndWrongZone() { Instant toConvert = Instant.EPOCH; String format = "yyyy MM dd HH:mm"; Map<String, String> attributes = new HashMap<>(); attributes.put("zone", "null"); attributes.put("format", format); String converted = instantConverter.toString(Instant.class, toConvert, attributes); assertThat(converted).isEqualTo("1969 12 31 18:00"); } @Test public void shouldReturnNullWhenConvertingToStringAndValueToConvertIsNull() { String converted = instantConverter.toString(Instant.class, null, emptyMap()); assertThat(converted).isNull(); } @Test public void shouldThrowExceptionWhenConvertingToStringAndWrongFormat() { Instant toConvert = Instant.EPOCH; String format = "invalid format"; Map<String, String> attributes = singletonMap("format", format); assertThatThrownBy(() -> instantConverter.toString(Instant.class, toConvert, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage("Unable to convert Instant to String. Invalid format: 'invalid format'"); } @Test public void shouldThrowExceptionWhenConvertingToStringAndTypeIsNull() { Instant toConvert = Instant.EPOCH; assertThatThrownBy(() -> instantConverter.toString(null, toConvert, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndTypeIsNull() { Instant toConvert = Instant.EPOCH; assertThatThrownBy(() -> instantConverter.toString(null, toConvert, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
StringConverter implements TypeConverter<String> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && String.class.isAssignableFrom((Class<?>) type); } StringConverter(boolean escape); StringConverter(); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override String fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, String value, Map<String, String> attributes); static final String ESCAPE; }
@Test public void shouldBeApplicableWhenStringType() { Type type = String.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotStringType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); }
StringConverter implements TypeConverter<String> { @Override public String fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return shouldEscape(attributes) ? unescapeJava(value) : value; } StringConverter(boolean escape); StringConverter(); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override String fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, String value, Map<String, String> attributes); static final String ESCAPE; }
@Test public void shouldConvertFromStringWhenFormatNotSpecified() { String in = "One\\\\Two"; String expected = "One\\Two"; String out = converter.fromString(String.class, in, null); assertThat(out).isEqualTo(expected); } @Test public void shouldConvertFromStringWhenFormatSpecifiedAndFalse() { String in = "One\\\\Two"; String escape = "false"; Map<String, String> attributes = singletonMap("escape", escape); String out = converter.fromString(String.class, in, attributes); assertThat(out).isEqualTo(in); } @Test public void shouldConvertFromStringWhenFormatSpecifiedAndTrue() { String in = "One\\\\Two"; String escape = "true"; Map<String, String> attributes = singletonMap("escape", escape); String out = converter.fromString(String.class, in, attributes); assertThat(out).isEqualTo("One\\Two"); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongEscapeValue() { String in = "One\\Two"; String escape = "wrong value"; Map<String, String> attributes = singletonMap("escape", escape); assertThatThrownBy(() -> converter.fromString(String.class, in, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageEndingWith("Invalid 'escape' meta-attribute value, it must be either 'true' or 'false', but 'wrong value' is provided."); }
GenericsExample { public static void main(String[] args) { new GenericsExample().run(); } static void main(String[] args); }
@Test public void shouldExecuteMainWithoutExceptions() { GenericsExample.main(new String[0]); }
StringConverter implements TypeConverter<String> { @Override public String toString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return shouldEscape(attributes) ? escapeJava(value) : value; } StringConverter(boolean escape); StringConverter(); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override String fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, String value, Map<String, String> attributes); static final String ESCAPE; }
@Test public void shouldConvertToStringWhenFormatNotSpecified() { String in = "One\\Two"; String expected = "One\\\\Two"; String out = converter.toString(String.class, in, null); assertThat(out).isEqualTo(expected); } @Test public void shouldConvertToStringWhenFormatSpecifiedAndFalse() { String in = "One\\Two"; String escape = "false"; Map<String, String> attributes = singletonMap(ESCAPE, escape); String out = converter.toString(String.class, in, attributes); assertThat(out).isEqualTo(in); } @Test public void shouldConvertToStringWhenFormatSpecifiedAndTrue() { String in = "One\\Two"; String escape = "true"; Map<String, String> attributes = singletonMap(ESCAPE, escape); String out = converter.toString(String.class, in, attributes); assertThat(out).isEqualTo("One\\\\Two"); } @Test public void shouldThrowExceptionWhenConvertingToStringAndWrongEscapeValue() { String in = "One\\Two"; String escape = "wrong value"; Map<String, String> attributes = singletonMap(ESCAPE, escape); assertThatThrownBy(() -> converter.toString(String.class, in, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageEndingWith("Invalid 'escape' meta-attribute value, it must be either 'true' or 'false', but 'wrong value' is provided."); }
JsonLikeConverter implements TypeConverter<Object> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if (parameterizedType.getRawType() instanceof Class) { Class<?> rawType = (Class<?>) parameterizedType.getRawType(); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (List.class.isAssignableFrom(rawType) && actualTypeArguments.length == 1) { Type itemType = actualTypeArguments[0]; return isApplicable(itemType, attributes) || innerTypeConverter.isApplicable(itemType, attributes); } else if (Map.class.isAssignableFrom(rawType) && actualTypeArguments.length == 2) { Type keyType = actualTypeArguments[0]; Type valueType = actualTypeArguments[1]; return (isApplicable(keyType, attributes) || innerTypeConverter.isApplicable(keyType, attributes)) && (isApplicable(valueType, attributes) || innerTypeConverter.isApplicable(valueType, attributes)); } } } return false; } JsonLikeConverter(TypeConverter<?> innerTypeConverter); @SuppressWarnings("unchecked") JsonLikeConverter(TypeConverter<?> innerTypeConverter, boolean compactMode); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Object fromString(Type type, String value, Map<String, String> attributes); @SuppressWarnings("unchecked") @Override String toString(Type type, Object value, Map<String, String> attributes); static final String FORMAT; static final String COMPACT; static final String JSON; static final String EMPTY_STRING; static final String JSON_NULL; static final String COMPACT_JSON_NULL; static final String COMPACT_JSON_EMPTY; }
@Test public void shouldProperlyIndicateSupportedTypes() { assertThat(typeConverter.isApplicable(SUPPORTED_LIST_TYPE, null)).isTrue(); assertThat(typeConverter.isApplicable(SUPPORTED_MAP_TYPE, null)).isTrue(); assertThat(typeConverter.isApplicable(SUPPORTED_COMPLEX_TYPE, null)).isTrue(); assertThat(typeConverter.isApplicable(NOT_SUPPORTED_COMPLEX_TYPE, null)).isFalse(); }
JsonLikeConverter implements TypeConverter<Object> { int consumeNull(CharSequence value, int current, ObjectBuilder builder, boolean compact) { int found = value.length(); boolean consume = false; if (compact) { if (value.charAt(current) == COMPACT_JSON_NULL.charAt(0)) { if (found != COMPACT_JSON_NULL.length() + current) { found = notEscapedIndexOf(value, current, COMMA, COLON, RIGHT_CURLY_BRACE, RIGHT_SQUARE_BRACKET); } consume = found == COMPACT_JSON_NULL.length() + current && COMPACT_JSON_NULL.equals(value.subSequence(current, found).toString()); } } else { if (value.charAt(current) == JSON_NULL.charAt(0)) { if (found != JSON_NULL.length() + current) { found = notEscapedIndexOf(value, current, COMMA, COLON, RIGHT_CURLY_BRACE, RIGHT_SQUARE_BRACKET); } consume = found == JSON_NULL.length() + current && JSON_NULL.equals(value.subSequence(current, found).toString()); } } if (consume) { builder.addValue(null); return found - current; } return 0; } JsonLikeConverter(TypeConverter<?> innerTypeConverter); @SuppressWarnings("unchecked") JsonLikeConverter(TypeConverter<?> innerTypeConverter, boolean compactMode); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Object fromString(Type type, String value, Map<String, String> attributes); @SuppressWarnings("unchecked") @Override String toString(Type type, Object value, Map<String, String> attributes); static final String FORMAT; static final String COMPACT; static final String JSON; static final String EMPTY_STRING; static final String JSON_NULL; static final String COMPACT_JSON_NULL; static final String COMPACT_JSON_EMPTY; }
@Test public void shouldProperlyConsumeJsonNullsAndAddNullValuesToBuilder() { boolean compact = false; ObjectBuilder builder = Mockito.mock(ObjectBuilder.class); assertThat(typeConverter.consumeNull(JSON_NULL, 0, builder, compact)).isEqualTo(JSON_NULL.length()); assertThat(typeConverter.consumeNull(JSON_NULL + ',', 0, builder, compact)).isEqualTo(JSON_NULL.length()); assertThat(typeConverter.consumeNull("ABC" + JSON_NULL, 3, builder, compact)).isEqualTo(JSON_NULL.length()); assertThat(typeConverter.consumeNull("ABC" + JSON_NULL + ',', 3, builder, compact)).isEqualTo(JSON_NULL.length()); assertThat(typeConverter.consumeNull("ABC" + JSON_NULL + ':', 3, builder, compact)).isEqualTo(JSON_NULL.length()); assertThat(typeConverter.consumeNull("ABC" + JSON_NULL + '}', 3, builder, compact)).isEqualTo(JSON_NULL.length()); assertThat(typeConverter.consumeNull("ABC" + JSON_NULL + ']', 3, builder, compact)).isEqualTo(JSON_NULL.length()); assertThat(typeConverter.consumeNull("ABC" + COMPACT_JSON_NULL + ',', 2, builder, compact)).isEqualTo(0); assertThat(typeConverter.consumeNull("ABC" + JSON_NULL + '{', 3, builder, compact)).isEqualTo(0); assertThat(typeConverter.consumeNull("ABC" + JSON_NULL + '[', 3, builder, compact)).isEqualTo(0); assertThat(typeConverter.consumeNull("ABC" + JSON_NULL + '[', 3, builder, compact)).isEqualTo(0); verify(builder, times(7)).addValue(eq(null)); } @Test public void shouldProperlyConsumeCompactJsonNullsAndAddNullValuesToBuilder() { boolean compact = true; ObjectBuilder builder = Mockito.mock(ObjectBuilder.class); assertThat(typeConverter.consumeNull(COMPACT_JSON_NULL, 0, builder, compact)).isEqualTo(COMPACT_JSON_NULL.length()); assertThat(typeConverter.consumeNull(COMPACT_JSON_NULL + ',', 0, builder, compact)).isEqualTo(COMPACT_JSON_NULL.length()); assertThat(typeConverter.consumeNull("ABC" + COMPACT_JSON_NULL, 3, builder, compact)).isEqualTo(COMPACT_JSON_NULL.length()); assertThat(typeConverter.consumeNull("ABC" + COMPACT_JSON_NULL + ',', 3, builder, compact)).isEqualTo(COMPACT_JSON_NULL.length()); assertThat(typeConverter.consumeNull("ABC" + COMPACT_JSON_NULL + ':', 3, builder, compact)).isEqualTo(COMPACT_JSON_NULL.length()); assertThat(typeConverter.consumeNull("ABC" + COMPACT_JSON_NULL + '}', 3, builder, compact)).isEqualTo(COMPACT_JSON_NULL.length()); assertThat(typeConverter.consumeNull("ABC" + COMPACT_JSON_NULL + ']', 3, builder, compact)).isEqualTo(COMPACT_JSON_NULL.length()); assertThat(typeConverter.consumeNull("ABC" + COMPACT_JSON_NULL + ',', 2, builder, compact)).isEqualTo(0); assertThat(typeConverter.consumeNull("ABC" + COMPACT_JSON_NULL + '{', 3, builder, compact)).isEqualTo(0); assertThat(typeConverter.consumeNull("ABC" + COMPACT_JSON_NULL + '{', 3, builder, compact)).isEqualTo(0); assertThat(typeConverter.consumeNull("ABC" + JSON_NULL + '[', 3, builder, compact)).isEqualTo(0); verify(builder, times(7)).addValue(eq(null)); }
ChainedTypeConverter implements TypeConverter<Object> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return converterFor(type, attributes, false) != null; } ChainedTypeConverter(List<TypeConverter<?>> converters); ChainedTypeConverter(TypeConverter<?>... converters); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Object fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Object value, Map<String, String> attributes); }
@Test public void shouldSupportConvertersFromTheChain() { TypeConverter<?> converter = new ChainedTypeConverter(new StringConverter(false), new IntegerConverter()); assertThat(converter.isApplicable(String.class, null)).isTrue(); assertThat(converter.isApplicable(Integer.class, null)).isTrue(); assertThat(converter.isApplicable(Long.class, null)).isFalse(); }
ChainedTypeConverter implements TypeConverter<Object> { @Override public Object fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return converterFor(type, attributes).fromString(type, value, attributes); } ChainedTypeConverter(List<TypeConverter<?>> converters); ChainedTypeConverter(TypeConverter<?>... converters); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Object fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Object value, Map<String, String> attributes); }
@Test public void shouldThrowIAEWhenTypeIsNotSupported() { assertThrows(IllegalArgumentException.class, () -> { TypeConverter<Object> converter = new ChainedTypeConverter(new StringConverter()); converter.fromString(Long.class, "10", null); }); }
FloatConverter extends AbstractNumberConverter<Float> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Float.class, Float.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }
@Test public void shouldBeApplicableWhenFloatType() { Type type = Float.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotFloatType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
UrlConverter implements TypeConverter<URL> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && URL.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override URL fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, URL value, Map<String, String> attributes); }
@Test public void shouldBeApplicableWhenUrlType() { Type type = URL.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotUrlType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
UrlConverter implements TypeConverter<URL> { @Override public String toString(Type type, URL value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return Objects.toString(value, null); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override URL fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, URL value, Map<String, String> attributes); }
@Test public void shouldConvertToString() throws MalformedURLException { String urlString = "http: URL toConvert = new URL(urlString); String converted = converter.toString(URL.class, toConvert, emptyMap()); assertThat(converted).isEqualTo(urlString); } @Test public void shouldReturnNullWhenConvertingToStringAndValueToConvertIsNull() { String converted = converter.toString(URL.class, null, emptyMap()); assertThat(converted).isNull(); }
UrlConverter implements TypeConverter<URL> { @Override public URL fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } try { return new URL(value); } catch (MalformedURLException e) { throw new IllegalArgumentException(format("Unable to convert to URL: %s", value), e); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override URL fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, URL value, Map<String, String> attributes); }
@Test public void shouldCovertFromString() throws MalformedURLException { String urlInString = "http: URL fromConversion = converter.fromString(URL.class, urlInString, emptyMap()); URL expected = new URL(urlInString); assertThat(fromConversion).isEqualTo(expected); } @Test public void shouldThrowExceptionWhenMalformedUrl() { String malformedUrlString = "malformed URL"; assertThatThrownBy(() -> converter.fromString(URL.class, malformedUrlString, emptyMap())) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage("Unable to convert to URL: malformed URL"); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndTypeIsNull() { String urlInString = "http: assertThatThrownBy(() -> converter.fromString(null, urlInString, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } @Test public void shouldReturnNullWhenConvertingFromStringAndValueToConvertIsNull() { URL fromConversion = converter.fromString(URL.class, null, emptyMap()); assertThat(fromConversion).isNull(); }
ShortConverter extends AbstractNumberConverter<Short> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Short.class, Short.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }
@Test public void shouldBeApplicableWhenShortType() { Type type = Short.class; boolean applicable = shortTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotShortType() { Type type = Boolean.class; boolean applicable = shortTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> shortTypeConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
EnumConverter implements TypeConverter<Enum<?>> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Enum.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @SuppressWarnings("unchecked") @Override Enum<?> fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Enum<?> value, Map<String, String> attributes); }
@Test public void shouldAcceptEnumType() { Type type = TestEnum.class; boolean isApplicable = enumTypeAdapter.isApplicable(type, null); assertThat(isApplicable).isTrue(); }
EnumConverter implements TypeConverter<Enum<?>> { @SuppressWarnings("unchecked") @Override public Enum<?> fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return value == null ? null : toEnumValue((Class<Enum<?>>) type, value); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @SuppressWarnings("unchecked") @Override Enum<?> fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Enum<?> value, Map<String, String> attributes); }
@Test public void shouldConvertFromString() { Enum<?> testEnum = enumTypeAdapter.fromString(TestEnum.class, "FIRST", null); assertThat(testEnum).isEqualTo(TestEnum.FIRST); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongValue() { String value = "WRONG_VALUE"; assertThatThrownBy(() -> enumTypeAdapter.fromString(TestEnum.class, value, null)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unable to convert a value to an enumeration:"); }
YamlConverter implements TypeConverter<T> { @Override public String toString(Type type, T value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } try { ObjectWriter objectWriter = objectMapper.writer(); return objectWriter.writeValueAsString(value); } catch (JsonProcessingException e) { throw new UncheckedIOException("Unable to process JSON.", e); } } YamlConverter(); YamlConverter(boolean ignoreConverterAttribute); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }
@Test void shouldConvertToString() { TestClass toConvert = new TestClass(1, "test-1"); String converted = typeConverter.toString(TestClass.class, toConvert, null); assertThat(converted).isEqualTo("" + "integer: 1\n" + "string: test-1\n"); } @Test void shouldConvertCollectionToString() { List<TestClass> toConvert = asList( new TestClass(1, "test-1"), new TestClass(2, "test-2") ); TypeConverter<List<TestClass>> typeConverter = new YamlConverter<>(); String converted = typeConverter.toString(parameterize(Collection.class, TestClass.class), toConvert, null); assertThat(converted).isEqualTo("" + "- integer: 1\n" + " string: test-1\n" + "- integer: 2\n" + " string: test-2\n"); } @Test void shouldConvertMapToString() { Map<String, TestClass> toConvert = new HashMap<>(); toConvert.put("first", new TestClass(1, "test-1")); toConvert.put("second", new TestClass(2, "test-2")); TypeConverter<Map<String, TestClass>> typeConverter = new YamlConverter<>(); String converted = typeConverter.toString(parameterize(Map.class, String.class, TestClass.class), toConvert, null); assertThat(converted).isEqualTo("" + "first:\n" + " integer: 1\n" + " string: test-1\n" + "second:\n" + " integer: 2\n" + " string: test-2\n"); } @Test void shouldReturnNullWhenToStringAndValueIsNull() { String converted = typeConverter.toString(TestClass.class, null, null); assertThat(converted).isNull(); } @Test void shouldThrowExceptionWhenTypeIsNullAndToString() { assertThatThrownBy(() -> typeConverter.toString(null, null, null)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
EnumConverter implements TypeConverter<Enum<?>> { @Override public String toString(Type type, Enum<?> value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return value == null ? null : value.name(); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @SuppressWarnings("unchecked") @Override Enum<?> fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Enum<?> value, Map<String, String> attributes); }
@Test public void shouldConvertToString() { String value = enumTypeAdapter.toString(TestEnum.class, TestEnum.SECOND_VALUE, null); assertThat(value).isEqualTo(TestEnum.SECOND_VALUE.name()); }
ConfigurationValueDecryptingProcessor implements ConfigurationValueProcessor { @Override public ConfigurationValue process(ConfigurationValue value) { requireNonNull(value, "value cannot be null"); if (value.isEncrypted() && Objects.equals(value.getEncryptionProvider(), decrypter.getName())) { String encrypted = value.getValue(); String decrypted = decrypter.decrypt(encrypted); value.setDecryptedValue(decrypted); } return value; } ConfigurationValueDecryptingProcessor(); ConfigurationValueDecryptingProcessor(ConfigurationValueDecrypter decrypter); void setDecrypter(ConfigurationValueDecrypter decrypter); @Override ConfigurationValue process(ConfigurationValue value); }
@Test public void decryptUnencryptedValueAndResetProvider() { String encrypted = "encrypted"; String decrypted = "decrypted"; ConfigurationValue value = new ConfigurationValue(null, encrypted, true, Encrypted.DEFAULT, null); processor = new ConfigurationValueDecryptingProcessor(decrypter); when(decrypter.getName()).thenReturn(Encrypted.DEFAULT); when(decrypter.decrypt(encrypted)).thenReturn(decrypted); ConfigurationValue processed = processor.process(value); assertThat(processed).isSameAs(value); assertThat(value.isEncrypted()).isFalse(); assertThat(value.getValue()).isEqualTo(decrypted); verify(decrypter, times(1)).decrypt(anyString()); verify(decrypter, times(1)).getName(); } @Test public void shouldNotDecryptUnencryptedValue() { String val = "value"; ConfigurationValue value = new ConfigurationValue(null, val, true, null, null); processor = new ConfigurationValueDecryptingProcessor(decrypter); processor.process(value); assertThat(value.isEncrypted()).isFalse(); assertThat(value.getValue()).isEqualTo(val); verify(decrypter, never()).getName(); verify(decrypter, never()).decrypt(anyString()); } @Test public void shouldNotDecryptEncryptedValueWhenProviderNameDiffers() { String encrypted = "encrypted"; String decrypted = "decrypted"; String encryptionProvider = Encrypted.DEFAULT; ConfigurationValue value = new ConfigurationValue(null, encrypted, true, encryptionProvider, null); processor = new ConfigurationValueDecryptingProcessor(decrypter); when(decrypter.getName()).thenReturn("notMatchingProviderName"); when(decrypter.decrypt(encrypted)).thenReturn(decrypted); ConfigurationValue processed = processor.process(value); assertThat(processed).isSameAs(value); assertThat(value.isEncrypted()).isTrue(); assertThat(value.getEncryptionProvider()).isEqualTo(encryptionProvider); verify(decrypter, times(1)).getName(); verify(decrypter, never()).decrypt(anyString()); } @Test public void shouldThrowIllegalArgumentExceptionFromNoOpConfigurationValueDecrypter() { assertThrows(IllegalArgumentException.class, () -> { processor = new ConfigurationValueDecryptingProcessor(); processor.process(new ConfigurationValue(null, null, true, Encrypted.DEFAULT, null)); }); }
JsonConverter implements TypeConverter<T> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); String converter = (attributes == null) ? null : attributes.get(CONVERTER); return ignoreConverterAttribute || Objects.equals(converter, JSON); } JsonConverter(); JsonConverter(boolean ignoreConverterAttribute); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }
@Test void shouldThrowExceptionWhenTypeIsNullAndIsApplicable() { assertThatThrownBy(() -> typeConverter.isApplicable(null, null)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
JsonConverter implements TypeConverter<T> { @Override public T fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } try { JavaType javaType = TypeFactory.defaultInstance().constructType(type); ObjectReader objectReader = objectMapper.readerFor(javaType); return objectReader.readValue(value); } catch (IOException e) { throw new IllegalStateException(e); } } JsonConverter(); JsonConverter(boolean ignoreConverterAttribute); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }
@Test void shouldConvertFromString() { String toConvert = "" + "{" + " \"integer\": \"10\"," + " \"string\": \"test\"" + "}"; TestClass converted = typeConverter.fromString(TestClass.class, toConvert, null); assertThat(converted).isNotNull(); assertThat(converted.integer).isEqualTo(10); assertThat(converted.string).isEqualTo("test"); } @Test void shouldConvertListFromString() { String toConvert = "" + "[" + " {" + " \"integer\": \"1\"," + " \"string\": \"test-1\"" + " }," + " {" + " \"integer\": \"2\"," + " \"string\": \"test-2\"" + " }" + "]"; TypeConverter<List<TestClass>> listConverter = new JsonConverter<>(); List<TestClass> converted = listConverter.fromString(parameterize(List.class, TestClass.class), toConvert, null); assertThat(converted) .hasSize(2) .containsSequence( new TestClass(1, "test-1"), new TestClass(2, "test-2")); } @Test void shouldConvertMapFromString() { String toConvert = "" + "{" + " \"one\": {" + " \"integer\": \"1\"," + " \"string\": \"test-1\"" + " }," + " \"two\": {" + " \"integer\": \"2\"," + " \"string\": \"test-2\"" + " }" + "}"; TypeConverter<Map<String, TestClass>> listConverter = new JsonConverter<>(); Map<String, TestClass> converted = listConverter.fromString(parameterize(Map.class, String.class, TestClass.class), toConvert, null); assertThat(converted) .hasSize(2) .containsExactly( entry("one", new TestClass(1, "test-1")), entry("two", new TestClass(2, "test-2"))); } @Test void shouldThrowAssertionErrorWhenTryToConvertFromStringWithInvalidProperty() { String toConvert = "" + "{" + " \"int\": \"10\"," + " \"string\": \"test\"" + "}"; assertThatThrownBy(() -> typeConverter.fromString(TestClass.class, toConvert, null)) .isExactlyInstanceOf(IllegalStateException.class) .hasCauseInstanceOf(IOException.class); } @Test void shouldThrowAssertionErrorWhenTryToConvertFromInvalidJsonString() { String toConvert = "" + " \"integer\": \"10\"," + " \"string\": \"test\"" + "}"; assertThatThrownBy(() -> typeConverter.fromString(TestClass.class, toConvert, null)) .isExactlyInstanceOf(IllegalStateException.class) .hasCauseInstanceOf(IOException.class); } @Test void shouldReturnNullWhenFromStringAndValueIsNull() { TestClass converted = typeConverter.fromString(TestClass.class, null, null); assertThat(converted).isNull(); } @Test void shouldThrowExceptionWhenTypeIsNullAndFromString() { assertThatThrownBy(() -> typeConverter.fromString(null, null, null)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
MetaDataExample { public static void main(String[] args) { new MetaDataExample().run(); } static void main(String[] args); }
@Test public void shouldExecuteMainWithoutExceptions() { MetaDataExample.main(new String[0]); }
JsonConverter implements TypeConverter<T> { @Override public String toString(Type type, T value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } try { ObjectWriter objectWriter = objectMapper.writer(); return objectWriter.writeValueAsString(value); } catch (JsonProcessingException e) { throw new UncheckedIOException("Unable to process JSON.", e); } } JsonConverter(); JsonConverter(boolean ignoreConverterAttribute); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }
@Test void shouldConvertToString() { TestClass toConvert = new TestClass(); toConvert.integer = 10; toConvert.string = "test"; String converted = typeConverter.toString(TestClass.class, toConvert, null); assertThat(converted).isEqualTo("" + "{" + "\"integer\":10," + "\"string\":\"test\"" + "}"); } @Test void shouldReturnNullWhenToStringAndValueIsNull() { String converted = typeConverter.toString(TestClass.class, null, null); assertThat(converted).isNull(); } @Test void shouldThrowExceptionWhenTypeIsNullAndToString() { assertThatThrownBy(() -> typeConverter.toString(null, null, null)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
KeySetUtils { public static List<String> keySet(KeyGenerator keyGenerator, List<String> keys, KeyGenerator fallbackKeyPrefixGenerator, String fallbackKey) { requireNonNull(keyGenerator, "keyGenerator cannot be null"); requireNonNull(keys, "keys cannot be null"); Set<String> keySet = new LinkedHashSet<>(keyGenerator.computeKeys(keys)); if (fallbackKeyPrefixGenerator != null) { keySet.addAll(fallbackKeyPrefixGenerator.computeKeys(keys)); } if (isNotBlank(fallbackKey)) { keySet.add(fallbackKey); } List<String> result = new ArrayList<>(keySet.size()); keySet.forEach(k -> result.add(k.intern())); return result; } private KeySetUtils(); static List<String> keySet(KeyGenerator keyGenerator, List<String> keys, KeyGenerator fallbackKeyPrefixGenerator, String fallbackKey); }
@Test public void shouldCreateEmptyKeySet() { KeyGenerator keyGenerator = emptyKeyGenerator(); List<String> configurationKeys = emptyList(); KeyGenerator fallbackKeyPrefixGenerator = emptyKeyGenerator(); List<String> keys = KeySetUtils.keySet(keyGenerator, configurationKeys, fallbackKeyPrefixGenerator, null); assertThat(keys).isEmpty(); } @Test public void shouldGenerateKeySet() { KeyGenerator keyGenerator = keyGenerator("fallback", "fallback.p1", "fallback.p1.p2"); List<String> configurationKeys = asList("key", "alternateKey", "duplicate", "duplicate"); KeyGenerator fallbackKeyPrefixGenerator = keyGenerator("fallbackKeyPrefix"); String fallbackKey = "fallbackKey"; List<String> keys = KeySetUtils.keySet(keyGenerator, configurationKeys, fallbackKeyPrefixGenerator, fallbackKey); assertThat(keys).containsSequence( "fallback.key", "fallback.alternateKey", "fallback.duplicate", "fallback.p1.key", "fallback.p1.alternateKey", "fallback.p1.duplicate", "fallback.p1.p2.key", "fallback.p1.p2.alternateKey", "fallback.p1.p2.duplicate", "fallbackKeyPrefix.key", "fallbackKeyPrefix.alternateKey", "fallbackKeyPrefix.duplicate", "fallbackKey" ); }
SpringAnnotationBasedExample { public static void main(String[] args) { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringAnnotationBasedExample.class)) { context.getBean(SpringAnnotationBasedExample.class).run(); } } static void main(String[] args); }
@Test public void shouldExecuteMainWithoutExceptions() { SpringAnnotationBasedExample.main(new String[0]); }
AnnotationMetadataExtractor implements MetadataExtractor { @Override public List<String> getPrefixes(Class<?> configurationType) { Key keyAnnotation = findAnnotation(configurationType, Key.class); String[] prefixes = (keyAnnotation == null) ? null : keyAnnotation.value(); if (prefixes != null && prefixes.length == 0) { prefixes = new String[]{decapitalize(configurationType.getSimpleName())}; } return prefixes == null ? emptyList() : unmodifiableList(asList(prefixes)); } static MetadataExtractor getInstance(); @Override boolean isConfigurationClass(Class<?> clazz); @Override boolean isAbstractConfiguration(Class<?> clazz); @Override boolean isValueConfigurationMethod(Class<?> configurationType, Method method); @Override boolean isSubConfigurationMethod(Class<?> configurationType, Method method); @Override Class<?> getSubConfigurationType(Class<?> configurationType, Method method); @Override boolean isSubConfigurationListMethod(Class<?> configurationType, Method method); @Override Class<?> getSubConfigurationListElementType(Class<?> configurationType, Method method); @Override String getDescription(Class<?> configurationType); @Override String getDescription(Class<?> configurationType, Method method); @Override List<String> getKeys(Class<?> configurationType, Method method); @Override List<String> getPrefixes(Class<?> configurationType); @Override List<String> getPrefixes(Class<?> configurationType, Method method); @Override boolean shouldResetPrefix(Class<?> configurationType, Method method); @Override String getFallbackKey(Class<?> configurationType, Method method); @Override @SuppressWarnings("unchecked") Class<TypeConverter<?>> getTypeConverter(Class<?> configurationType, Method method); @Override String getEncryptionProvider(Class<?> configurationType, Method method); @Override Integer getDefaultSubConfigurationListSize(Class<?> configurationType, Method method); @Override OptionalValue<String> getDefaultValue(Class<?> configurationType, Method method); @Override Map<String, String> getSubConfigurationDefaultValues(Class<?> configurationType, Method method); @Override List<Map<String, String>> getSubConfigurationListDefaultValues(Class<?> configurationType, Method method); @Override Map<String, String> attributes(Class<?> configurationType); @Override Map<String, String> attributes(Class<?> configurationType, Method method); }
@Test public void shouldProvidePrefixForSubConfiguration() { List<String> prefixes = extractor.getPrefixes(TestConfiguration.class, getMethod(TestConfiguration.class, "getSubConfiguration")); assertThat(prefixes).containsSequence("subConfiguration"); prefixes = extractor.getPrefixes(TestConfiguration.class, getMethod(TestConfiguration.class, "getSubConfigurations")); assertThat(prefixes).containsSequence("subConfigurations"); } @Test public void shouldProvidePrefixForSubConfigurationWithPrefix() { List<String> prefixes = extractor.getPrefixes(TestConfiguration.class, getMethod(TestConfiguration.class, "getSubConfigurationWithPrefix")); assertThat(prefixes).isEmpty(); prefixes = extractor.getPrefixes(TestConfiguration.class, getMethod(TestConfiguration.class, "getSubConfigurationWithPrefixList")); assertThat(prefixes).isEmpty(); }
AnnotationMetadataExtractor implements MetadataExtractor { @Override public List<Map<String, String>> getSubConfigurationListDefaultValues(Class<?> configurationType, Method method) { Class<?> subConfigurationClazz = getSubConfigurationListElementType(configurationType, method); Annotation[] defaultsAnnotations = getDefaultsAnnotations(subConfigurationClazz, method); return getDefaultValues(defaultsAnnotations); } static MetadataExtractor getInstance(); @Override boolean isConfigurationClass(Class<?> clazz); @Override boolean isAbstractConfiguration(Class<?> clazz); @Override boolean isValueConfigurationMethod(Class<?> configurationType, Method method); @Override boolean isSubConfigurationMethod(Class<?> configurationType, Method method); @Override Class<?> getSubConfigurationType(Class<?> configurationType, Method method); @Override boolean isSubConfigurationListMethod(Class<?> configurationType, Method method); @Override Class<?> getSubConfigurationListElementType(Class<?> configurationType, Method method); @Override String getDescription(Class<?> configurationType); @Override String getDescription(Class<?> configurationType, Method method); @Override List<String> getKeys(Class<?> configurationType, Method method); @Override List<String> getPrefixes(Class<?> configurationType); @Override List<String> getPrefixes(Class<?> configurationType, Method method); @Override boolean shouldResetPrefix(Class<?> configurationType, Method method); @Override String getFallbackKey(Class<?> configurationType, Method method); @Override @SuppressWarnings("unchecked") Class<TypeConverter<?>> getTypeConverter(Class<?> configurationType, Method method); @Override String getEncryptionProvider(Class<?> configurationType, Method method); @Override Integer getDefaultSubConfigurationListSize(Class<?> configurationType, Method method); @Override OptionalValue<String> getDefaultValue(Class<?> configurationType, Method method); @Override Map<String, String> getSubConfigurationDefaultValues(Class<?> configurationType, Method method); @Override List<Map<String, String>> getSubConfigurationListDefaultValues(Class<?> configurationType, Method method); @Override Map<String, String> attributes(Class<?> configurationType); @Override Map<String, String> attributes(Class<?> configurationType, Method method); }
@Test public void shouldProvideDefaultValuesForSubConfigurationList() { List<Map<String, String>> values = extractor.getSubConfigurationListDefaultValues(TestConfiguration.class, getMethod(TestConfiguration.class, "getSubConfigurations")); assertThat(values).hasSize(2); assertThat(values.get(0)).contains( entry("one", "1"), entry("two", "first")); assertThat(values.get(1)).contains( entry("one", "2"), entry("two", "second")); }
AnnotationMetadataExtractor implements MetadataExtractor { @Override public Map<String, String> getSubConfigurationDefaultValues(Class<?> configurationType, Method method) { if (!isAnnotationDeclaredLocally(method.getReturnType(), DefaultsAnnotation.class)) { return emptyMap(); } Class<?> defaultsAnnotation = findAnnotation(method.getReturnType(), DefaultsAnnotation.class).value(); @SuppressWarnings("unchecked") Annotation annotation = findAnnotation(method, (Class<? extends Annotation>) defaultsAnnotation); return getDefaultValues(annotation); } static MetadataExtractor getInstance(); @Override boolean isConfigurationClass(Class<?> clazz); @Override boolean isAbstractConfiguration(Class<?> clazz); @Override boolean isValueConfigurationMethod(Class<?> configurationType, Method method); @Override boolean isSubConfigurationMethod(Class<?> configurationType, Method method); @Override Class<?> getSubConfigurationType(Class<?> configurationType, Method method); @Override boolean isSubConfigurationListMethod(Class<?> configurationType, Method method); @Override Class<?> getSubConfigurationListElementType(Class<?> configurationType, Method method); @Override String getDescription(Class<?> configurationType); @Override String getDescription(Class<?> configurationType, Method method); @Override List<String> getKeys(Class<?> configurationType, Method method); @Override List<String> getPrefixes(Class<?> configurationType); @Override List<String> getPrefixes(Class<?> configurationType, Method method); @Override boolean shouldResetPrefix(Class<?> configurationType, Method method); @Override String getFallbackKey(Class<?> configurationType, Method method); @Override @SuppressWarnings("unchecked") Class<TypeConverter<?>> getTypeConverter(Class<?> configurationType, Method method); @Override String getEncryptionProvider(Class<?> configurationType, Method method); @Override Integer getDefaultSubConfigurationListSize(Class<?> configurationType, Method method); @Override OptionalValue<String> getDefaultValue(Class<?> configurationType, Method method); @Override Map<String, String> getSubConfigurationDefaultValues(Class<?> configurationType, Method method); @Override List<Map<String, String>> getSubConfigurationListDefaultValues(Class<?> configurationType, Method method); @Override Map<String, String> attributes(Class<?> configurationType); @Override Map<String, String> attributes(Class<?> configurationType, Method method); }
@Test public void shouldProvideDefaultValuesForSubConfiguration() { Map<String, String> values = extractor.getSubConfigurationDefaultValues(TestConfiguration.class, getMethod(TestConfiguration.class, "getSubConfiguration")); assertThat(values).hasSize(2); assertThat(values).contains( entry("one", "1"), entry("two", "the one")); }
AnnotationMetadataExtractor implements MetadataExtractor { @Override public Map<String, String> attributes(Class<?> configurationType) { return AttributesUtils.attributes(getMetaAttributes(configurationType)); } static MetadataExtractor getInstance(); @Override boolean isConfigurationClass(Class<?> clazz); @Override boolean isAbstractConfiguration(Class<?> clazz); @Override boolean isValueConfigurationMethod(Class<?> configurationType, Method method); @Override boolean isSubConfigurationMethod(Class<?> configurationType, Method method); @Override Class<?> getSubConfigurationType(Class<?> configurationType, Method method); @Override boolean isSubConfigurationListMethod(Class<?> configurationType, Method method); @Override Class<?> getSubConfigurationListElementType(Class<?> configurationType, Method method); @Override String getDescription(Class<?> configurationType); @Override String getDescription(Class<?> configurationType, Method method); @Override List<String> getKeys(Class<?> configurationType, Method method); @Override List<String> getPrefixes(Class<?> configurationType); @Override List<String> getPrefixes(Class<?> configurationType, Method method); @Override boolean shouldResetPrefix(Class<?> configurationType, Method method); @Override String getFallbackKey(Class<?> configurationType, Method method); @Override @SuppressWarnings("unchecked") Class<TypeConverter<?>> getTypeConverter(Class<?> configurationType, Method method); @Override String getEncryptionProvider(Class<?> configurationType, Method method); @Override Integer getDefaultSubConfigurationListSize(Class<?> configurationType, Method method); @Override OptionalValue<String> getDefaultValue(Class<?> configurationType, Method method); @Override Map<String, String> getSubConfigurationDefaultValues(Class<?> configurationType, Method method); @Override List<Map<String, String>> getSubConfigurationListDefaultValues(Class<?> configurationType, Method method); @Override Map<String, String> attributes(Class<?> configurationType); @Override Map<String, String> attributes(Class<?> configurationType, Method method); }
@Test public void shouldProvideAttributesForValueProperty() { Map<String, String> attributes = extractor.attributes(TestConfiguration.class, getMethod(TestConfiguration.class, "getUrl")); assertThat(attributes).containsExactly( entry("custom", "url")); } @Test public void shouldProvideAttributesForSubConfigurationProperty() { Map<String, String> attributes = extractor.attributes(TestConfiguration.class, getMethod(TestConfiguration.class, "getSubConfiguration")); assertThat(attributes).containsExactly( entry("custom", "sub-configuration")); } @Test public void shouldProvideAttributesForSubConfigurationListProperty() { Map<String, String> attributes = extractor.attributes(TestConfiguration.class, getMethod(TestConfiguration.class, "getSubConfigurations")); assertThat(attributes).containsExactly( entry("custom", "sub-configuration-list")); } @Test public void shouldProvideAttributesForType() { Map<String, String> attributes = extractor.attributes(TestConfiguration.class); assertThat(attributes).containsExactly( entry("type1", "value1"), entry("type2", "value2")); } @Test public void shouldProvideAttributesForCustomMetaAnnotations() { Map<String, String> attributes = extractor.attributes(TestConfiguration.class, getMethod(TestConfiguration.class, "getCustomMetaAnnotations")); assertThat(attributes).containsOnly( entry("fixed-one", "one"), entry("fixed-two", "two"), entry("custom", "custom-meta"), entry("attribute", "custom-attribute"), entry("another-attribute", "another-custom-attribute") ); }
AttributesExtractor { static Map<String, String> getMetaAttributes(Class<?> clazz) { requireNonNull(clazz, "clazz cannot be null"); return attributesByTypeCache.computeIfAbsent(clazz, c -> getMetaAttributes(getAnnotations(c))); } private AttributesExtractor(); }
@Test public void shouldExtractAttributesFromFixedAnnotation() { Map<String, String> attributes = getMetaAttributes(FixedAttributesUsage.class); assertThat(attributes).containsOnly( entry("one", "value-one"), entry("two", "value-two") ); } @Test public void shouldExtractAttributesFromFixedAnnotationForMethod() { Map<String, String> attributes = getMetaAttributes(getMethod(FixedAttributesUsage.class, "fixedAnnotationOnly")); assertThat(attributes).containsOnly( entry("one", "value-one"), entry("two", "value-two") ); } @Test public void shouldExtractAttributesFromFixedAnnotationAndMetaForMethod() { Map<String, String> attributes = getMetaAttributes(getMethod(FixedAttributesUsage.class, "fixedAnnotationAndMeta")); assertThat(attributes).containsOnly( entry("one", "value-one"), entry("two", "value-two"), entry("another-meta", "anotherValue") ); } @Test public void shouldExtractAttributesFromCustomizableForType() { Map<String, String> attributes = getMetaAttributes(CustomizableValueUsage.class); assertThat(attributes).containsOnly( entry("name", "type-level") ); } @Test public void shouldExtractAttributesFromCustomizableForMethod() { Map<String, String> attributes = getMetaAttributes(getMethod(CustomizableValueUsage.class, "customizableOnly")); assertThat(attributes).containsOnly( entry("name", "method-level") ); } @Test public void shouldExtractAttributesFromCustomizableAndMetaForMethod() { Map<String, String> attributes = getMetaAttributes(getMethod(CustomizableValueUsage.class, "customizableAndMeta")); assertThat(attributes).containsOnly( entry("name", "method-level-with-additional-meta"), entry("another-meta", "anotherValue") ); } @Test public void shouldExtractAttributesFromMultipleAttributesForType() { Map<String, String> attributes = getMetaAttributes(MultipleAttributesUsage.class); assertThat(attributes).containsOnly( entry("first", "first-attribute-value"), entry("second", "second-attribute-value") ); } @Test public void shouldExtractAttributesFromMultipleAttributesForMethod() { Map<String, String> attributes = getMetaAttributes(getMethod(MultipleAttributesUsage.class, "customizableOnly")); assertThat(attributes).containsOnly( entry("first", "first-attribute-value"), entry("second", "second-attribute-value") ); } @Test public void shouldExtractAttributesFromMultipleAttributesAndMetaForMethod() { Map<String, String> attributes = getMetaAttributes(getMethod(MultipleAttributesUsage.class, "customizableAndMeta")); assertThat(attributes).containsOnly( entry("first", "first-attribute-value"), entry("second", "defaultSecondValue"), entry("another-meta", "anotherValue-meta") ); } @Test public void shouldExtractAttributesFromManyAnnotationsForMethod() { Map<String, String> attributes = getMetaAttributes(MultipleAnnotationsUsage.class); assertThat(attributes).containsOnly( entry("one", "value-one"), entry("two", "value-two"), entry("name", "custom-value"), entry("first", "first"), entry("second", "second"), entry("meta", "custom-meta") ); } @Test public void shouldFindAllMetaDataInTheHierarchy() { Map<String, String> attributes; attributes = getMetaAttributes(BaseConfiguration.class); assertThat(attributes).containsOnly( entry("name", "type-base"), entry("base", "type-base") ); attributes = getMetaAttributes(ChildConfiguration.class); assertThat(attributes).containsOnly( entry("name", "type-child"), entry("base", "type-base"), entry("child", "type-base") ); attributes = getMetaAttributes(getMethod(BaseConfiguration.class, "getValue")); assertThat(attributes).containsOnly( entry("name", "property-base"), entry("meta", "property-base") ); attributes = getMetaAttributes(getMethod(ChildConfiguration.class, "getAnotherValue")); assertThat(attributes).containsOnly( entry("name", "another-property-child") ); attributes = getMetaAttributes(getMethod(ChildConfiguration.class, "getAnotherValue")); assertThat(attributes).containsOnly( entry("name", "another-property-child") ); } @Test public void shouldFailIfNotAllAttributesAreAnnotated() { assertThrows(IllegalArgumentException.class, () -> getMetaAttributes(NotAllAttributesAreAnnotatedUsage.class), "All @com.sabre.oss.conf4j.internal.model.provider.annotation.AttributesExtractorTest$NotAllAttributesAreAnnotated(annotated=annotatedValue, notAnnotated=notAnnotatedValue) " + "annotations attributes must be annotated with @com.sabre.oss.conf4j.annotation.Meta." ); } @Test public void shouldFailIfMoreThanAttributeIsDefined() { assertThrows(IllegalArgumentException.class, () -> getMetaAttributes(TooManyAttributesUsage.class), "@com.sabre.oss.conf4j.internal.model.provider.annotation.AttributesExtractorTest$TooManyAttributes(attribute=attribute, anotherAttribute=anotherAttribute) " + "annotation is meta-annotated with @com.sabre.oss.conf4j.annotation.Meta and define more than one attribute: " + "anotherAttribute, attribute " ); } @Test public void shouldFailIfInvalidAttributeType() { assertThrows(IllegalArgumentException.class, () -> getMetaAttributes(InvalidAttributeTypeUsage.class), "@com.sabre.oss.conf4j.internal.model.provider.annotation.AttributesExtractorTest$InvalidAttributeType(attribute=[1, 2]) " + "annotation is meta-annotated with @com.sabre.oss.conf4j.annotation.Meta and its attribute 'attribute' " + "type is [Ljava.lang.String;. Only scalar, simple types are supported." ); }
SpringExample { public static void main(String[] args) { new SpringExample().run(); } static void main(String[] args); }
@Test public void shouldExecuteMainWithoutExceptions() { SpringExample.main(new String[0]); }
CoreExample { public static void main(String[] args) { new CoreExample().run(); } static void main(String[] args); }
@Test public void shouldExecuteMainWithoutExceptions() { CoreExample.main(new String[0]); }
MethodsProvider { public Collection<Method> getAllDeclaredMethods(Class<?> configurationType) { Class<?> type = configurationType; Set<MethodWrapper> methods = new LinkedHashSet<>(addMethods(type.getMethods())); if (type.getSuperclass() != null) { do { methods.addAll(addMethods(type.getDeclaredMethods())); type = type.getSuperclass(); } while (!Object.class.equals(type)); } return methods.stream() .map(MethodWrapper::getMethod) .collect(toList()); } Collection<Method> getAllDeclaredMethods(Class<?> configurationType); }
@Test public void shouldFindPublicAbstractMethodInClass() throws NoSuchMethodException { abstract class TestClass { public abstract int propertyA(); } Collection<Method> methods = methodsProvider.getAllDeclaredMethods(TestClass.class); assertThat(methods).contains(TestClass.class.getMethod("propertyA")); } @Test public void shouldFindPublicAbstractMethodInheritedFromAbstractMethod() throws NoSuchMethodException { abstract class AbstractClass { public abstract int propertyA(); } abstract class TestClass extends AbstractClass { public abstract int propertyB(); } Collection<Method> methods = methodsProvider.getAllDeclaredMethods(TestClass.class); assertThat(methods).contains(AbstractClass.class.getMethod("propertyA"), TestClass.class.getMethod("propertyB")); } @Test public void shouldFindMethodInheritedFromInterface() throws NoSuchMethodException { abstract class TestClass implements TestInterface { public abstract int propertyB(); } Collection<Method> methods = methodsProvider.getAllDeclaredMethods(TestClass.class); assertThat(methods).contains(TestInterface.class.getMethod("propertyA"), TestClass.class.getMethod("propertyB")); } @Test public void shouldHandleMethodFromSubclass() throws NoSuchMethodException { abstract class BaseConf { public abstract Integer propertyA(); } abstract class SpecificConf extends BaseConf { @Override public abstract Integer propertyA(); } abstract class AbstractClass { public abstract BaseConf propertyB(); } abstract class TestClass extends AbstractClass { @Override public abstract SpecificConf propertyB(); } Collection<Method> methods = methodsProvider.getAllDeclaredMethods(TestClass.class); assertThat(methods).contains(TestClass.class.getMethod("propertyB")); }
DefaultConfigurationValueProvider implements ConfigurationValueProvider { @Override public <T> OptionalValue<T> getConfigurationValue(TypeConverter<T> typeConverter, ConfigurationSource configurationSource, PropertyMetadata metadata) { requireNonNull(typeConverter, "typeConverter cannot be null"); requireNonNull(metadata, "metadata cannot be null"); OptionalValue<String> value = absent(); String resolvedKey = null; Map<String, String> attributes = metadata.getAttributes(); if (configurationSource != null) { ConfigurationEntry configurationEntry = configurationSource.findEntry(metadata.getKeySet(), attributes); if (configurationEntry != null) { resolvedKey = configurationEntry.getKey(); value = present(configurationEntry.getValue()); } } boolean fromDefaultValue = value.isAbsent(); if (fromDefaultValue) { value = metadata.getDefaultValue(); } if (value.isAbsent()) { return absent(); } String resolvedValue = value.get(); String val = applyProcessors(new ConfigurationValue(resolvedKey, resolvedValue, fromDefaultValue, metadata.getEncryptionProvider(), attributes)); @SuppressWarnings("unchecked") TypeConverter<T> currentTypeConverter = defaultIfNull((TypeConverter<T>) metadata.getTypeConverter(), typeConverter); return present(currentTypeConverter.fromString(metadata.getType(), val, attributes)); } DefaultConfigurationValueProvider(List<ConfigurationValueProcessor> configurationValueProcessors); @Override OptionalValue<T> getConfigurationValue(TypeConverter<T> typeConverter, ConfigurationSource configurationSource, PropertyMetadata metadata); }
@Test public void shouldReturnFromFallbackKey() { when(source.getValue("fallback.p1.p2.key", null)).thenReturn(present("value")); OptionalValue<String> result = provider.getConfigurationValue(typeConverter, source, metadata(getKeySet(), defaultValue, notEncrypted)); assertThat(result).isEqualTo(present("value")); } @Test public void shouldReturnFromFallbackAlternateKey() { when(source.getValue("fallback.p1.p2.alternateKey", null)).thenReturn(present("value")); OptionalValue<String> result = provider.getConfigurationValue(typeConverter, source, metadata(getKeySet(), defaultValue, notEncrypted)); assertThat(result).isEqualTo(present("value")); } @Test public void shouldReturnFromFallbackPrefix() { when(source.getValue("fallback.key", null)).thenReturn(present("value")); OptionalValue<String> result = provider.getConfigurationValue(typeConverter, source, metadata(getKeySet(), defaultValue, notEncrypted)); assertThat(result).isEqualTo(present("value")); } @Test public void shouldReturnFromFallbackKeyPrefix() { Mockito.lenient().when(source.getValue("fallbackKeyPrefix.key", null)).thenReturn(present("value")); OptionalValue<String> result = provider.getConfigurationValue(typeConverter, source, metadata(getKeySet(), defaultValue, notEncrypted)); assertThat(result).isEqualTo(present("value")); } @Test public void shouldNotReturnFallbackKeyPrefixValueWhenFallbackKeyPrefixIsEmpty() { Mockito.lenient().when(source.getValue(".key", null)).thenReturn(present("value")); fallbackKeyPrefixGenerator = emptyKeyGenerator(); OptionalValue<String> result = provider.getConfigurationValue(typeConverter, source, metadata(getKeySet(), defaultValue, notEncrypted)); assertThat(result).isEqualTo(present("methodDefaultValue")); } @Test public void shouldReturnFallbackKeyValue() { when(source.getValue("fallbackKey", null)).thenReturn(present("value")); OptionalValue<String> result = provider.getConfigurationValue(typeConverter, source, metadata(getKeySet(), defaultValue, notEncrypted)); assertThat(result).isEqualTo(present("value")); } @Test public void shouldNotReturnFallbackKeyValueWhenFallbackKeyIsEmpty() { Mockito.lenient().when(source.getValue("", null)).thenReturn(present("value")); fallbackKey = null; OptionalValue<String> result = provider.getConfigurationValue(typeConverter, source, metadata(getKeySet(), defaultValue, notEncrypted)); assertThat(result).isEqualTo(present("methodDefaultValue")); } @Test public void shouldReturnMethodDefaultValue() { OptionalValue<String> result = provider.getConfigurationValue(typeConverter, source, metadata(getKeySet(), defaultValue, notEncrypted)); assertThat(result).isEqualTo(present("methodDefaultValue")); } @Test public void shouldCallValueProcessor() { ConfigurationValueProcessor configurationValueProcessor = mock(ConfigurationValueProcessor.class); when(configurationValueProcessor.process(any(ConfigurationValue.class))).thenAnswer(invocation -> invocation.getArguments()[0]); when(source.getValue("fallback.key", null)).thenReturn(present("fallback.key")); provider = new DefaultConfigurationValueProvider(singletonList(configurationValueProcessor)); provider.getConfigurationValue(typeConverter, source, metadata(getKeySet(), defaultValue, notEncrypted)); verify(configurationValueProcessor, times(1)).process(any(ConfigurationValue.class)); }
PropertySourceConfigurationSource implements ConfigurationSource, BeanFactoryAware, EnvironmentAware, InitializingBean { @Override public OptionalValue<String> getValue(String key, Map<String, String> attributes) { requireNonNull(key, "key cannot be null"); for (PropertySource<?> propertySource : flattenedPropertySources) { OptionalValue<String> value = getProperty(propertySource, key); if (value.isPresent()) { return value; } } return absent(); } void setPropertySources(PropertySources propertySources); @Override void setBeanFactory(BeanFactory beanFactory); @Override void setEnvironment(Environment environment); void setConversionService(ConversionService conversionService); @Override void afterPropertiesSet(); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override ConfigurationEntry findEntry(Collection<String> keys, Map<String, String> attributes); }
@Test public void shouldResolvePropertyPlaceholdersSetWithCorrectOrder() { assertThat(source.getValue("property.only.in.A", null)).isEqualTo(present("A")); assertThat(source.getValue("property.only.in.B", null)).isEqualTo(present("B")); assertThat(source.getValue("property.in.A.and.B", null)).isEqualTo(present("B")); }
AttributesUtils implements Serializable { public static Map<String, String> attributes(Map<String, String> attributes) { return getCached(attributes, true); } private AttributesUtils(); static Map<String, String> attributes(Map<String, String> attributes); static Map<String, String> mergeAttributes(Map<String, String> parent, Map<String, String> child); }
@Test public void shouldReturnNullWhenPropertiesAreNull() { Map<String, String> properties = null; Map<String, String> attributes = attributes(properties); assertThat(attributes).isNull(); } @Test public void shouldConstructFromMap() { Map<String, String> properties = MapUtils.of("key1", "val1", "key2", "val2"); Map<String, String> attributes = attributes(properties); assertThat(attributes).isNotNull(); assertThat(attributes).contains(entry("key1", "val1"), entry("key2", "val2")); } @Test public void shouldBeImmutable() { assertThrows(UnsupportedOperationException.class, () -> attributes(MapUtils.of("key", "value")).put("anything", "value") ); } @Test public void shouldProvideSameInstanceForSameProperties() { Map<String, String> properties = MapUtils.of("key1", "value1", "key2", "value2"); Map<String, String> sameProperties = new HashMap<>(properties); Map<String, String> attributes = attributes(properties); Map<String, String> attributesForSameProperties = attributes(sameProperties); assertThat(attributesForSameProperties).isSameAs(attributes); }
AttributesUtils implements Serializable { public static Map<String, String> mergeAttributes(Map<String, String> parent, Map<String, String> child) { if (parent == null) { return getCached(child, true); } if (child == null) { return getCached(parent, true); } Map<String, String> merged = new LinkedHashMap<>(parent.size() + child.size()); merged.putAll(parent); merged.putAll(child); return getCached(unmodifiableMap(merged), false); } private AttributesUtils(); static Map<String, String> attributes(Map<String, String> attributes); static Map<String, String> mergeAttributes(Map<String, String> parent, Map<String, String> child); }
@Test public void shouldMergeToNullWhenBothAreNull() { Map<String, String> merged = mergeAttributes(null, null); assertThat(merged).isNull(); }
CachingTypeConverter implements TypeConverter<T>, InitializingBean { @SuppressWarnings("unchecked") @Override public T fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); SimpleKey key = new SimpleKey(type, attributes, value); ValueWrapper valueWrapper = cache.get(key); if (valueWrapper != null) { return (T) valueWrapper.get(); } else { T val = typeConverter.fromString(type, value, attributes); valueWrapper = cache.putIfAbsent(key, val); if (valueWrapper == null) { return val; } else { return (T) valueWrapper.get(); } } } TypeConverter<?> getTypeConverter(); void setTypeConverter(TypeConverter<T> typeConverter); CacheManager getCacheManager(); void setCacheManager(CacheManager cacheManager); String getCacheName(); void setCacheName(String cacheName); @Override void afterPropertiesSet(); @Override boolean isApplicable(Type type, Map<String, String> attributes); @SuppressWarnings("unchecked") @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }
@Test public void shouldIntegrateWithSpring() { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class)) { TypeConverter<?> typeConverter = context.getBean(TypeConverter.class); assertThat(typeConverter).isInstanceOf(CachingTypeConverter.class); Long val = (Long) typeConverter.fromString(Long.class, "10", null); Long val2 = (Long) typeConverter.fromString(Long.class, "10", null); assertThat(val).isEqualTo(10L); assertThat(val2).isSameAs(val); SampleConfiguration configuration = context.getBean(SampleConfiguration.class); Long valueFromConfiguration = configuration.getValue(); assertThat(valueFromConfiguration).isEqualTo(10L); assertThat(valueFromConfiguration).isSameAs(val); } }
PropertyUtils { public static Object getProperty(Object bean, String name) { requireNonNull(bean, "bean cannot be null"); requireNonNull(name, "name cannot be null"); Class<?> beanClass = bean.getClass(); try { PropertyDescriptor descriptor = findPropertyDescriptor(beanClass, name); Method readMethod = descriptor.getReadMethod(); return readMethod.invoke(bean, EMPTY_OBJECT_ARRAY); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalArgumentException("Unable to get property " + name + " on " + bean.getClass(), e); } } private PropertyUtils(); static String getPropertyName(Method method); static Object getProperty(Object bean, String name); static void setProperty(Object bean, String name, Object value); }
@Test public void shouldGetProperties() { Bean bean = new Bean(); assertThat(getProperty(bean, "intValue")).isEqualTo(0); assertThat(getProperty(bean, "stringValue")).isNull(); assertThat(getProperty(bean, "beanValue")).isNull(); bean.setIntValue(1); assertThat(getProperty(bean, "intValue")).isEqualTo(bean.getIntValue()); bean.setStringValue("string"); assertThat(getProperty(bean, "stringValue")).isSameAs(bean.getStringValue()); bean.setBeanValue(new Bean()); assertThat(getProperty(bean, "beanValue")).isSameAs(bean.getBeanValue()); } @Test public void getPropertyShouldThrowNoSuchMethodExceptionWhenPropertyNotFound() { assertThrows(IllegalArgumentException.class, () -> getProperty(new Bean(), "unknownProperty")); } @Test public void getPropertyShouldThrowNoSuchMethodExceptionWhenPropertyIsCapitalized() { assertThrows(IllegalArgumentException.class, () -> getProperty(new Bean(), "BeanValue")); } @Test public void getPropertyShouldThrowNullPointerExceptionWhenNullBean() { assertThrows(NullPointerException.class, () -> getProperty(null, "intValue")); } @Test public void getPropertyShouldThrowNullPointerExceptionWhenNullPropertyName() { assertThrows(NullPointerException.class, () -> getProperty(new Bean(), null)); }