src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
StringUtils { public static String newStringUtf16(final byte[] bytes) { return new String(bytes, Charsets.UTF_16); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }
@Test public void testNewStringUtf16() throws UnsupportedEncodingException { final String charsetName = "UTF-16"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE, charsetName); final String actual = StringUtils.newStringUtf16(BYTES_FIXTURE); Assert.assertEquals(expected, actual); }
LessThanOp extends Param1Op { @Override public String keyword() { return "LessThan"; } @Override String keyword(); @Override String operator(); }
@Test public void test() throws Exception { Op op = new LessThanOp(); assertThat(op.keyword(), equalTo("LessThan")); assertThat(op.paramCount(), equalTo(1)); assertThat(op.render("id", new String[] {":1"}), equalTo("id < :1")); }
StringUtils { public static String newStringUtf16Be(final byte[] bytes) { return new String(bytes, Charsets.UTF_16BE); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }
@Test public void testNewStringUtf16Be() throws UnsupportedEncodingException { final String charsetName = "UTF-16BE"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE_16BE, charsetName); final String actual = StringUtils.newStringUtf16Be(BYTES_FIXTURE_16BE); Assert.assertEquals(expected, actual); }
StringUtils { public static String newStringUtf16Le(final byte[] bytes) { return new String(bytes, Charsets.UTF_16LE); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }
@Test public void testNewStringUtf16Le() throws UnsupportedEncodingException { final String charsetName = "UTF-16LE"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE_16LE, charsetName); final String actual = StringUtils.newStringUtf16Le(BYTES_FIXTURE_16LE); Assert.assertEquals(expected, actual); }
StringUtils { public static String newStringUtf8(final byte[] bytes) { return newString(bytes, Charsets.UTF_8); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }
@Test public void testNewStringUtf8() throws UnsupportedEncodingException { final String charsetName = "UTF-8"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE, charsetName); final String actual = StringUtils.newStringUtf8(BYTES_FIXTURE); Assert.assertEquals(expected, actual); }
BaseNCodec implements BinaryEncoder, BinaryDecoder { protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength) { this(unencodedBlockSize, encodedBlockSize, lineLength, chunkSeparatorLength, PAD_DEFAULT); } protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength); protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength, final byte pad); @Override Object encode(final Object obj); String encodeToString(final byte[] pArray); String encodeAsString(final byte[] pArray); @Override Object decode(final Object obj); byte[] decode(final String pArray); @Override byte[] decode(final byte[] pArray); @Override byte[] encode(final byte[] pArray); boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad); boolean isInAlphabet(final String basen); long getEncodedLength(final byte[] pArray); static final int MIME_CHUNK_SIZE; static final int PEM_CHUNK_SIZE; }
@Test public void testBaseNCodec() { assertNotNull(codec); }
BaseNCodec implements BinaryEncoder, BinaryDecoder { protected static boolean isWhiteSpace(final byte byteToCheck) { switch (byteToCheck) { case ' ' : case '\n' : case '\r' : case '\t' : return true; default : return false; } } protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength); protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength, final byte pad); @Override Object encode(final Object obj); String encodeToString(final byte[] pArray); String encodeAsString(final byte[] pArray); @Override Object decode(final Object obj); byte[] decode(final String pArray); @Override byte[] decode(final byte[] pArray); @Override byte[] encode(final byte[] pArray); boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad); boolean isInAlphabet(final String basen); long getEncodedLength(final byte[] pArray); static final int MIME_CHUNK_SIZE; static final int PEM_CHUNK_SIZE; }
@Test public void testIsWhiteSpace() { assertTrue(BaseNCodec.isWhiteSpace((byte) ' ')); assertTrue(BaseNCodec.isWhiteSpace((byte) '\n')); assertTrue(BaseNCodec.isWhiteSpace((byte) '\r')); assertTrue(BaseNCodec.isWhiteSpace((byte) '\t')); }
BaseNCodec implements BinaryEncoder, BinaryDecoder { protected abstract boolean isInAlphabet(byte value); protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength); protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength, final byte pad); @Override Object encode(final Object obj); String encodeToString(final byte[] pArray); String encodeAsString(final byte[] pArray); @Override Object decode(final Object obj); byte[] decode(final String pArray); @Override byte[] decode(final byte[] pArray); @Override byte[] encode(final byte[] pArray); boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad); boolean isInAlphabet(final String basen); long getEncodedLength(final byte[] pArray); static final int MIME_CHUNK_SIZE; static final int PEM_CHUNK_SIZE; }
@Test public void testIsInAlphabetByte() { assertFalse(codec.isInAlphabet((byte) 0)); assertFalse(codec.isInAlphabet((byte) 'a')); assertTrue(codec.isInAlphabet((byte) 'O')); assertTrue(codec.isInAlphabet((byte) 'K')); } @Test public void testIsInAlphabetByteArrayBoolean() { assertTrue(codec.isInAlphabet(new byte[]{}, false)); assertTrue(codec.isInAlphabet(new byte[]{'O'}, false)); assertFalse(codec.isInAlphabet(new byte[]{'O',' '}, false)); assertFalse(codec.isInAlphabet(new byte[]{' '}, false)); assertTrue(codec.isInAlphabet(new byte[]{}, true)); assertTrue(codec.isInAlphabet(new byte[]{'O'}, true)); assertTrue(codec.isInAlphabet(new byte[]{'O',' '}, true)); assertTrue(codec.isInAlphabet(new byte[]{' '}, true)); } @Test public void testIsInAlphabetString() { assertTrue(codec.isInAlphabet("OK")); assertTrue(codec.isInAlphabet("O=K= \t\n\r")); }
BaseNCodec implements BinaryEncoder, BinaryDecoder { protected boolean containsAlphabetOrPad(final byte[] arrayOctet) { if (arrayOctet == null) { return false; } for (final byte element : arrayOctet) { if (pad == element || isInAlphabet(element)) { return true; } } return false; } protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength); protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength, final byte pad); @Override Object encode(final Object obj); String encodeToString(final byte[] pArray); String encodeAsString(final byte[] pArray); @Override Object decode(final Object obj); byte[] decode(final String pArray); @Override byte[] decode(final byte[] pArray); @Override byte[] encode(final byte[] pArray); boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad); boolean isInAlphabet(final String basen); long getEncodedLength(final byte[] pArray); static final int MIME_CHUNK_SIZE; static final int PEM_CHUNK_SIZE; }
@Test public void testContainsAlphabetOrPad() { assertFalse(codec.containsAlphabetOrPad(null)); assertFalse(codec.containsAlphabetOrPad(new byte[]{})); assertTrue(codec.containsAlphabetOrPad("OK".getBytes())); assertTrue(codec.containsAlphabetOrPad("OK ".getBytes())); assertFalse(codec.containsAlphabetOrPad("ok ".getBytes())); assertTrue(codec.containsAlphabetOrPad(new byte[]{codec.pad})); }
Base64 extends BaseNCodec { public static boolean isBase64(final byte octet) { return octet == PAD_DEFAULT || (octet >= 0 && octet < DECODE_TABLE.length && DECODE_TABLE[octet] != -1); } Base64(); Base64(final boolean urlSafe); Base64(final int lineLength); Base64(final int lineLength, final byte[] lineSeparator); Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); boolean isUrlSafe(); @Deprecated static boolean isArrayByteBase64(final byte[] arrayOctet); static boolean isBase64(final byte octet); static boolean isBase64(final String base64); static boolean isBase64(final byte[] arrayOctet); static byte[] encodeBase64(final byte[] binaryData); static String encodeBase64String(final byte[] binaryData); static byte[] encodeBase64URLSafe(final byte[] binaryData); static String encodeBase64URLSafeString(final byte[] binaryData); static byte[] encodeBase64Chunked(final byte[] binaryData); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); static byte[] decodeBase64(final String base64String); static byte[] decodeBase64(final byte[] base64Data); static BigInteger decodeInteger(final byte[] pArray); static byte[] encodeInteger(final BigInteger bigInt); }
@Test public void testIsStringBase64() { final String nullString = null; final String emptyString = ""; final String validString = "abc===defg\n\r123456\r789\r\rABC\n\nDEF==GHI\r\nJKL=============="; final String invalidString = validString + (char)0; try { Base64.isBase64(nullString); fail("Base64.isStringBase64() should not be null-safe."); } catch (final NullPointerException npe) { assertNotNull("Base64.isStringBase64() should not be null-safe.", npe); } assertTrue("Base64.isStringBase64(empty-string) is true", Base64.isBase64(emptyString)); assertTrue("Base64.isStringBase64(valid-string) is true", Base64.isBase64(validString)); assertFalse("Base64.isStringBase64(invalid-string) is false", Base64.isBase64(invalidString)); }
EqualsOp extends Param1Op { @Override public String keyword() { return "Equals"; } @Override String keyword(); @Override String operator(); }
@Test public void test() throws Exception { Op op = new EqualsOp(); assertThat(op.keyword(), equalTo("Equals")); assertThat(op.paramCount(), equalTo(1)); assertThat(op.render("id", new String[] {":1"}), equalTo("id = :1")); }
Base64 extends BaseNCodec { public Base64() { this(0); } Base64(); Base64(final boolean urlSafe); Base64(final int lineLength); Base64(final int lineLength, final byte[] lineSeparator); Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); boolean isUrlSafe(); @Deprecated static boolean isArrayByteBase64(final byte[] arrayOctet); static boolean isBase64(final byte octet); static boolean isBase64(final String base64); static boolean isBase64(final byte[] arrayOctet); static byte[] encodeBase64(final byte[] binaryData); static String encodeBase64String(final byte[] binaryData); static byte[] encodeBase64URLSafe(final byte[] binaryData); static String encodeBase64URLSafeString(final byte[] binaryData); static byte[] encodeBase64Chunked(final byte[] binaryData); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); static byte[] decodeBase64(final String base64String); static byte[] decodeBase64(final byte[] base64Data); static BigInteger decodeInteger(final byte[] pArray); static byte[] encodeInteger(final BigInteger bigInt); }
@Test public void testBase64() { final String content = "Hello World"; String encodedContent; byte[] encodedBytes = Base64.encodeBase64(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); Base64 b64 = new Base64(BaseNCodec.MIME_CHUNK_SIZE, null); encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); b64 = new Base64(0, null); encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); final byte[] decode = b64.decode("SGVsbG{\u00e9\u00e9\u00e9\u00e9\u00e9\u00e9}8gV29ybGQ="); final String decodeString = StringUtils.newStringUtf8(decode); assertEquals("decode hello world", "Hello World", decodeString); }
Base64 extends BaseNCodec { public static byte[] decodeBase64(final String base64String) { return new Base64().decode(base64String); } Base64(); Base64(final boolean urlSafe); Base64(final int lineLength); Base64(final int lineLength, final byte[] lineSeparator); Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); boolean isUrlSafe(); @Deprecated static boolean isArrayByteBase64(final byte[] arrayOctet); static boolean isBase64(final byte octet); static boolean isBase64(final String base64); static boolean isBase64(final byte[] arrayOctet); static byte[] encodeBase64(final byte[] binaryData); static String encodeBase64String(final byte[] binaryData); static byte[] encodeBase64URLSafe(final byte[] binaryData); static String encodeBase64URLSafeString(final byte[] binaryData); static byte[] encodeBase64Chunked(final byte[] binaryData); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); static byte[] decodeBase64(final String base64String); static byte[] decodeBase64(final byte[] base64Data); static BigInteger decodeInteger(final byte[] pArray); static byte[] encodeInteger(final BigInteger bigInt); }
@Test public void testDecodeWithInnerPad() { final String content = "SGVsbG8gV29ybGQ=SGVsbG8gV29ybGQ="; final byte[] result = Base64.decodeBase64(content); final byte[] shouldBe = StringUtils.getBytesUtf8("Hello World"); assertTrue("decode should halt at pad (=)", Arrays.equals(result, shouldBe)); } @Test public void testCodec68() { final byte[] x = new byte[]{'n', 'A', '=', '=', (byte) 0x9c}; Base64.decodeBase64(x); } @Test public void testDecodePadMarkerIndex2() { assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes(Charsets.UTF_8)))); } @Test public void testDecodePadMarkerIndex3() { assertEquals("AA", new String(Base64.decodeBase64("QUE=".getBytes(Charsets.UTF_8)))); assertEquals("AAA", new String(Base64.decodeBase64("QUFB".getBytes(Charsets.UTF_8)))); } @Test public void testDecodePadOnly() { assertEquals(0, Base64.decodeBase64("====".getBytes(Charsets.UTF_8)).length); assertEquals("", new String(Base64.decodeBase64("====".getBytes(Charsets.UTF_8)))); assertEquals(0, Base64.decodeBase64("===".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("==".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("=".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("".getBytes(Charsets.UTF_8)).length); } @Test public void testDecodePadOnlyChunked() { assertEquals(0, Base64.decodeBase64("====\n".getBytes(Charsets.UTF_8)).length); assertEquals("", new String(Base64.decodeBase64("====\n".getBytes(Charsets.UTF_8)))); assertEquals(0, Base64.decodeBase64("===\n".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("==\n".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("=\n".getBytes(Charsets.UTF_8)).length); assertEquals(0, Base64.decodeBase64("\n".getBytes(Charsets.UTF_8)).length); } @Test public void testIgnoringNonBase64InDecode() throws Exception { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 .decodeBase64("VGhlIH@$#$@%F1aWN@#@#@@rIGJyb3duIGZve\n\r\t%#%#%#%CBqd##$#$W1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes(Charsets.UTF_8)))); } @Test public void testKnownDecodings() { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 .decodeBase64("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes(Charsets.UTF_8)))); assertEquals("It was the best of times, it was the worst of times.", new String(Base64 .decodeBase64("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes(Charsets.UTF_8)))); assertEquals("http: .decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes(Charsets.UTF_8)))); assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64 .decodeBase64("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes(Charsets.UTF_8)))); assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=" .getBytes(Charsets.UTF_8)))); assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes(Charsets.UTF_8)))); } @Test public void testRfc4648Section10Decode() { assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64(""))); assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg=="))); assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8="))); assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v"))); assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg=="))); assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE="))); assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy"))); } @Test public void testRfc4648Section10DecodeWithCrLf() { final String CRLF = StringUtils.newStringUsAscii(Base64.CHUNK_SEPARATOR); assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64("" + CRLF))); assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg==" + CRLF))); assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8=" + CRLF))); assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v" + CRLF))); assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg==" + CRLF))); assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE=" + CRLF))); assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy" + CRLF))); } @Test public void testUrlSafe() { for (int i = 0; i <= 150; i++) { final byte[][] randomData = Base64TestData.randomData(i, true); final byte[] encoded = randomData[1]; final byte[] decoded = randomData[0]; final byte[] result = Base64.decodeBase64(encoded); assertTrue("url-safe i=" + i, Arrays.equals(decoded, result)); assertFalse("url-safe i=" + i + " no '='", Base64TestData.bytesContain(encoded, (byte) '=')); assertFalse("url-safe i=" + i + " no '\\'", Base64TestData.bytesContain(encoded, (byte) '\\')); assertFalse("url-safe i=" + i + " no '+'", Base64TestData.bytesContain(encoded, (byte) '+')); } }
Base64 extends BaseNCodec { public static byte[] encodeBase64(final byte[] binaryData) { return encodeBase64(binaryData, false); } Base64(); Base64(final boolean urlSafe); Base64(final int lineLength); Base64(final int lineLength, final byte[] lineSeparator); Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); boolean isUrlSafe(); @Deprecated static boolean isArrayByteBase64(final byte[] arrayOctet); static boolean isBase64(final byte octet); static boolean isBase64(final String base64); static boolean isBase64(final byte[] arrayOctet); static byte[] encodeBase64(final byte[] binaryData); static String encodeBase64String(final byte[] binaryData); static byte[] encodeBase64URLSafe(final byte[] binaryData); static String encodeBase64URLSafeString(final byte[] binaryData); static byte[] encodeBase64Chunked(final byte[] binaryData); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); static byte[] decodeBase64(final String base64String); static byte[] decodeBase64(final byte[] base64Data); static BigInteger decodeInteger(final byte[] pArray); static byte[] encodeInteger(final BigInteger bigInt); }
@Test public void testChunkedEncodeMultipleOf76() { final byte[] expectedEncode = Base64.encodeBase64(Base64TestData.DECODED, true); final String actualResult = Base64TestData.ENCODED_76_CHARS_PER_LINE.replaceAll("\n", "\r\n"); final byte[] actualEncode = StringUtils.getBytesUtf8(actualResult); assertTrue("chunkedEncodeMultipleOf76", Arrays.equals(expectedEncode, actualEncode)); } @Test public void testCodec112() { final byte[] in = new byte[] {0}; final byte[] out=Base64.encodeBase64(in); Base64.encodeBase64(in, false, false, out.length); } @Test public void testTriplets() { assertEquals("AAAA", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 0}))); assertEquals("AAAB", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 1}))); assertEquals("AAAC", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 2}))); assertEquals("AAAD", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 3}))); assertEquals("AAAE", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 4}))); assertEquals("AAAF", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 5}))); assertEquals("AAAG", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 6}))); assertEquals("AAAH", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 7}))); assertEquals("AAAI", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 8}))); assertEquals("AAAJ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 9}))); assertEquals("AAAK", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 10}))); assertEquals("AAAL", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 11}))); assertEquals("AAAM", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 12}))); assertEquals("AAAN", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 13}))); assertEquals("AAAO", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 14}))); assertEquals("AAAP", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 15}))); assertEquals("AAAQ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 16}))); assertEquals("AAAR", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 17}))); assertEquals("AAAS", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 18}))); assertEquals("AAAT", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 19}))); assertEquals("AAAU", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 20}))); assertEquals("AAAV", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 21}))); assertEquals("AAAW", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 22}))); assertEquals("AAAX", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 23}))); assertEquals("AAAY", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 24}))); assertEquals("AAAZ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 25}))); assertEquals("AAAa", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 26}))); assertEquals("AAAb", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 27}))); assertEquals("AAAc", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 28}))); assertEquals("AAAd", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 29}))); assertEquals("AAAe", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 30}))); assertEquals("AAAf", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 31}))); assertEquals("AAAg", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 32}))); assertEquals("AAAh", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 33}))); assertEquals("AAAi", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 34}))); assertEquals("AAAj", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 35}))); assertEquals("AAAk", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 36}))); assertEquals("AAAl", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 37}))); assertEquals("AAAm", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 38}))); assertEquals("AAAn", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 39}))); assertEquals("AAAo", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 40}))); assertEquals("AAAp", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 41}))); assertEquals("AAAq", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 42}))); assertEquals("AAAr", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 43}))); assertEquals("AAAs", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 44}))); assertEquals("AAAt", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 45}))); assertEquals("AAAu", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 46}))); assertEquals("AAAv", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 47}))); assertEquals("AAAw", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 48}))); assertEquals("AAAx", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 49}))); assertEquals("AAAy", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 50}))); assertEquals("AAAz", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 51}))); assertEquals("AAA0", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 52}))); assertEquals("AAA1", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 53}))); assertEquals("AAA2", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 54}))); assertEquals("AAA3", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 55}))); assertEquals("AAA4", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 56}))); assertEquals("AAA5", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 57}))); assertEquals("AAA6", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 58}))); assertEquals("AAA7", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 59}))); assertEquals("AAA8", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 60}))); assertEquals("AAA9", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 61}))); assertEquals("AAA+", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 62}))); assertEquals("AAA/", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 63}))); }
Base64 extends BaseNCodec { public static byte[] encodeInteger(final BigInteger bigInt) { if (bigInt == null) { throw new NullPointerException("encodeInteger called with null parameter"); } return encodeBase64(toIntegerBytes(bigInt), false); } Base64(); Base64(final boolean urlSafe); Base64(final int lineLength); Base64(final int lineLength, final byte[] lineSeparator); Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); boolean isUrlSafe(); @Deprecated static boolean isArrayByteBase64(final byte[] arrayOctet); static boolean isBase64(final byte octet); static boolean isBase64(final String base64); static boolean isBase64(final byte[] arrayOctet); static byte[] encodeBase64(final byte[] binaryData); static String encodeBase64String(final byte[] binaryData); static byte[] encodeBase64URLSafe(final byte[] binaryData); static String encodeBase64URLSafeString(final byte[] binaryData); static byte[] encodeBase64Chunked(final byte[] binaryData); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); static byte[] decodeBase64(final String base64String); static byte[] decodeBase64(final byte[] base64Data); static BigInteger decodeInteger(final byte[] pArray); static byte[] encodeInteger(final BigInteger bigInt); }
@Test public void testCodeIntegerNull() { try { Base64.encodeInteger(null); fail("Exception not thrown when passing in null to encodeInteger(BigInteger)"); } catch (final NullPointerException npe) { } catch (final Exception e) { fail("Incorrect Exception caught when passing in null to encodeInteger(BigInteger)"); } }
Base64 extends BaseNCodec { @Override void encode(final byte[] in, int inPos, final int inAvail, final Context context) { if (context.eof) { return; } if (inAvail < 0) { context.eof = true; if (0 == context.modulus && lineLength == 0) { return; } final byte[] buffer = ensureBufferSize(encodeSize, context); final int savedPos = context.pos; switch (context.modulus) { case 0 : break; case 1 : buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 2) & MASK_6BITS]; buffer[context.pos++] = encodeTable[(context.ibitWorkArea << 4) & MASK_6BITS]; if (encodeTable == STANDARD_ENCODE_TABLE) { buffer[context.pos++] = pad; buffer[context.pos++] = pad; } break; case 2 : buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 10) & MASK_6BITS]; buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 4) & MASK_6BITS]; buffer[context.pos++] = encodeTable[(context.ibitWorkArea << 2) & MASK_6BITS]; if (encodeTable == STANDARD_ENCODE_TABLE) { buffer[context.pos++] = pad; } break; default: throw new IllegalStateException("Impossible modulus "+context.modulus); } context.currentLinePos += context.pos - savedPos; if (lineLength > 0 && context.currentLinePos > 0) { System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length); context.pos += lineSeparator.length; } } else { for (int i = 0; i < inAvail; i++) { final byte[] buffer = ensureBufferSize(encodeSize, context); context.modulus = (context.modulus+1) % BYTES_PER_UNENCODED_BLOCK; int b = in[inPos++]; if (b < 0) { b += 256; } context.ibitWorkArea = (context.ibitWorkArea << 8) + b; if (0 == context.modulus) { buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 18) & MASK_6BITS]; buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 12) & MASK_6BITS]; buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 6) & MASK_6BITS]; buffer[context.pos++] = encodeTable[context.ibitWorkArea & MASK_6BITS]; context.currentLinePos += BYTES_PER_ENCODED_BLOCK; if (lineLength > 0 && lineLength <= context.currentLinePos) { System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length); context.pos += lineSeparator.length; context.currentLinePos = 0; } } } } } Base64(); Base64(final boolean urlSafe); Base64(final int lineLength); Base64(final int lineLength, final byte[] lineSeparator); Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); boolean isUrlSafe(); @Deprecated static boolean isArrayByteBase64(final byte[] arrayOctet); static boolean isBase64(final byte octet); static boolean isBase64(final String base64); static boolean isBase64(final byte[] arrayOctet); static byte[] encodeBase64(final byte[] binaryData); static String encodeBase64String(final byte[] binaryData); static byte[] encodeBase64URLSafe(final byte[] binaryData); static String encodeBase64URLSafeString(final byte[] binaryData); static byte[] encodeBase64Chunked(final byte[] binaryData); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); static byte[] decodeBase64(final String base64String); static byte[] decodeBase64(final byte[] base64Data); static BigInteger decodeInteger(final byte[] pArray); static byte[] encodeInteger(final BigInteger bigInt); }
@Test public void testConstructor_Int_ByteArray_Boolean() { final Base64 base64 = new Base64(65, new byte[]{'\t'}, false); final byte[] encoded = base64.encode(Base64TestData.DECODED); String expectedResult = Base64TestData.ENCODED_64_CHARS_PER_LINE; expectedResult = expectedResult.replace('\n', '\t'); final String result = StringUtils.newStringUtf8(encoded); assertEquals("new Base64(65, \\t, false)", expectedResult, result); } @Test public void testConstructor_Int_ByteArray_Boolean_UrlSafe() { final Base64 base64 = new Base64(64, new byte[]{'\t'}, true); final byte[] encoded = base64.encode(Base64TestData.DECODED); String expectedResult = Base64TestData.ENCODED_64_CHARS_PER_LINE; expectedResult = expectedResult.replaceAll("=", ""); expectedResult = expectedResult.replace('\n', '\t'); expectedResult = expectedResult.replace('+', '-'); expectedResult = expectedResult.replace('/', '_'); final String result = StringUtils.newStringUtf8(encoded); assertEquals("new Base64(64, \\t, true)", result, expectedResult); } @Test public void testObjectEncodeWithInvalidParameter() throws Exception { final Base64 b64 = new Base64(); try { b64.encode("Yadayadayada"); fail("encode(Object) didn't throw an exception when passed a String object"); } catch (final EncoderException e) { } } @Test public void testObjectEncode() throws Exception { final Base64 b64 = new Base64(); assertEquals("SGVsbG8gV29ybGQ=", new String(b64.encode("Hello World".getBytes(Charsets.UTF_8)))); }
CustomQueryBuilder extends AbstractCustomBuilder { @Override public String buildSql() { String s1 = Joiner.on(", ").join(columns); return String.format(SQL_TEMPLATE, s1, tailOfSql); } CustomQueryBuilder(List<String> columns, String tailOfSql); @Override String buildSql(); }
@Test public void buildSql() throws Exception { List<String> columns = Lists.newArrayList("id2", "user_name", "user_age"); CustomQueryBuilder b = new CustomQueryBuilder(columns, "where id = :1"); assertThat(b.buildSql(), equalTo("select id2, user_name, user_age from #table where id = :1")); }
Base64 extends BaseNCodec { @Deprecated public static boolean isArrayByteBase64(final byte[] arrayOctet) { return isBase64(arrayOctet); } Base64(); Base64(final boolean urlSafe); Base64(final int lineLength); Base64(final int lineLength, final byte[] lineSeparator); Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); boolean isUrlSafe(); @Deprecated static boolean isArrayByteBase64(final byte[] arrayOctet); static boolean isBase64(final byte octet); static boolean isBase64(final String base64); static boolean isBase64(final byte[] arrayOctet); static byte[] encodeBase64(final byte[] binaryData); static String encodeBase64String(final byte[] binaryData); static byte[] encodeBase64URLSafe(final byte[] binaryData); static String encodeBase64URLSafeString(final byte[] binaryData); static byte[] encodeBase64Chunked(final byte[] binaryData); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); static byte[] decodeBase64(final String base64String); static byte[] decodeBase64(final byte[] base64Data); static BigInteger decodeInteger(final byte[] pArray); static byte[] encodeInteger(final BigInteger bigInt); }
@Test public void testIsArrayByteBase64() { assertFalse(Base64.isBase64(new byte[]{Byte.MIN_VALUE})); assertFalse(Base64.isBase64(new byte[]{-125})); assertFalse(Base64.isBase64(new byte[]{-10})); assertFalse(Base64.isBase64(new byte[]{0})); assertFalse(Base64.isBase64(new byte[]{64, Byte.MAX_VALUE})); assertFalse(Base64.isBase64(new byte[]{Byte.MAX_VALUE})); assertTrue(Base64.isBase64(new byte[]{'A'})); assertFalse(Base64.isBase64(new byte[]{'A', Byte.MIN_VALUE})); assertTrue(Base64.isBase64(new byte[]{'A', 'Z', 'a'})); assertTrue(Base64.isBase64(new byte[]{'/', '=', '+'})); assertFalse(Base64.isBase64(new byte[]{'$'})); }
Base64 extends BaseNCodec { public boolean isUrlSafe() { return this.encodeTable == URL_SAFE_ENCODE_TABLE; } Base64(); Base64(final boolean urlSafe); Base64(final int lineLength); Base64(final int lineLength, final byte[] lineSeparator); Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); boolean isUrlSafe(); @Deprecated static boolean isArrayByteBase64(final byte[] arrayOctet); static boolean isBase64(final byte octet); static boolean isBase64(final String base64); static boolean isBase64(final byte[] arrayOctet); static byte[] encodeBase64(final byte[] binaryData); static String encodeBase64String(final byte[] binaryData); static byte[] encodeBase64URLSafe(final byte[] binaryData); static String encodeBase64URLSafeString(final byte[] binaryData); static byte[] encodeBase64Chunked(final byte[] binaryData); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); static byte[] decodeBase64(final String base64String); static byte[] decodeBase64(final byte[] base64Data); static BigInteger decodeInteger(final byte[] pArray); static byte[] encodeInteger(final BigInteger bigInt); }
@Test public void testIsUrlSafe() { final Base64 base64Standard = new Base64(false); final Base64 base64URLSafe = new Base64(true); assertFalse("Base64.isUrlSafe=false", base64Standard.isUrlSafe()); assertTrue("Base64.isUrlSafe=true", base64URLSafe.isUrlSafe()); final byte[] whiteSpace = {' ', '\n', '\r', '\t'}; assertTrue("Base64.isBase64(whiteSpace)=true", Base64.isBase64(whiteSpace)); }
Base64 extends BaseNCodec { @Override void decode(final byte[] in, int inPos, final int inAvail, final Context context) { if (context.eof) { return; } if (inAvail < 0) { context.eof = true; } for (int i = 0; i < inAvail; i++) { final byte[] buffer = ensureBufferSize(decodeSize, context); final byte b = in[inPos++]; if (b == pad) { context.eof = true; break; } else { if (b >= 0 && b < DECODE_TABLE.length) { final int result = DECODE_TABLE[b]; if (result >= 0) { context.modulus = (context.modulus+1) % BYTES_PER_ENCODED_BLOCK; context.ibitWorkArea = (context.ibitWorkArea << BITS_PER_ENCODED_BYTE) + result; if (context.modulus == 0) { buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 16) & MASK_8BITS); buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 8) & MASK_8BITS); buffer[context.pos++] = (byte) (context.ibitWorkArea & MASK_8BITS); } } } } } if (context.eof && context.modulus != 0) { final byte[] buffer = ensureBufferSize(decodeSize, context); switch (context.modulus) { case 1 : break; case 2 : context.ibitWorkArea = context.ibitWorkArea >> 4; buffer[context.pos++] = (byte) ((context.ibitWorkArea) & MASK_8BITS); break; case 3 : context.ibitWorkArea = context.ibitWorkArea >> 2; buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 8) & MASK_8BITS); buffer[context.pos++] = (byte) ((context.ibitWorkArea) & MASK_8BITS); break; default: throw new IllegalStateException("Impossible modulus "+context.modulus); } } } Base64(); Base64(final boolean urlSafe); Base64(final int lineLength); Base64(final int lineLength, final byte[] lineSeparator); Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); boolean isUrlSafe(); @Deprecated static boolean isArrayByteBase64(final byte[] arrayOctet); static boolean isBase64(final byte octet); static boolean isBase64(final String base64); static boolean isBase64(final byte[] arrayOctet); static byte[] encodeBase64(final byte[] binaryData); static String encodeBase64String(final byte[] binaryData); static byte[] encodeBase64URLSafe(final byte[] binaryData); static String encodeBase64URLSafeString(final byte[] binaryData); static byte[] encodeBase64Chunked(final byte[] binaryData); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); static byte[] decodeBase64(final String base64String); static byte[] decodeBase64(final byte[] base64Data); static BigInteger decodeInteger(final byte[] pArray); static byte[] encodeInteger(final BigInteger bigInt); }
@Test public void testObjectDecodeWithInvalidParameter() throws Exception { final Base64 b64 = new Base64(); try { b64.decode(Integer.valueOf(5)); fail("decode(Object) didn't throw an exception when passed an Integer object"); } catch (final DecoderException e) { } }
CustomCountBuilder extends AbstractCustomBuilder { @Override public String buildSql() { return String.format(SQL_TEMPLATE, tailOfSql); } CustomCountBuilder(String tailOfSql); @Override String buildSql(); }
@Test public void buildSql() throws Exception { CustomCountBuilder b = new CustomCountBuilder("where id = :1"); assertThat(b.buildSql(), equalTo("select count(1) from #table where id = :1")); }
Base64 extends BaseNCodec { public static String encodeBase64String(final byte[] binaryData) { return StringUtils.newStringUtf8(encodeBase64(binaryData, false)); } Base64(); Base64(final boolean urlSafe); Base64(final int lineLength); Base64(final int lineLength, final byte[] lineSeparator); Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); boolean isUrlSafe(); @Deprecated static boolean isArrayByteBase64(final byte[] arrayOctet); static boolean isBase64(final byte octet); static boolean isBase64(final String base64); static boolean isBase64(final byte[] arrayOctet); static byte[] encodeBase64(final byte[] binaryData); static String encodeBase64String(final byte[] binaryData); static byte[] encodeBase64URLSafe(final byte[] binaryData); static String encodeBase64URLSafeString(final byte[] binaryData); static byte[] encodeBase64Chunked(final byte[] binaryData); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); static byte[] decodeBase64(final String base64String); static byte[] decodeBase64(final byte[] base64Data); static BigInteger decodeInteger(final byte[] pArray); static byte[] encodeInteger(final BigInteger bigInt); }
@Test public void testRfc4648Section10Encode() { assertEquals("", Base64.encodeBase64String(StringUtils.getBytesUtf8(""))); assertEquals("Zg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("f"))); assertEquals("Zm8=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fo"))); assertEquals("Zm9v", Base64.encodeBase64String(StringUtils.getBytesUtf8("foo"))); assertEquals("Zm9vYg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("foob"))); assertEquals("Zm9vYmE=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fooba"))); assertEquals("Zm9vYmFy", Base64.encodeBase64String(StringUtils.getBytesUtf8("foobar"))); }
Base64 extends BaseNCodec { public static byte[] encodeBase64Chunked(final byte[] binaryData) { return encodeBase64(binaryData, true); } Base64(); Base64(final boolean urlSafe); Base64(final int lineLength); Base64(final int lineLength, final byte[] lineSeparator); Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); boolean isUrlSafe(); @Deprecated static boolean isArrayByteBase64(final byte[] arrayOctet); static boolean isBase64(final byte octet); static boolean isBase64(final String base64); static boolean isBase64(final byte[] arrayOctet); static byte[] encodeBase64(final byte[] binaryData); static String encodeBase64String(final byte[] binaryData); static byte[] encodeBase64URLSafe(final byte[] binaryData); static String encodeBase64URLSafeString(final byte[] binaryData); static byte[] encodeBase64Chunked(final byte[] binaryData); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); static byte[] decodeBase64(final String base64String); static byte[] decodeBase64(final byte[] base64Data); static BigInteger decodeInteger(final byte[] pArray); static byte[] encodeInteger(final BigInteger bigInt); }
@Test public void testSingletonsChunked() { assertEquals("AA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0}))); assertEquals("AQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 1}))); assertEquals("Ag==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 2}))); assertEquals("Aw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 3}))); assertEquals("BA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 4}))); assertEquals("BQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 5}))); assertEquals("Bg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 6}))); assertEquals("Bw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 7}))); assertEquals("CA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 8}))); assertEquals("CQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 9}))); assertEquals("Cg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 10}))); assertEquals("Cw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 11}))); assertEquals("DA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 12}))); assertEquals("DQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 13}))); assertEquals("Dg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 14}))); assertEquals("Dw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 15}))); assertEquals("EA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 16}))); assertEquals("EQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 17}))); assertEquals("Eg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 18}))); assertEquals("Ew==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 19}))); assertEquals("FA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 20}))); assertEquals("FQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 21}))); assertEquals("Fg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 22}))); assertEquals("Fw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 23}))); assertEquals("GA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 24}))); assertEquals("GQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 25}))); assertEquals("Gg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 26}))); assertEquals("Gw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 27}))); assertEquals("HA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 28}))); assertEquals("HQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 29}))); assertEquals("Hg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 30}))); assertEquals("Hw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 31}))); assertEquals("IA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 32}))); assertEquals("IQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 33}))); assertEquals("Ig==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 34}))); assertEquals("Iw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 35}))); assertEquals("JA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 36}))); assertEquals("JQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 37}))); assertEquals("Jg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 38}))); assertEquals("Jw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 39}))); assertEquals("KA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 40}))); assertEquals("KQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 41}))); assertEquals("Kg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 42}))); assertEquals("Kw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 43}))); assertEquals("LA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 44}))); assertEquals("LQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 45}))); assertEquals("Lg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 46}))); assertEquals("Lw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 47}))); assertEquals("MA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 48}))); assertEquals("MQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 49}))); assertEquals("Mg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 50}))); assertEquals("Mw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 51}))); assertEquals("NA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 52}))); assertEquals("NQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 53}))); assertEquals("Ng==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 54}))); assertEquals("Nw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 55}))); assertEquals("OA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 56}))); assertEquals("OQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 57}))); assertEquals("Og==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 58}))); assertEquals("Ow==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 59}))); assertEquals("PA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 60}))); assertEquals("PQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 61}))); assertEquals("Pg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 62}))); assertEquals("Pw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 63}))); assertEquals("QA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 64}))); assertEquals("QQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 65}))); assertEquals("Qg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 66}))); assertEquals("Qw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 67}))); assertEquals("RA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 68}))); assertEquals("RQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 69}))); assertEquals("Rg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 70}))); assertEquals("Rw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 71}))); assertEquals("SA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 72}))); assertEquals("SQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 73}))); assertEquals("Sg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 74}))); assertEquals("Sw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 75}))); assertEquals("TA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 76}))); assertEquals("TQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 77}))); assertEquals("Tg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 78}))); assertEquals("Tw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 79}))); assertEquals("UA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 80}))); assertEquals("UQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 81}))); assertEquals("Ug==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 82}))); assertEquals("Uw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 83}))); assertEquals("VA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 84}))); assertEquals("VQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 85}))); assertEquals("Vg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 86}))); assertEquals("Vw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 87}))); assertEquals("WA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 88}))); assertEquals("WQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 89}))); assertEquals("Wg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 90}))); assertEquals("Ww==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 91}))); assertEquals("XA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 92}))); assertEquals("XQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 93}))); assertEquals("Xg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 94}))); assertEquals("Xw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 95}))); assertEquals("YA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 96}))); assertEquals("YQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 97}))); assertEquals("Yg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 98}))); assertEquals("Yw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 99}))); assertEquals("ZA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 100}))); assertEquals("ZQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 101}))); assertEquals("Zg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 102}))); assertEquals("Zw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 103}))); assertEquals("aA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 104}))); } @Test public void testTripletsChunked() { assertEquals("AAAA\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 0}))); assertEquals("AAAB\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 1}))); assertEquals("AAAC\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 2}))); assertEquals("AAAD\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 3}))); assertEquals("AAAE\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 4}))); assertEquals("AAAF\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 5}))); assertEquals("AAAG\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 6}))); assertEquals("AAAH\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 7}))); assertEquals("AAAI\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 8}))); assertEquals("AAAJ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 9}))); assertEquals("AAAK\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 10}))); assertEquals("AAAL\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 11}))); assertEquals("AAAM\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 12}))); assertEquals("AAAN\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 13}))); assertEquals("AAAO\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 14}))); assertEquals("AAAP\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 15}))); assertEquals("AAAQ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 16}))); assertEquals("AAAR\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 17}))); assertEquals("AAAS\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 18}))); assertEquals("AAAT\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 19}))); assertEquals("AAAU\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 20}))); assertEquals("AAAV\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 21}))); assertEquals("AAAW\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 22}))); assertEquals("AAAX\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 23}))); assertEquals("AAAY\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 24}))); assertEquals("AAAZ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 25}))); assertEquals("AAAa\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 26}))); assertEquals("AAAb\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 27}))); assertEquals("AAAc\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 28}))); assertEquals("AAAd\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 29}))); assertEquals("AAAe\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 30}))); assertEquals("AAAf\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 31}))); assertEquals("AAAg\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 32}))); assertEquals("AAAh\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 33}))); assertEquals("AAAi\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 34}))); assertEquals("AAAj\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 35}))); assertEquals("AAAk\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 36}))); assertEquals("AAAl\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 37}))); assertEquals("AAAm\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 38}))); assertEquals("AAAn\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 39}))); assertEquals("AAAo\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 40}))); assertEquals("AAAp\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 41}))); assertEquals("AAAq\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 42}))); assertEquals("AAAr\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 43}))); assertEquals("AAAs\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 44}))); assertEquals("AAAt\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 45}))); assertEquals("AAAu\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 46}))); assertEquals("AAAv\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 47}))); assertEquals("AAAw\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 48}))); assertEquals("AAAx\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 49}))); assertEquals("AAAy\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 50}))); assertEquals("AAAz\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 51}))); assertEquals("AAA0\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 52}))); assertEquals("AAA1\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 53}))); assertEquals("AAA2\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 54}))); assertEquals("AAA3\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 55}))); assertEquals("AAA4\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 56}))); assertEquals("AAA5\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 57}))); assertEquals("AAA6\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 58}))); assertEquals("AAA7\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 59}))); assertEquals("AAA8\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 60}))); assertEquals("AAA9\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 61}))); assertEquals("AAA+\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 62}))); assertEquals("AAA/\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 63}))); }
BinaryCodec implements BinaryDecoder, BinaryEncoder { @Override public Object decode(final Object ascii) throws DecoderException { if (ascii == null) { return EMPTY_BYTE_ARRAY; } if (ascii instanceof byte[]) { return fromAscii((byte[]) ascii); } if (ascii instanceof char[]) { return fromAscii((char[]) ascii); } if (ascii instanceof String) { return fromAscii(((String) ascii).toCharArray()); } throw new DecoderException("argument not a byte array"); } @Override byte[] encode(final byte[] raw); @Override Object encode(final Object raw); @Override Object decode(final Object ascii); @Override byte[] decode(final byte[] ascii); byte[] toByteArray(final String ascii); static byte[] fromAscii(final char[] ascii); static byte[] fromAscii(final byte[] ascii); static byte[] toAsciiBytes(final byte[] raw); static char[] toAsciiChars(final byte[] raw); static String toAsciiString(final byte[] raw); }
@Test public void testDecodeObjectException() { try { this.instance.decode(new Object()); } catch (final DecoderException e) { return; } fail("Expected DecoderException"); } @Test public void testDecodeByteArray() { byte[] bits = new byte[1]; byte[] decoded = instance.decode("00000000".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0; decoded = instance.decode("00000001".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; decoded = instance.decode("00000011".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; decoded = instance.decode("00000111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; decoded = instance.decode("00001111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; decoded = instance.decode("00011111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; decoded = instance.decode("00111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; decoded = instance.decode("01111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("11111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("0000000011111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("0000000111111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("0000001111111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("0000011111111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("0000111111111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("0001111111111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("0011111111111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("0111111111111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("1111111111111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); }
BinaryCodec implements BinaryDecoder, BinaryEncoder { public byte[] toByteArray(final String ascii) { if (ascii == null) { return EMPTY_BYTE_ARRAY; } return fromAscii(ascii.toCharArray()); } @Override byte[] encode(final byte[] raw); @Override Object encode(final Object raw); @Override Object decode(final Object ascii); @Override byte[] decode(final byte[] ascii); byte[] toByteArray(final String ascii); static byte[] fromAscii(final char[] ascii); static byte[] fromAscii(final byte[] ascii); static byte[] toAsciiBytes(final byte[] raw); static char[] toAsciiChars(final byte[] raw); static String toAsciiString(final byte[] raw); }
@Test public void testToByteArrayFromString() { byte[] bits = new byte[1]; byte[] decoded = instance.toByteArray("00000000"); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0; decoded = instance.toByteArray("00000001"); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; decoded = instance.toByteArray("00000011"); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; decoded = instance.toByteArray("00000111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; decoded = instance.toByteArray("00001111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; decoded = instance.toByteArray("00011111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; decoded = instance.toByteArray("00111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; decoded = instance.toByteArray("01111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("11111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("0000000011111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("0000000111111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("0000001111111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("0000011111111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("0000111111111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("0001111111111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("0011111111111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("0111111111111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("1111111111111111"); assertEquals(new String(bits), new String(decoded)); assertEquals(0, instance.toByteArray((String) null).length); }
BinaryCodec implements BinaryDecoder, BinaryEncoder { public static byte[] fromAscii(final char[] ascii) { if (ascii == null || ascii.length == 0) { return EMPTY_BYTE_ARRAY; } final byte[] l_raw = new byte[ascii.length >> 3]; for (int ii = 0, jj = ascii.length - 1; ii < l_raw.length; ii++, jj -= 8) { for (int bits = 0; bits < BITS.length; ++bits) { if (ascii[jj - bits] == '1') { l_raw[ii] |= BITS[bits]; } } } return l_raw; } @Override byte[] encode(final byte[] raw); @Override Object encode(final Object raw); @Override Object decode(final Object ascii); @Override byte[] decode(final byte[] ascii); byte[] toByteArray(final String ascii); static byte[] fromAscii(final char[] ascii); static byte[] fromAscii(final byte[] ascii); static byte[] toAsciiBytes(final byte[] raw); static char[] toAsciiChars(final byte[] raw); static String toAsciiString(final byte[] raw); }
@Test public void testFromAsciiCharArray() { assertEquals(0, BinaryCodec.fromAscii((char[]) null).length); assertEquals(0, BinaryCodec.fromAscii(new char[0]).length); byte[] bits = new byte[1]; byte[] decoded = BinaryCodec.fromAscii("00000000".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0; decoded = BinaryCodec.fromAscii("00000001".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; decoded = BinaryCodec.fromAscii("00000011".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; decoded = BinaryCodec.fromAscii("00000111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; decoded = BinaryCodec.fromAscii("00001111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; decoded = BinaryCodec.fromAscii("00011111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; decoded = BinaryCodec.fromAscii("00111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; decoded = BinaryCodec.fromAscii("01111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("11111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000000011111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000000111111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000001111111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000011111111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000111111111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0001111111111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0011111111111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0111111111111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("1111111111111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); assertEquals(0, BinaryCodec.fromAscii((char[]) null).length); } @Test public void testFromAsciiByteArray() { assertEquals(0, BinaryCodec.fromAscii((byte[]) null).length); assertEquals(0, BinaryCodec.fromAscii(new byte[0]).length); byte[] bits = new byte[1]; byte[] decoded = BinaryCodec.fromAscii("00000000".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0; decoded = BinaryCodec.fromAscii("00000001".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; decoded = BinaryCodec.fromAscii("00000011".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; decoded = BinaryCodec.fromAscii("00000111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; decoded = BinaryCodec.fromAscii("00001111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; decoded = BinaryCodec.fromAscii("00011111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; decoded = BinaryCodec.fromAscii("00111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; decoded = BinaryCodec.fromAscii("01111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("11111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000000011111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000000111111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000001111111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000011111111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000111111111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0001111111111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0011111111111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0111111111111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("1111111111111111".getBytes(Charsets.UTF_8)); assertEquals(new String(bits), new String(decoded)); assertEquals(0, BinaryCodec.fromAscii((byte[]) null).length); }
CustomDeleteBuilder extends AbstractCustomBuilder { @Override public String buildSql() { return String.format(SQL_TEMPLATE, tailOfSql); } CustomDeleteBuilder(String tailOfSql); @Override String buildSql(); }
@Test public void buildSql() throws Exception { CustomDeleteBuilder b = new CustomDeleteBuilder("where id = :1"); assertThat(b.buildSql(), equalTo("delete from #table where id = :1")); }
BinaryCodec implements BinaryDecoder, BinaryEncoder { @Override public byte[] encode(final byte[] raw) { return toAsciiBytes(raw); } @Override byte[] encode(final byte[] raw); @Override Object encode(final Object raw); @Override Object decode(final Object ascii); @Override byte[] decode(final byte[] ascii); byte[] toByteArray(final String ascii); static byte[] fromAscii(final char[] ascii); static byte[] fromAscii(final byte[] ascii); static byte[] toAsciiBytes(final byte[] raw); static char[] toAsciiChars(final byte[] raw); static String toAsciiString(final byte[] raw); }
@Test public void testEncodeByteArray() { byte[] bits = new byte[1]; String l_encoded = new String(instance.encode(bits)); assertEquals("00000000", l_encoded); bits = new byte[1]; bits[0] = BIT_0; l_encoded = new String(instance.encode(bits)); assertEquals("00000001", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; l_encoded = new String(instance.encode(bits)); assertEquals("00000011", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = new String(instance.encode(bits)); assertEquals("00000111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = new String(instance.encode(bits)); assertEquals("00001111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = new String(instance.encode(bits)); assertEquals("00011111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = new String(instance.encode(bits)); assertEquals("00111111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = new String(instance.encode(bits)); assertEquals("01111111", l_encoded); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("11111111", l_encoded); bits = new byte[2]; l_encoded = new String(instance.encode(bits)); assertEquals("0000000000000000", l_encoded); bits = new byte[2]; bits[0] = BIT_0; l_encoded = new String(instance.encode(bits)); assertEquals("0000000000000001", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1; l_encoded = new String(instance.encode(bits)); assertEquals("0000000000000011", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = new String(instance.encode(bits)); assertEquals("0000000000000111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = new String(instance.encode(bits)); assertEquals("0000000000001111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = new String(instance.encode(bits)); assertEquals("0000000000011111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = new String(instance.encode(bits)); assertEquals("0000000000111111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = new String(instance.encode(bits)); assertEquals("0000000001111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("0000000011111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("0000000111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("0000001111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("0000011111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("0000111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("0001111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("0011111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("0111111111111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("1111111111111111", l_encoded); assertEquals(0, instance.encode((byte[]) null).length); } @Test public void testEncodeObjectNull() throws Exception { final Object obj = new byte[0]; assertEquals(0, ((char[]) instance.encode(obj)).length); } @Test public void testEncodeObjectException() { try { instance.encode(""); } catch (final EncoderException e) { return; } fail("Expected EncoderException"); } @Test public void testEncodeObject() throws Exception { byte[] bits = new byte[1]; String l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("00000000", l_encoded); bits = new byte[1]; bits[0] = BIT_0; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("00000001", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("00000011", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("00000111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("00001111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("00011111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("00111111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("01111111", l_encoded); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("11111111", l_encoded); bits = new byte[2]; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000000000000", l_encoded); bits = new byte[2]; bits[0] = BIT_0; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000000000001", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000000000011", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000000000111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000000001111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000000011111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000000111111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000001111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000011111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000001111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000011111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0001111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0011111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0111111111111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("1111111111111111", l_encoded); }
BinaryCodec implements BinaryDecoder, BinaryEncoder { public static byte[] toAsciiBytes(final byte[] raw) { if (isEmpty(raw)) { return EMPTY_BYTE_ARRAY; } final byte[] l_ascii = new byte[raw.length << 3]; for (int ii = 0, jj = l_ascii.length - 1; ii < raw.length; ii++, jj -= 8) { for (int bits = 0; bits < BITS.length; ++bits) { if ((raw[ii] & BITS[bits]) == 0) { l_ascii[jj - bits] = '0'; } else { l_ascii[jj - bits] = '1'; } } } return l_ascii; } @Override byte[] encode(final byte[] raw); @Override Object encode(final Object raw); @Override Object decode(final Object ascii); @Override byte[] decode(final byte[] ascii); byte[] toByteArray(final String ascii); static byte[] fromAscii(final char[] ascii); static byte[] fromAscii(final byte[] ascii); static byte[] toAsciiBytes(final byte[] raw); static char[] toAsciiChars(final byte[] raw); static String toAsciiString(final byte[] raw); }
@Test public void testToAsciiBytes() { byte[] bits = new byte[1]; String l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("00000000", l_encoded); bits = new byte[1]; bits[0] = BIT_0; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("00000001", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("00000011", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("00000111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("00001111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("00011111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("00111111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("01111111", l_encoded); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("11111111", l_encoded); bits = new byte[2]; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000000000000", l_encoded); bits = new byte[2]; bits[0] = BIT_0; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000000000001", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000000000011", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000000000111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000000001111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000000011111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000000111111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000001111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000011111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000001111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000011111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0001111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0011111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0111111111111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("1111111111111111", l_encoded); assertEquals(0, BinaryCodec.toAsciiBytes((byte[]) null).length); }
BinaryCodec implements BinaryDecoder, BinaryEncoder { public static char[] toAsciiChars(final byte[] raw) { if (isEmpty(raw)) { return EMPTY_CHAR_ARRAY; } final char[] l_ascii = new char[raw.length << 3]; for (int ii = 0, jj = l_ascii.length - 1; ii < raw.length; ii++, jj -= 8) { for (int bits = 0; bits < BITS.length; ++bits) { if ((raw[ii] & BITS[bits]) == 0) { l_ascii[jj - bits] = '0'; } else { l_ascii[jj - bits] = '1'; } } } return l_ascii; } @Override byte[] encode(final byte[] raw); @Override Object encode(final Object raw); @Override Object decode(final Object ascii); @Override byte[] decode(final byte[] ascii); byte[] toByteArray(final String ascii); static byte[] fromAscii(final char[] ascii); static byte[] fromAscii(final byte[] ascii); static byte[] toAsciiBytes(final byte[] raw); static char[] toAsciiChars(final byte[] raw); static String toAsciiString(final byte[] raw); }
@Test public void testToAsciiChars() { byte[] bits = new byte[1]; String l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("00000000", l_encoded); bits = new byte[1]; bits[0] = BIT_0; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("00000001", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("00000011", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("00000111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("00001111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("00011111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("00111111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("01111111", l_encoded); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("11111111", l_encoded); bits = new byte[2]; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000000000000", l_encoded); bits = new byte[2]; bits[0] = BIT_0; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000000000001", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000000000011", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000000000111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000000001111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000000011111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000000111111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000001111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000011111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000001111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000011111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0001111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0011111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0111111111111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("1111111111111111", l_encoded); assertEquals(0, BinaryCodec.toAsciiChars((byte[]) null).length); }
BinaryCodec implements BinaryDecoder, BinaryEncoder { public static String toAsciiString(final byte[] raw) { return new String(toAsciiChars(raw)); } @Override byte[] encode(final byte[] raw); @Override Object encode(final Object raw); @Override Object decode(final Object ascii); @Override byte[] decode(final byte[] ascii); byte[] toByteArray(final String ascii); static byte[] fromAscii(final char[] ascii); static byte[] fromAscii(final byte[] ascii); static byte[] toAsciiBytes(final byte[] raw); static char[] toAsciiChars(final byte[] raw); static String toAsciiString(final byte[] raw); }
@Test public void testToAsciiString() { byte[] bits = new byte[1]; String l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("00000000", l_encoded); bits = new byte[1]; bits[0] = BIT_0; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("00000001", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("00000011", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("00000111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("00001111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("00011111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("00111111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("01111111", l_encoded); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("11111111", l_encoded); bits = new byte[2]; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000000000000", l_encoded); bits = new byte[2]; bits[0] = BIT_0; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000000000001", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000000000011", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000000000111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000000001111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000000011111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000000111111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000001111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000011111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000001111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000011111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0001111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0011111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0111111111111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("1111111111111111", l_encoded); }
Hex implements BinaryEncoder, BinaryDecoder { @Override public String toString() { return super.toString() + "[charsetName=" + this.charset + "]"; } Hex(); Hex(final Charset charset); Hex(final String charsetName); static byte[] decodeHex(final char[] data); static char[] encodeHex(final byte[] data); static char[] encodeHex(final byte[] data, final boolean toLowerCase); static String encodeHexString(final byte[] data); @Override byte[] decode(final byte[] array); @Override Object decode(final Object object); @Override byte[] encode(final byte[] array); @Override Object encode(final Object object); Charset getCharset(); String getCharsetName(); @Override String toString(); static final Charset DEFAULT_CHARSET; static final String DEFAULT_CHARSET_NAME; }
@Test public void testCustomCharsetToString() { assertTrue(new Hex().toString().indexOf(Hex.DEFAULT_CHARSET_NAME) >= 0); }
Hex implements BinaryEncoder, BinaryDecoder { @Override public byte[] decode(final byte[] array) throws DecoderException { return decodeHex(new String(array, getCharset()).toCharArray()); } Hex(); Hex(final Charset charset); Hex(final String charsetName); static byte[] decodeHex(final char[] data); static char[] encodeHex(final byte[] data); static char[] encodeHex(final byte[] data, final boolean toLowerCase); static String encodeHexString(final byte[] data); @Override byte[] decode(final byte[] array); @Override Object decode(final Object object); @Override byte[] encode(final byte[] array); @Override Object encode(final Object object); Charset getCharset(); String getCharsetName(); @Override String toString(); static final Charset DEFAULT_CHARSET; static final String DEFAULT_CHARSET_NAME; }
@Test public void testDecodeArrayOddCharacters() { try { new Hex().decode(new byte[]{65}); fail("An exception wasn't thrown when trying to decode an odd number of characters"); } catch (final DecoderException e) { } } @Test public void testDecodeBadCharacterPos0() { try { new Hex().decode("q0"); fail("An exception wasn't thrown when trying to decode an illegal character"); } catch (final DecoderException e) { } } @Test public void testDecodeBadCharacterPos1() { try { new Hex().decode("0q"); fail("An exception wasn't thrown when trying to decode an illegal character"); } catch (final DecoderException e) { } } @Test public void testDecodeClassCastException() { try { new Hex().decode(new int[]{65}); fail("An exception wasn't thrown when trying to decode."); } catch (final DecoderException e) { } } @Test public void testDecodeStringOddCharacters() { try { new Hex().decode("6"); fail("An exception wasn't thrown when trying to decode an odd number of characters"); } catch (final DecoderException e) { } }
CommonGetBuilder extends AbstractCommonBuilder { @Override public String buildSql() { String s1 = Joiner.on(", ").join(columns); return isBatch ? String.format(BATCH_SQL_TEMPLATE, s1, columnId) : String.format(SQL_TEMPLATE, s1, columnId); } CommonGetBuilder(String colId, List<String> cols, boolean isBatch); @Override String buildSql(); }
@Test public void build() throws Exception { List<String> columns = Lists.newArrayList("id2", "user_name", "user_age"); CommonGetBuilder b = new CommonGetBuilder("id2", columns, false); assertThat(b.buildSql(), equalTo("select id2, user_name, user_age from #table where id2 = :1")); b = new CommonGetBuilder("id2", columns, true); assertThat(b.buildSql(), equalTo("select id2, user_name, user_age from #table where id2 in (:1)")); }
Hex implements BinaryEncoder, BinaryDecoder { @Override public byte[] encode(final byte[] array) { return encodeHexString(array).getBytes(this.getCharset()); } Hex(); Hex(final Charset charset); Hex(final String charsetName); static byte[] decodeHex(final char[] data); static char[] encodeHex(final byte[] data); static char[] encodeHex(final byte[] data, final boolean toLowerCase); static String encodeHexString(final byte[] data); @Override byte[] decode(final byte[] array); @Override Object decode(final Object object); @Override byte[] encode(final byte[] array); @Override Object encode(final Object object); Charset getCharset(); String getCharsetName(); @Override String toString(); static final Charset DEFAULT_CHARSET; static final String DEFAULT_CHARSET_NAME; }
@Test public void testEncodeClassCastException() { try { new Hex().encode(new int[]{65}); fail("An exception wasn't thrown when trying to encode."); } catch (final EncoderException e) { } }
Hex implements BinaryEncoder, BinaryDecoder { public static char[] encodeHex(final byte[] data) { return encodeHex(data, true); } Hex(); Hex(final Charset charset); Hex(final String charsetName); static byte[] decodeHex(final char[] data); static char[] encodeHex(final byte[] data); static char[] encodeHex(final byte[] data, final boolean toLowerCase); static String encodeHexString(final byte[] data); @Override byte[] decode(final byte[] array); @Override Object decode(final Object object); @Override byte[] encode(final byte[] array); @Override Object encode(final Object object); Charset getCharset(); String getCharsetName(); @Override String toString(); static final Charset DEFAULT_CHARSET; static final String DEFAULT_CHARSET_NAME; }
@Test public void testEncodeZeroes() { final char[] c = Hex.encodeHex(new byte[36]); assertEquals("000000000000000000000000000000000000000000000000000000000000000000000000", new String(c)); } @Test public void testHelloWorldLowerCaseHex() { final byte[] b = StringUtils.getBytesUtf8("Hello World"); final String expected = "48656c6c6f20576f726c64"; char[] actual; actual = Hex.encodeHex(b); assertEquals(expected, new String(actual)); actual = Hex.encodeHex(b, true); assertEquals(expected, new String(actual)); actual = Hex.encodeHex(b, false); assertFalse(expected.equals(new String(actual))); } @Test public void testHelloWorldUpperCaseHex() { final byte[] b = StringUtils.getBytesUtf8("Hello World"); final String expected = "48656C6C6F20576F726C64"; char[] actual; actual = Hex.encodeHex(b); assertFalse(expected.equals(new String(actual))); actual = Hex.encodeHex(b, true); assertFalse(expected.equals(new String(actual))); actual = Hex.encodeHex(b, false); assertTrue(expected.equals(new String(actual))); }
Base32 extends BaseNCodec { @Override void encode(final byte[] in, int inPos, final int inAvail, final Context context) { if (context.eof) { return; } if (inAvail < 0) { context.eof = true; if (0 == context.modulus && lineLength == 0) { return; } final byte[] buffer = ensureBufferSize(encodeSize, context); final int savedPos = context.pos; switch (context.modulus) { case 0 : break; case 1 : buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 3) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea << 2) & MASK_5BITS]; buffer[context.pos++] = pad; buffer[context.pos++] = pad; buffer[context.pos++] = pad; buffer[context.pos++] = pad; buffer[context.pos++] = pad; buffer[context.pos++] = pad; break; case 2 : buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 11) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 6) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 1) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea << 4) & MASK_5BITS]; buffer[context.pos++] = pad; buffer[context.pos++] = pad; buffer[context.pos++] = pad; buffer[context.pos++] = pad; break; case 3 : buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 19) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 14) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 9) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 4) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea << 1) & MASK_5BITS]; buffer[context.pos++] = pad; buffer[context.pos++] = pad; buffer[context.pos++] = pad; break; case 4 : buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 27) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 22) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 17) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 12) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 7) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 2) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea << 3) & MASK_5BITS]; buffer[context.pos++] = pad; break; default: throw new IllegalStateException("Impossible modulus "+context.modulus); } context.currentLinePos += context.pos - savedPos; if (lineLength > 0 && context.currentLinePos > 0){ System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length); context.pos += lineSeparator.length; } } else { for (int i = 0; i < inAvail; i++) { final byte[] buffer = ensureBufferSize(encodeSize, context); context.modulus = (context.modulus+1) % BYTES_PER_UNENCODED_BLOCK; int b = in[inPos++]; if (b < 0) { b += 256; } context.lbitWorkArea = (context.lbitWorkArea << 8) + b; if (0 == context.modulus) { buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 35) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 30) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 25) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 20) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 15) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 10) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)(context.lbitWorkArea >> 5) & MASK_5BITS]; buffer[context.pos++] = encodeTable[(int)context.lbitWorkArea & MASK_5BITS]; context.currentLinePos += BYTES_PER_ENCODED_BLOCK; if (lineLength > 0 && lineLength <= context.currentLinePos) { System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length); context.pos += lineSeparator.length; context.currentLinePos = 0; } } } } } Base32(); Base32(final byte pad); Base32(final boolean useHex); Base32(final boolean useHex, final byte pad); Base32(final int lineLength); Base32(final int lineLength, final byte[] lineSeparator); Base32(final int lineLength, final byte[] lineSeparator, final boolean useHex); Base32(final int lineLength, final byte[] lineSeparator, final boolean useHex, final byte pad); @Override boolean isInAlphabet(final byte octet); }
@Test public void testSingleCharEncoding() { for (int i = 0; i < 20; i++) { Base32 codec = new Base32(); final BaseNCodec.Context context = new BaseNCodec.Context(); final byte unencoded[] = new byte[i]; final byte allInOne[] = codec.encode(unencoded); codec = new Base32(); for (int j=0; j< unencoded.length; j++) { codec.encode(unencoded, j, 1, context); } codec.encode(unencoded, 0, -1, context); final byte singly[] = new byte[allInOne.length]; codec.readResults(singly, 0, 100, context); if (!Arrays.equals(allInOne, singly)){ fail(); } } }
QuotedPrintableCodec implements BinaryEncoder, BinaryDecoder, StringEncoder, StringDecoder { @Override public byte[] decode(final byte[] bytes) throws DecoderException { return decodeQuotedPrintable(bytes); } QuotedPrintableCodec(); QuotedPrintableCodec(final boolean strict); QuotedPrintableCodec(final Charset charset); QuotedPrintableCodec(final Charset charset, final boolean strict); QuotedPrintableCodec(final String charsetName); static final byte[] encodeQuotedPrintable(BitSet printable, final byte[] bytes); static final byte[] encodeQuotedPrintable(BitSet printable, final byte[] bytes, boolean strict); static final byte[] decodeQuotedPrintable(final byte[] bytes); @Override byte[] encode(final byte[] bytes); @Override byte[] decode(final byte[] bytes); @Override String encode(final String str); String decode(final String str, final Charset charset); String decode(final String str, final String charset); @Override String decode(final String str); @Override Object encode(final Object obj); @Override Object decode(final Object obj); Charset getCharset(); String getDefaultCharset(); String encode(final String str, final Charset charset); String encode(final String str, final String charset); }
@Test public void testDecodeInvalid() throws Exception { final QuotedPrintableCodec qpcodec = new QuotedPrintableCodec(); try { qpcodec.decode("="); fail("DecoderException should have been thrown"); } catch (final DecoderException e) { } try { qpcodec.decode("=A"); fail("DecoderException should have been thrown"); } catch (final DecoderException e) { } try { qpcodec.decode("=WW"); fail("DecoderException should have been thrown"); } catch (final DecoderException e) { } } @Test public void testDecodeStringWithNull() throws Exception { final QuotedPrintableCodec qpcodec = new QuotedPrintableCodec(); final String test = null; final String result = qpcodec.decode( test, "charset" ); assertEquals("Result should be null", null, result); } @Test public void testDecodeObjects() throws Exception { final QuotedPrintableCodec qpcodec = new QuotedPrintableCodec(); final String plain = "1+1 =3D 2"; String decoded = (String) qpcodec.decode((Object) plain); assertEquals("Basic quoted-printable decoding test", "1+1 = 2", decoded); final byte[] plainBA = plain.getBytes(Charsets.UTF_8); final byte[] decodedBA = (byte[]) qpcodec.decode((Object) plainBA); decoded = new String(decodedBA); assertEquals("Basic quoted-printable decoding test", "1+1 = 2", decoded); final Object result = qpcodec.decode((Object) null); assertEquals( "Decoding a null Object should return null", null, result); try { final Object dObj = new Double(3.0); qpcodec.decode( dObj ); fail( "Trying to url encode a Double object should cause an exception."); } catch (final DecoderException ee) { } }
CommonDeleteBuilder extends AbstractCommonBuilder { @Override public String buildSql() { return String.format(SQL_TEMPLATE, columnId); } CommonDeleteBuilder(String colId); @Override String buildSql(); }
@Test public void build() throws Exception { CommonDeleteBuilder b = new CommonDeleteBuilder("id2"); assertThat(b.buildSql(), equalTo("delete from #table where id2 = :1")); }
QuotedPrintableCodec implements BinaryEncoder, BinaryDecoder, StringEncoder, StringDecoder { @Override public byte[] encode(final byte[] bytes) { return encodeQuotedPrintable(PRINTABLE_CHARS, bytes, strict); } QuotedPrintableCodec(); QuotedPrintableCodec(final boolean strict); QuotedPrintableCodec(final Charset charset); QuotedPrintableCodec(final Charset charset, final boolean strict); QuotedPrintableCodec(final String charsetName); static final byte[] encodeQuotedPrintable(BitSet printable, final byte[] bytes); static final byte[] encodeQuotedPrintable(BitSet printable, final byte[] bytes, boolean strict); static final byte[] decodeQuotedPrintable(final byte[] bytes); @Override byte[] encode(final byte[] bytes); @Override byte[] decode(final byte[] bytes); @Override String encode(final String str); String decode(final String str, final Charset charset); String decode(final String str, final String charset); @Override String decode(final String str); @Override Object encode(final Object obj); @Override Object decode(final Object obj); Charset getCharset(); String getDefaultCharset(); String encode(final String str, final Charset charset); String encode(final String str, final String charset); }
@Test public void testEncodeNull() throws Exception { final QuotedPrintableCodec qpcodec = new QuotedPrintableCodec(); final byte[] plain = null; final byte[] encoded = qpcodec.encode(plain); assertEquals("Encoding a null string should return null", null, encoded); } @Test public void testEncodeStringWithNull() throws Exception { final QuotedPrintableCodec qpcodec = new QuotedPrintableCodec(); final String test = null; final String result = qpcodec.encode( test, "charset" ); assertEquals("Result should be null", null, result); } @Test public void testEncodeObjects() throws Exception { final QuotedPrintableCodec qpcodec = new QuotedPrintableCodec(); final String plain = "1+1 = 2"; String encoded = (String) qpcodec.encode((Object) plain); assertEquals("Basic quoted-printable encoding test", "1+1 =3D 2", encoded); final byte[] plainBA = plain.getBytes(Charsets.UTF_8); final byte[] encodedBA = (byte[]) qpcodec.encode((Object) plainBA); encoded = new String(encodedBA); assertEquals("Basic quoted-printable encoding test", "1+1 =3D 2", encoded); final Object result = qpcodec.encode((Object) null); assertEquals( "Encoding a null Object should return null", null, result); try { final Object dObj = new Double(3.0); qpcodec.encode( dObj ); fail( "Trying to url encode a Double object should cause an exception."); } catch (final EncoderException ee) { } } @Test public void testDefaultEncoding() throws Exception { final String plain = "Hello there!"; final QuotedPrintableCodec qpcodec = new QuotedPrintableCodec("UnicodeBig"); qpcodec.encode(plain); final String encoded1 = qpcodec.encode(plain, "UnicodeBig"); final String encoded2 = qpcodec.encode(plain); assertEquals(encoded1, encoded2); } @Test public void testTrailingSpecial() throws Exception { final QuotedPrintableCodec qpcodec = new QuotedPrintableCodec(true); String plain ="This is a example of a quoted-printable text file. This might contain sp=cial chars."; String expected = "This is a example of a quoted-printable text file. This might contain sp=3D=\r\ncial chars."; assertEquals(expected, qpcodec.encode(plain)); plain ="This is a example of a quoted-printable text file. This might contain ta\tbs as well."; expected = "This is a example of a quoted-printable text file. This might contain ta=09=\r\nbs as well."; assertEquals(expected, qpcodec.encode(plain)); } @Test public void testUltimateSoftBreak() throws Exception { final QuotedPrintableCodec qpcodec = new QuotedPrintableCodec(true); String plain ="This is a example of a quoted-printable text file. There is no end to it\t"; String expected = "This is a example of a quoted-printable text file. There is no end to i=\r\nt=09"; assertEquals(expected, qpcodec.encode(plain)); plain ="This is a example of a quoted-printable text file. There is no end to it "; expected = "This is a example of a quoted-printable text file. There is no end to i=\r\nt=20"; assertEquals(expected, qpcodec.encode(plain)); plain ="This is a example of a quoted-printable text file. There is no end to "; expected = "This is a example of a quoted-printable text file. There is no end to=20=\r\n =20"; assertEquals(expected, qpcodec.encode(plain)); plain ="This is a example of a quoted-printable text file. There is no end to= "; expected = "This is a example of a quoted-printable text file. There is no end to=3D=\r\n =20"; assertEquals(expected, qpcodec.encode(plain)); } @Test public void testFinalBytes() throws Exception { final String plain ="This is a example of a quoted=printable text file. There is no tt"; final String expected = "This is a example of a quoted=3Dprintable text file. There is no tt"; assertEquals(expected, new QuotedPrintableCodec(true).encode(plain)); }
QuotedPrintableCodec implements BinaryEncoder, BinaryDecoder, StringEncoder, StringDecoder { public static final byte[] decodeQuotedPrintable(final byte[] bytes) throws DecoderException { if (bytes == null) { return null; } final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for (int i = 0; i < bytes.length; i++) { final int b = bytes[i]; if (b == ESCAPE_CHAR) { try { if (bytes[++i] == CR) { continue; } final int u = Utils.digit16(bytes[i]); final int l = Utils.digit16(bytes[++i]); buffer.write((char) ((u << 4) + l)); } catch (final ArrayIndexOutOfBoundsException e) { throw new DecoderException("Invalid quoted-printable encoding", e); } } else if (b != CR && b != LF) { buffer.write(b); } } return buffer.toByteArray(); } QuotedPrintableCodec(); QuotedPrintableCodec(final boolean strict); QuotedPrintableCodec(final Charset charset); QuotedPrintableCodec(final Charset charset, final boolean strict); QuotedPrintableCodec(final String charsetName); static final byte[] encodeQuotedPrintable(BitSet printable, final byte[] bytes); static final byte[] encodeQuotedPrintable(BitSet printable, final byte[] bytes, boolean strict); static final byte[] decodeQuotedPrintable(final byte[] bytes); @Override byte[] encode(final byte[] bytes); @Override byte[] decode(final byte[] bytes); @Override String encode(final String str); String decode(final String str, final Charset charset); String decode(final String str, final String charset); @Override String decode(final String str); @Override Object encode(final Object obj); @Override Object decode(final Object obj); Charset getCharset(); String getDefaultCharset(); String encode(final String str, final Charset charset); String encode(final String str, final String charset); }
@Test public void testDecodeWithNullArray() throws Exception { final byte[] plain = null; final byte[] result = QuotedPrintableCodec.decodeQuotedPrintable( plain ); assertEquals("Result should be null", null, result); }
CommonUpdateBuilder extends AbstractCommonBuilder { @Override public String buildSql() { List<String> exps = new ArrayList<String>(); for (int i = 0; i < properties.size(); i++) { String exp = columns.get(i) + " = :" + properties.get(i); exps.add(exp); } String s1 = Joiner.on(", ").join(exps); String s2 = columnId + " = :" + propertyId; return String.format(SQL_TEMPLATE, s1, s2); } CommonUpdateBuilder(String propId, List<String> props, List<String> cols); @Override String buildSql(); }
@Test public void build() throws Exception { List<String> properties = Lists.newArrayList("id", "userName", "userAge"); List<String> columns = Lists.newArrayList("id", "user_name", "user_age"); CommonUpdateBuilder b = new CommonUpdateBuilder("id", properties, columns); assertThat(b.buildSql(), equalTo("update #table set user_name = :userName, user_age = :userAge where id = :id")); }
URLCodec implements BinaryEncoder, BinaryDecoder, StringEncoder, StringDecoder { @Override public byte[] decode(final byte[] bytes) throws DecoderException { return decodeUrl(bytes); } URLCodec(); URLCodec(final String charset); static final byte[] encodeUrl(BitSet urlsafe, final byte[] bytes); static final byte[] decodeUrl(final byte[] bytes); @Override byte[] encode(final byte[] bytes); @Override byte[] decode(final byte[] bytes); String encode(final String str, final String charset); @Override String encode(final String str); String decode(final String str, final String charset); @Override String decode(final String str); @Override Object encode(final Object obj); @Override Object decode(final Object obj); String getDefaultCharset(); @Deprecated String getEncoding(); }
@Test public void testDecodeInvalid() throws Exception { final URLCodec urlCodec = new URLCodec(); try { urlCodec.decode("%"); fail("DecoderException should have been thrown"); } catch (final DecoderException e) { } try { urlCodec.decode("%A"); fail("DecoderException should have been thrown"); } catch (final DecoderException e) { } try { urlCodec.decode("%WW"); fail("DecoderException should have been thrown"); } catch (final DecoderException e) { } try { urlCodec.decode("%0W"); fail("DecoderException should have been thrown"); } catch (final DecoderException e) { } this.validateState(urlCodec); } @Test public void testDecodeInvalidContent() throws UnsupportedEncodingException, DecoderException { final String ch_msg = constructString(SWISS_GERMAN_STUFF_UNICODE); final URLCodec urlCodec = new URLCodec(); final byte[] input = ch_msg.getBytes("ISO-8859-1"); final byte[] output = urlCodec.decode(input); assertEquals(input.length, output.length); for (int i = 0; i < input.length; i++) { assertEquals(input[i], output[i]); } this.validateState(urlCodec); } @Test public void testDecodeStringWithNull() throws Exception { final URLCodec urlCodec = new URLCodec(); final String test = null; final String result = urlCodec.decode( test, "charset" ); assertEquals("Result should be null", null, result); } @Test public void testDecodeObjects() throws Exception { final URLCodec urlCodec = new URLCodec(); final String plain = "Hello+there%21"; String decoded = (String) urlCodec.decode((Object) plain); assertEquals("Basic URL decoding test", "Hello there!", decoded); final byte[] plainBA = plain.getBytes(Charsets.UTF_8); final byte[] decodedBA = (byte[]) urlCodec.decode((Object) plainBA); decoded = new String(decodedBA); assertEquals("Basic URL decoding test", "Hello there!", decoded); final Object result = urlCodec.decode((Object) null); assertEquals( "Decoding a null Object should return null", null, result); try { final Object dObj = new Double(3.0); urlCodec.decode( dObj ); fail( "Trying to url encode a Double object should cause an exception."); } catch (final DecoderException ee) { } this.validateState(urlCodec); }
URLCodec implements BinaryEncoder, BinaryDecoder, StringEncoder, StringDecoder { @Override public byte[] encode(final byte[] bytes) { return encodeUrl(WWW_FORM_URL, bytes); } URLCodec(); URLCodec(final String charset); static final byte[] encodeUrl(BitSet urlsafe, final byte[] bytes); static final byte[] decodeUrl(final byte[] bytes); @Override byte[] encode(final byte[] bytes); @Override byte[] decode(final byte[] bytes); String encode(final String str, final String charset); @Override String encode(final String str); String decode(final String str, final String charset); @Override String decode(final String str); @Override Object encode(final Object obj); @Override Object decode(final Object obj); String getDefaultCharset(); @Deprecated String getEncoding(); }
@Test public void testEncodeNull() throws Exception { final URLCodec urlCodec = new URLCodec(); final byte[] plain = null; final byte[] encoded = urlCodec.encode(plain); assertEquals("Encoding a null string should return null", null, encoded); this.validateState(urlCodec); } @Test public void testEncodeStringWithNull() throws Exception { final URLCodec urlCodec = new URLCodec(); final String test = null; final String result = urlCodec.encode( test, "charset" ); assertEquals("Result should be null", null, result); } @Test public void testEncodeObjects() throws Exception { final URLCodec urlCodec = new URLCodec(); final String plain = "Hello there!"; String encoded = (String) urlCodec.encode((Object) plain); assertEquals("Basic URL encoding test", "Hello+there%21", encoded); final byte[] plainBA = plain.getBytes(Charsets.UTF_8); final byte[] encodedBA = (byte[]) urlCodec.encode((Object) plainBA); encoded = new String(encodedBA); assertEquals("Basic URL encoding test", "Hello+there%21", encoded); final Object result = urlCodec.encode((Object) null); assertEquals( "Encoding a null Object should return null", null, result); try { final Object dObj = new Double(3.0); urlCodec.encode( dObj ); fail( "Trying to url encode a Double object should cause an exception."); } catch (final EncoderException ee) { } this.validateState(urlCodec); } @Test public void testDefaultEncoding() throws Exception { final String plain = "Hello there!"; final URLCodec urlCodec = new URLCodec("UnicodeBig"); urlCodec.encode(plain); final String encoded1 = urlCodec.encode(plain, "UnicodeBig"); final String encoded2 = urlCodec.encode(plain); assertEquals(encoded1, encoded2); this.validateState(urlCodec); }
URLCodec implements BinaryEncoder, BinaryDecoder, StringEncoder, StringDecoder { public static final byte[] decodeUrl(final byte[] bytes) throws DecoderException { if (bytes == null) { return null; } final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for (int i = 0; i < bytes.length; i++) { final int b = bytes[i]; if (b == '+') { buffer.write(' '); } else if (b == ESCAPE_CHAR) { try { final int u = Utils.digit16(bytes[++i]); final int l = Utils.digit16(bytes[++i]); buffer.write((char) ((u << 4) + l)); } catch (final ArrayIndexOutOfBoundsException e) { throw new DecoderException("Invalid URL encoding: ", e); } } else { buffer.write(b); } } return buffer.toByteArray(); } URLCodec(); URLCodec(final String charset); static final byte[] encodeUrl(BitSet urlsafe, final byte[] bytes); static final byte[] decodeUrl(final byte[] bytes); @Override byte[] encode(final byte[] bytes); @Override byte[] decode(final byte[] bytes); String encode(final String str, final String charset); @Override String encode(final String str); String decode(final String str, final String charset); @Override String decode(final String str); @Override Object encode(final Object obj); @Override Object decode(final Object obj); String getDefaultCharset(); @Deprecated String getEncoding(); }
@Test public void testDecodeWithNullArray() throws Exception { final byte[] plain = null; final byte[] result = URLCodec.decodeUrl( plain ); assertEquals("Result should be null", null, result); }
QCodec extends RFC1522Codec implements StringEncoder, StringDecoder { public String encode(final String str, final Charset charset) throws EncoderException { if (str == null) { return null; } return encodeText(str, charset); } QCodec(); QCodec(final Charset charset); QCodec(final String charsetName); String encode(final String str, final Charset charset); String encode(final String str, final String charset); @Override String encode(final String str); @Override String decode(final String str); @Override Object encode(final Object obj); @Override Object decode(final Object obj); Charset getCharset(); String getDefaultCharset(); boolean isEncodeBlanks(); void setEncodeBlanks(final boolean b); }
@Test public void testEncodeStringWithNull() throws Exception { final QCodec qcodec = new QCodec(); final String test = null; final String result = qcodec.encode( test, "charset" ); assertEquals("Result should be null", null, result); } @Test public void testEncodeObjects() throws Exception { final QCodec qcodec = new QCodec(); final String plain = "1+1 = 2"; final String encoded = (String) qcodec.encode((Object) plain); assertEquals("Basic Q encoding test", "=?UTF-8?Q?1+1 =3D 2?=", encoded); final Object result = qcodec.encode((Object) null); assertEquals( "Encoding a null Object should return null", null, result); try { final Object dObj = new Double(3.0); qcodec.encode( dObj ); fail( "Trying to url encode a Double object should cause an exception."); } catch (final EncoderException ee) { } }
CommonAddBuilder extends AbstractCommonBuilder { @Override public String buildSql() { String s1 = Joiner.on(", ").join(columns); List<String> cps = new ArrayList<String>(); for (String prop : properties) { cps.add(":" + prop); } String s2 = Joiner.on(", ").join(cps); return String.format(SQL_TEMPLATE, s1, s2); } CommonAddBuilder(String propId, List<String> props, List<String> cols, boolean isAutoGenerateId); @Override String buildSql(); }
@Test public void build() throws Exception { List<String> properties = Lists.newArrayList("id", "name", "age"); List<String> columns = Lists.newArrayList("id2", "name2", "age2"); CommonAddBuilder b = new CommonAddBuilder("id", properties, columns, true); assertThat(b.buildSql(), equalTo("insert into #table(name2, age2) values(:name, :age)")); properties = Lists.newArrayList("id", "name", "age"); columns = Lists.newArrayList("id2", "name2", "age2"); b = new CommonAddBuilder("id", properties, columns, false); assertThat(b.buildSql(), equalTo("insert into #table(id2, name2, age2) values(:id, :name, :age)")); }
Reflection { public static <T> T instantiate(Class<T> clazz) throws BeanInstantiationException { if (clazz.isInterface()) { throw new BeanInstantiationException(clazz, "specified class is an interface"); } try { return clazz.newInstance(); } catch (InstantiationException e) { throw new BeanInstantiationException(clazz, "Is it an abstract class?", e); } catch (IllegalAccessException e) { throw new BeanInstantiationException(clazz, "Is the constructor accessible?", e); } } static T instantiate(Class<T> clazz); static T instantiateClass(Class<T> clazz); static T instantiateClass(Constructor<T> ctor, Object... args); static T newProxy( Class<T> interfaceType, InvocationHandler handler); static void makeAccessible(Constructor<?> ctor); static Set<Annotation> getAnnotations(Class<?> clazz); }
@Test public void testInstantiate() throws Exception { Reflection.instantiateClass(A.class); }
QCodec extends RFC1522Codec implements StringEncoder, StringDecoder { @Override public String decode(final String str) throws DecoderException { if (str == null) { return null; } try { return decodeText(str); } catch (final UnsupportedEncodingException e) { throw new DecoderException(e.getMessage(), e); } } QCodec(); QCodec(final Charset charset); QCodec(final String charsetName); String encode(final String str, final Charset charset); String encode(final String str, final String charset); @Override String encode(final String str); @Override String decode(final String str); @Override Object encode(final Object obj); @Override Object decode(final Object obj); Charset getCharset(); String getDefaultCharset(); boolean isEncodeBlanks(); void setEncodeBlanks(final boolean b); }
@Test public void testDecodeStringWithNull() throws Exception { final QCodec qcodec = new QCodec(); final String test = null; final String result = qcodec.decode( test ); assertEquals("Result should be null", null, result); } @Test public void testDecodeObjects() throws Exception { final QCodec qcodec = new QCodec(); final String decoded = "=?UTF-8?Q?1+1 =3D 2?="; final String plain = (String) qcodec.decode((Object) decoded); assertEquals("Basic Q decoding test", "1+1 = 2", plain); final Object result = qcodec.decode((Object) null); assertEquals( "Decoding a null Object should return null", null, result); try { final Object dObj = new Double(3.0); qcodec.decode( dObj ); fail( "Trying to url encode a Double object should cause an exception."); } catch (final DecoderException ee) { } }
BCodec extends RFC1522Codec implements StringEncoder, StringDecoder { public String encode(final String value, final Charset charset) throws EncoderException { if (value == null) { return null; } return encodeText(value, charset); } BCodec(); BCodec(final Charset charset); BCodec(final String charsetName); String encode(final String value, final Charset charset); String encode(final String value, final String charset); @Override String encode(final String value); @Override String decode(final String value); @Override Object encode(final Object value); @Override Object decode(final Object value); Charset getCharset(); String getDefaultCharset(); }
@Test public void testEncodeStringWithNull() throws Exception { final BCodec bcodec = new BCodec(); final String test = null; final String result = bcodec.encode(test, "charset"); assertEquals("Result should be null", null, result); } @Test public void testEncodeObjects() throws Exception { final BCodec bcodec = new BCodec(); final String plain = "what not"; final String encoded = (String) bcodec.encode((Object) plain); assertEquals("Basic B encoding test", "=?UTF-8?B?d2hhdCBub3Q=?=", encoded); final Object result = bcodec.encode((Object) null); assertEquals("Encoding a null Object should return null", null, result); try { final Object dObj = new Double(3.0); bcodec.encode(dObj); fail("Trying to url encode a Double object should cause an exception."); } catch (final EncoderException ee) { } }
BCodec extends RFC1522Codec implements StringEncoder, StringDecoder { @Override public String decode(final String value) throws DecoderException { if (value == null) { return null; } try { return this.decodeText(value); } catch (final UnsupportedEncodingException e) { throw new DecoderException(e.getMessage(), e); } } BCodec(); BCodec(final Charset charset); BCodec(final String charsetName); String encode(final String value, final Charset charset); String encode(final String value, final String charset); @Override String encode(final String value); @Override String decode(final String value); @Override Object encode(final Object value); @Override Object decode(final Object value); Charset getCharset(); String getDefaultCharset(); }
@Test public void testDecodeStringWithNull() throws Exception { final BCodec bcodec = new BCodec(); final String test = null; final String result = bcodec.decode(test); assertEquals("Result should be null", null, result); } @Test public void testDecodeObjects() throws Exception { final BCodec bcodec = new BCodec(); final String decoded = "=?UTF-8?B?d2hhdCBub3Q=?="; final String plain = (String) bcodec.decode((Object) decoded); assertEquals("Basic B decoding test", "what not", plain); final Object result = bcodec.decode((Object) null); assertEquals("Decoding a null Object should return null", null, result); try { final Object dObj = new Double(3.0); bcodec.decode(dObj); fail("Trying to url encode a Double object should cause an exception."); } catch (final DecoderException ee) { } }
DaitchMokotoffSoundex implements StringEncoder { public String soundex(final String source) { final String[] branches = soundex(source, true); final StringBuilder sb = new StringBuilder(); int index = 0; for (final String branch : branches) { sb.append(branch); if (++index < branches.length) { sb.append('|'); } } return sb.toString(); } DaitchMokotoffSoundex(); DaitchMokotoffSoundex(final boolean folding); @Override Object encode(final Object obj); @Override String encode(final String source); String soundex(final String source); }
@Test public void testAccentedCharacterFolding() { Assert.assertEquals("294795", soundex("Straßburg")); Assert.assertEquals("294795", soundex("Strasburg")); Assert.assertEquals("095600", soundex("Éregon")); Assert.assertEquals("095600", soundex("Eregon")); } @Test public void testAdjacentCodes() { Assert.assertEquals("054800", soundex("AKSSOL")); Assert.assertEquals("547830|545783|594783|594578", soundex("GERSCHFELD")); } @Test public void testSoundexBasic() { Assert.assertEquals("583600", soundex("GOLDEN")); Assert.assertEquals("087930", soundex("Alpert")); Assert.assertEquals("791900", soundex("Breuer")); Assert.assertEquals("579000", soundex("Haber")); Assert.assertEquals("665600", soundex("Mannheim")); Assert.assertEquals("664000", soundex("Mintz")); Assert.assertEquals("370000", soundex("Topf")); Assert.assertEquals("586660", soundex("Kleinmann")); Assert.assertEquals("769600", soundex("Ben Aron")); Assert.assertEquals("097400|097500", soundex("AUERBACH")); Assert.assertEquals("097400|097500", soundex("OHRBACH")); Assert.assertEquals("874400", soundex("LIPSHITZ")); Assert.assertEquals("874400|874500", soundex("LIPPSZYC")); Assert.assertEquals("876450", soundex("LEWINSKY")); Assert.assertEquals("876450", soundex("LEVINSKI")); Assert.assertEquals("486740", soundex("SZLAMAWICZ")); Assert.assertEquals("486740", soundex("SHLAMOVITZ")); } @Test public void testSoundexBasic2() { Assert.assertEquals("467000|567000", soundex("Ceniow")); Assert.assertEquals("467000", soundex("Tsenyuv")); Assert.assertEquals("587400|587500", soundex("Holubica")); Assert.assertEquals("587400", soundex("Golubitsa")); Assert.assertEquals("746480|794648", soundex("Przemysl")); Assert.assertEquals("746480", soundex("Pshemeshil")); Assert.assertEquals("944744|944745|944754|944755|945744|945745|945754|945755", soundex("Rosochowaciec")); Assert.assertEquals("945744", soundex("Rosokhovatsets")); } @Test public void testSoundexBasic3() { Assert.assertEquals("734000|739400", soundex("Peters")); Assert.assertEquals("734600|739460", soundex("Peterson")); Assert.assertEquals("645740", soundex("Moskowitz")); Assert.assertEquals("645740", soundex("Moskovitz")); Assert.assertEquals("154600|145460|454600|445460", soundex("Jackson")); Assert.assertEquals("154654|154645|154644|145465|145464|454654|454645|454644|445465|445464", soundex("Jackson-Jackson")); } @Test public void testSpecialRomanianCharacters() { Assert.assertEquals("364000|464000", soundex("ţamas")); Assert.assertEquals("364000|464000", soundex("țamas")); }
DaitchMokotoffSoundex implements StringEncoder { @Override public Object encode(final Object obj) throws EncoderException { if (!(obj instanceof String)) { throw new EncoderException( "Parameter supplied to DaitchMokotoffSoundex encode is not of type java.lang.String"); } return encode((String) obj); } DaitchMokotoffSoundex(); DaitchMokotoffSoundex(final boolean folding); @Override Object encode(final Object obj); @Override String encode(final String source); String soundex(final String source); }
@Test public void testEncodeIgnoreTrimmable() { Assert.assertEquals("746536", encode(" \t\n\r Washington \t\n\r ")); Assert.assertEquals("746536", encode("Washington")); }
CommonGetAllBuilder extends AbstractCommonBuilder { @Override public String buildSql() { String s1 = Joiner.on(", ").join(columns); return String.format(SQL, s1, s1); } CommonGetAllBuilder(List<String> cols); @Override String buildSql(); }
@Test public void build() throws Exception { List<String> columns = Lists.newArrayList("id2", "user_name", "user_age"); CommonGetAllBuilder b = new CommonGetAllBuilder(columns); assertThat(b.buildSql(), equalTo("select id2, user_name, user_age from #table")); }
ColognePhonetic implements StringEncoder { public boolean isEncodeEqual(final String text1, final String text2) { return colognePhonetic(text1).equals(colognePhonetic(text2)); } String colognePhonetic(String text); @Override Object encode(final Object object); @Override String encode(final String text); boolean isEncodeEqual(final String text1, final String text2); }
@Test public void testIsEncodeEquals() { final String[][] data = { {"Meyer", "M\u00fcller"}, {"Meyer", "Mayr"}, {"house", "house"}, {"House", "house"}, {"Haus", "house"}, {"ganz", "Gans"}, {"ganz", "G\u00e4nse"}, {"Miyagi", "Miyako"}}; for (final String[] element : data) { this.getStringEncoder().isEncodeEqual(element[1], element[0]); } }
RefinedSoundex implements StringEncoder { public int difference(final String s1, final String s2) throws EncoderException { return SoundexUtils.difference(this, s1, s2); } RefinedSoundex(); RefinedSoundex(final char[] mapping); RefinedSoundex(final String mapping); int difference(final String s1, final String s2); @Override Object encode(final Object obj); @Override String encode(final String str); String soundex(String str); static final String US_ENGLISH_MAPPING_STRING; static final RefinedSoundex US_ENGLISH; }
@Test public void testDifference() throws EncoderException { assertEquals(0, this.getStringEncoder().difference(null, null)); assertEquals(0, this.getStringEncoder().difference("", "")); assertEquals(0, this.getStringEncoder().difference(" ", " ")); assertEquals(6, this.getStringEncoder().difference("Smith", "Smythe")); assertEquals(3, this.getStringEncoder().difference("Ann", "Andrew")); assertEquals(1, this.getStringEncoder().difference("Margaret", "Andrew")); assertEquals(1, this.getStringEncoder().difference("Janet", "Margaret")); assertEquals(5, this.getStringEncoder().difference("Green", "Greene")); assertEquals(1, this.getStringEncoder().difference("Blotchet-Halls", "Greene")); assertEquals(6, this.getStringEncoder().difference("Smith", "Smythe")); assertEquals(8, this.getStringEncoder().difference("Smithers", "Smythers")); assertEquals(5, this.getStringEncoder().difference("Anothers", "Brothers")); }
RefinedSoundex implements StringEncoder { @Override public Object encode(final Object obj) throws EncoderException { if (!(obj instanceof String)) { throw new EncoderException("Parameter supplied to RefinedSoundex encode is not of type java.lang.String"); } return soundex((String) obj); } RefinedSoundex(); RefinedSoundex(final char[] mapping); RefinedSoundex(final String mapping); int difference(final String s1, final String s2); @Override Object encode(final Object obj); @Override String encode(final String str); String soundex(String str); static final String US_ENGLISH_MAPPING_STRING; static final RefinedSoundex US_ENGLISH; }
@Test public void testEncode() { assertEquals("T6036084", this.getStringEncoder().encode("testing")); assertEquals("T6036084", this.getStringEncoder().encode("TESTING")); assertEquals("T60", this.getStringEncoder().encode("The")); assertEquals("Q503", this.getStringEncoder().encode("quick")); assertEquals("B1908", this.getStringEncoder().encode("brown")); assertEquals("F205", this.getStringEncoder().encode("fox")); assertEquals("J408106", this.getStringEncoder().encode("jumped")); assertEquals("O0209", this.getStringEncoder().encode("over")); assertEquals("T60", this.getStringEncoder().encode("the")); assertEquals("L7050", this.getStringEncoder().encode("lazy")); assertEquals("D6043", this.getStringEncoder().encode("dogs")); assertEquals("D6043", RefinedSoundex.US_ENGLISH.encode("dogs")); }
RefinedSoundex implements StringEncoder { char getMappingCode(final char c) { if (!Character.isLetter(c)) { return 0; } return this.soundexMapping[Character.toUpperCase(c) - 'A']; } RefinedSoundex(); RefinedSoundex(final char[] mapping); RefinedSoundex(final String mapping); int difference(final String s1, final String s2); @Override Object encode(final Object obj); @Override String encode(final String str); String soundex(String str); static final String US_ENGLISH_MAPPING_STRING; static final RefinedSoundex US_ENGLISH; }
@Test public void testGetMappingCodeNonLetter() { final char code = this.getStringEncoder().getMappingCode('#'); assertEquals("Code does not equals zero", 0, code); }
RefinedSoundex implements StringEncoder { public String soundex(String str) { if (str == null) { return null; } str = SoundexUtils.clean(str); if (str.length() == 0) { return str; } final StringBuilder sBuf = new StringBuilder(); sBuf.append(str.charAt(0)); char last, current; last = '*'; for (int i = 0; i < str.length(); i++) { current = getMappingCode(str.charAt(i)); if (current == last) { continue; } else if (current != 0) { sBuf.append(current); } last = current; } return sBuf.toString(); } RefinedSoundex(); RefinedSoundex(final char[] mapping); RefinedSoundex(final String mapping); int difference(final String s1, final String s2); @Override Object encode(final Object obj); @Override String encode(final String str); String soundex(String str); static final String US_ENGLISH_MAPPING_STRING; static final RefinedSoundex US_ENGLISH; }
@Test public void testNewInstance() { assertEquals("D6043", new RefinedSoundex().soundex("dogs")); } @Test public void testNewInstance2() { assertEquals("D6043", new RefinedSoundex(RefinedSoundex.US_ENGLISH_MAPPING_STRING.toCharArray()).soundex("dogs")); } @Test public void testNewInstance3() { assertEquals("D6043", new RefinedSoundex(RefinedSoundex.US_ENGLISH_MAPPING_STRING).soundex("dogs")); }
PhoneticEngine { public String encode(final String input) { final Languages.LanguageSet languageSet = this.lang.guessLanguages(input); return encode(input, languageSet); } PhoneticEngine(final NameType nameType, final RuleType ruleType, final boolean concat); PhoneticEngine(final NameType nameType, final RuleType ruleType, final boolean concat, final int maxPhonemes); String encode(final String input); String encode(String input, final Languages.LanguageSet languageSet); Lang getLang(); NameType getNameType(); RuleType getRuleType(); boolean isConcat(); int getMaxPhonemes(); }
@Test(timeout = 10000L) public void testEncode() { final PhoneticEngine engine = new PhoneticEngine(this.nameType, this.ruleType, this.concat, this.maxPhonemes); final String phoneticActual = engine.encode(this.name); assertEquals("phoneme incorrect", this.phoneticExpected, phoneticActual); if (this.concat) { final String[] split = phoneticActual.split("\\|"); assertTrue(split.length <= this.maxPhonemes); } else { final String[] words = phoneticActual.split("-"); for (final String word : words) { final String[] split = word.split("\\|"); assertTrue(split.length <= this.maxPhonemes); } } }
BeiderMorseEncoder implements StringEncoder { @Override public Object encode(final Object source) throws EncoderException { if (!(source instanceof String)) { throw new EncoderException("BeiderMorseEncoder encode parameter is not of type String"); } return encode((String) source); } @Override Object encode(final Object source); @Override String encode(final String source); NameType getNameType(); RuleType getRuleType(); boolean isConcat(); void setConcat(final boolean concat); void setNameType(final NameType nameType); void setRuleType(final RuleType ruleType); void setMaxPhonemes(final int maxPhonemes); }
@Test public void testAllChars() throws EncoderException { final BeiderMorseEncoder bmpm = createGenericApproxEncoder(); for (char c = Character.MIN_VALUE; c < Character.MAX_VALUE; c++) { bmpm.encode(Character.toString(c)); } } @Test public void testEncodeGna() throws EncoderException { final BeiderMorseEncoder bmpm = createGenericApproxEncoder(); bmpm.encode("gna"); } @Test(timeout = 10000L) public void testLongestEnglishSurname() throws EncoderException { final BeiderMorseEncoder bmpm = createGenericApproxEncoder(); bmpm.encode("MacGhilleseatheanaich"); } @Test() public void testSpeedCheck() throws EncoderException { final BeiderMorseEncoder bmpm = this.createGenericApproxEncoder(); final StringBuilder stringBuffer = new StringBuilder(); stringBuffer.append(TEST_CHARS[0]); for (int i = 0, j = 1; i < 40; i++, j++) { if (j == TEST_CHARS.length) { j = 0; } bmpm.encode(stringBuffer.toString()); stringBuffer.append(TEST_CHARS[j]); } } @Test public void testSpeedCheck2() throws EncoderException { final BeiderMorseEncoder bmpm = this.createGenericApproxEncoder(); final String phrase = "ItstheendoftheworldasweknowitandIfeelfine"; for (int i = 1; i <= phrase.length(); i++) { bmpm.encode(phrase.subSequence(0, i)); } } @Test public void testSpeedCheck3() throws EncoderException { final BeiderMorseEncoder bmpm = this.createGenericApproxEncoder(); final String phrase = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; for (int i = 1; i <= phrase.length(); i++) { bmpm.encode(phrase.subSequence(0, i)); } }
BeiderMorseEncoder implements StringEncoder { public void setConcat(final boolean concat) { this.engine = new PhoneticEngine(this.engine.getNameType(), this.engine.getRuleType(), concat, this.engine.getMaxPhonemes()); } @Override Object encode(final Object source); @Override String encode(final String source); NameType getNameType(); RuleType getRuleType(); boolean isConcat(); void setConcat(final boolean concat); void setNameType(final NameType nameType); void setRuleType(final RuleType ruleType); void setMaxPhonemes(final int maxPhonemes); }
@Test public void testSetConcat() { final BeiderMorseEncoder bmpm = new BeiderMorseEncoder(); bmpm.setConcat(false); assertFalse("Should be able to set concat to false", bmpm.isConcat()); }
BeiderMorseEncoder implements StringEncoder { public void setRuleType(final RuleType ruleType) { this.engine = new PhoneticEngine(this.engine.getNameType(), ruleType, this.engine.isConcat(), this.engine.getMaxPhonemes()); } @Override Object encode(final Object source); @Override String encode(final String source); NameType getNameType(); RuleType getRuleType(); boolean isConcat(); void setConcat(final boolean concat); void setNameType(final NameType nameType); void setRuleType(final RuleType ruleType); void setMaxPhonemes(final int maxPhonemes); }
@Test(expected = IllegalArgumentException.class) public void testSetRuleTypeToRulesIllegalArgumentException() { final BeiderMorseEncoder bmpm = new BeiderMorseEncoder(); bmpm.setRuleType(RuleType.RULES); }
Metaphone implements StringEncoder { public Metaphone() { super(); } Metaphone(); String metaphone(final String txt); @Override Object encode(final Object obj); @Override String encode(final String str); boolean isMetaphoneEqual(final String str1, final String str2); int getMaxCodeLen(); void setMaxCodeLen(final int maxCodeLen); }
@Test public void testMetaphone() { assertEquals("HL", this.getStringEncoder().metaphone("howl")); assertEquals("TSTN", this.getStringEncoder().metaphone("testing")); assertEquals("0", this.getStringEncoder().metaphone("The")); assertEquals("KK", this.getStringEncoder().metaphone("quick")); assertEquals("BRN", this.getStringEncoder().metaphone("brown")); assertEquals("FKS", this.getStringEncoder().metaphone("fox")); assertEquals("JMPT", this.getStringEncoder().metaphone("jumped")); assertEquals("OFR", this.getStringEncoder().metaphone("over")); assertEquals("0", this.getStringEncoder().metaphone("the")); assertEquals("LS", this.getStringEncoder().metaphone("lazy")); assertEquals("TKS", this.getStringEncoder().metaphone("dogs")); } @Test public void testWordEndingInMB() { assertEquals( "KM", this.getStringEncoder().metaphone("COMB") ); assertEquals( "TM", this.getStringEncoder().metaphone("TOMB") ); assertEquals( "WM", this.getStringEncoder().metaphone("WOMB") ); } @Test public void testDiscardOfSCEOrSCIOrSCY() { assertEquals( "SNS", this.getStringEncoder().metaphone("SCIENCE") ); assertEquals( "SN", this.getStringEncoder().metaphone("SCENE") ); assertEquals( "S", this.getStringEncoder().metaphone("SCY") ); } @Test public void testWhy() { assertEquals("", this.getStringEncoder().metaphone("WHY")); } @Test public void testWordsWithCIA() { assertEquals( "XP", this.getStringEncoder().metaphone("CIAPO") ); } @Test public void testTranslateOfSCHAndCH() { assertEquals( "SKTL", this.getStringEncoder().metaphone("SCHEDULE") ); assertEquals( "SKMT", this.getStringEncoder().metaphone("SCHEMATIC") ); assertEquals( "KRKT", this.getStringEncoder().metaphone("CHARACTER") ); assertEquals( "TX", this.getStringEncoder().metaphone("TEACH") ); } @Test public void testTranslateToJOfDGEOrDGIOrDGY() { assertEquals( "TJ", this.getStringEncoder().metaphone("DODGY") ); assertEquals( "TJ", this.getStringEncoder().metaphone("DODGE") ); assertEquals( "AJMT", this.getStringEncoder().metaphone("ADGIEMTI") ); } @Test public void testDiscardOfSilentHAfterG() { assertEquals( "KNT", this.getStringEncoder().metaphone("GHENT") ); assertEquals( "B", this.getStringEncoder().metaphone("BAUGH") ); } @Test public void testDiscardOfSilentGN() { assertEquals( "N", this.getStringEncoder().metaphone("GNU") ); assertEquals( "SNT", this.getStringEncoder().metaphone("SIGNED") ); } @Test public void testPHTOF() { assertEquals( "FX", this.getStringEncoder().metaphone("PHISH") ); } @Test public void testSHAndSIOAndSIAToX() { assertEquals( "XT", this.getStringEncoder().metaphone("SHOT") ); assertEquals( "OTXN", this.getStringEncoder().metaphone("ODSIAN") ); assertEquals( "PLXN", this.getStringEncoder().metaphone("PULSION") ); } @Test public void testTIOAndTIAToX() { assertEquals( "OX", this.getStringEncoder().metaphone("OTIA") ); assertEquals( "PRXN", this.getStringEncoder().metaphone("PORTION") ); } @Test public void testTCH() { assertEquals( "RX", this.getStringEncoder().metaphone("RETCH") ); assertEquals( "WX", this.getStringEncoder().metaphone("WATCH") ); } @Test public void testExceedLength() { assertEquals( "AKSK", this.getStringEncoder().metaphone("AXEAXE") ); }
DoubleMetaphone implements StringEncoder { public boolean isDoubleMetaphoneEqual(final String value1, final String value2) { return isDoubleMetaphoneEqual(value1, value2, false); } DoubleMetaphone(); String doubleMetaphone(final String value); String doubleMetaphone(String value, final boolean alternate); @Override Object encode(final Object obj); @Override String encode(final String value); boolean isDoubleMetaphoneEqual(final String value1, final String value2); boolean isDoubleMetaphoneEqual(final String value1, final String value2, final boolean alternate); int getMaxCodeLen(); void setMaxCodeLen(final int maxCodeLen); }
@Test public void testCCedilla() { assertTrue(this.getStringEncoder().isDoubleMetaphoneEqual("\u00e7", "S")); } @Test public void testCodec184() throws Throwable { assertTrue(new DoubleMetaphone().isDoubleMetaphoneEqual("", "", false)); assertTrue(new DoubleMetaphone().isDoubleMetaphoneEqual("", "", true)); assertFalse(new DoubleMetaphone().isDoubleMetaphoneEqual("aa", "", false)); assertFalse(new DoubleMetaphone().isDoubleMetaphoneEqual("aa", "", true)); assertFalse(new DoubleMetaphone().isDoubleMetaphoneEqual("", "aa", false)); assertFalse(new DoubleMetaphone().isDoubleMetaphoneEqual("", "aa", true)); } @Test public void testIsDoubleMetaphoneEqualExtended3() { this.validateFixture(FIXTURE); final StringBuilder failures = new StringBuilder(); final StringBuilder matches = new StringBuilder(); final String cr = System.getProperty("line.separator"); matches.append("private static final String[][] MATCHES = {" + cr); int failCount = 0; for (int i = 0; i < FIXTURE.length; i++) { final String name0 = FIXTURE[i][0]; final String name1 = FIXTURE[i][1]; final boolean match1 = this.getStringEncoder().isDoubleMetaphoneEqual(name0, name1, false); final boolean match2 = this.getStringEncoder().isDoubleMetaphoneEqual(name0, name1, true); if (match1 == false && match2 == false) { final String failMsg = "[" + i + "] " + name0 + " and " + name1 + cr; failures.append(failMsg); failCount++; } else { matches.append("{\"" + name0 + "\", \"" + name1 + "\"}," + cr); } } matches.append("};"); if (failCount > 0) { } } @Test public void testIsDoubleMetaphoneEqualWithMATCHES() { this.validateFixture(MATCHES); for (int i = 0; i < MATCHES.length; i++) { final String name0 = MATCHES[i][0]; final String name1 = MATCHES[i][1]; final boolean match1 = this.getStringEncoder().isDoubleMetaphoneEqual(name0, name1, false); final boolean match2 = this.getStringEncoder().isDoubleMetaphoneEqual(name0, name1, true); if (match1 == false && match2 == false) { fail("Expected match [" + i + "] " + name0 + " and " + name1); } } } @Test public void testNTilde() { assertTrue(this.getStringEncoder().isDoubleMetaphoneEqual("\u00f1", "N")); }
DoubleMetaphone implements StringEncoder { public DoubleMetaphone() { super(); } DoubleMetaphone(); String doubleMetaphone(final String value); String doubleMetaphone(String value, final boolean alternate); @Override Object encode(final Object obj); @Override String encode(final String value); boolean isDoubleMetaphoneEqual(final String value1, final String value2); boolean isDoubleMetaphoneEqual(final String value1, final String value2, final boolean alternate); int getMaxCodeLen(); void setMaxCodeLen(final int maxCodeLen); }
@Test public void testDoubleMetaphone() { assertDoubleMetaphone("TSTN", "testing"); assertDoubleMetaphone("0", "The"); assertDoubleMetaphone("KK", "quick"); assertDoubleMetaphone("PRN", "brown"); assertDoubleMetaphone("FKS", "fox"); assertDoubleMetaphone("JMPT", "jumped"); assertDoubleMetaphone("AFR", "over"); assertDoubleMetaphone("0", "the"); assertDoubleMetaphone("LS", "lazy"); assertDoubleMetaphone("TKS", "dogs"); assertDoubleMetaphone("MKFR", "MacCafferey"); assertDoubleMetaphone("STFN", "Stephan"); assertDoubleMetaphone("KSSK", "Kuczewski"); assertDoubleMetaphone("MKLL", "McClelland"); assertDoubleMetaphone("SNHS", "san jose"); assertDoubleMetaphone("SNFP", "xenophobia"); assertDoubleMetaphoneAlt("TSTN", "testing"); assertDoubleMetaphoneAlt("T", "The"); assertDoubleMetaphoneAlt("KK", "quick"); assertDoubleMetaphoneAlt("PRN", "brown"); assertDoubleMetaphoneAlt("FKS", "fox"); assertDoubleMetaphoneAlt("AMPT", "jumped"); assertDoubleMetaphoneAlt("AFR", "over"); assertDoubleMetaphoneAlt("T", "the"); assertDoubleMetaphoneAlt("LS", "lazy"); assertDoubleMetaphoneAlt("TKS", "dogs"); assertDoubleMetaphoneAlt("MKFR", "MacCafferey"); assertDoubleMetaphoneAlt("STFN", "Stephan"); assertDoubleMetaphoneAlt("KXFS", "Kutchefski"); assertDoubleMetaphoneAlt("MKLL", "McClelland"); assertDoubleMetaphoneAlt("SNHS", "san jose"); assertDoubleMetaphoneAlt("SNFP", "xenophobia"); assertDoubleMetaphoneAlt("FKR", "Fokker"); assertDoubleMetaphoneAlt("AK", "Joqqi"); assertDoubleMetaphoneAlt("HF", "Hovvi"); assertDoubleMetaphoneAlt("XRN", "Czerny"); } @Test public void testEmpty() { assertEquals(null, this.getStringEncoder().doubleMetaphone(null)); assertEquals(null, this.getStringEncoder().doubleMetaphone("")); assertEquals(null, this.getStringEncoder().doubleMetaphone(" ")); assertEquals(null, this.getStringEncoder().doubleMetaphone("\t\n\r ")); }
Nysiis implements StringEncoder { @Override public Object encode(final Object obj) throws EncoderException { if (!(obj instanceof String)) { throw new EncoderException("Parameter supplied to Nysiis encode is not of type java.lang.String"); } return this.nysiis((String) obj); } Nysiis(); Nysiis(final boolean strict); @Override Object encode(final Object obj); @Override String encode(final String str); boolean isStrict(); String nysiis(String str); }
@Test public void testTrueVariant() { final Nysiis encoder = new Nysiis(true); final String encoded = encoder.encode("WESTERLUND"); Assert.assertTrue(encoded.length() <= 6); Assert.assertEquals("WASTAR", encoded); }
MatchRatingApproachEncoder implements StringEncoder { String removeAccents(final String accentedWord) { if (accentedWord == null) { return null; } final StringBuilder sb = new StringBuilder(); final int n = accentedWord.length(); for (int i = 0; i < n; i++) { final char c = accentedWord.charAt(i); final int pos = UNICODE.indexOf(c); if (pos > -1) { sb.append(PLAIN_ASCII.charAt(pos)); } else { sb.append(c); } } return sb.toString(); } @Override final Object encode(final Object pObject); @Override final String encode(String name); boolean isEncodeEquals(String name1, String name2); }
@Test public final void testAccentRemoval_AllLower_SuccessfullyRemoved() { assertEquals("aeiou", this.getStringEncoder().removeAccents("áéíóú")); } @Test public final void testAccentRemoval_WithSpaces_SuccessfullyRemovedAndSpacesInvariant() { assertEquals("ae io u", this.getStringEncoder().removeAccents("áé íó ú")); } @Test public final void testAccentRemoval_UpperandLower_SuccessfullyRemovedAndCaseInvariant() { assertEquals("AeiOuu", this.getStringEncoder().removeAccents("ÁeíÓuu")); } @Test public final void testAccentRemoval_MixedWithUnusualChars_SuccessfullyRemovedAndUnusualcharactersInvariant() { assertEquals("A-e'i.,o&u", this.getStringEncoder().removeAccents("Á-e'í.,ó&ú")); } @Test public final void testAccentRemoval_ComprehensiveAccentMix_AllSuccessfullyRemoved() { assertEquals("E,E,E,E,U,U,I,I,A,A,O,e,e,e,e,u,u,i,i,a,a,o,c", this.getStringEncoder().removeAccents("È,É,Ê,Ë,Û,Ù,Ï,Î,À,Â,Ô,è,é,ê,ë,û,ù,ï,î,à,â,ô,ç")); } @Test public final void testAccentRemovalNormalString_NoChange() { assertEquals("Colorless green ideas sleep furiously", this.getStringEncoder().removeAccents("Colorless green ideas sleep furiously")); } @Test public final void testAccentRemoval_NINO_NoChange() { assertEquals("", this.getStringEncoder().removeAccents("")); } @Test public final void testAccentRemoval_NullValue_ReturnNullSuccessfully() { assertEquals(null, this.getStringEncoder().removeAccents(null)); }
MatchRatingApproachEncoder implements StringEncoder { String removeDoubleConsonants(final String name) { String replacedName = name.toUpperCase(); for (final String dc : DOUBLE_CONSONANT) { if (replacedName.contains(dc)) { final String singleLetter = dc.substring(0, 1); replacedName = replacedName.replace(dc, singleLetter); } } return replacedName; } @Override final Object encode(final Object pObject); @Override final String encode(String name); boolean isEncodeEquals(String name1, String name2); }
@Test public final void testRemoveSingleDoubleConsonants_BUBLE_RemovedSuccessfully() { assertEquals("BUBLE", this.getStringEncoder().removeDoubleConsonants("BUBBLE")); } @Test public final void testRemoveDoubleConsonants_MISSISSIPPI_RemovedSuccessfully() { assertEquals("MISISIPI", this.getStringEncoder().removeDoubleConsonants("MISSISSIPPI")); } @Test public final void testRemoveDoubleDoubleVowel_BEETLE_NotRemoved() { assertEquals("BEETLE", this.getStringEncoder().removeDoubleConsonants("BEETLE")); }
MatchRatingApproachEncoder implements StringEncoder { boolean isVowel(final String letter) { return letter.equalsIgnoreCase("E") || letter.equalsIgnoreCase("A") || letter.equalsIgnoreCase("O") || letter.equalsIgnoreCase("I") || letter.equalsIgnoreCase("U"); } @Override final Object encode(final Object pObject); @Override final String encode(String name); boolean isEncodeEquals(String name1, String name2); }
@Test public final void testIsVowel_CapitalA_ReturnsTrue() { assertTrue(this.getStringEncoder().isVowel("A")); } @Test public final void testIsVowel_SmallD_ReturnsFalse() { assertFalse(this.getStringEncoder().isVowel("d")); } @Test public final void testisVowel_SingleVowel_ReturnsTrue() { assertTrue(this.getStringEncoder().isVowel(("I"))); }
MatchRatingApproachEncoder implements StringEncoder { String removeVowels(String name) { final String firstLetter = name.substring(0, 1); name = name.replaceAll("A", EMPTY); name = name.replaceAll("E", EMPTY); name = name.replaceAll("I", EMPTY); name = name.replaceAll("O", EMPTY); name = name.replaceAll("U", EMPTY); name = name.replaceAll("\\s{2,}\\b", SPACE); if (isVowel(firstLetter)) { return firstLetter + name; } else { return name; } } @Override final Object encode(final Object pObject); @Override final String encode(String name); boolean isEncodeEquals(String name1, String name2); }
@Test public final void testRemoveVowel_ALESSANDRA_Returns_ALSSNDR() { assertEquals("ALSSNDR", this.getStringEncoder().removeVowels("ALESSANDRA")); } @Test public final void testRemoveVowel__AIDAN_Returns_ADN() { assertEquals("ADN", this.getStringEncoder().removeVowels("AIDAN")); } @Test public final void testRemoveVowel__DECLAN_Returns_DCLN() { assertEquals("DCLN", this.getStringEncoder().removeVowels("DECLAN")); }
MatchRatingApproachEncoder implements StringEncoder { String getFirst3Last3(final String name) { final int nameLength = name.length(); if (nameLength > SIX) { final String firstThree = name.substring(0, THREE); final String lastThree = name.substring(nameLength - THREE, nameLength); return firstThree + lastThree; } else { return name; } } @Override final Object encode(final Object pObject); @Override final String encode(String name); boolean isEncodeEquals(String name1, String name2); }
@Test public final void testGetFirstLast3__ALEXANDER_Returns_Aleder() { assertEquals("Aleder", this.getStringEncoder().getFirst3Last3("Alexzander")); } @Test public final void testGetFirstLast3_PETE_Returns_PETE() { assertEquals("PETE", this.getStringEncoder().getFirst3Last3("PETE")); }
MatchRatingApproachEncoder implements StringEncoder { int leftToRightThenRightToLeftProcessing(final String name1, final String name2) { final char[] name1Char = name1.toCharArray(); final char[] name2Char = name2.toCharArray(); final int name1Size = name1.length() - 1; final int name2Size = name2.length() - 1; String name1LtRStart = EMPTY; String name1LtREnd = EMPTY; String name2RtLStart = EMPTY; String name2RtLEnd = EMPTY; for (int i = 0; i < name1Char.length; i++) { if (i > name2Size) { break; } name1LtRStart = name1.substring(i, i + 1); name1LtREnd = name1.substring(name1Size - i, name1Size - i + 1); name2RtLStart = name2.substring(i, i + 1); name2RtLEnd = name2.substring(name2Size - i, name2Size - i + 1); if (name1LtRStart.equals(name2RtLStart)) { name1Char[i] = ' '; name2Char[i] = ' '; } if (name1LtREnd.equals(name2RtLEnd)) { name1Char[name1Size - i] = ' '; name2Char[name2Size - i] = ' '; } } final String strA = new String(name1Char).replaceAll("\\s+", EMPTY); final String strB = new String(name2Char).replaceAll("\\s+", EMPTY); if (strA.length() > strB.length()) { return Math.abs(SIX - strA.length()); } else { return Math.abs(SIX - strB.length()); } } @Override final Object encode(final Object pObject); @Override final String encode(String name); boolean isEncodeEquals(String name1, String name2); }
@Test public final void testleftTorightThenRightToLeft_ALEXANDER_ALEXANDRA_Returns4() { assertEquals(4, this.getStringEncoder().leftToRightThenRightToLeftProcessing("ALEXANDER", "ALEXANDRA")); } @Test public final void testleftTorightThenRightToLeft_EINSTEIN_MICHAELA_Returns0() { assertEquals(0, this.getStringEncoder().leftToRightThenRightToLeftProcessing("EINSTEIN", "MICHAELA")); }
MatchRatingApproachEncoder implements StringEncoder { int getMinRating(final int sumLength) { int minRating = 0; if (sumLength <= FOUR) { minRating = FIVE; } else if (sumLength >= FIVE && sumLength <= SEVEN) { minRating = FOUR; } else if (sumLength >= EIGHT && sumLength <= ELEVEN) { minRating = THREE; } else if (sumLength == TWELVE) { minRating = TWO; } else { minRating = ONE; } return minRating; } @Override final Object encode(final Object pObject); @Override final String encode(String name); boolean isEncodeEquals(String name1, String name2); }
@Test public final void testGetMinRating_7_Return4_Successfully() { assertEquals(4, this.getStringEncoder().getMinRating(7)); } @Test public final void testGetMinRating_1_Returns5_Successfully() { assertEquals(5, this.getStringEncoder().getMinRating(1)); } @Test public final void testGetMinRating_2_Returns5_Successfully() { assertEquals(5, this.getStringEncoder().getMinRating(2)); } @Test public final void testgetMinRating_5_Returns4_Successfully(){ assertEquals(4, this.getStringEncoder().getMinRating(5)); } @Test public final void testgetMinRating_5_Returns4_Successfully2(){ assertEquals(4, this.getStringEncoder().getMinRating(5)); } @Test public final void testgetMinRating_6_Returns4_Successfully(){ assertEquals(4, this.getStringEncoder().getMinRating(6)); } @Test public final void testgetMinRating_7_Returns4_Successfully(){ assertEquals(4, this.getStringEncoder().getMinRating(7)); } @Test public final void testgetMinRating_8_Returns3_Successfully(){ assertEquals(3, this.getStringEncoder().getMinRating(8)); } @Test public final void testgetMinRating_10_Returns3_Successfully(){ assertEquals(3, this.getStringEncoder().getMinRating(10)); } @Test public final void testgetMinRating_11_Returns_3_Successfully(){ assertEquals(3, this.getStringEncoder().getMinRating(11)); } @Test public final void testGetMinRating_13_Returns_1_Successfully() { assertEquals(1, this.getStringEncoder().getMinRating(13)); }
MatchRatingApproachEncoder implements StringEncoder { String cleanName(final String name) { String upperName = name.toUpperCase(Locale.ENGLISH); final String[] charsToTrim = { "\\-", "[&]", "\\'", "\\.", "[\\,]" }; for (final String str : charsToTrim) { upperName = upperName.replaceAll(str, EMPTY); } upperName = removeAccents(upperName); upperName = upperName.replaceAll("\\s+", EMPTY); return upperName; } @Override final Object encode(final Object pObject); @Override final String encode(String name); boolean isEncodeEquals(String name1, String name2); }
@Test public final void testcleanName_SuccessfullyClean() { assertEquals("THISISATEST", this.getStringEncoder().cleanName("This-ís a t.,es &t")); }
MatchRatingApproachEncoder implements StringEncoder { @Override public final Object encode(final Object pObject) throws EncoderException { if (!(pObject instanceof String)) { throw new EncoderException( "Parameter supplied to Match Rating Approach encoder is not of type java.lang.String"); } return encode((String) pObject); } @Override final Object encode(final Object pObject); @Override final String encode(String name); boolean isEncodeEquals(String name1, String name2); }
@Test public final void testGetEncoding_HARPER_HRPR() { assertEquals("HRPR", this.getStringEncoder().encode("HARPER")); } @Test public final void testGetEncoding_SMITH_to_SMTH() { assertEquals("SMTH", this.getStringEncoder().encode("Smith")); } @Test public final void testGetEncoding_SMYTH_to_SMYTH() { assertEquals("SMYTH", this.getStringEncoder().encode("Smyth")); } @Test public final void testGetEncoding_Space_to_Nothing() { assertEquals("", this.getStringEncoder().encode(" ")); } @Test public final void testGetEncoding_NoSpace_to_Nothing() { assertEquals("", this.getStringEncoder().encode("")); } @Test public final void testGetEncoding_Null_to_Nothing() { assertEquals("", this.getStringEncoder().encode(null)); } @Test public final void testGetEncoding_One_Letter_to_Nothing() { assertEquals("", this.getStringEncoder().encode("E")); }
Parser implements ParserTreeConstants, ParserConstants { final public void Expression() throws ParseException { ASTExpression jjtn000 = new ASTExpression(JJTEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1)); try { ConditionalOrExpression(); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtn000.jjtSetLastToken(getToken(0)); } } } Parser(String s); Parser(java.io.InputStream stream); Parser(java.io.InputStream stream, String encoding); Parser(Reader stream); Parser(ParserTokenManager tm); final ASTRootNode parse(); final void DML(); final void Insert(); final void Delete(); final void Update(); final void Select(); final void Replace(); final void Merge(); final void Truncate(); final void Statement(); final void JDBCParameter(); final void JDBCIterableParameter(); final void GlobalTable(); final void JoinParameter(); final void QuoteText(); final void Text(); final void Blank(); final void IfStatement(); final void ElseStatement(); final void ElseIfStatement(); final void Expression(); final void ConditionalOrExpression(); final void ConditionalAndExpression(); final void RelationalExpression(); final void UnaryExpression(); final void PrimaryExpression(); final void ExpressionParameter(); final void IntegerLiteral(); final void StringLiteral(); final void True(); final void False(); final void Null(); void ReInit(java.io.InputStream stream); void ReInit(java.io.InputStream stream, String encoding); void ReInit(Reader stream); void ReInit(ParserTokenManager tm); final Token getNextToken(); final Token getToken(int index); ParseException generateParseException(); final void enable_tracing(); final void disable_tracing(); public ParserTokenManager token_source; public Token token; public Token jj_nt; }
@Test public void testExpression() throws Exception { String sql = "select where 1=1 #if(:1==false && :2!=null && :3==true) and id>10 #end"; ASTRootNode n = new Parser(sql).parse().init(); ParameterContext ctx = getParameterContext(Lists.newArrayList((Type) Boolean.class, Object.class, Boolean.class)); n.checkAndBind(ctx); InvocationContext context = DefaultInvocationContext.create(); context.addParameter("1", false); context.addParameter("2", new Object()); context.addParameter("3", true); n.render(context); BoundSql boundSql = context.getBoundSql(); assertThat(boundSql.getSql().toString(), equalTo("select where 1=1 and id>10 ")); }
Reflection { public static Set<Annotation> getAnnotations(Class<?> clazz) { Set<Annotation> annos = new HashSet<Annotation>(); getAnnotations(clazz, annos); return annos; } static T instantiate(Class<T> clazz); static T instantiateClass(Class<T> clazz); static T instantiateClass(Constructor<T> ctor, Object... args); static T newProxy( Class<T> interfaceType, InvocationHandler handler); static void makeAccessible(Constructor<?> ctor); static Set<Annotation> getAnnotations(Class<?> clazz); }
@Test public void testGetAnnotations() throws Exception { Set<Annotation> annos = new HashSet<Annotation>(); Reflection.getAnnotations(SubDao.class, annos); assertThat(annos.size(), equalTo(1)); }
DefaultProviderDataAccessor implements ProviderDataAccessor { @Override @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED) public List<ProviderProject> getProjectsByProviderConfigName(String providerConfigName) { try { Optional<Long> optionalConfigId = configurationAccessor.getProviderConfigurationByName(providerConfigName) .map(ConfigurationModel::getConfigurationId); if (optionalConfigId.isPresent()) { return providerProjectRepository.findByProviderConfigId(optionalConfigId.get()) .stream() .map(this::convertToProjectModel) .collect(Collectors.toList()); } } catch (AlertDatabaseConstraintException ignored) { } return List.of(); } @Autowired DefaultProviderDataAccessor(ProviderProjectRepository providerProjectRepository, ProviderUserProjectRelationRepository providerUserProjectRelationRepository, ProviderUserRepository providerUserRepository, ConfigurationAccessor configurationAccessor); @Override @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED) List<ProviderProject> getProjectsByProviderConfigName(String providerConfigName); @Override @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED) List<ProviderProject> getProjectsByProviderConfigId(Long providerConfigId); @Override void deleteProjects(Collection<ProviderProject> providerProjects); @Override @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED) Set<String> getEmailAddressesForProjectHref(String projectHref); @Override @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED) List<ProviderUserModel> getUsersByProviderConfigId(Long providerConfigId); @Override List<ProviderUserModel> getUsersByProviderConfigName(String providerConfigName); @Override void updateProjectAndUserData(Long providerConfigId, Map<ProviderProject, Set<String>> projectToUserData, Set<String> additionalRelevantUsers); static final int MAX_DESCRIPTION_LENGTH; static final int MAX_PROJECT_NAME_LENGTH; }
@Test public void getProjectsByProviderConfigNameTest() throws Exception { ConfigurationModel configurationModel = createConfigurationModel(); ProviderProjectEntity providerProjectEntity = new ProviderProjectEntity(name, description, href, projectOwnerEmail, 1L); ConfigurationAccessor configurationAccessor = Mockito.mock(ConfigurationAccessor.class); ProviderProjectRepository providerProjectRepository = Mockito.mock(ProviderProjectRepository.class); Mockito.when(configurationAccessor.getProviderConfigurationByName(Mockito.any())).thenReturn(Optional.of(configurationModel)); Mockito.when(providerProjectRepository.findByProviderConfigId(Mockito.any())).thenReturn(List.of(providerProjectEntity)); DefaultProviderDataAccessor providerDataAccessor = new DefaultProviderDataAccessor(providerProjectRepository, null, null, configurationAccessor); List<ProviderProject> providerProjectList = providerDataAccessor.getProjectsByProviderConfigName("test-providerConfigName"); assertEquals(1, providerProjectList.size()); ProviderProject providerProject = providerProjectList.get(0); testProviderProject(expectedProviderProject, providerProject); } @Test public void getProjectsByProviderConfigNameEmptyTest() throws Exception { ConfigurationAccessor configurationAccessor = Mockito.mock(ConfigurationAccessor.class); ProviderProjectRepository providerProjectRepository = Mockito.mock(ProviderProjectRepository.class); Mockito.when(configurationAccessor.getProviderConfigurationByName(Mockito.any())).thenReturn(Optional.empty()); DefaultProviderDataAccessor providerDataAccessor = new DefaultProviderDataAccessor(providerProjectRepository, null, null, configurationAccessor); List<ProviderProject> providerProjectList = providerDataAccessor.getProjectsByProviderConfigName("test-providerConfigName"); assertTrue(providerProjectList.isEmpty()); }
DefaultProviderTaskPropertiesAccessor implements ProviderTaskPropertiesAccessor { @Override public void setTaskProperty(Long configId, String taskName, String propertyKey, String propertyValue) throws AlertDatabaseConstraintException { if (null == configId || StringUtils.isBlank(taskName) || StringUtils.isBlank(propertyKey) || StringUtils.isBlank(propertyValue)) { throw new AlertDatabaseConstraintException("All fields are required to save a task property"); } ProviderTaskPropertiesEntity taskPropertyToSave = new ProviderTaskPropertiesEntity(configId, taskName, propertyKey, propertyValue); providerTaskPropertiesRepository.save(taskPropertyToSave); } @Autowired DefaultProviderTaskPropertiesAccessor(ProviderTaskPropertiesRepository providerTaskPropertiesRepository); @Override Optional<String> getTaskProperty(String taskName, String propertyKey); @Override void setTaskProperty(Long configId, String taskName, String propertyKey, String propertyValue); }
@Test public void setTaskPropertyExceptionTest() throws Exception { DefaultProviderTaskPropertiesAccessor providerTaskPropertiesAccessor = new DefaultProviderTaskPropertiesAccessor(providerTaskPropertiesRepository); try { providerTaskPropertiesAccessor.setTaskProperty(null, "", "", ""); fail(); } catch (AlertDatabaseConstraintException e) { assertNotNull(e); } } @Test public void setTaskPropertyTest() throws Exception { final Long newConfigId = 2L; final String newTaskName = "taskName-new"; final String newPropertyName = "propertyName-new"; final String newValue = "value-new"; DefaultProviderTaskPropertiesAccessor providerTaskPropertiesAccessor = new DefaultProviderTaskPropertiesAccessor(providerTaskPropertiesRepository); providerTaskPropertiesAccessor.setTaskProperty(newConfigId, newTaskName, newPropertyName, newValue); Optional<ProviderTaskPropertiesEntity> providerTaskPropertiesEntityOptional = providerTaskPropertiesRepository.findByTaskNameAndPropertyName(newTaskName, newPropertyName); assertTrue(providerTaskPropertiesEntityOptional.isPresent()); ProviderTaskPropertiesEntity providerTaskPropertiesEntity = providerTaskPropertiesEntityOptional.get(); assertEquals(newConfigId, providerTaskPropertiesEntity.getProviderConfigId()); assertEquals(newTaskName, providerTaskPropertiesEntity.getTaskName()); assertEquals(newPropertyName, providerTaskPropertiesEntity.getPropertyName()); assertEquals(newValue, providerTaskPropertiesEntity.getValue()); }
DefaultDescriptorAccessor implements DescriptorAccessor { @Override public List<RegisteredDescriptorModel> getRegisteredDescriptors() throws AlertDatabaseConstraintException { List<RegisteredDescriptorEntity> allDescriptors = registeredDescriptorRepository.findAll(); List<RegisteredDescriptorModel> descriptorModels = new ArrayList<>(); for (RegisteredDescriptorEntity entity : allDescriptors) { descriptorModels.add(createRegisteredDescriptorModel(entity)); } return descriptorModels; } @Autowired DefaultDescriptorAccessor(RegisteredDescriptorRepository registeredDescriptorRepository, DefinedFieldRepository definedFieldRepository, ConfigContextRepository configContextRepository, DescriptorTypeRepository descriptorTypeRepository); @Override List<RegisteredDescriptorModel> getRegisteredDescriptors(); @Override Optional<RegisteredDescriptorModel> getRegisteredDescriptorByKey(DescriptorKey descriptorKey); @Override List<RegisteredDescriptorModel> getRegisteredDescriptorsByType(DescriptorType descriptorType); @Override Optional<RegisteredDescriptorModel> getRegisteredDescriptorById(Long descriptorId); @Override List<DefinedFieldModel> getFieldsForDescriptor(DescriptorKey descriptorKey, ConfigContextEnum context); @Override List<DefinedFieldModel> getFieldsForDescriptorById(Long descriptorId, ConfigContextEnum context); }
@Test public void getRegisteredDescriptorsTest() throws Exception { final String name = "name-test"; final Long typeId = 1L; final DescriptorType descriptorType = DescriptorType.CHANNEL; RegisteredDescriptorEntity registeredDescriptorEntity = new RegisteredDescriptorEntity(name, typeId); registeredDescriptorEntity.setId(1L); DescriptorTypeEntity descriptorTypeEntity = new DescriptorTypeEntity(descriptorType.name()); RegisteredDescriptorRepository registeredDescriptorRepository = Mockito.mock(RegisteredDescriptorRepository.class); DescriptorTypeRepository descriptorTypeRepository = Mockito.mock(DescriptorTypeRepository.class); Mockito.when(registeredDescriptorRepository.findAll()).thenReturn(List.of(registeredDescriptorEntity)); Mockito.when(descriptorTypeRepository.findById(Mockito.any())).thenReturn(Optional.of(descriptorTypeEntity)); DefaultDescriptorAccessor descriptorAccessor = new DefaultDescriptorAccessor(registeredDescriptorRepository, null, null, descriptorTypeRepository); List<RegisteredDescriptorModel> registeredDescriptorModelList = descriptorAccessor.getRegisteredDescriptors(); assertEquals(1, registeredDescriptorModelList.size()); RegisteredDescriptorModel registeredDescriptorModel = registeredDescriptorModelList.get(0); assertEquals(name, registeredDescriptorModel.getName()); assertEquals(descriptorType, registeredDescriptorModel.getType()); }
DefaultDescriptorAccessor implements DescriptorAccessor { @Override public Optional<RegisteredDescriptorModel> getRegisteredDescriptorByKey(DescriptorKey descriptorKey) throws AlertDatabaseConstraintException { if (null == descriptorKey || StringUtils.isBlank(descriptorKey.getUniversalKey())) { throw new AlertDatabaseConstraintException(String.format("DescriptorKey is not valid. %s", descriptorKey)); } Optional<RegisteredDescriptorEntity> descriptorEntity = registeredDescriptorRepository.findFirstByName(descriptorKey.getUniversalKey()); if (descriptorEntity.isPresent()) { return Optional.of(createRegisteredDescriptorModel(descriptorEntity.get())); } return Optional.empty(); } @Autowired DefaultDescriptorAccessor(RegisteredDescriptorRepository registeredDescriptorRepository, DefinedFieldRepository definedFieldRepository, ConfigContextRepository configContextRepository, DescriptorTypeRepository descriptorTypeRepository); @Override List<RegisteredDescriptorModel> getRegisteredDescriptors(); @Override Optional<RegisteredDescriptorModel> getRegisteredDescriptorByKey(DescriptorKey descriptorKey); @Override List<RegisteredDescriptorModel> getRegisteredDescriptorsByType(DescriptorType descriptorType); @Override Optional<RegisteredDescriptorModel> getRegisteredDescriptorById(Long descriptorId); @Override List<DefinedFieldModel> getFieldsForDescriptor(DescriptorKey descriptorKey, ConfigContextEnum context); @Override List<DefinedFieldModel> getFieldsForDescriptorById(Long descriptorId, ConfigContextEnum context); }
@Test public void getRegisteredDescriptorByKeyTest() throws Exception { final String name = "name-test"; final Long typeId = 1L; final DescriptorType descriptorType = DescriptorType.CHANNEL; RegisteredDescriptorEntity registeredDescriptorEntity = new RegisteredDescriptorEntity(name, typeId); registeredDescriptorEntity.setId(1L); DescriptorKey descriptorKey = createDescriptorKey("descriptorKey-test"); DescriptorKey emptyDescriptorKey = createDescriptorKey("bad-key"); DescriptorTypeEntity descriptorTypeEntity = new DescriptorTypeEntity(descriptorType.name()); RegisteredDescriptorRepository registeredDescriptorRepository = Mockito.mock(RegisteredDescriptorRepository.class); DescriptorTypeRepository descriptorTypeRepository = Mockito.mock(DescriptorTypeRepository.class); Mockito.when(registeredDescriptorRepository.findFirstByName(descriptorKey.getUniversalKey())).thenReturn(Optional.of(registeredDescriptorEntity)); Mockito.when(registeredDescriptorRepository.findFirstByName(emptyDescriptorKey.getUniversalKey())).thenReturn(Optional.empty()); Mockito.when(descriptorTypeRepository.findById(Mockito.any())).thenReturn(Optional.of(descriptorTypeEntity)); DefaultDescriptorAccessor descriptorAccessor = new DefaultDescriptorAccessor(registeredDescriptorRepository, null, null, descriptorTypeRepository); Optional<RegisteredDescriptorModel> registeredDescriptorModelOptional = descriptorAccessor.getRegisteredDescriptorByKey(descriptorKey); Optional<RegisteredDescriptorModel> registeredDescriptorModelOptionalEmpty = descriptorAccessor.getRegisteredDescriptorByKey(emptyDescriptorKey); assertTrue(registeredDescriptorModelOptional.isPresent()); RegisteredDescriptorModel registeredDescriptorModel = registeredDescriptorModelOptional.get(); assertFalse(registeredDescriptorModelOptionalEmpty.isPresent()); assertEquals(name, registeredDescriptorModel.getName()); assertEquals(descriptorType, registeredDescriptorModel.getType()); } @Test public void descriptorKeyFailureTest() throws Exception { DefaultDescriptorAccessor descriptorAccessor = new DefaultDescriptorAccessor(null, null, null, null); DescriptorKey descriptorKey = createDescriptorKey(""); try { descriptorAccessor.getRegisteredDescriptorByKey(descriptorKey); fail(); } catch (AlertDatabaseConstraintException e) { logger.error(e.getMessage(), e); } }
DefaultDescriptorAccessor implements DescriptorAccessor { @Override public List<RegisteredDescriptorModel> getRegisteredDescriptorsByType(DescriptorType descriptorType) throws AlertDatabaseConstraintException { if (null == descriptorType) { throw new AlertDatabaseConstraintException("Descriptor type cannot be null"); } Long typeId = saveDescriptorTypeAndReturnId(descriptorType); Collection<RegisteredDescriptorEntity> allDescriptors = registeredDescriptorRepository.findByTypeId(typeId); List<RegisteredDescriptorModel> descriptorModels = new ArrayList<>(); for (RegisteredDescriptorEntity entity : allDescriptors) { descriptorModels.add(createRegisteredDescriptorModel(entity)); } return descriptorModels; } @Autowired DefaultDescriptorAccessor(RegisteredDescriptorRepository registeredDescriptorRepository, DefinedFieldRepository definedFieldRepository, ConfigContextRepository configContextRepository, DescriptorTypeRepository descriptorTypeRepository); @Override List<RegisteredDescriptorModel> getRegisteredDescriptors(); @Override Optional<RegisteredDescriptorModel> getRegisteredDescriptorByKey(DescriptorKey descriptorKey); @Override List<RegisteredDescriptorModel> getRegisteredDescriptorsByType(DescriptorType descriptorType); @Override Optional<RegisteredDescriptorModel> getRegisteredDescriptorById(Long descriptorId); @Override List<DefinedFieldModel> getFieldsForDescriptor(DescriptorKey descriptorKey, ConfigContextEnum context); @Override List<DefinedFieldModel> getFieldsForDescriptorById(Long descriptorId, ConfigContextEnum context); }
@Test public void getRegisteredDescriptorsByTypeTest() throws Exception { final String name = "name-test"; final Long typeId = 1L; final DescriptorType descriptorType = DescriptorType.CHANNEL; RegisteredDescriptorRepository registeredDescriptorRepository = Mockito.mock(RegisteredDescriptorRepository.class); DescriptorTypeRepository descriptorTypeRepository = Mockito.mock(DescriptorTypeRepository.class); RegisteredDescriptorEntity registeredDescriptorEntity = new RegisteredDescriptorEntity(name, typeId); registeredDescriptorEntity.setId(1L); DescriptorTypeEntity descriptorTypeEntity = new DescriptorTypeEntity(descriptorType.name()); descriptorTypeEntity.setId(1L); Mockito.when(descriptorTypeRepository.findFirstByType(descriptorType.name())).thenReturn(Optional.of(descriptorTypeEntity)); Mockito.when(registeredDescriptorRepository.findByTypeId(Mockito.any())).thenReturn(List.of(registeredDescriptorEntity)); Mockito.when(descriptorTypeRepository.findById(registeredDescriptorEntity.getTypeId())).thenReturn(Optional.of(descriptorTypeEntity)); DefaultDescriptorAccessor descriptorAccessor = new DefaultDescriptorAccessor(registeredDescriptorRepository, null, null, descriptorTypeRepository); List<RegisteredDescriptorModel> registeredDescriptorModelList = descriptorAccessor.getRegisteredDescriptorsByType(descriptorType); assertEquals(1, registeredDescriptorModelList.size()); RegisteredDescriptorModel registeredDescriptorModel = registeredDescriptorModelList.get(0); assertEquals(name, registeredDescriptorModel.getName()); assertEquals(descriptorType, registeredDescriptorModel.getType()); } @Test public void getRegisteredDescriptorsByTypeMissingDescriptorTypeTest() throws Exception { final String name = "name-test"; final Long typeId = 1L; final DescriptorType descriptorType = DescriptorType.CHANNEL; RegisteredDescriptorRepository registeredDescriptorRepository = Mockito.mock(RegisteredDescriptorRepository.class); DescriptorTypeRepository descriptorTypeRepository = Mockito.mock(DescriptorTypeRepository.class); RegisteredDescriptorEntity registeredDescriptorEntity = new RegisteredDescriptorEntity(name, typeId); registeredDescriptorEntity.setId(1L); DescriptorTypeEntity descriptorTypeEntity = new DescriptorTypeEntity(descriptorType.name()); descriptorTypeEntity.setId(1L); Mockito.when(descriptorTypeRepository.findFirstByType(descriptorType.name())).thenReturn(Optional.empty()); Mockito.when(descriptorTypeRepository.save(Mockito.any())).thenReturn(descriptorTypeEntity); Mockito.when(registeredDescriptorRepository.findByTypeId(Mockito.any())).thenReturn(List.of(registeredDescriptorEntity)); Mockito.when(descriptorTypeRepository.findById(registeredDescriptorEntity.getTypeId())).thenReturn(Optional.of(descriptorTypeEntity)); DefaultDescriptorAccessor descriptorAccessor = new DefaultDescriptorAccessor(registeredDescriptorRepository, null, null, descriptorTypeRepository); List<RegisteredDescriptorModel> registeredDescriptorModelList = descriptorAccessor.getRegisteredDescriptorsByType(descriptorType); assertEquals(1, registeredDescriptorModelList.size()); RegisteredDescriptorModel registeredDescriptorModel = registeredDescriptorModelList.get(0); assertEquals(name, registeredDescriptorModel.getName()); assertEquals(descriptorType, registeredDescriptorModel.getType()); } @Test public void descriptorTypeFailureTest() throws Exception { DefaultDescriptorAccessor descriptorAccessor = new DefaultDescriptorAccessor(null, null, null, null); DescriptorType descriptorType = null; try { descriptorAccessor.getRegisteredDescriptorsByType(descriptorType); fail(); } catch (AlertDatabaseConstraintException e) { logger.error(e.getMessage(), e); } }
DefaultDescriptorAccessor implements DescriptorAccessor { @Override public Optional<RegisteredDescriptorModel> getRegisteredDescriptorById(Long descriptorId) throws AlertDatabaseConstraintException { RegisteredDescriptorEntity descriptor = findDescriptorById(descriptorId); return Optional.of(createRegisteredDescriptorModel(descriptor)); } @Autowired DefaultDescriptorAccessor(RegisteredDescriptorRepository registeredDescriptorRepository, DefinedFieldRepository definedFieldRepository, ConfigContextRepository configContextRepository, DescriptorTypeRepository descriptorTypeRepository); @Override List<RegisteredDescriptorModel> getRegisteredDescriptors(); @Override Optional<RegisteredDescriptorModel> getRegisteredDescriptorByKey(DescriptorKey descriptorKey); @Override List<RegisteredDescriptorModel> getRegisteredDescriptorsByType(DescriptorType descriptorType); @Override Optional<RegisteredDescriptorModel> getRegisteredDescriptorById(Long descriptorId); @Override List<DefinedFieldModel> getFieldsForDescriptor(DescriptorKey descriptorKey, ConfigContextEnum context); @Override List<DefinedFieldModel> getFieldsForDescriptorById(Long descriptorId, ConfigContextEnum context); }
@Test public void getRegisteredDescriptorByIdTest() throws Exception { final String name = "name-test"; final Long typeId = 1L; final DescriptorType descriptorType = DescriptorType.CHANNEL; final Long descriptorId = 2L; RegisteredDescriptorEntity registeredDescriptorEntity = new RegisteredDescriptorEntity(name, typeId); registeredDescriptorEntity.setId(1L); DescriptorTypeEntity descriptorTypeEntity = new DescriptorTypeEntity(descriptorType.name()); descriptorTypeEntity.setId(2L); RegisteredDescriptorRepository registeredDescriptorRepository = Mockito.mock(RegisteredDescriptorRepository.class); DescriptorTypeRepository descriptorTypeRepository = Mockito.mock(DescriptorTypeRepository.class); Mockito.when(registeredDescriptorRepository.findById(descriptorId)).thenReturn(Optional.of(registeredDescriptorEntity)); Mockito.when(descriptorTypeRepository.findById(Mockito.any())).thenReturn(Optional.of(descriptorTypeEntity)); DefaultDescriptorAccessor descriptorAccessor = new DefaultDescriptorAccessor(registeredDescriptorRepository, null, null, descriptorTypeRepository); Optional<RegisteredDescriptorModel> registeredDescriptorModelOptional = descriptorAccessor.getRegisteredDescriptorById(descriptorId); assertTrue(registeredDescriptorModelOptional.isPresent()); RegisteredDescriptorModel registeredDescriptorModel = registeredDescriptorModelOptional.get(); assertEquals(typeId, registeredDescriptorModel.getId()); assertEquals(name, registeredDescriptorModel.getName()); assertEquals(descriptorType, registeredDescriptorModel.getType()); }
DefaultDescriptorAccessor implements DescriptorAccessor { @Override public List<DefinedFieldModel> getFieldsForDescriptor(DescriptorKey descriptorKey, ConfigContextEnum context) throws AlertDatabaseConstraintException { RegisteredDescriptorEntity descriptor = findDescriptorByKey(descriptorKey); Long contextId = saveContextAndReturnId(context); return getFieldsForDescriptorId(descriptor.getId(), contextId, context); } @Autowired DefaultDescriptorAccessor(RegisteredDescriptorRepository registeredDescriptorRepository, DefinedFieldRepository definedFieldRepository, ConfigContextRepository configContextRepository, DescriptorTypeRepository descriptorTypeRepository); @Override List<RegisteredDescriptorModel> getRegisteredDescriptors(); @Override Optional<RegisteredDescriptorModel> getRegisteredDescriptorByKey(DescriptorKey descriptorKey); @Override List<RegisteredDescriptorModel> getRegisteredDescriptorsByType(DescriptorType descriptorType); @Override Optional<RegisteredDescriptorModel> getRegisteredDescriptorById(Long descriptorId); @Override List<DefinedFieldModel> getFieldsForDescriptor(DescriptorKey descriptorKey, ConfigContextEnum context); @Override List<DefinedFieldModel> getFieldsForDescriptorById(Long descriptorId, ConfigContextEnum context); }
@Test public void getFieldsForDescriptorTest() throws Exception { final String name = "name-test"; final Long typeId = 1L; final ConfigContextEnum configContextEnum = ConfigContextEnum.GLOBAL; final ConfigContextEnum invalidConfigContextEnum = ConfigContextEnum.DISTRIBUTION; final String definedFieldsKey = "defined-field-key-test"; Boolean isSensitive = Boolean.TRUE; RegisteredDescriptorEntity registeredDescriptorEntity = new RegisteredDescriptorEntity(name, typeId); registeredDescriptorEntity.setId(1L); DescriptorKey descriptorKey = createDescriptorKey("descriptorKey-test"); ConfigContextEntity configContextEntity = new ConfigContextEntity(configContextEnum.name()); configContextEntity.setId(3L); DefinedFieldEntity definedFieldEntity = new DefinedFieldEntity(definedFieldsKey, isSensitive); RegisteredDescriptorRepository registeredDescriptorRepository = Mockito.mock(RegisteredDescriptorRepository.class); DefinedFieldRepository definedFieldRepository = Mockito.mock(DefinedFieldRepository.class); ConfigContextRepository configContextRepository = Mockito.mock(ConfigContextRepository.class); DescriptorTypeRepository descriptorTypeRepository = Mockito.mock(DescriptorTypeRepository.class); Mockito.when(registeredDescriptorRepository.findFirstByName(descriptorKey.getUniversalKey())).thenReturn(Optional.of(registeredDescriptorEntity)); Mockito.when(configContextRepository.findFirstByContext(configContextEnum.name())).thenReturn(Optional.of(configContextEntity)); Mockito.when(configContextRepository.findFirstByContext(invalidConfigContextEnum.name())).thenReturn(Optional.empty()); Mockito.when(configContextRepository.save(Mockito.any())).thenReturn(configContextEntity); Mockito.when(definedFieldRepository.findByDescriptorIdAndContext(Mockito.any(), Mockito.any())).thenReturn(List.of(definedFieldEntity)); DefaultDescriptorAccessor descriptorAccessor = new DefaultDescriptorAccessor(registeredDescriptorRepository, definedFieldRepository, configContextRepository, descriptorTypeRepository); List<DefinedFieldModel> definedFieldModelList = descriptorAccessor.getFieldsForDescriptor(descriptorKey, configContextEnum); List<DefinedFieldModel> emptyConfigContextDefinedFieldModelList = descriptorAccessor.getFieldsForDescriptor(descriptorKey, invalidConfigContextEnum); assertEquals(1, definedFieldModelList.size()); DefinedFieldModel definedFieldModel = definedFieldModelList.get(0); assertEquals(definedFieldsKey, definedFieldModel.getKey()); assertEquals(isSensitive, definedFieldModel.getSensitive()); List<ConfigContextEnum> configContextList = new ArrayList<>(definedFieldModel.getContexts()); assertEquals(configContextEnum, configContextList.get(0)); assertEquals(1, emptyConfigContextDefinedFieldModelList.size()); DefinedFieldModel emptyConfigContextDefinedFieldModel = emptyConfigContextDefinedFieldModelList.get(0); assertEquals(definedFieldsKey, emptyConfigContextDefinedFieldModel.getKey()); assertEquals(isSensitive, emptyConfigContextDefinedFieldModel.getSensitive()); List<ConfigContextEnum> configContextList2 = new ArrayList<>(emptyConfigContextDefinedFieldModel.getContexts()); assertEquals(invalidConfigContextEnum, configContextList2.get(0)); }
DefaultDescriptorAccessor implements DescriptorAccessor { @Override public List<DefinedFieldModel> getFieldsForDescriptorById(Long descriptorId, ConfigContextEnum context) throws AlertDatabaseConstraintException { RegisteredDescriptorEntity descriptor = findDescriptorById(descriptorId); Long contextId = saveContextAndReturnId(context); return getFieldsForDescriptorId(descriptor.getId(), contextId, context); } @Autowired DefaultDescriptorAccessor(RegisteredDescriptorRepository registeredDescriptorRepository, DefinedFieldRepository definedFieldRepository, ConfigContextRepository configContextRepository, DescriptorTypeRepository descriptorTypeRepository); @Override List<RegisteredDescriptorModel> getRegisteredDescriptors(); @Override Optional<RegisteredDescriptorModel> getRegisteredDescriptorByKey(DescriptorKey descriptorKey); @Override List<RegisteredDescriptorModel> getRegisteredDescriptorsByType(DescriptorType descriptorType); @Override Optional<RegisteredDescriptorModel> getRegisteredDescriptorById(Long descriptorId); @Override List<DefinedFieldModel> getFieldsForDescriptor(DescriptorKey descriptorKey, ConfigContextEnum context); @Override List<DefinedFieldModel> getFieldsForDescriptorById(Long descriptorId, ConfigContextEnum context); }
@Test public void getFieldsForDescriptorByIdTest() throws Exception { final String name = "name-test"; final Long typeId = 1L; final ConfigContextEnum configContextEnum = ConfigContextEnum.GLOBAL; final String definedFieldsKey = "defined-field-key-test"; Boolean isSensitive = Boolean.TRUE; final Long descriptorId = 1L; RegisteredDescriptorEntity registeredDescriptorEntity = new RegisteredDescriptorEntity(name, typeId); registeredDescriptorEntity.setId(1L); ConfigContextEntity configContextEntity = new ConfigContextEntity(configContextEnum.name()); configContextEntity.setId(3L); DefinedFieldEntity definedFieldEntity = new DefinedFieldEntity(definedFieldsKey, isSensitive); RegisteredDescriptorRepository registeredDescriptorRepository = Mockito.mock(RegisteredDescriptorRepository.class); DefinedFieldRepository definedFieldRepository = Mockito.mock(DefinedFieldRepository.class); ConfigContextRepository configContextRepository = Mockito.mock(ConfigContextRepository.class); DescriptorTypeRepository descriptorTypeRepository = Mockito.mock(DescriptorTypeRepository.class); Mockito.when(registeredDescriptorRepository.findById(descriptorId)).thenReturn(Optional.of(registeredDescriptorEntity)); Mockito.when(configContextRepository.findFirstByContext(configContextEnum.name())).thenReturn(Optional.of(configContextEntity)); Mockito.when(definedFieldRepository.findByDescriptorIdAndContext(Mockito.any(), Mockito.any())).thenReturn(List.of(definedFieldEntity)); DefaultDescriptorAccessor descriptorAccessor = new DefaultDescriptorAccessor(registeredDescriptorRepository, definedFieldRepository, configContextRepository, descriptorTypeRepository); List<DefinedFieldModel> definedFieldModelList = descriptorAccessor.getFieldsForDescriptorById(descriptorId, configContextEnum); assertEquals(1, definedFieldModelList.size()); DefinedFieldModel definedFieldModel = definedFieldModelList.get(0); assertEquals(definedFieldsKey, definedFieldModel.getKey()); assertEquals(isSensitive, definedFieldModel.getSensitive()); List<ConfigContextEnum> configContextList = new ArrayList<>(definedFieldModel.getContexts()); assertEquals(configContextEnum, configContextList.get(0)); }
DefaultProviderDataAccessor implements ProviderDataAccessor { @Override public List<ProviderUserModel> getUsersByProviderConfigName(String providerConfigName) { if (StringUtils.isBlank(providerConfigName)) { return List.of(); } try { Optional<Long> optionalProviderConfigId = configurationAccessor.getProviderConfigurationByName(providerConfigName) .map(ConfigurationModel::getConfigurationId); if (optionalProviderConfigId.isPresent()) { return getUsersByProviderConfigId(optionalProviderConfigId.get()); } } catch (AlertDatabaseConstraintException ignored) { } return List.of(); } @Autowired DefaultProviderDataAccessor(ProviderProjectRepository providerProjectRepository, ProviderUserProjectRelationRepository providerUserProjectRelationRepository, ProviderUserRepository providerUserRepository, ConfigurationAccessor configurationAccessor); @Override @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED) List<ProviderProject> getProjectsByProviderConfigName(String providerConfigName); @Override @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED) List<ProviderProject> getProjectsByProviderConfigId(Long providerConfigId); @Override void deleteProjects(Collection<ProviderProject> providerProjects); @Override @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED) Set<String> getEmailAddressesForProjectHref(String projectHref); @Override @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED) List<ProviderUserModel> getUsersByProviderConfigId(Long providerConfigId); @Override List<ProviderUserModel> getUsersByProviderConfigName(String providerConfigName); @Override void updateProjectAndUserData(Long providerConfigId, Map<ProviderProject, Set<String>> projectToUserData, Set<String> additionalRelevantUsers); static final int MAX_DESCRIPTION_LENGTH; static final int MAX_PROJECT_NAME_LENGTH; }
@Test public void getUsersByProviderConfigNameOptionalEmptyTest() throws Exception { ConfigurationAccessor configurationAccessor = Mockito.mock(ConfigurationAccessor.class); Mockito.when(configurationAccessor.getProviderConfigurationByName(Mockito.any())).thenReturn(Optional.empty()); DefaultProviderDataAccessor providerDataAccessor = new DefaultProviderDataAccessor(null, null, null, configurationAccessor); List<ProviderUserModel> providerUserModelList = providerDataAccessor.getUsersByProviderConfigName("providerConfigName-test"); assertTrue(providerUserModelList.isEmpty()); } @Test public void getUsersByProviderConfigNameTest() throws Exception { ConfigurationModel configurationModel = createConfigurationModel(); ProviderUserEntity providerUserEntity = new ProviderUserEntity(projectOwnerEmail, true, 1L); ProviderProjectRepository providerProjectRepository = Mockito.mock(ProviderProjectRepository.class); ProviderUserRepository providerUserRepository = Mockito.mock(ProviderUserRepository.class); ConfigurationAccessor configurationAccessor = Mockito.mock(ConfigurationAccessor.class); Mockito.when(configurationAccessor.getProviderConfigurationByName(Mockito.any())).thenReturn(Optional.of(configurationModel)); Mockito.when(providerUserRepository.findByProviderConfigId(Mockito.any())).thenReturn(List.of(providerUserEntity)); DefaultProviderDataAccessor providerDataAccessor = new DefaultProviderDataAccessor(providerProjectRepository, null, providerUserRepository, configurationAccessor); List<ProviderUserModel> providerUserModelList = providerDataAccessor.getUsersByProviderConfigName("providerConfigName-test"); assertEquals(1, providerUserModelList.size()); ProviderUserModel providerUserModel = providerUserModelList.get(0); assertEquals(projectOwnerEmail, providerUserModel.getEmailAddress()); assertTrue(providerUserModel.getOptOut()); } @Test public void getUsersByProviderConfigNameBlankTest() { DefaultProviderDataAccessor providerDataAccessor = new DefaultProviderDataAccessor(null, null, null, null); List<ProviderUserModel> providerUserModelList = providerDataAccessor.getUsersByProviderConfigName(""); assertTrue(providerUserModelList.isEmpty()); }
DefaultUserAccessor implements UserAccessor { @Override public List<UserModel> getUsers() { List<UserEntity> userList = userRepository.findAll(); return userList.stream().map(this::createModel).collect(Collectors.toList()); } @Autowired DefaultUserAccessor(UserRepository userRepository, UserRoleRepository userRoleRepository, PasswordEncoder defaultPasswordEncoder, DefaultRoleAccessor roleAccessor, AuthenticationTypeAccessor authenticationTypeAccessor); @Override List<UserModel> getUsers(); @Override Optional<UserModel> getUser(Long userId); @Override Optional<UserModel> getUser(String username); @Override UserModel addUser(String userName, String password, String emailAddress); @Override UserModel addUser(UserModel user, boolean passwordEncoded); @Override UserModel updateUser(UserModel user, boolean passwordEncoded); @Override boolean assignRoles(String username, Set<Long> roleIds); @Override boolean changeUserPassword(String username, String newPassword); @Override boolean changeUserEmailAddress(String username, String emailAddress); @Override void deleteUser(String userName); @Override void deleteUser(Long userId); }
@Test public void getUsersTest() { final Long authenticationTypeId = 1L; final String roleName = "userName"; UserEntity userEntity = new UserEntity(username, password, emailAddress, authenticationTypeId); userEntity.setId(1L); UserRoleRelation userRoleRelation = new UserRoleRelation(1L, 2L); UserRoleModel userRoleModel = createUserRoleModel(1L, roleName, true); Mockito.when(userRepository.findAll()).thenReturn(List.of(userEntity)); createModelMocks(userRoleRelation, userRoleModel, AuthenticationType.DATABASE); DefaultUserAccessor defaultUserAccessor = new DefaultUserAccessor(userRepository, userRoleRepository, defaultPasswordEncoder, roleAccessor, authenticationTypeAccessor); List<UserModel> userModelList = defaultUserAccessor.getUsers(); assertEquals(1, userModelList.size()); UserModel userModel = userModelList.get(0); testUserModel(userEntity.getId(), username, emailAddress, roleName, userModel); }
DefaultUserAccessor implements UserAccessor { @Override public Optional<UserModel> getUser(Long userId) { return userRepository.findById(userId).map(this::createModel); } @Autowired DefaultUserAccessor(UserRepository userRepository, UserRoleRepository userRoleRepository, PasswordEncoder defaultPasswordEncoder, DefaultRoleAccessor roleAccessor, AuthenticationTypeAccessor authenticationTypeAccessor); @Override List<UserModel> getUsers(); @Override Optional<UserModel> getUser(Long userId); @Override Optional<UserModel> getUser(String username); @Override UserModel addUser(String userName, String password, String emailAddress); @Override UserModel addUser(UserModel user, boolean passwordEncoded); @Override UserModel updateUser(UserModel user, boolean passwordEncoded); @Override boolean assignRoles(String username, Set<Long> roleIds); @Override boolean changeUserPassword(String username, String newPassword); @Override boolean changeUserEmailAddress(String username, String emailAddress); @Override void deleteUser(String userName); @Override void deleteUser(Long userId); }
@Test public void getUserByUserIdTest() { final Long userId = 1L; final Long emptyUserId = 5L; final Long authenticationTypeId = 1L; final String roleName = "userName"; UserEntity userEntity = new UserEntity(username, password, emailAddress, authenticationTypeId); userEntity.setId(1L); UserRoleRelation userRoleRelation = new UserRoleRelation(1L, 2L); UserRoleModel userRoleModel = createUserRoleModel(1L, roleName, true); Mockito.when(userRepository.findById(userId)).thenReturn(Optional.of(userEntity)); Mockito.when(userRepository.findById(emptyUserId)).thenReturn(Optional.empty()); createModelMocks(userRoleRelation, userRoleModel, AuthenticationType.DATABASE); DefaultUserAccessor defaultUserAccessor = new DefaultUserAccessor(userRepository, userRoleRepository, defaultPasswordEncoder, roleAccessor, authenticationTypeAccessor); Optional<UserModel> userModelOptional = defaultUserAccessor.getUser(userId); Optional<UserModel> userModelOptionalEmpty = defaultUserAccessor.getUser(emptyUserId); assertTrue(userModelOptional.isPresent()); assertFalse(userModelOptionalEmpty.isPresent()); UserModel userModel = userModelOptional.get(); testUserModel(userEntity.getId(), username, emailAddress, roleName, userModel); } @Test public void getUserByUsernameTest() { final String emptyUsername = ""; final Long authenticationTypeId = 1L; final String roleName = "userName"; UserEntity userEntity = new UserEntity(username, password, emailAddress, authenticationTypeId); userEntity.setId(1L); UserRoleRelation userRoleRelation = new UserRoleRelation(1L, 2L); UserRoleModel userRoleModel = createUserRoleModel(1L, roleName, true); Mockito.when(userRepository.findByUserName(username)).thenReturn(Optional.of(userEntity)); Mockito.when(userRepository.findByUserName(emptyUsername)).thenReturn(Optional.empty()); createModelMocks(userRoleRelation, userRoleModel, AuthenticationType.DATABASE); DefaultUserAccessor defaultUserAccessor = new DefaultUserAccessor(userRepository, userRoleRepository, defaultPasswordEncoder, roleAccessor, authenticationTypeAccessor); Optional<UserModel> userModelOptional = defaultUserAccessor.getUser(username); Optional<UserModel> userModelOptionalEmpty = defaultUserAccessor.getUser(emptyUsername); assertTrue(userModelOptional.isPresent()); assertFalse(userModelOptionalEmpty.isPresent()); UserModel userModel = userModelOptional.get(); testUserModel(userEntity.getId(), username, emailAddress, roleName, userModel); }
DefaultUserAccessor implements UserAccessor { @Override public UserModel addUser(String userName, String password, String emailAddress) throws AlertDatabaseConstraintException { return addUser(UserModel.newUser(userName, password, emailAddress, AuthenticationType.DATABASE, Collections.emptySet(), true), false); } @Autowired DefaultUserAccessor(UserRepository userRepository, UserRoleRepository userRoleRepository, PasswordEncoder defaultPasswordEncoder, DefaultRoleAccessor roleAccessor, AuthenticationTypeAccessor authenticationTypeAccessor); @Override List<UserModel> getUsers(); @Override Optional<UserModel> getUser(Long userId); @Override Optional<UserModel> getUser(String username); @Override UserModel addUser(String userName, String password, String emailAddress); @Override UserModel addUser(UserModel user, boolean passwordEncoded); @Override UserModel updateUser(UserModel user, boolean passwordEncoded); @Override boolean assignRoles(String username, Set<Long> roleIds); @Override boolean changeUserPassword(String username, String newPassword); @Override boolean changeUserEmailAddress(String username, String emailAddress); @Override void deleteUser(String userName); @Override void deleteUser(Long userId); }
@Test public void addUserTest() throws Exception { final String roleName = "userName"; UserEntity userEntity = new UserEntity(username, password, emailAddress, 2L); userEntity.setId(1L); AuthenticationTypeDetails authenticationTypeDetails = new AuthenticationTypeDetails(2L, "authentication-name"); UserRoleRelation userRoleRelation = new UserRoleRelation(1L, 2L); UserRoleModel userRoleModel = createUserRoleModel(1L, roleName, true); Mockito.when(userRepository.findByUserName(Mockito.any())).thenReturn(Optional.empty()); Mockito.when(authenticationTypeAccessor.getAuthenticationTypeDetails(Mockito.any())).thenReturn(Optional.of(authenticationTypeDetails)); Mockito.when(userRepository.save(Mockito.any())).thenReturn(userEntity); createModelMocks(userRoleRelation, userRoleModel, AuthenticationType.DATABASE); DefaultUserAccessor defaultUserAccessor = new DefaultUserAccessor(userRepository, userRoleRepository, defaultPasswordEncoder, roleAccessor, authenticationTypeAccessor); UserModel userModel = defaultUserAccessor.addUser(username, password, emailAddress); testUserModel(userEntity.getId(), username, emailAddress, roleName, userModel); } @Test public void addUserExistsTest() throws Exception { UserEntity userEntity = new UserEntity(username, password, emailAddress, 2L); userEntity.setId(1L); Mockito.when(userRepository.findByUserName(Mockito.any())).thenReturn(Optional.of(userEntity)); DefaultUserAccessor defaultUserAccessor = new DefaultUserAccessor(userRepository, userRoleRepository, defaultPasswordEncoder, roleAccessor, authenticationTypeAccessor); try { defaultUserAccessor.addUser(username, password, emailAddress); fail("User with the same name that already exists in the userRepository did not throw expected AlertForbiddenOperationException."); } catch (AlertDatabaseConstraintException e) { assertNotNull(e); } }
DefaultUserAccessor implements UserAccessor { @Override public UserModel updateUser(UserModel user, boolean passwordEncoded) throws AlertDatabaseConstraintException { Long userId = user.getId(); if (null == userId) { throw new AlertDatabaseConstraintException("A user id must be specified"); } UserEntity existingUser = userRepository.findById(userId) .orElseThrow(() -> new AlertDatabaseConstraintException(String.format("No user found with id '%s'", userId))); Long existingUserId = existingUser.getId(); UserEntity savedEntity = existingUser; Optional<AuthenticationType> authenticationType = authenticationTypeAccessor.getAuthenticationType(existingUser.getAuthenticationType()); if (!authenticationType.isPresent()) { throw new AlertDatabaseConstraintException("Unknown Authentication Type, user not updated."); } else if (AuthenticationType.DATABASE != authenticationType.get()) { boolean isUserNameInvalid = !StringUtils.equals(existingUser.getUserName(), user.getName()); boolean isEmailInvalid = !StringUtils.equals(existingUser.getEmailAddress(), user.getEmailAddress()); boolean isPasswordSet = StringUtils.isNotBlank(user.getPassword()); if (isUserNameInvalid || isEmailInvalid || isPasswordSet) { throw new AlertDatabaseConstraintException("An external user cannot change its credentials."); } } else { String password = passwordEncoded ? user.getPassword() : defaultPasswordEncoder.encode(user.getPassword()); UserEntity newEntity = new UserEntity(user.getName(), password, user.getEmailAddress(), user.isExpired(), user.isLocked(), user.isPasswordExpired(), user.isEnabled(), existingUser.getAuthenticationType()); newEntity.setId(existingUserId); savedEntity = userRepository.save(newEntity); } roleAccessor.updateUserRoles(existingUserId, user.getRoles()); return createModel(savedEntity); } @Autowired DefaultUserAccessor(UserRepository userRepository, UserRoleRepository userRoleRepository, PasswordEncoder defaultPasswordEncoder, DefaultRoleAccessor roleAccessor, AuthenticationTypeAccessor authenticationTypeAccessor); @Override List<UserModel> getUsers(); @Override Optional<UserModel> getUser(Long userId); @Override Optional<UserModel> getUser(String username); @Override UserModel addUser(String userName, String password, String emailAddress); @Override UserModel addUser(UserModel user, boolean passwordEncoded); @Override UserModel updateUser(UserModel user, boolean passwordEncoded); @Override boolean assignRoles(String username, Set<Long> roleIds); @Override boolean changeUserPassword(String username, String newPassword); @Override boolean changeUserEmailAddress(String username, String emailAddress); @Override void deleteUser(String userName); @Override void deleteUser(Long userId); }
@Test public void updateUserTest() throws Exception { final String roleName = "userName"; AuthenticationType authenticationType = AuthenticationType.DATABASE; UserEntity userEntity = new UserEntity(username, password, emailAddress, 2L); userEntity.setId(1L); UserRoleModel roles = createUserRoleModel(1L, roleName, true); UserModel userModel = UserModel.existingUser(1L, username, password, emailAddress, authenticationType, Set.of(roles), true); UserRoleRelation userRoleRelation = new UserRoleRelation(1L, 2L); UserRoleModel userRoleModel = createUserRoleModel(1L, roleName, true); Mockito.when(userRepository.findById(Mockito.any())).thenReturn(Optional.of(userEntity)); Mockito.when(authenticationTypeAccessor.getAuthenticationType(Mockito.any())).thenReturn(Optional.of(authenticationType)); Mockito.when(userRepository.save(Mockito.any())).thenReturn(userEntity); createModelMocks(userRoleRelation, userRoleModel, authenticationType); DefaultUserAccessor defaultUserAccessor = new DefaultUserAccessor(userRepository, userRoleRepository, defaultPasswordEncoder, roleAccessor, authenticationTypeAccessor); UserModel newUserModel = defaultUserAccessor.updateUser(userModel, false); Mockito.verify(roleAccessor).updateUserRoles(Mockito.eq(userEntity.getId()), Mockito.any()); testUserModel(userEntity.getId(), username, emailAddress, roleName, newUserModel); } @Test public void updateUserNullTest() { UserRoleModel roles = createUserRoleModel(1L, "roleName", true); UserModel userModel = UserModel.newUser(username, password, emailAddress, AuthenticationType.DATABASE, Set.of(roles), true); DefaultUserAccessor defaultUserAccessor = new DefaultUserAccessor(userRepository, userRoleRepository, defaultPasswordEncoder, roleAccessor, authenticationTypeAccessor); try { defaultUserAccessor.updateUser(userModel, false); fail("Null userId did not throw expected AlertForbiddenOperationException."); } catch (AlertDatabaseConstraintException e) { assertNotNull(e); } } @Test public void updateUserAuthenticationTypeEmptyTest() { final String roleName = "userName"; AuthenticationType authenticationType = AuthenticationType.DATABASE; UserEntity userEntity = new UserEntity(username, password, emailAddress, 2L); userEntity.setId(1L); UserRoleModel roles = createUserRoleModel(1L, roleName, true); UserModel userModel = UserModel.existingUser(1L, username, password, emailAddress, authenticationType, Set.of(roles), true); Mockito.when(userRepository.findById(Mockito.any())).thenReturn(Optional.of(userEntity)); Mockito.when(authenticationTypeAccessor.getAuthenticationType(Mockito.any())).thenReturn(Optional.empty()); DefaultUserAccessor defaultUserAccessor = new DefaultUserAccessor(userRepository, userRoleRepository, defaultPasswordEncoder, roleAccessor, authenticationTypeAccessor); try { defaultUserAccessor.updateUser(userModel, false); fail("Null userId did not throw expected AlertForbiddenOperationException."); } catch (AlertDatabaseConstraintException e) { assertNotNull(e); } } @Test public void updateUserNonDatabaseAuthTest() throws Exception { final String roleName = "roleName"; AuthenticationType authenticationType = AuthenticationType.LDAP; UserEntity userEntity = new UserEntity(username, password, emailAddress, 2L); userEntity.setId(1L); UserRoleModel roles = createUserRoleModel(1L, roleName, true); UserModel userModel = UserModel.existingUser(1L, username, "", emailAddress, authenticationType, Set.of(roles), true); UserRoleRelation userRoleRelation = new UserRoleRelation(1L, 2L); UserRoleModel userRoleModel = createUserRoleModel(1L, roleName, true); Mockito.when(userRepository.findById(Mockito.any())).thenReturn(Optional.of(userEntity)); Mockito.when(authenticationTypeAccessor.getAuthenticationType(Mockito.any())).thenReturn(Optional.of(authenticationType)); Mockito.when(userRepository.save(Mockito.any())).thenReturn(userEntity); createModelMocks(userRoleRelation, userRoleModel, authenticationType); DefaultUserAccessor defaultUserAccessor = new DefaultUserAccessor(userRepository, userRoleRepository, defaultPasswordEncoder, roleAccessor, authenticationTypeAccessor); UserModel updatedUserModel = defaultUserAccessor.updateUser(userModel, false); Mockito.verify(roleAccessor).updateUserRoles(Mockito.eq(userEntity.getId()), Mockito.any()); testUserModel(userEntity.getId(), username, emailAddress, roleName, updatedUserModel); } @Test public void updateUserNonDatabaseAuthInvalidTest() throws Exception { final String roleName = "roleName"; AuthenticationType authenticationType = AuthenticationType.LDAP; UserEntity userEntity = new UserEntity(username, password, emailAddress, 2L); userEntity.setId(1L); UserEntity existingUserEntity = new UserEntity("usernam-teste", "existing-password", "old-email.noreply@blackducksoftware.com", 2L); existingUserEntity.setId(1L); UserRoleModel roles = createUserRoleModel(1L, roleName, true); UserModel userModel = UserModel.existingUser(1L, username, password, emailAddress, authenticationType, Set.of(roles), true); UserRoleRelation userRoleRelation = new UserRoleRelation(1L, 2L); UserRoleModel userRoleModel = createUserRoleModel(1L, roleName, true); Mockito.when(userRepository.findById(Mockito.any())).thenReturn(Optional.of(existingUserEntity)); Mockito.when(authenticationTypeAccessor.getAuthenticationType(Mockito.any())).thenReturn(Optional.of(authenticationType)); Mockito.when(userRepository.save(Mockito.any())).thenReturn(existingUserEntity); createModelMocks(userRoleRelation, userRoleModel, authenticationType); DefaultUserAccessor defaultUserAccessor = new DefaultUserAccessor(userRepository, userRoleRepository, defaultPasswordEncoder, roleAccessor, authenticationTypeAccessor); try { defaultUserAccessor.updateUser(userModel, false); fail("External user with did not throw expected AlertForbiddenOperationException."); } catch (AlertDatabaseConstraintException e) { assertNotNull(e); } }
DefaultProviderDataAccessor implements ProviderDataAccessor { @Override public void updateProjectAndUserData(Long providerConfigId, Map<ProviderProject, Set<String>> projectToUserData, Set<String> additionalRelevantUsers) { updateProjectDB(providerConfigId, projectToUserData.keySet()); Set<String> userData = projectToUserData.values().stream().flatMap(Collection::stream).collect(Collectors.toSet()); userData.addAll(additionalRelevantUsers); updateUserDB(providerConfigId, userData); updateUserProjectRelations(providerConfigId, projectToUserData); } @Autowired DefaultProviderDataAccessor(ProviderProjectRepository providerProjectRepository, ProviderUserProjectRelationRepository providerUserProjectRelationRepository, ProviderUserRepository providerUserRepository, ConfigurationAccessor configurationAccessor); @Override @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED) List<ProviderProject> getProjectsByProviderConfigName(String providerConfigName); @Override @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED) List<ProviderProject> getProjectsByProviderConfigId(Long providerConfigId); @Override void deleteProjects(Collection<ProviderProject> providerProjects); @Override @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED) Set<String> getEmailAddressesForProjectHref(String projectHref); @Override @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED) List<ProviderUserModel> getUsersByProviderConfigId(Long providerConfigId); @Override List<ProviderUserModel> getUsersByProviderConfigName(String providerConfigName); @Override void updateProjectAndUserData(Long providerConfigId, Map<ProviderProject, Set<String>> projectToUserData, Set<String> additionalRelevantUsers); static final int MAX_DESCRIPTION_LENGTH; static final int MAX_PROJECT_NAME_LENGTH; }
@Test public void updateProjectAndUserDataTest() { ProviderProjectEntity storedProviderProjectEntity = new ProviderProjectEntity("stored-name", "stored-description", "stored-href", "stored-Email", 2L); ProviderProject providerProject = new ProviderProject(name, description, href, projectOwnerEmail); ProviderProjectEntity providerProjectEntity = new ProviderProjectEntity(name, description, href, projectOwnerEmail, 1L); providerProjectEntity.setId(3L); ProviderUserEntity providerUserEntity = new ProviderUserEntity("test-email", true, 1L); providerUserEntity.setId(4L); Map<ProviderProject, Set<String>> projectToUserData = new HashMap<>(); projectToUserData.put(providerProject, Set.of("test-user-email")); final String additionalRelevantUsers = "additional-test-user-email"; ProviderProjectRepository providerProjectRepository = Mockito.mock(ProviderProjectRepository.class); ProviderUserRepository providerUserRepository = Mockito.mock(ProviderUserRepository.class); ConfigurationAccessor configurationAccessor = Mockito.mock(ConfigurationAccessor.class); ProviderUserProjectRelationRepository providerUserProjectRelationRepository = Mockito.mock(ProviderUserProjectRelationRepository.class); Mockito.when(providerProjectRepository.findByProviderConfigId(Mockito.any())).thenReturn(List.of(storedProviderProjectEntity)); Mockito.when(providerProjectRepository.saveAll(Mockito.any())).thenReturn(List.of(providerProjectEntity)); Mockito.when(providerUserRepository.findByProviderConfigId(Mockito.any())).thenReturn(List.of(providerUserEntity)); Mockito.when(providerUserRepository.save(Mockito.any())).thenReturn(providerUserEntity); Mockito.when(providerProjectRepository.findFirstByHref(Mockito.any())).thenReturn(Optional.of(providerProjectEntity)); Mockito.when(providerUserRepository.findByEmailAddressAndProviderConfigId(Mockito.any(), Mockito.any())).thenReturn(List.of(providerUserEntity)); DefaultProviderDataAccessor providerDataAccessor = new DefaultProviderDataAccessor(providerProjectRepository, providerUserProjectRelationRepository, providerUserRepository, configurationAccessor); providerDataAccessor.updateProjectAndUserData(1L, projectToUserData, Set.of(additionalRelevantUsers)); Mockito.verify(providerProjectRepository).deleteByHref(Mockito.any()); Mockito.verify(providerUserRepository).deleteByProviderConfigIdAndEmailAddress(Mockito.any(), Mockito.any()); Mockito.verify(providerUserProjectRelationRepository).saveAll(Mockito.any()); }
DefaultUserAccessor implements UserAccessor { @Override public boolean assignRoles(String username, Set<Long> roleIds) { Optional<Long> optionalUserId = userRepository.findByUserName(username).map(UserEntity::getId); if (optionalUserId.isPresent()) { roleAccessor.updateUserRoles(optionalUserId.get(), roleAccessor.getRoles(roleIds)); return true; } return false; } @Autowired DefaultUserAccessor(UserRepository userRepository, UserRoleRepository userRoleRepository, PasswordEncoder defaultPasswordEncoder, DefaultRoleAccessor roleAccessor, AuthenticationTypeAccessor authenticationTypeAccessor); @Override List<UserModel> getUsers(); @Override Optional<UserModel> getUser(Long userId); @Override Optional<UserModel> getUser(String username); @Override UserModel addUser(String userName, String password, String emailAddress); @Override UserModel addUser(UserModel user, boolean passwordEncoded); @Override UserModel updateUser(UserModel user, boolean passwordEncoded); @Override boolean assignRoles(String username, Set<Long> roleIds); @Override boolean changeUserPassword(String username, String newPassword); @Override boolean changeUserEmailAddress(String username, String emailAddress); @Override void deleteUser(String userName); @Override void deleteUser(Long userId); }
@Test public void assignRolesTest() { final String badUsername = "badUsername"; final Long roleId = 5L; UserEntity userEntity = new UserEntity(username, password, emailAddress, 2L); userEntity.setId(1L); Mockito.when(userRepository.findByUserName(Mockito.eq(username))).thenReturn(Optional.of(userEntity)); Mockito.when(userRepository.findByUserName(Mockito.eq(badUsername))).thenReturn(Optional.empty()); DefaultUserAccessor defaultUserAccessor = new DefaultUserAccessor(userRepository, userRoleRepository, defaultPasswordEncoder, roleAccessor, authenticationTypeAccessor); boolean assignedRoles = defaultUserAccessor.assignRoles(username, Set.of(roleId)); boolean assignedRolesFalse = defaultUserAccessor.assignRoles(badUsername, Set.of(roleId)); Mockito.verify(roleAccessor).updateUserRoles(Mockito.eq(userEntity.getId()), Mockito.any()); Mockito.verify(roleAccessor).getRoles(Mockito.any()); assertTrue(assignedRoles); assertFalse(assignedRolesFalse); }
DefaultUserAccessor implements UserAccessor { @Override public boolean changeUserPassword(String username, String newPassword) { Optional<UserEntity> entity = userRepository.findByUserName(username); if (entity.isPresent()) { return changeUserPassword(entity.get(), newPassword); } return false; } @Autowired DefaultUserAccessor(UserRepository userRepository, UserRoleRepository userRoleRepository, PasswordEncoder defaultPasswordEncoder, DefaultRoleAccessor roleAccessor, AuthenticationTypeAccessor authenticationTypeAccessor); @Override List<UserModel> getUsers(); @Override Optional<UserModel> getUser(Long userId); @Override Optional<UserModel> getUser(String username); @Override UserModel addUser(String userName, String password, String emailAddress); @Override UserModel addUser(UserModel user, boolean passwordEncoded); @Override UserModel updateUser(UserModel user, boolean passwordEncoded); @Override boolean assignRoles(String username, Set<Long> roleIds); @Override boolean changeUserPassword(String username, String newPassword); @Override boolean changeUserEmailAddress(String username, String emailAddress); @Override void deleteUser(String userName); @Override void deleteUser(Long userId); }
@Test public void changeUserPasswordTest() { final String badUsername = "badUsername"; final String newPassword = "newPassword"; UserEntity userEntity = new UserEntity(username, password, emailAddress, 2L); userEntity.setId(1L); UserEntity newUserEntity = new UserEntity(username, newPassword, emailAddress, 2L); userEntity.setId(1L); Mockito.when(userRepository.findByUserName(Mockito.eq(username))).thenReturn(Optional.of(userEntity)); Mockito.when(userRepository.findByUserName(Mockito.eq(badUsername))).thenReturn(Optional.empty()); Mockito.when(defaultPasswordEncoder.encode(Mockito.any())).thenReturn(newPassword); Mockito.when(userRepository.save(Mockito.any())).thenReturn(newUserEntity); DefaultUserAccessor defaultUserAccessor = new DefaultUserAccessor(userRepository, userRoleRepository, defaultPasswordEncoder, roleAccessor, authenticationTypeAccessor); assertTrue(defaultUserAccessor.changeUserPassword(username, newPassword)); assertFalse(defaultUserAccessor.changeUserPassword(badUsername, newPassword)); }
DefaultUserAccessor implements UserAccessor { @Override public boolean changeUserEmailAddress(String username, String emailAddress) { Optional<UserEntity> entity = userRepository.findByUserName(username); if (entity.isPresent()) { return changeUserEmailAddress(entity.get(), emailAddress); } return false; } @Autowired DefaultUserAccessor(UserRepository userRepository, UserRoleRepository userRoleRepository, PasswordEncoder defaultPasswordEncoder, DefaultRoleAccessor roleAccessor, AuthenticationTypeAccessor authenticationTypeAccessor); @Override List<UserModel> getUsers(); @Override Optional<UserModel> getUser(Long userId); @Override Optional<UserModel> getUser(String username); @Override UserModel addUser(String userName, String password, String emailAddress); @Override UserModel addUser(UserModel user, boolean passwordEncoded); @Override UserModel updateUser(UserModel user, boolean passwordEncoded); @Override boolean assignRoles(String username, Set<Long> roleIds); @Override boolean changeUserPassword(String username, String newPassword); @Override boolean changeUserEmailAddress(String username, String emailAddress); @Override void deleteUser(String userName); @Override void deleteUser(Long userId); }
@Test public void changeUserEmailAddressTest() { final String badUsername = "badUsername"; final String newEmailAddress = "newemail.noreplay@blackducksoftware.com"; UserEntity userEntity = new UserEntity(username, password, emailAddress, 2L); userEntity.setId(1L); UserEntity newUserEntity = new UserEntity(username, password, newEmailAddress, 2L); userEntity.setId(1L); Mockito.when(userRepository.findByUserName(Mockito.eq(username))).thenReturn(Optional.of(userEntity)); Mockito.when(userRepository.findByUserName(Mockito.eq(badUsername))).thenReturn(Optional.empty()); Mockito.when(userRepository.save(Mockito.any())).thenReturn(newUserEntity); DefaultUserAccessor defaultUserAccessor = new DefaultUserAccessor(userRepository, userRoleRepository, defaultPasswordEncoder, roleAccessor, authenticationTypeAccessor); assertTrue(defaultUserAccessor.changeUserEmailAddress(username, newEmailAddress)); assertFalse(defaultUserAccessor.changeUserEmailAddress(badUsername, newEmailAddress)); }
DefaultUserAccessor implements UserAccessor { @Override public void deleteUser(String userName) throws AlertForbiddenOperationException { Optional<UserEntity> optionalUser = userRepository.findByUserName(userName); if (optionalUser.isPresent()) { UserEntity user = optionalUser.get(); deleteUserEntity(user); } } @Autowired DefaultUserAccessor(UserRepository userRepository, UserRoleRepository userRoleRepository, PasswordEncoder defaultPasswordEncoder, DefaultRoleAccessor roleAccessor, AuthenticationTypeAccessor authenticationTypeAccessor); @Override List<UserModel> getUsers(); @Override Optional<UserModel> getUser(Long userId); @Override Optional<UserModel> getUser(String username); @Override UserModel addUser(String userName, String password, String emailAddress); @Override UserModel addUser(UserModel user, boolean passwordEncoded); @Override UserModel updateUser(UserModel user, boolean passwordEncoded); @Override boolean assignRoles(String username, Set<Long> roleIds); @Override boolean changeUserPassword(String username, String newPassword); @Override boolean changeUserEmailAddress(String username, String emailAddress); @Override void deleteUser(String userName); @Override void deleteUser(Long userId); }
@Test public void deleteUserByNameTest() throws Exception { UserEntity userEntity = new UserEntity(username, password, emailAddress, 2L); userEntity.setId(5L); Mockito.when(userRepository.findByUserName(Mockito.eq(username))).thenReturn(Optional.of(userEntity)); DefaultUserAccessor defaultUserAccessor = new DefaultUserAccessor(userRepository, userRoleRepository, defaultPasswordEncoder, roleAccessor, authenticationTypeAccessor); defaultUserAccessor.deleteUser(username); Mockito.verify(roleAccessor).updateUserRoles(Mockito.any(), Mockito.any()); Mockito.verify(userRepository).deleteById(Mockito.any()); } @Test public void deleteUserByIdTest() throws Exception { UserEntity userEntity = new UserEntity(username, password, emailAddress, 2L); userEntity.setId(5L); Mockito.when(userRepository.findById(Mockito.eq(userEntity.getId()))).thenReturn(Optional.of(userEntity)); DefaultUserAccessor defaultUserAccessor = new DefaultUserAccessor(userRepository, userRoleRepository, defaultPasswordEncoder, roleAccessor, authenticationTypeAccessor); defaultUserAccessor.deleteUser(userEntity.getId()); Mockito.verify(roleAccessor).updateUserRoles(Mockito.any(), Mockito.any()); Mockito.verify(userRepository).deleteById(Mockito.any()); } @Test public void deleteUserReservedIdTest() throws Exception { UserEntity userEntity = new UserEntity(username, password, emailAddress, 2L); userEntity.setId(1L); Mockito.when(userRepository.findByUserName(Mockito.eq(username))).thenReturn(Optional.of(userEntity)); Mockito.when(userRepository.findById(Mockito.any())).thenReturn(Optional.of(userEntity)); DefaultUserAccessor defaultUserAccessor = new DefaultUserAccessor(userRepository, userRoleRepository, defaultPasswordEncoder, roleAccessor, authenticationTypeAccessor); try { defaultUserAccessor.deleteUser(username); fail("A forbidden userEntity id did not throw the expected AlertForbiddenOperationException"); } catch (AlertForbiddenOperationException e) { assertNotNull(e); } }
AzureFieldsExtractor { public <T> Optional<T> extractField(JsonObject fieldsObject, AzureFieldDefinition<T> fieldDefinition) { JsonElement foundField = fieldsObject.get(fieldDefinition.getFieldName()); if (null != foundField) { T fieldValue = gson.fromJson(foundField, fieldDefinition.getFieldType()); return Optional.of(fieldValue); } return Optional.empty(); } AzureFieldsExtractor(Gson gson); Optional<T> extractField(JsonObject fieldsObject, AzureFieldDefinition<T> fieldDefinition); }
@Test public void extractFieldValidTest() { Gson gson = new GsonBuilder().create(); AzureFieldsExtractor azureFieldsExtractor = new AzureFieldsExtractor(gson); FieldsTestClass originalCopy = createTestClass("a value", 42, "a different value", 8675309); String jsonString = gson.toJson(originalCopy); JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class); Optional<String> field1Value = azureFieldsExtractor.extractField(jsonObject, FieldsTestClass.FIELD_1); assertTrue(field1Value.isPresent(), "Field 1 was not present"); assertEquals(originalCopy.getField1(), field1Value.get()); Optional<Integer> field2Value = azureFieldsExtractor.extractField(jsonObject, FieldsTestClass.FIELD_2); assertTrue(field2Value.isPresent(), "Field 2 was not present"); assertEquals(originalCopy.getField2(), field2Value.get()); Optional<FieldsTestInnerClass> field3Value = azureFieldsExtractor.extractField(jsonObject, FieldsTestClass.FIELD_3); assertTrue(field3Value.isPresent(), "Field 3 was not present"); FieldsTestInnerClass field3Object = field3Value.get(); assertEquals(originalCopy.getField3().getInnerField1(), field3Object.getInnerField1()); assertEquals(originalCopy.getField3().getInnerField2(), field3Object.getInnerField2()); }
JiraServerProperties implements IssueTrackerServiceConfig { public JiraServerServiceFactory createJiraServicesServerFactory(Logger logger, Gson gson) throws IssueTrackerException { JiraServerRestConfig jiraServerConfig = createJiraServerConfig(); Slf4jIntLogger intLogger = new Slf4jIntLogger(logger); JiraHttpClient jiraHttpClient = jiraServerConfig.createJiraHttpClient(intLogger); return new JiraServerServiceFactory(intLogger, jiraHttpClient, gson); } JiraServerProperties(String url, String password, String username, boolean pluginCheckDisabled); JiraServerRestConfig createJiraServerConfig(); JiraServerServiceFactory createJiraServicesServerFactory(Logger logger, Gson gson); String getUrl(); String getPassword(); String getUsername(); boolean isPluginCheckDisabled(); }
@Test public void testServerServiceFactory() { try { JiraServerProperties properties = new JiraServerProperties("http: JiraServerServiceFactory serviceFactory = properties.createJiraServicesServerFactory(LoggerFactory.getLogger(getClass()), new Gson()); assertNotNull(serviceFactory); } catch (IssueTrackerException ex) { ex.printStackTrace(); fail(); } }
JiraServerIssueConfigValidator extends JiraIssueConfigValidator { @Override public Collection<ProjectComponent> getProjectsByName(String jiraProjectName) throws IntegrationException { return projectService.getProjectsByName(jiraProjectName); } JiraServerIssueConfigValidator(ProjectService projectService, UserSearchService userSearchService, IssueTypeService issueTypeService, IssueMetaDataService issueMetaDataService); @Override String getProjectFieldKey(); @Override String getIssueTypeFieldKey(); @Override String getIssueCreatorFieldKey(); @Override String getAddCommentsFieldKey(); @Override String getResolveTransitionFieldKey(); @Override String getOpenTransitionFieldKey(); @Override Collection<ProjectComponent> getProjectsByName(String jiraProjectName); @Override boolean isUserValid(String issueCreator); }
@Test public void validateSuccessTest() throws IntegrationException { ProjectService projectService = Mockito.mock(ProjectService.class); UserSearchService userSearchService = Mockito.mock(UserSearchService.class); IssueTypeService issueTypeService = Mockito.mock(IssueTypeService.class); IssueMetaDataService issueMetaDataService = Mockito.mock(IssueMetaDataService.class); Mockito.when(issueMetaDataService.doesProjectContainIssueType(Mockito.anyString(), Mockito.anyString())).thenReturn(Boolean.TRUE); JiraServerIssueConfigValidator jiraIssueConfigValidator = new JiraServerIssueConfigValidator(projectService, userSearchService, issueTypeService, issueMetaDataService); String resolveTransitionString = "Resolve"; String projectName = "ProjectName"; String issueTypeString = "IssueType"; String issueCreatorString = "IssueCreator"; IssueConfig issueConfig = new IssueConfig(); issueConfig.setCommentOnIssues(true); issueConfig.setResolveTransition(resolveTransitionString); issueConfig.setProjectName(projectName); issueConfig.setIssueType(issueTypeString); issueConfig.setIssueCreator(issueCreatorString); IssueTypeResponseModel issue = Mockito.mock(IssueTypeResponseModel.class); Mockito.when(issue.getName()).thenReturn(issueTypeString); List<IssueTypeResponseModel> issueResponses = new ArrayList<>(1); issueResponses.add(issue); Mockito.when(issueTypeService.getAllIssueTypes()).thenReturn(issueResponses); UserDetailsResponseModel user = Mockito.mock(UserDetailsResponseModel.class); Mockito.when(user.getName()).thenReturn(issueCreatorString); Mockito.when(userSearchService.findUserByUsername(Mockito.anyString())).thenReturn(Optional.of(user)); ProjectComponent projectComponent = Mockito.mock(ProjectComponent.class); Mockito.when(projectComponent.getName()).thenReturn(projectName); List<ProjectComponent> projectComponents = new ArrayList<>(1); projectComponents.add(projectComponent); Mockito.when(projectService.getProjectsByName(Mockito.anyString())).thenReturn(projectComponents); try { IssueTrackerContext context = new IssueTrackerContext(null, issueConfig); jiraIssueConfigValidator.createValidIssueConfig(context); Assertions.assertEquals(resolveTransitionString, issueConfig.getResolveTransition().orElse("")); Assertions.assertEquals(projectName, issueConfig.getProjectName()); Assertions.assertEquals(issueCreatorString, issueConfig.getIssueCreator()); Assertions.assertEquals(issueTypeString, issueConfig.getIssueType()); } catch (AlertFieldException e) { fail(); } }
JiraServerRequestDelegator { public IssueTrackerResponse sendRequests(List<IssueTrackerRequest> requests) throws IntegrationException { if (null == context) { throw new IssueTrackerException("Context missing. Cannot determine Jira Server instance."); } if (null == requests || requests.isEmpty()) { throw new IssueTrackerException("Requests missing. Require at least one request."); } JiraServerProperties jiraProperties = (JiraServerProperties) context.getIssueTrackerConfig(); JiraServerServiceFactory jiraServerServiceFactory = jiraProperties.createJiraServicesServerFactory(logger, gson); if (!jiraProperties.isPluginCheckDisabled()) { checkIfAlertPluginIsInstalled(jiraServerServiceFactory.createPluginManagerService()); } ProjectService projectService = jiraServerServiceFactory.createProjectService(); UserSearchService userSearchService = jiraServerServiceFactory.createUserSearchService(); IssueTypeService issueTypeService = jiraServerServiceFactory.createIssueTypeService(); IssueMetaDataService issueMetaDataService = jiraServerServiceFactory.createIssueMetadataService(); JiraServerIssueConfigValidator jiraIssueConfigValidator = new JiraServerIssueConfigValidator(projectService, userSearchService, issueTypeService, issueMetaDataService); IssueConfig validIssueConfig = jiraIssueConfigValidator.createValidIssueConfig(context); IssueService issueService = jiraServerServiceFactory.createIssueService(); IssuePropertyService issuePropertyService = jiraServerServiceFactory.createIssuePropertyService(); IssueSearchService issueSearchService = jiraServerServiceFactory.createIssueSearchService(); JiraContentValidator jiraContentValidator = new JiraContentValidator(); JiraServerTransitionHandler jiraTransitionHandler = new JiraServerTransitionHandler(issueService); JiraServerIssuePropertyHandler jiraIssuePropertyHandler = new JiraServerIssuePropertyHandler(issueSearchService, issuePropertyService); JiraServerIssueHandler jiraIssueHandler = new JiraServerIssueHandler(issueService, jiraProperties, gson, jiraTransitionHandler, jiraIssuePropertyHandler, jiraContentValidator); return jiraIssueHandler.createOrUpdateIssues(validIssueConfig, requests); } JiraServerRequestDelegator(Gson gson, IssueTrackerContext context); IssueTrackerResponse sendRequests(List<IssueTrackerRequest> requests); static final String ERROR_MESSAGE_PLUGIN_CONFIG; }
@Test public void testContextNull() throws Exception { JiraServerRequestDelegator service = new JiraServerRequestDelegator(gson, null); List<IssueTrackerRequest> requests = new ArrayList<>(); try { service.sendRequests(requests); fail(); } catch (IssueTrackerException ex) { assertTrue(ex.getMessage().contains("Context missing.")); } } @Test public void testRequestsNull() throws Exception { JiraServerRequestDelegator service = new JiraServerRequestDelegator(gson, createContext()); List<IssueTrackerRequest> requests = null; try { service.sendRequests(requests); fail(); } catch (IssueTrackerException ex) { assertTrue(ex.getMessage().contains("Requests missing.")); } } @Test public void testRequestsEmpty() throws Exception { JiraServerRequestDelegator service = new JiraServerRequestDelegator(gson, createContext()); List<IssueTrackerRequest> requests = new ArrayList<>(); try { service.sendRequests(requests); fail(); } catch (IssueTrackerException ex) { assertTrue(ex.getMessage().contains("Requests missing.")); } } @Test public void testAppMissing() throws Exception { JiraServerChannel jiraServerChannel = new JiraServerChannel(gson, new JiraServerChannelKey(), null, null, null); List<IssueTrackerRequest> requests = new ArrayList<>(); IssueContentModel content = createContentModel(); IssueSearchProperties searchProperties = createSearchProperties(); AlertIssueOrigin alertIssueOrigin = new AlertIssueOrigin(null, null); requests.add(IssueCreationRequest.of(searchProperties, content, alertIssueOrigin)); requests.add(IssueCommentRequest.of(searchProperties, content, alertIssueOrigin)); requests.add(IssueResolutionRequest.of(searchProperties, content, alertIssueOrigin)); Mockito.when(pluginManagerService.isAppInstalled(Mockito.eq(JiraConstants.JIRA_APP_KEY))).thenReturn(false); try { jiraServerChannel.sendRequests(createContext(), requests); fail(); } catch (IssueTrackerException ex) { assertTrue(ex.getMessage().contains("Please configure the Jira Server plugin")); } } @Test public void testCreateIssue() throws Exception { Mockito.when(pluginManagerService.isAppInstalled(Mockito.eq(JiraConstants.JIRA_APP_KEY))).thenReturn(true); List<ProjectComponent> projectComponents = new ArrayList<>(); projectComponents.add(new ProjectComponent(null, "1", "project", "project", null, null, null, null)); Mockito.when(projectService.getProjectsByName(Mockito.anyString())).thenReturn(projectComponents); List<IssueTypeResponseModel> issueTypes = new ArrayList<>(); issueTypes.add(new TestIssueTypeResponseModel()); Mockito.when(issueTypeService.getAllIssueTypes()).thenReturn(issueTypes); Optional<UserDetailsResponseModel> userDetails = Optional.of(new TestIssueCreator()); Mockito.when(userSearchService.findUserByUsername(Mockito.anyString())).thenReturn(userDetails); Mockito.when(issueMetaDataService.doesProjectContainIssueType(Mockito.anyString(), Mockito.anyString())).thenReturn(Boolean.TRUE); List<IssueSearchIssueComponent> issues = new ArrayList<>(); IssueSearchResponseModel searchResponseModel = new IssueSearchResponseModel("", issues); Mockito.when(issueSearchService.queryForIssues(Mockito.anyString())).thenReturn(searchResponseModel); IssueResponseModel issue = createIssueResponse(); Mockito.when(issueService.createIssue(Mockito.any(IssueCreationRequestModel.class))).thenReturn(issue); JiraServerRequestDelegator service = new JiraServerRequestDelegator(gson, createContext()); List<IssueTrackerRequest> requests = new ArrayList<>(); IssueContentModel content = createContentModel(); IssueSearchProperties searchProperties = Mockito.mock(JiraIssueSearchProperties.class); AlertIssueOrigin alertIssueOrigin = new AlertIssueOrigin(null, null); requests.add(IssueCreationRequest.of(searchProperties, content, alertIssueOrigin)); IssueTrackerResponse response = service.sendRequests(requests); assertNotNull(response); assertNotNull(response.getStatusMessage()); boolean anyIssuesMatchKey = response.getUpdatedIssues() .stream() .map(IssueTrackerIssueResponseModel::getIssueKey) .anyMatch("project-1"::equals); assertTrue(anyIssuesMatchKey, "No issues matched the expected key"); } @Test public void testResolveIssue() throws Exception { Mockito.when(pluginManagerService.isAppInstalled(Mockito.eq(JiraConstants.JIRA_APP_KEY))).thenReturn(true); List<ProjectComponent> projectComponents = new ArrayList<>(); projectComponents.add(new ProjectComponent(null, "1", "project", "project", null, null, null, null)); Mockito.when(projectService.getProjectsByName(Mockito.anyString())).thenReturn(projectComponents); List<IssueTypeResponseModel> issueTypes = new ArrayList<>(); issueTypes.add(new TestIssueTypeResponseModel()); Mockito.when(issueTypeService.getAllIssueTypes()).thenReturn(issueTypes); Optional<UserDetailsResponseModel> userDetails = Optional.of(new TestIssueCreator()); Mockito.when(userSearchService.findUserByUsername(Mockito.anyString())).thenReturn(userDetails); Mockito.when(issueMetaDataService.doesProjectContainIssueType(Mockito.anyString(), Mockito.anyString())).thenReturn(Boolean.TRUE); List<IssueSearchIssueComponent> issues = new ArrayList<>(); issues.add(new TestIssueSearchIssueComponent()); IssueSearchResponseModel searchResponseModel = new IssueSearchResponseModel("", issues); Mockito.when(issueSearchService.queryForIssues(Mockito.anyString())).thenReturn(searchResponseModel); Mockito.when(issueService.getIssue(Mockito.anyString())).thenReturn(createIssueResponse()); StatusDetailsComponent statusDetailsComponent = new TestNewStatusDetailsComponent(); Mockito.when(issueService.getStatus(Mockito.anyString())).thenReturn(statusDetailsComponent); TransitionsResponseModel transitionsResponseModel = new TestTransitionResponsesModel(); Mockito.when(issueService.getTransitions(Mockito.anyString())).thenReturn(transitionsResponseModel); JiraServerRequestDelegator service = new JiraServerRequestDelegator(gson, createContext()); List<IssueTrackerRequest> requests = new ArrayList<>(); IssueContentModel content = createContentModel(); AlertIssueOrigin alertIssueOrigin = new AlertIssueOrigin(null, null); IssueSearchProperties searchProperties = Mockito.mock(JiraIssueSearchProperties.class); requests.add(IssueCommentRequest.of(searchProperties, content, alertIssueOrigin)); requests.add(IssueResolutionRequest.of(searchProperties, content, alertIssueOrigin)); IssueTrackerResponse response = service.sendRequests(requests); assertNotNull(response); assertNotNull(response.getStatusMessage()); boolean anyIssuesMatchKey = response.getUpdatedIssues() .stream() .map(IssueTrackerIssueResponseModel::getIssueKey) .anyMatch("project-1"::equals); assertTrue(anyIssuesMatchKey, "No issues matched the expected key"); }