method2testcases stringlengths 118 3.08k |
|---|
### Question:
AbstractRowInsertionBuilder extends
AbstractRowBuilder<RowInsertionBuilder> implements RowInsertionBuilder { @Override public String toString() { return toSql(); } AbstractRowInsertionBuilder(U updateCallback, Table table); @Override Table getTable(); @Override RowInsertionBuilder like(Row row); @Override String toSql(); @Override String toString(); }### Answer:
@Test public void testToString() { final MutableTable table = new MutableTable("tbl"); final MutableColumn col1 = new MutableColumn("col1").setTable(table); final MutableColumn col2 = new MutableColumn("col2").setTable(table); table.addColumn(col1).addColumn(col2); final AbstractRowInsertionBuilder<UpdateCallback> builder = new AbstractRowInsertionBuilder<UpdateCallback>( null, table) { @Override public void execute() throws MetaModelException { throw new UnsupportedOperationException(); } }; builder.value(col1, "value1").value(col2, "value2"); assertEquals("INSERT INTO tbl(col1,col2) VALUES (\"value1\",\"value2\")", builder.toString()); } |
### Question:
OracleQueryRewriter extends OffsetFetchQueryRewriter { @Override public String rewriteFilterItem(final FilterItem item) { if (item.getOperand() instanceof String && item.getOperand().equals("")) { return super.rewriteFilterItem(new FilterItem(item.getSelectItem(), item.getOperator(), null)); } else { return super.rewriteFilterItem(item); } } OracleQueryRewriter(JdbcDataContext dataContext); @Override ColumnType getColumnType(int jdbcType, String nativeType, Integer columnSize); @Override String rewriteColumnType(ColumnType columnType, Integer columnSize); @Override String rewriteFilterItem(final FilterItem item); static final int FIRST_FETCH_SUPPORTING_VERSION; }### Answer:
@Test public void testReplaceEmptyStringWithNull() throws Exception { final String alias = "alias"; SelectItem selectItem = new SelectItem("expression", alias); final FilterItem filterItem = new FilterItem(selectItem, OperatorType.DIFFERENT_FROM, ""); final String rewrittenValue = qr.rewriteFilterItem(filterItem); final String expectedValue = alias + " IS NOT NULL"; assertEquals(expectedValue, rewrittenValue); } |
### Question:
PostgresqlQueryRewriter extends LimitOffsetQueryRewriter { @Override public void setStatementParameter(PreparedStatement st, int valueIndex, Column column, Object value) throws SQLException { switch (column.getNativeType()) { case "json": case "jsonb": assert column.getType() == ColumnType.MAP; if (value == null) { st.setObject(valueIndex, null); } else { final PGobject pgo = new PGobject(); pgo.setType(column.getNativeType()); if (value instanceof Map) { try { pgo.setValue(jsonObjectMapper.writeValueAsString(value)); } catch (Exception e) { throw new IllegalArgumentException("Unable to write value as JSON string: " + value); } } else { pgo.setValue(value.toString()); } st.setObject(valueIndex, pgo); } return; } super.setStatementParameter(st, valueIndex, column, value); } PostgresqlQueryRewriter(JdbcDataContext dataContext); @Override ColumnType getColumnType(int jdbcType, String nativeType, Integer columnSize); @Override String rewriteColumnType(ColumnType columnType, Integer columnSize); @Override void setStatementParameter(PreparedStatement st, int valueIndex, Column column, Object value); @Override Object getResultSetValue(ResultSet resultSet, int columnIndex, Column column); }### Answer:
@Test public void testInsertNullMap() throws SQLException { final PreparedStatement statementMock = EasyMock.createMock(PreparedStatement.class); final PostgresqlQueryRewriter queryRewriter = new PostgresqlQueryRewriter(null); final Column column = new MutableColumn("col").setType(ColumnType.MAP).setNativeType("jsonb"); final Object value = null; statementMock.setObject(0, null); EasyMock.replay(statementMock); queryRewriter.setStatementParameter(statementMock, 0, column, value); EasyMock.verify(statementMock); } |
### Question:
ColumnTypeResolver { public ColumnType[] getColumnTypes() { final List<ColumnType> columnTypes = new ArrayList<>(); try { columnTypes.addAll(getColumnTypesFromMetadata()); columnTypes.addAll(getColumnTypesFromData()); } catch (final JSONException e) { } columnTypes.addAll(getColumnTypesFromRemainingColumns()); return columnTypes.toArray(new ColumnType[columnTypes.size()]); } ColumnTypeResolver(final JSONObject jsonObject, final String[] columnNamesArray); ColumnType[] getColumnTypes(); }### Answer:
@Test public void testGetColumnTypes() throws Exception { final JSONObject jsonObject = createJSONObject(); final String[] columnNames = new String[] { NEO4J_COLUMN_NAME_ID, COLUMN_BOOLEAN, COLUMN_INTEGER, COLUMN_LONG, COLUMN_DOUBLE, COLUMN_ARRAY, COLUMN_STRING }; final ColumnTypeResolver resolver = new ColumnTypeResolver(jsonObject, columnNames); final ColumnType[] columnTypes = resolver.getColumnTypes(); assertEquals(columnTypes.length, columnNames.length); assertEquals(columnTypes[0], ColumnType.BIGINT); assertEquals(columnTypes[1], ColumnType.BOOLEAN); assertEquals(columnTypes[2], ColumnType.STRING); assertEquals(columnTypes[3], ColumnType.LIST); assertEquals(columnTypes[4], ColumnType.DOUBLE); assertEquals(columnTypes[5], ColumnType.INTEGER); assertEquals(columnTypes[6], ColumnType.BIGINT); } |
### Question:
ByteUtil { public static byte[] int2BytesBigEndian(int i) { byte[] bytes = new byte[4]; bytes[0] = (byte) ((i >> 24) & 0xff); bytes[1] = (byte) ((i >> 16) & 0xff); bytes[2] = (byte) ((i >> 8) & 0xff); bytes[3] = (byte) (i & 0xff); return bytes; } static byte[] int2BytesBigEndian(int i); static int bytes2IntBigEndian(byte... bytes); static byte[] long2BytesBigEndian(long l); static long bytes2LongBigEndian(byte... bytes); static byte[] int2BytesLittleEndian(int i); static int bytes2IntLittleEndian(byte... bytes); static byte[] long2BytesLittleEndian(long l); static long bytes2LongLittleEndian(byte... bytes); static byte[] reverse(byte... bytes); static int bytesIndexOf(byte[] source, byte[] target, int begin); static byte bbc(byte... datas); static byte[] crc16Modbus(byte... datas); }### Answer:
@Test public void int2BytesBigEndian() { assertArrayEquals(new byte[]{0, 0, (byte) 0x12, (byte) 0x34}, ByteUtil.int2BytesBigEndian(0x1234)); assertArrayEquals(new byte[]{(byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78}, ByteUtil.int2BytesBigEndian(0x12345678)); } |
### Question:
ByteUtil { public static byte bbc(byte... datas){ byte bbc = 0x00; for (int i = 0; i < datas.length; i++) { bbc ^= datas[i]; } return bbc; } static byte[] int2BytesBigEndian(int i); static int bytes2IntBigEndian(byte... bytes); static byte[] long2BytesBigEndian(long l); static long bytes2LongBigEndian(byte... bytes); static byte[] int2BytesLittleEndian(int i); static int bytes2IntLittleEndian(byte... bytes); static byte[] long2BytesLittleEndian(long l); static long bytes2LongLittleEndian(byte... bytes); static byte[] reverse(byte... bytes); static int bytesIndexOf(byte[] source, byte[] target, int begin); static byte bbc(byte... datas); static byte[] crc16Modbus(byte... datas); }### Answer:
@Test public void bbc() { assertEquals((byte) 0x29, ByteUtil.bbc(TextUtil.hex2Bytes("78 B0 00 01 01 42 00 00 00 01 00 00 00 00 00 00 09 5A FF FF F1 00 00 00 00 00 00 00"))); } |
### Question:
TextUtil { public static String MD5(String content) { return bytes2Hex(digest(content.getBytes(), "MD5")); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void MD5() { assertEquals("033bd94b1168d7e4f0d644c3c95e35bf", TextUtil.MD5("TEST")); } |
### Question:
TextUtil { public static String SHA1(String content) { return bytes2Hex(digest(content.getBytes(), "SHA-1")); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void SHA1() { assertEquals("984816fd329622876e14907634264e6f332e9fb3", TextUtil.SHA1("TEST")); } |
### Question:
TextUtil { public static String SHA224(String content) { return bytes2Hex(digest(content.getBytes(), "SHA-224")); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void SHA224() { assertEquals("917ecca24f3e6ceaf52375d8083381f1f80a21e6e49fbadc40afeb8e", TextUtil.SHA224("TEST")); } |
### Question:
TextUtil { public static String SHA256(String content) { return bytes2Hex(digest(content.getBytes(), "SHA-256")); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void SHA256() { assertEquals("94ee059335e587e501cc4bf90613e0814f00a7b08bc7c648fd865a2af6a22cc2", TextUtil.SHA256("TEST")); } |
### Question:
TextUtil { public static String SHA384(String content) { return bytes2Hex(digest(content.getBytes(), "SHA-384")); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void SHA384() { assertEquals("4f37c49c0024445f91977dbc47bd4da9c4de8d173d03379ee19c2bb15435c2c7e624ea42f7cc1689961cb7aca50c7d17", TextUtil.SHA384("TEST")); } |
### Question:
TextUtil { public static String SHA512(String content) { return bytes2Hex(digest(content.getBytes(), "SHA-512")); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void SHA512() { assertEquals("7bfa95a688924c47c7d22381f20cc926f524beacb13f84e203d4bd8cb6ba2fce81c57a5f059bf3d509926487bde925b3bcee0635e4f7baeba054e5dba696b2bf", TextUtil.SHA512("TEST")); } |
### Question:
TextUtil { public static byte[] digest(byte[] data, String algorithm) { if (data == null || data.length == 0) throw new NullPointerException(); try { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); messageDigest.update(data); return messageDigest.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void digest() { } |
### Question:
TextUtil { public static String HmacMD5(String content, String key) { return bytes2Hex(Hmac(content.getBytes(), "HmacMD5", key.getBytes())); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void hmacMD5() { assertEquals("1aee732e9c1d3faa20775d1438af9472", TextUtil.HmacMD5("TEST", "KEY")); } |
### Question:
ByteUtil { public static int bytes2IntBigEndian(byte... bytes) { int result = 0; if (bytes == null || bytes.length == 0) return result; result |= (bytes[0] & 0xff); for (int i = 1; i < bytes.length; i++) { result = result << 8; result |= (bytes[i] & 0xff); } return result; } static byte[] int2BytesBigEndian(int i); static int bytes2IntBigEndian(byte... bytes); static byte[] long2BytesBigEndian(long l); static long bytes2LongBigEndian(byte... bytes); static byte[] int2BytesLittleEndian(int i); static int bytes2IntLittleEndian(byte... bytes); static byte[] long2BytesLittleEndian(long l); static long bytes2LongLittleEndian(byte... bytes); static byte[] reverse(byte... bytes); static int bytesIndexOf(byte[] source, byte[] target, int begin); static byte bbc(byte... datas); static byte[] crc16Modbus(byte... datas); }### Answer:
@Test public void bytes2IntBigEndian() { assertEquals(0x1234, ByteUtil.bytes2IntBigEndian((byte) 0x12, (byte) 0x34)); assertEquals(0x12345678, ByteUtil.bytes2IntBigEndian((byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78)); } |
### Question:
TextUtil { public static String HmacSHA1(String content, String key) { return bytes2Hex(Hmac(content.getBytes(), "HmacSHA1", key.getBytes())); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void hmacSHA1() { assertEquals("7403a7476a1758ff716b8bd405d0ef5574e9cd0a", TextUtil.HmacSHA1("TEST", "KEY")); } |
### Question:
TextUtil { public static String HmacSHA224(String content, String key) { return bytes2Hex(Hmac(content.getBytes(), "HmacSHA224", key.getBytes())); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void hmacSHA224() { assertEquals("e802b12b9dbfca2785fb1d93864eb984494e110acefe468fea6a3f79", TextUtil.HmacSHA224("TEST", "KEY")); } |
### Question:
TextUtil { public static String HmacSHA256(String content, String key) { return bytes2Hex(Hmac(content.getBytes(), "HmacSHA256", key.getBytes())); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void hmacSHA256() { assertEquals("615dac1c53c9396d8f69a419a0b2d9393a0461d7ad5f7f3d9beb57264129ef12", TextUtil.HmacSHA256("TEST", "KEY")); } |
### Question:
TextUtil { public static String HmacSHA384(String content, String key) { return bytes2Hex(Hmac(content.getBytes(), "HmacSHA384", key.getBytes())); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void hmacSHA384() { assertEquals("03ae3f1ba7a6626b24de55db51dbaa498c2baaa58b4a2617f48c8f7eae58a31e70f2d9f82241e1bbb287d89902f2fe3a", TextUtil.HmacSHA384("TEST", "KEY")); } |
### Question:
TextUtil { public static byte[] Hmac(byte[] data, String algorithm, byte[] key) { SecretKey secretKey = new SecretKeySpec(key, algorithm); Mac mac = null; try { mac = Mac.getInstance(algorithm); mac.init(secretKey); return mac.doFinal(data); } catch (NoSuchAlgorithmException|InvalidKeyException e) { e.printStackTrace(); } return null; } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void hmac() { } |
### Question:
TextUtil { public static String encodeURL(String data, String enc) { try { if (isEmpty(enc)) enc = "utf-8"; return URLEncoder.encode(data, enc); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return data; } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void encodeURL() { assertEquals("https%3A%2F%2F6xyun.cn%2Fapi%3Fkey%3D%E6%B5%8B%E8%AF%95", TextUtil.encodeURL("https: } |
### Question:
TextUtil { public static String decodeURL(String data, String enc) { try { if (isEmpty(enc)) enc = "utf-8"; return URLDecoder.decode(data, enc); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return data; } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void decodeURL() { assertEquals("https: } |
### Question:
TextUtil { public static String string2Unicode(String string) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); stringBuilder.append("\\u"); String hex = Integer.toHexString(c); switch (hex.length()) { case 2: stringBuilder.append("00"); break; case 3: stringBuilder.append("0"); break; } stringBuilder.append(hex); } return stringBuilder.toString(); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void string2Unicode() { assertEquals("\\u0054\\u0045\\u0053\\u0054", TextUtil.string2Unicode("TEST")); } |
### Question:
TextUtil { public static String unicode2String(String unicode) { StringBuilder stringBuilder = new StringBuilder(); String[] hex = unicode.split("\\\\u"); for (int i = 1; i < hex.length; i++) { int data = Integer.parseInt(hex[i], 16); stringBuilder.append((char) data); } return stringBuilder.toString(); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void unicode2String() { assertEquals("TEST", TextUtil.unicode2String("\\u0054\\u0045\\u0053\\u0054")); } |
### Question:
TextUtil { public static String money2ChineseTraditional(double money) { return number2Traditional( money2Chinese(money) ); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void money2ChineseTraditional() { assertEquals("壹亿零贰佰肆拾万零玖拾元整", TextUtil.money2ChineseTraditional(102400090)); } |
### Question:
TextUtil { public static String bytes2Hex(byte... bytes) { return bytes2Hex(bytes, false); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void bytes2Hex() { assertEquals("54455354", TextUtil.bytes2Hex("TEST".getBytes())); assertEquals("54455354", TextUtil.bytes2Hex("TEST".getBytes(), false)); assertEquals("54 45 53 54", TextUtil.bytes2Hex("TEST".getBytes(), true)); } |
### Question:
TextUtil { public static String encodeBase64(byte[] content) { return Base64.encodeToString(content, Base64.NO_WRAP); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void encodeBase64() { assertEquals("VEVTVA==", TextUtil.encodeBase64("TEST".getBytes())); } |
### Question:
TextUtil { public static byte[] decodeBase64(String content) { return Base64.decode(content, Base64.NO_WRAP); } static boolean isEmpty(String text); static String MD5(String content); static String SHA1(String content); static String SHA224(String content); static String SHA256(String content); static String SHA384(String content); static String SHA512(String content); static byte[] digest(byte[] data, String algorithm); static String HmacMD5(String content, String key); static String HmacSHA1(String content, String key); static String HmacSHA224(String content, String key); static String HmacSHA256(String content, String key); static String HmacSHA384(String content, String key); static String HmacSHA512(String content, String key); static byte[] Hmac(byte[] data, String algorithm, byte[] key); static String encodeURL(String data, String enc); static String decodeURL(String data, String enc); static String string2Unicode(String string); static String unicode2String(String unicode); static String formetByteLength(long size); static String money2Chinese(double money); static String money2ChineseTraditional(double money); static String number2Chinese(long number); static String bytes2Hex(byte... bytes); static String bytes2Hex(byte[] bytes, boolean space); static byte[] hex2Bytes(String inHex); static String encodeBase64(byte[] content); static byte[] decodeBase64(String content); }### Answer:
@Test public void decodeBase64() { assertArrayEquals(TextUtil.hex2Bytes("54 45 53 54"), TextUtil.decodeBase64("VEVTVA==")); } |
### Question:
BitUtil { public static String int2Bin(int source) { return Integer.toBinaryString(source); } static String int2Bin(int source); static int bin2Int(String source); static String long2Bin(long source); static long bin2Long(String source); static boolean getIntBit(int source, int pos); static int setIntBit(int source, int pos, boolean value); static boolean getLongBit(long source, int pos); static long setLongBit(long source, int pos, boolean value); }### Answer:
@Test public void int2Bin() { assertEquals("111_1111_1111_1111_1111_1111_1111_1111".replace("_", ""), BitUtil.int2Bin(2147483647)); } |
### Question:
BitUtil { public static int bin2Int(String source) { if (source.startsWith("0b")) source = source.substring(2); return Integer.parseInt(source, 2); } static String int2Bin(int source); static int bin2Int(String source); static String long2Bin(long source); static long bin2Long(String source); static boolean getIntBit(int source, int pos); static int setIntBit(int source, int pos, boolean value); static boolean getLongBit(long source, int pos); static long setLongBit(long source, int pos, boolean value); }### Answer:
@Test public void bin2Int() { assertEquals(2147483647, BitUtil.bin2Int("111_1111_1111_1111_1111_1111_1111_1111".replace("_", ""))); assertEquals(2147483647, BitUtil.bin2Int("0b111_1111_1111_1111_1111_1111_1111_1111".replace("_", ""))); } |
### Question:
ByteUtil { public static long bytes2LongBigEndian(byte... bytes) { long result = 0L; if (bytes == null || bytes.length == 0) return result; result |= (bytes[0] & 0xff); for (int i = 1; i < bytes.length; i++) { result = result << 8; result |= (bytes[i] & 0xff); } return result; } static byte[] int2BytesBigEndian(int i); static int bytes2IntBigEndian(byte... bytes); static byte[] long2BytesBigEndian(long l); static long bytes2LongBigEndian(byte... bytes); static byte[] int2BytesLittleEndian(int i); static int bytes2IntLittleEndian(byte... bytes); static byte[] long2BytesLittleEndian(long l); static long bytes2LongLittleEndian(byte... bytes); static byte[] reverse(byte... bytes); static int bytesIndexOf(byte[] source, byte[] target, int begin); static byte bbc(byte... datas); static byte[] crc16Modbus(byte... datas); }### Answer:
@Test public void bytes2LongBigEndian() { assertEquals(0x1234L, ByteUtil.bytes2LongBigEndian((byte) 0x12, (byte) 0x34)); assertEquals(0x1234567890ABL, ByteUtil.bytes2LongBigEndian((byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x90, (byte) 0xAB)); } |
### Question:
BitUtil { public static String long2Bin(long source) { return Long.toBinaryString(source); } static String int2Bin(int source); static int bin2Int(String source); static String long2Bin(long source); static long bin2Long(String source); static boolean getIntBit(int source, int pos); static int setIntBit(int source, int pos, boolean value); static boolean getLongBit(long source, int pos); static long setLongBit(long source, int pos, boolean value); }### Answer:
@Test public void long2Bin() { assertEquals("1_0000_0000_0000_0000_0000_0000_0000_0000".replace("_", ""), BitUtil.long2Bin(4294967296L)); } |
### Question:
BitUtil { public static long bin2Long(String source) { if (source.startsWith("0b")) source = source.substring(2); return Long.parseLong(source, 2); } static String int2Bin(int source); static int bin2Int(String source); static String long2Bin(long source); static long bin2Long(String source); static boolean getIntBit(int source, int pos); static int setIntBit(int source, int pos, boolean value); static boolean getLongBit(long source, int pos); static long setLongBit(long source, int pos, boolean value); }### Answer:
@Test public void bin2Long() { assertEquals(4294967296L, BitUtil.bin2Long("1_0000_0000_0000_0000_0000_0000_0000_0000".replace("_", ""))); assertEquals(4294967296L, BitUtil.bin2Long("0b1_0000_0000_0000_0000_0000_0000_0000_0000".replace("_", ""))); } |
### Question:
BitUtil { public static boolean getIntBit(int source, int pos) { pos = pos - 1; int bitValue = 1 << pos; return (source & bitValue) == bitValue; } static String int2Bin(int source); static int bin2Int(String source); static String long2Bin(long source); static long bin2Long(String source); static boolean getIntBit(int source, int pos); static int setIntBit(int source, int pos, boolean value); static boolean getLongBit(long source, int pos); static long setLongBit(long source, int pos, boolean value); }### Answer:
@Test public void getIntBit() { assertTrue(BitUtil.getIntBit(4, 3)); assertFalse(BitUtil.getIntBit(4, 2)); } |
### Question:
BitUtil { public static int setIntBit(int source, int pos, boolean value) { if (getIntBit(source, pos) == value) return source; pos = pos - 1; int bitValue = 1 << pos; if (value) { return source | bitValue; } else { return source ^ bitValue; } } static String int2Bin(int source); static int bin2Int(String source); static String long2Bin(long source); static long bin2Long(String source); static boolean getIntBit(int source, int pos); static int setIntBit(int source, int pos, boolean value); static boolean getLongBit(long source, int pos); static long setLongBit(long source, int pos, boolean value); }### Answer:
@Test public void setIntBit() { assertEquals("1011", BitUtil.int2Bin(BitUtil.setIntBit(BitUtil.bin2Int("1011"), 2, true))); assertEquals("1011", BitUtil.int2Bin(BitUtil.setIntBit(BitUtil.bin2Int("1001"), 2, true))); assertEquals("1001", BitUtil.int2Bin(BitUtil.setIntBit(BitUtil.bin2Int("1011"), 2, false))); assertEquals("1001", BitUtil.int2Bin(BitUtil.setIntBit(BitUtil.bin2Int("1001"), 2, false))); } |
### Question:
BitUtil { public static boolean getLongBit(long source, int pos) { pos = pos - 1; long bitValue = 1 << pos; return (source & bitValue) == bitValue; } static String int2Bin(int source); static int bin2Int(String source); static String long2Bin(long source); static long bin2Long(String source); static boolean getIntBit(int source, int pos); static int setIntBit(int source, int pos, boolean value); static boolean getLongBit(long source, int pos); static long setLongBit(long source, int pos, boolean value); }### Answer:
@Test public void getLongBit() { assertTrue(BitUtil.getLongBit(4, 3)); assertFalse(BitUtil.getLongBit(4, 2)); } |
### Question:
BitUtil { public static long setLongBit(long source, int pos, boolean value) { if (getLongBit(source, pos) == value) return source; pos = pos - 1; long bitValue = 1 << pos; if (value) { return source | bitValue; } else { return source ^ bitValue; } } static String int2Bin(int source); static int bin2Int(String source); static String long2Bin(long source); static long bin2Long(String source); static boolean getIntBit(int source, int pos); static int setIntBit(int source, int pos, boolean value); static boolean getLongBit(long source, int pos); static long setLongBit(long source, int pos, boolean value); }### Answer:
@Test public void setLongBit() { assertEquals("1011", BitUtil.long2Bin(BitUtil.setLongBit(BitUtil.bin2Long("1011"), 2, true))); assertEquals("1011", BitUtil.long2Bin(BitUtil.setLongBit(BitUtil.bin2Long("1001"), 2, true))); assertEquals("1001", BitUtil.long2Bin(BitUtil.setLongBit(BitUtil.bin2Long("1011"), 2, false))); assertEquals("1001", BitUtil.long2Bin(BitUtil.setLongBit(BitUtil.bin2Long("1001"), 2, false))); } |
### Question:
RegexUtil { public static boolean isCellphoneNumber(String num) { return isCellphoneNumber(num, true); } static boolean isIdentityNumber(String num); static boolean isCellphoneNumber(String num); static boolean isCellphoneNumber(String num, boolean virtual); static boolean isPhoneNumber(String num); static boolean isAuthCode(String num); static boolean isAuthCode(String num, int min, int max); static boolean isName(String name); static boolean isVehicleLicence(String license); static boolean isEmail(String email); static boolean isBankCard(String card); static boolean isLowerMoney(String money); static boolean isInteger(String integer, long min, long max); static boolean isPassword(String password); static boolean isComplexPassword(String password); static boolean isIpAddress(String address); static boolean isIp4Address(String address); static boolean isIp6Address(String address); }### Answer:
@Test public void isCellphoneNumber() { assertTrue(RegexUtil.isCellphoneNumber("13086668581")); assertTrue(RegexUtil.isCellphoneNumber("17108387204", true)); assertFalse(RegexUtil.isCellphoneNumber("17108387204", false)); } |
### Question:
RegexUtil { public static boolean isPhoneNumber(String num) { if (num == null) return false; num = num.replace(" ", ""); num = num.replaceAll("^\\+?86", ""); return num.matches("^0\\d{2,3}-?[1-9]\\d{4,7}$"); } static boolean isIdentityNumber(String num); static boolean isCellphoneNumber(String num); static boolean isCellphoneNumber(String num, boolean virtual); static boolean isPhoneNumber(String num); static boolean isAuthCode(String num); static boolean isAuthCode(String num, int min, int max); static boolean isName(String name); static boolean isVehicleLicence(String license); static boolean isEmail(String email); static boolean isBankCard(String card); static boolean isLowerMoney(String money); static boolean isInteger(String integer, long min, long max); static boolean isPassword(String password); static boolean isComplexPassword(String password); static boolean isIpAddress(String address); static boolean isIp4Address(String address); static boolean isIp6Address(String address); }### Answer:
@Test public void isPhoneNumber() { assertTrue(RegexUtil.isPhoneNumber("08387450459")); assertTrue(RegexUtil.isPhoneNumber("0838-7450459")); assertTrue(RegexUtil.isPhoneNumber("8608387450459")); assertTrue(RegexUtil.isPhoneNumber("+8608387450459")); } |
### Question:
RegexUtil { public static boolean isAuthCode(String num) { return isAuthCode(num, 4, 8); } static boolean isIdentityNumber(String num); static boolean isCellphoneNumber(String num); static boolean isCellphoneNumber(String num, boolean virtual); static boolean isPhoneNumber(String num); static boolean isAuthCode(String num); static boolean isAuthCode(String num, int min, int max); static boolean isName(String name); static boolean isVehicleLicence(String license); static boolean isEmail(String email); static boolean isBankCard(String card); static boolean isLowerMoney(String money); static boolean isInteger(String integer, long min, long max); static boolean isPassword(String password); static boolean isComplexPassword(String password); static boolean isIpAddress(String address); static boolean isIp4Address(String address); static boolean isIp6Address(String address); }### Answer:
@Test public void isAuthCode() { assertTrue(RegexUtil.isAuthCode("001235")); assertTrue(RegexUtil.isAuthCode("1232", 4, 8)); } |
### Question:
ByteUtil { public static byte[] int2BytesLittleEndian(int i) { byte[] bytes = new byte[4]; bytes[0] = (byte) (i & 0xff); bytes[1] = (byte) ((i >> 8) & 0xff); bytes[2] = (byte) ((i >> 16) & 0xff); bytes[3] = (byte) ((i >> 24) & 0xff); return bytes; } static byte[] int2BytesBigEndian(int i); static int bytes2IntBigEndian(byte... bytes); static byte[] long2BytesBigEndian(long l); static long bytes2LongBigEndian(byte... bytes); static byte[] int2BytesLittleEndian(int i); static int bytes2IntLittleEndian(byte... bytes); static byte[] long2BytesLittleEndian(long l); static long bytes2LongLittleEndian(byte... bytes); static byte[] reverse(byte... bytes); static int bytesIndexOf(byte[] source, byte[] target, int begin); static byte bbc(byte... datas); static byte[] crc16Modbus(byte... datas); }### Answer:
@Test public void int2BytesLittleEndian() { assertArrayEquals(new byte[]{(byte) 0x34, (byte) 0x12, 0, 0}, ByteUtil.int2BytesLittleEndian(0x1234)); assertArrayEquals(new byte[]{(byte) 0x78, (byte) 0x56, (byte) 0x34, (byte) 0x12}, ByteUtil.int2BytesLittleEndian(0x12345678)); } |
### Question:
RegexUtil { public static boolean isName(String name) { if (name == null) return false; return name.matches("^[\\u4e00-\\u9fa5]+([·•][\\u4e00-\\u9fa5]+)*$"); } static boolean isIdentityNumber(String num); static boolean isCellphoneNumber(String num); static boolean isCellphoneNumber(String num, boolean virtual); static boolean isPhoneNumber(String num); static boolean isAuthCode(String num); static boolean isAuthCode(String num, int min, int max); static boolean isName(String name); static boolean isVehicleLicence(String license); static boolean isEmail(String email); static boolean isBankCard(String card); static boolean isLowerMoney(String money); static boolean isInteger(String integer, long min, long max); static boolean isPassword(String password); static boolean isComplexPassword(String password); static boolean isIpAddress(String address); static boolean isIp4Address(String address); static boolean isIp6Address(String address); }### Answer:
@Test public void isName() { assertTrue(RegexUtil.isName("李荣浩")); assertTrue(RegexUtil.isName("尼格买提·买买提·阿凡提")); } |
### Question:
RegexUtil { public static boolean isVehicleLicence(String license) { if (license == null) return false; return license.matches("^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$"); } static boolean isIdentityNumber(String num); static boolean isCellphoneNumber(String num); static boolean isCellphoneNumber(String num, boolean virtual); static boolean isPhoneNumber(String num); static boolean isAuthCode(String num); static boolean isAuthCode(String num, int min, int max); static boolean isName(String name); static boolean isVehicleLicence(String license); static boolean isEmail(String email); static boolean isBankCard(String card); static boolean isLowerMoney(String money); static boolean isInteger(String integer, long min, long max); static boolean isPassword(String password); static boolean isComplexPassword(String password); static boolean isIpAddress(String address); static boolean isIp4Address(String address); static boolean isIp6Address(String address); }### Answer:
@Test public void isVehicleLicence() { assertTrue(RegexUtil.isVehicleLicence("川A12345")); assertTrue(RegexUtil.isVehicleLicence("川A54374D")); } |
### Question:
RegexUtil { public static boolean isEmail(String email) { if (email == null) return false; return email.matches("^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$"); } static boolean isIdentityNumber(String num); static boolean isCellphoneNumber(String num); static boolean isCellphoneNumber(String num, boolean virtual); static boolean isPhoneNumber(String num); static boolean isAuthCode(String num); static boolean isAuthCode(String num, int min, int max); static boolean isName(String name); static boolean isVehicleLicence(String license); static boolean isEmail(String email); static boolean isBankCard(String card); static boolean isLowerMoney(String money); static boolean isInteger(String integer, long min, long max); static boolean isPassword(String password); static boolean isComplexPassword(String password); static boolean isIpAddress(String address); static boolean isIp4Address(String address); static boolean isIp6Address(String address); }### Answer:
@Test public void isEmail() { assertTrue(RegexUtil.isEmail("name_001@qq.com")); } |
### Question:
RegexUtil { public static boolean isBankCard(String card) { if (card == null) return false; card = card.replace(" ", ""); return card.matches("^\\d{16,19}$"); } static boolean isIdentityNumber(String num); static boolean isCellphoneNumber(String num); static boolean isCellphoneNumber(String num, boolean virtual); static boolean isPhoneNumber(String num); static boolean isAuthCode(String num); static boolean isAuthCode(String num, int min, int max); static boolean isName(String name); static boolean isVehicleLicence(String license); static boolean isEmail(String email); static boolean isBankCard(String card); static boolean isLowerMoney(String money); static boolean isInteger(String integer, long min, long max); static boolean isPassword(String password); static boolean isComplexPassword(String password); static boolean isIpAddress(String address); static boolean isIp4Address(String address); static boolean isIp6Address(String address); }### Answer:
@Test public void isBankCard() { assertTrue(RegexUtil.isBankCard("6222600260001072444")); } |
### Question:
RegexUtil { public static boolean isLowerMoney(String money) { if (money == null) return false; money = money.replace(",", ""); return money.matches("^\\d+\\.?\\d{0,2}$"); } static boolean isIdentityNumber(String num); static boolean isCellphoneNumber(String num); static boolean isCellphoneNumber(String num, boolean virtual); static boolean isPhoneNumber(String num); static boolean isAuthCode(String num); static boolean isAuthCode(String num, int min, int max); static boolean isName(String name); static boolean isVehicleLicence(String license); static boolean isEmail(String email); static boolean isBankCard(String card); static boolean isLowerMoney(String money); static boolean isInteger(String integer, long min, long max); static boolean isPassword(String password); static boolean isComplexPassword(String password); static boolean isIpAddress(String address); static boolean isIp4Address(String address); static boolean isIp6Address(String address); }### Answer:
@Test public void isLowerMoney() { assertTrue(RegexUtil.isLowerMoney("1234567890.73")); assertFalse(RegexUtil.isLowerMoney("-1234567890.73")); } |
### Question:
RegexUtil { public static boolean isInteger(String integer, long min, long max) { if (integer == null) return false; if (!integer.matches("^-?[0-9](\\d)*$")) return false; long num; try { num = Long.valueOf(integer); } catch (NumberFormatException e) { e.printStackTrace(); return false; } return num >= min && num <= max; } static boolean isIdentityNumber(String num); static boolean isCellphoneNumber(String num); static boolean isCellphoneNumber(String num, boolean virtual); static boolean isPhoneNumber(String num); static boolean isAuthCode(String num); static boolean isAuthCode(String num, int min, int max); static boolean isName(String name); static boolean isVehicleLicence(String license); static boolean isEmail(String email); static boolean isBankCard(String card); static boolean isLowerMoney(String money); static boolean isInteger(String integer, long min, long max); static boolean isPassword(String password); static boolean isComplexPassword(String password); static boolean isIpAddress(String address); static boolean isIp4Address(String address); static boolean isIp6Address(String address); }### Answer:
@Test public void isInteger() { assertTrue(RegexUtil.isInteger("64646416846", Long.MIN_VALUE, Long.MAX_VALUE)); } |
### Question:
RegexUtil { public static boolean isPassword(String password) { if (password == null) return false; if (password.length() < 6 || password.length() > 16) return false; return password.matches("^[0-9a-zA-Z~!@#\\$%\\^&\\*\\(\\)_\\\\+-=:\";'<>?,\\.\\/]{6,16}$"); } static boolean isIdentityNumber(String num); static boolean isCellphoneNumber(String num); static boolean isCellphoneNumber(String num, boolean virtual); static boolean isPhoneNumber(String num); static boolean isAuthCode(String num); static boolean isAuthCode(String num, int min, int max); static boolean isName(String name); static boolean isVehicleLicence(String license); static boolean isEmail(String email); static boolean isBankCard(String card); static boolean isLowerMoney(String money); static boolean isInteger(String integer, long min, long max); static boolean isPassword(String password); static boolean isComplexPassword(String password); static boolean isIpAddress(String address); static boolean isIp4Address(String address); static boolean isIp6Address(String address); }### Answer:
@Test public void isPassword() { assertTrue(RegexUtil.isPassword("123456789")); } |
### Question:
RegexUtil { public static boolean isComplexPassword(String password) { if (!isPassword(password)) return false; return password.matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z`~!@#$%^&*()\\-_=+\\[\\]{};:'\"\\\\|,<.>/?]{6,16}$"); } static boolean isIdentityNumber(String num); static boolean isCellphoneNumber(String num); static boolean isCellphoneNumber(String num, boolean virtual); static boolean isPhoneNumber(String num); static boolean isAuthCode(String num); static boolean isAuthCode(String num, int min, int max); static boolean isName(String name); static boolean isVehicleLicence(String license); static boolean isEmail(String email); static boolean isBankCard(String card); static boolean isLowerMoney(String money); static boolean isInteger(String integer, long min, long max); static boolean isPassword(String password); static boolean isComplexPassword(String password); static boolean isIpAddress(String address); static boolean isIp4Address(String address); static boolean isIp6Address(String address); }### Answer:
@Test public void isComplexPassword() { assertFalse(RegexUtil.isComplexPassword("123456789")); assertFalse(RegexUtil.isComplexPassword("qwerQWER")); assertTrue(RegexUtil.isComplexPassword("QWER0000")); assertTrue(RegexUtil.isComplexPassword("QWER0000.~@.,;'")); } |
### Question:
RegexUtil { public static boolean isIpAddress(String address) { if (address == null) return false; return isIp4Address(address) || isIp6Address(address); } static boolean isIdentityNumber(String num); static boolean isCellphoneNumber(String num); static boolean isCellphoneNumber(String num, boolean virtual); static boolean isPhoneNumber(String num); static boolean isAuthCode(String num); static boolean isAuthCode(String num, int min, int max); static boolean isName(String name); static boolean isVehicleLicence(String license); static boolean isEmail(String email); static boolean isBankCard(String card); static boolean isLowerMoney(String money); static boolean isInteger(String integer, long min, long max); static boolean isPassword(String password); static boolean isComplexPassword(String password); static boolean isIpAddress(String address); static boolean isIp4Address(String address); static boolean isIp6Address(String address); }### Answer:
@Test public void isIpAddress() { assertTrue(RegexUtil.isIpAddress("0.0.0.0")); assertTrue(RegexUtil.isIpAddress("192.168.1.255")); assertTrue(RegexUtil.isIpAddress("fe80:0:0:0:20c:29ff:fe6b:2516")); assertTrue(RegexUtil.isIpAddress("1040::1")); } |
### Question:
RegexUtil { public static boolean isIp4Address(String address) { if (address == null) return false; return address.matches("^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$"); } static boolean isIdentityNumber(String num); static boolean isCellphoneNumber(String num); static boolean isCellphoneNumber(String num, boolean virtual); static boolean isPhoneNumber(String num); static boolean isAuthCode(String num); static boolean isAuthCode(String num, int min, int max); static boolean isName(String name); static boolean isVehicleLicence(String license); static boolean isEmail(String email); static boolean isBankCard(String card); static boolean isLowerMoney(String money); static boolean isInteger(String integer, long min, long max); static boolean isPassword(String password); static boolean isComplexPassword(String password); static boolean isIpAddress(String address); static boolean isIp4Address(String address); static boolean isIp6Address(String address); }### Answer:
@Test public void isIp4Address() { assertTrue(RegexUtil.isIp4Address("0.0.0.0")); assertTrue(RegexUtil.isIp4Address("192.168.1.255")); } |
### Question:
ByteUtil { public static int bytes2IntLittleEndian(byte... bytes) { int result = 0; for (int i = 0; i < bytes.length; i++) { result |= (bytes[i] & 0xFF) << (i * 8); if (i == 3) break; } return result; } static byte[] int2BytesBigEndian(int i); static int bytes2IntBigEndian(byte... bytes); static byte[] long2BytesBigEndian(long l); static long bytes2LongBigEndian(byte... bytes); static byte[] int2BytesLittleEndian(int i); static int bytes2IntLittleEndian(byte... bytes); static byte[] long2BytesLittleEndian(long l); static long bytes2LongLittleEndian(byte... bytes); static byte[] reverse(byte... bytes); static int bytesIndexOf(byte[] source, byte[] target, int begin); static byte bbc(byte... datas); static byte[] crc16Modbus(byte... datas); }### Answer:
@Test public void bytes2IntLittleEndian() { assertEquals(0x3412, ByteUtil.bytes2IntLittleEndian((byte) 0x12, (byte) 0x34)); assertEquals(0x78563412, ByteUtil.bytes2IntLittleEndian((byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78)); } |
### Question:
ByteUtil { public static long bytes2LongLittleEndian(byte... bytes) { long result = 0; for (int i = 0; i < bytes.length; i++) { result |= ((long) (bytes[i] & 0xFF)) << (i * 8); if (i == 7) break; } return result; } static byte[] int2BytesBigEndian(int i); static int bytes2IntBigEndian(byte... bytes); static byte[] long2BytesBigEndian(long l); static long bytes2LongBigEndian(byte... bytes); static byte[] int2BytesLittleEndian(int i); static int bytes2IntLittleEndian(byte... bytes); static byte[] long2BytesLittleEndian(long l); static long bytes2LongLittleEndian(byte... bytes); static byte[] reverse(byte... bytes); static int bytesIndexOf(byte[] source, byte[] target, int begin); static byte bbc(byte... datas); static byte[] crc16Modbus(byte... datas); }### Answer:
@Test public void bytes2LongLittleEndian() { assertEquals(0x3412L, ByteUtil.bytes2LongLittleEndian((byte) 0x12, (byte) 0x34)); assertEquals(0xAB9078563412L, ByteUtil.bytes2LongLittleEndian((byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x90, (byte) 0xAB)); } |
### Question:
ByteUtil { public static byte[] reverse(byte... bytes) { int length = bytes.length; byte[] result = new byte[length]; for (int i = 0; i < length; i++) { result[length - i - 1] = bytes[i]; } return result; } static byte[] int2BytesBigEndian(int i); static int bytes2IntBigEndian(byte... bytes); static byte[] long2BytesBigEndian(long l); static long bytes2LongBigEndian(byte... bytes); static byte[] int2BytesLittleEndian(int i); static int bytes2IntLittleEndian(byte... bytes); static byte[] long2BytesLittleEndian(long l); static long bytes2LongLittleEndian(byte... bytes); static byte[] reverse(byte... bytes); static int bytesIndexOf(byte[] source, byte[] target, int begin); static byte bbc(byte... datas); static byte[] crc16Modbus(byte... datas); }### Answer:
@Test public void reverse() { assertArrayEquals(new byte[]{(byte) 0x78, (byte) 0x56, (byte) 0x34, (byte) 0x12}, ByteUtil.reverse((byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78)); } |
### Question:
ByteUtil { public static int bytesIndexOf(byte[] source, byte[] target, int begin) { if (source == null || target == null || target.length == 0 || source.length < target.length) return -1; int i, j, max = source.length - target.length; for (i = begin; i <= max; i++) { if (source[i] == target[0]) { for (j = 1; j < target.length; j++) { if (source[i + j] != target[j]) break; } if (j == target.length) return i; } } return -1; } static byte[] int2BytesBigEndian(int i); static int bytes2IntBigEndian(byte... bytes); static byte[] long2BytesBigEndian(long l); static long bytes2LongBigEndian(byte... bytes); static byte[] int2BytesLittleEndian(int i); static int bytes2IntLittleEndian(byte... bytes); static byte[] long2BytesLittleEndian(long l); static long bytes2LongLittleEndian(byte... bytes); static byte[] reverse(byte... bytes); static int bytesIndexOf(byte[] source, byte[] target, int begin); static byte bbc(byte... datas); static byte[] crc16Modbus(byte... datas); }### Answer:
@Test public void bytesIndexOf() { assertEquals(2, ByteUtil.bytesIndexOf(new byte[]{(byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6}, new byte[]{(byte) 0xF3, (byte) 0xF4}, 0)); } |
### Question:
ListObject extends WeiboResponse implements java.io.Serializable { public void setFullName(String fullName) { this.fullName = fullName; } ListObject(Response res, Weibo weibo); ListObject(Response res, Element elem, Weibo weibo); ListObject(JSONObject json); String getName(); void setName(String name); String getFullName(); void setFullName(String fullName); String getSlug(); void setSlug(String slug); String getDescription(); void setDescription(String description); String getUri(); void setUri(String uri); int getSubscriberCount(); void setSubscriberCount(int subscriberCount); int getMemberCount(); void setMemberCount(int memberCount); void setId(long id); long getId(); String getMode(); void setMode(String mode); User getUser(); void setUser(User user); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void testSetFullName() { fail("Not yet implemented"); } |
### Question:
Nulls { public static String notEmpty(String value, String fallback) { if (value == null || value.trim().isEmpty()) { return fallback; } return value; } static T notNull(T value, T fallback); static String notNull(String value); static Boolean notNull(Boolean value); static Long notNull(Long value); static BigDecimal notNull(BigDecimal value); static List<T> notNull(List<T> value); static Set<T> notNull(Set<T> value); static Map<K, V> notNull(Map<K, V> value); static void accept(T value, Consumer<T> consumer); static R apply(T value, Function<T, R> function, R fallback); static String notEmpty(String value, String fallback); static TARGET notNull(SOURCE value, PropertyValueProvider<SOURCE, TARGET> provider, TARGET fallback); static String notEmpty(SOURCE value, PropertyValueProvider<SOURCE, String> provider, String fallback); static boolean noneNullValue(T... values); static boolean anyNoneNullValue(T... values); }### Answer:
@Test public void simpleNotEmpty() { String value = null; String result = Nulls.notEmpty(value, "-"); assertThat(result, notNullValue()); assertThat(result, equalTo("-")); }
@Test public void propertyProviderNullObject() { SampleObject value = null; String result = Nulls.notEmpty(value, SampleObject::getValue, "-"); assertThat(result, notNullValue()); assertThat(result, equalTo("-")); }
@Test public void propertyProviderNullProperty() { SampleObject value = new SampleObject(); String result = Nulls.notEmpty(value, SampleObject::getValue, "-"); assertThat(result, notNullValue()); assertThat(result, equalTo("-")); }
@Test public void propertyProviderEmptyProperty() { SampleObject value = new SampleObject(); value.setValue(" "); String result = Nulls.notEmpty(value, SampleObject::getValue, "-"); assertThat(result, notNullValue()); assertThat(result, equalTo("-")); } |
### Question:
TimeUtil { public static LocalDate firstDayOfYear(int year) { return LocalDate.of(year, 1, 1); } static LocalDate min(LocalDate one, LocalDate two); static LocalTime min(LocalTime one, LocalTime two); static LocalDateTime min(LocalDateTime one, LocalDateTime two); static Instant min(Instant one, Instant two); static LocalDate max(LocalDate one, LocalDate two); static LocalTime max(LocalTime one, LocalTime two); static LocalDateTime max(LocalDateTime one, LocalDateTime two); static Instant max(Instant one, Instant two); static LocalDate firstDayOfYear(int year); static LocalDate lastDayOfYear(int year); static boolean isBeforeOrEquals(LocalDate val, LocalDate compare); static boolean isBeforeOrEquals(LocalDateTime val, LocalDateTime compare); static boolean isBeforeOrEquals(Instant val, Instant compare); static boolean isAfterOrEquals(LocalDate val, LocalDate compare); static boolean isAfterOrEquals(LocalDateTime val, LocalDateTime compare); static boolean isAfterOrEquals(Instant val, Instant compare); static String convertMillisToMinSecFormat(long millis); }### Answer:
@Test public void firstDayOfYear() { assertThat(TimeUtil.firstDayOfYear(2000), equalTo(LocalDate.of(2000, 1, 1))); } |
### Question:
TimeUtil { public static LocalDate lastDayOfYear(int year) { return LocalDate.of(year, 12, 31); } static LocalDate min(LocalDate one, LocalDate two); static LocalTime min(LocalTime one, LocalTime two); static LocalDateTime min(LocalDateTime one, LocalDateTime two); static Instant min(Instant one, Instant two); static LocalDate max(LocalDate one, LocalDate two); static LocalTime max(LocalTime one, LocalTime two); static LocalDateTime max(LocalDateTime one, LocalDateTime two); static Instant max(Instant one, Instant two); static LocalDate firstDayOfYear(int year); static LocalDate lastDayOfYear(int year); static boolean isBeforeOrEquals(LocalDate val, LocalDate compare); static boolean isBeforeOrEquals(LocalDateTime val, LocalDateTime compare); static boolean isBeforeOrEquals(Instant val, Instant compare); static boolean isAfterOrEquals(LocalDate val, LocalDate compare); static boolean isAfterOrEquals(LocalDateTime val, LocalDateTime compare); static boolean isAfterOrEquals(Instant val, Instant compare); static String convertMillisToMinSecFormat(long millis); }### Answer:
@Test public void lastDayOfYear() { assertThat(TimeUtil.lastDayOfYear(2000), equalTo(LocalDate.of(2000, 12, 31))); } |
### Question:
TimeUtil { public static String convertMillisToMinSecFormat(long millis) { long ms = millis % 1000; long s = (millis / 1000) % 60; long m = ((millis / 1000) / 60) % 60; if (s > 0 && m <= 0) { return String.format("%d sec %d ms", s, ms); } else if (s > 0 || m > 0) { return String.format("%d min %d sec %d ms", m, s, ms); } else { return String.format("%d ms", ms); } } static LocalDate min(LocalDate one, LocalDate two); static LocalTime min(LocalTime one, LocalTime two); static LocalDateTime min(LocalDateTime one, LocalDateTime two); static Instant min(Instant one, Instant two); static LocalDate max(LocalDate one, LocalDate two); static LocalTime max(LocalTime one, LocalTime two); static LocalDateTime max(LocalDateTime one, LocalDateTime two); static Instant max(Instant one, Instant two); static LocalDate firstDayOfYear(int year); static LocalDate lastDayOfYear(int year); static boolean isBeforeOrEquals(LocalDate val, LocalDate compare); static boolean isBeforeOrEquals(LocalDateTime val, LocalDateTime compare); static boolean isBeforeOrEquals(Instant val, Instant compare); static boolean isAfterOrEquals(LocalDate val, LocalDate compare); static boolean isAfterOrEquals(LocalDateTime val, LocalDateTime compare); static boolean isAfterOrEquals(Instant val, Instant compare); static String convertMillisToMinSecFormat(long millis); }### Answer:
@Test public void convertMillisToMinSecFormat() { assertThat(TimeUtil.convertMillisToMinSecFormat(100), equalTo("100 ms")); assertThat(TimeUtil.convertMillisToMinSecFormat(1010), equalTo("1 sec 10 ms")); assertThat(TimeUtil.convertMillisToMinSecFormat(60010), equalTo("1 min 0 sec 10 ms")); } |
### Question:
StringShorten { public static String left(String value, int maxLength) { return left(value, maxLength, "..."); } static String left(String value, int maxLength); static String left(String value, int maxLength, String end); static String right(String value, int maxLength); static String right(String value, int maxLength, String beginning); }### Answer:
@Test public void leftNull() { String value = null; String result = StringShorten.left(value, 10, "..."); assertThat(result, notNullValue()); assertThat(result, equalTo("")); }
@Test public void leftShort() { String value = "hello"; String result = StringShorten.left(value, 10, "..."); assertThat(result, notNullValue()); assertThat(result, equalTo(value)); }
@Test public void leftTooLong() { String value = "hello again in the wold of java and rest"; String result = StringShorten.left(value, 10, "..."); assertThat(result, notNullValue()); assertThat(result.length(), equalTo(10)); assertThat(result, equalTo("hello a...")); } |
### Question:
StringShorten { public static String right(String value, int maxLength) { return right(value, maxLength, "..."); } static String left(String value, int maxLength); static String left(String value, int maxLength, String end); static String right(String value, int maxLength); static String right(String value, int maxLength, String beginning); }### Answer:
@Test public void rightNull() { String value = null; String result = StringShorten.right(value, 10, "..."); assertThat(result, notNullValue()); assertThat(result.length(), equalTo(0)); assertThat(result, equalTo("")); }
@Test public void rightShort() { String value = "hello"; String result = StringShorten.right(value, 10, "..."); assertThat(result, notNullValue()); assertThat(result.length(), equalTo(5)); assertThat(result, equalTo(value)); }
@Test public void rightTooLong() { String value = "hello again in the wold of java and rest"; String result = StringShorten.right(value, 10, "..."); assertThat(result, notNullValue()); assertThat(result.length(), equalTo(10)); assertThat(result, equalTo("...nd rest")); } |
### Question:
UrlParts { public static String concatPaths(Object... parts) { String result = ""; if (parts != null) { for (Object p : parts) { String str = String.valueOf(p); if (p != null && !StringUtils.isEmpty(str)) { if (result.length() > 0 && !str.startsWith("/") && !result.endsWith("/")) { result += "/"; } result += str; } } } return result; } static String concatPaths(Object... parts); static String ensureEndsWithSlash(String uri); static String ensureStartsWithSlash(String uri); static String ensureStartsAndEndsWithSlash(String path); static String removeEndsWithSlash(String path); static String getBaseUrl(HttpServletRequest request); }### Answer:
@Test public void testConcatPaths() { String blaSample = UrlParts.concatPaths("bla", 23); String nullSample = UrlParts.concatPaths(null); String withEndSample = UrlParts.concatPaths("/bla/", 23); assertThat(blaSample, equalTo("bla/23")); assertThat(nullSample, equalTo("")); assertThat(withEndSample, equalTo("/bla/23")); } |
### Question:
UrlParts { public static String ensureEndsWithSlash(String uri) { if (uri == null) { return "/"; } if (!uri.endsWith("/")) { return String.format("%s/", uri); } return uri; } static String concatPaths(Object... parts); static String ensureEndsWithSlash(String uri); static String ensureStartsWithSlash(String uri); static String ensureStartsAndEndsWithSlash(String path); static String removeEndsWithSlash(String path); static String getBaseUrl(HttpServletRequest request); }### Answer:
@Test public void testEnsureEndsWithSlash() { String blaSample = UrlParts.ensureEndsWithSlash("/bla"); String nullSample = UrlParts.ensureEndsWithSlash(null); String withEndSample = UrlParts.ensureEndsWithSlash("/bla/"); assertThat(blaSample, equalTo("/bla/")); assertThat(nullSample, equalTo("/")); assertThat(withEndSample, equalTo("/bla/")); } |
### Question:
UrlParts { public static String ensureStartsWithSlash(String uri) { if (uri == null) { return "/"; } if (!uri.startsWith("/")) { return String.format("/%s", uri); } return uri; } static String concatPaths(Object... parts); static String ensureEndsWithSlash(String uri); static String ensureStartsWithSlash(String uri); static String ensureStartsAndEndsWithSlash(String path); static String removeEndsWithSlash(String path); static String getBaseUrl(HttpServletRequest request); }### Answer:
@Test public void ensureStartsWithSlash() { String blaSample = UrlParts.ensureStartsWithSlash("/bla"); String nullSample = UrlParts.ensureStartsWithSlash(null); String withEndSample = UrlParts.ensureStartsWithSlash("bla/"); assertThat(blaSample, equalTo("/bla")); assertThat(nullSample, equalTo("/")); assertThat(withEndSample, equalTo("/bla/")); } |
### Question:
UrlParts { public static String ensureStartsAndEndsWithSlash(String path) { String fixedStart = ensureStartsWithSlash(path); return ensureEndsWithSlash(fixedStart); } static String concatPaths(Object... parts); static String ensureEndsWithSlash(String uri); static String ensureStartsWithSlash(String uri); static String ensureStartsAndEndsWithSlash(String path); static String removeEndsWithSlash(String path); static String getBaseUrl(HttpServletRequest request); }### Answer:
@Test public void ensureStartsAndEndsWithSlash() { String blaSample = UrlParts.ensureStartsAndEndsWithSlash("/bla"); String nullSample = UrlParts.ensureStartsAndEndsWithSlash(null); String withEndSample = UrlParts.ensureStartsAndEndsWithSlash("bla/"); String withoutSample = UrlParts.ensureStartsAndEndsWithSlash("bla"); assertThat(blaSample, equalTo("/bla/")); assertThat(nullSample, equalTo("/")); assertThat(withEndSample, equalTo("/bla/")); assertThat(withoutSample, equalTo("/bla/")); } |
### Question:
UrlParts { public static String removeEndsWithSlash(String path) { String value = Nulls.notNull(path); if (value.endsWith("/")) { value = value.substring(0, value.length() - 1); } return value; } static String concatPaths(Object... parts); static String ensureEndsWithSlash(String uri); static String ensureStartsWithSlash(String uri); static String ensureStartsAndEndsWithSlash(String path); static String removeEndsWithSlash(String path); static String getBaseUrl(HttpServletRequest request); }### Answer:
@Test public void removeEndsWithSlash() { String blaSample = UrlParts.removeEndsWithSlash("/bla"); String nullSample = UrlParts.removeEndsWithSlash(null); String withEndSample = UrlParts.removeEndsWithSlash("bla/"); String withoutSample = UrlParts.removeEndsWithSlash("bla"); assertThat(blaSample, equalTo("/bla")); assertThat(nullSample, equalTo("")); assertThat(withEndSample, equalTo("bla")); assertThat(withoutSample, equalTo("bla")); } |
### Question:
AbstractCrudChildRestResource extends AbstractBaseCrudRestResource<Read, Write> { protected UriComponentsBuilder buildBaseUriBuilder(ID parentId) { UriComponentsBuilder builder = createUriComponentsBuilder(getBaseParentApiUrl()); builder.path(String.valueOf(parentId)); builder.path(ensureStartsAndEndsWithSlash(getChildPath())); return builder; } PageableResult<Read> find(ID parentId, int page, int pagesize); PageableResult<Read> find(ID parentId, Pageable pageable); Optional<Read> getById(ID parentId, ID id); Read create(ID parentId, Write write); Read update(ID parentId, ID id, Write write); void delete(ID parentId, ID id); }### Answer:
@Test public void buildBaseUriBuilderWithoutSlash() { TestWithoutSlashCrudChildRestResource resoure = new TestWithoutSlashCrudChildRestResource(); UriComponentsBuilder builder = resoure.buildBaseUriBuilder("123"); assertThat(builder, notNullValue()); assertThat(builder.toUriString(), equalTo(TestWithoutSlashCrudChildRestResource.BASE_PARENT_API_URL + "/123/child/")); }
@Test public void buildBaseUriBuilderWithSlash() { TestWithSlashCrudChildRestResource resoure = new TestWithSlashCrudChildRestResource(); UriComponentsBuilder builder = resoure.buildBaseUriBuilder("123"); assertThat(builder, notNullValue()); assertThat(builder.toUriString(), equalTo("https: } |
### Question:
AbstractCrudRestResource extends AbstractBaseCrudRestResource<Read, Write> { protected UriComponentsBuilder buildBaseUriBuilder() { return createUriComponentsBuilder(getBaseApiUrl()); } void executeAll(Consumer<Read> execute, int batchSize); PageableResult<Read> find(int page, int pagesize); PageableResult<Read> find(Pageable pageable); Optional<Read> getById(ID id); Read create(Write write); Read update(ID id, Write write); void delete(ID id); }### Answer:
@Test public void buildBaseUriBuilder() { TestWithoutSlashCrudRestResource resoure = new TestWithoutSlashCrudRestResource(); UriComponentsBuilder builder = resoure.buildBaseUriBuilder(); assertThat(builder, notNullValue()); assertThat(builder.toUriString(), equalTo(TestWithoutSlashCrudRestResource.BASE_PARENT_API_URL + "/")); } |
### Question:
Nulls { public static <T> T notNull(T value, T fallback) { if (value == null) { return fallback; } return value; } static T notNull(T value, T fallback); static String notNull(String value); static Boolean notNull(Boolean value); static Long notNull(Long value); static BigDecimal notNull(BigDecimal value); static List<T> notNull(List<T> value); static Set<T> notNull(Set<T> value); static Map<K, V> notNull(Map<K, V> value); static void accept(T value, Consumer<T> consumer); static R apply(T value, Function<T, R> function, R fallback); static String notEmpty(String value, String fallback); static TARGET notNull(SOURCE value, PropertyValueProvider<SOURCE, TARGET> provider, TARGET fallback); static String notEmpty(SOURCE value, PropertyValueProvider<SOURCE, String> provider, String fallback); static boolean noneNullValue(T... values); static boolean anyNoneNullValue(T... values); }### Answer:
@Test public void propertyProviderNotNullProperty() { SampleObject value = new SampleObject(); Long result = Nulls.notNull(value, SampleObject::getId, 100L); assertThat(result, notNullValue()); assertThat(result, equalTo(100L)); } |
### Question:
AnalyzeImageViewModel extends BaseObservable { public void onClickAnalyze() { eventBus.register(this); imageApi.getLabels(thumbnailPath); analysisPending = true; errorOccurred = false; notifyPropertyChanged(BR.analyzeEnabled); notifyPropertyChanged(BR.progressBarVisibility); notifyPropertyChanged(BR.errorVisibility); } AnalyzeImageViewModel(String thumbnailPath, EventBus eventBus, ImageApi imageApi); @Bindable String getImagePath(); @Bindable boolean isAnalyzeEnabled(); @Bindable int getProgressBarVisibility(); @Bindable int getErrorVisibility(); void setFullImagePath(String imagePath); void onClickAnalyze(); }### Answer:
@Test public void testOnClickAnalyze() { viewModel.onClickAnalyze(); assertFalse(viewModel.isAnalyzeEnabled()); assertEquals(View.VISIBLE, viewModel.getProgressBarVisibility()); assertEquals(View.GONE, viewModel.getErrorVisibility()); verify(eventBus).register(viewModel); verify(imageApi).getLabels(THUMBNAIL_PATH); } |
### Question:
ThumbnailViewModel extends BaseObservable { public void onClickImage(View view) { eventBus.post(new ViewImageEvent(thumbnailPath, String.valueOf(fullImageId), view)); } ThumbnailViewModel(EventBus eventBus); @Bindable String getImagePath(); void setThumbnailPath(String path); void setFullImageId(int fullImageId); void onClickImage(View view); }### Answer:
@Test public void testOnClickImage() { View view = mock(View.class); viewModel.setThumbnailPath(THUMBNAIL_PATH); viewModel.setFullImageId(IMAGE_ID); viewModel.onClickImage(view); verify(eventBus).post(eventCaptor.capture()); ViewImageEvent event = eventCaptor.getValue(); assertNotNull(event); assertEquals(view, event.getView()); assertEquals(EXPECTED_IMAGED_ID, event.getFullImageId()); assertEquals(THUMBNAIL_PATH, event.getThumbnailPath()); } |
### Question:
ThumbnailAdapter extends RecyclerView.Adapter<ThumbnailViewHolder> { @Override public int getItemCount() { if (cursor == null) { return 0; } else { return cursor.getCount(); } } ThumbnailAdapter(EventBus eventBus); void setCursor(Cursor cursor); @Override ThumbnailViewHolder onCreateViewHolder(ViewGroup parent, int viewType); @Override void onBindViewHolder(ThumbnailViewHolder holder, int position); @Override int getItemCount(); }### Answer:
@Test public void testNullCursor() { assertEquals(0, adapter.getItemCount()); } |
### Question:
ThumbnailViewHolder extends RecyclerView.ViewHolder { void setData(String path, int imageId) { viewModel.setThumbnailPath(path); viewModel.setFullImageId(imageId); binding.executePendingBindings(); } ThumbnailViewHolder(View itemView, ViewDataBinding binding,
ThumbnailViewModel viewModel); }### Answer:
@Test public void testSetData() { holder.setData(IMAGE_PATH, IMAGE_ID); verify(viewModel).setThumbnailPath(IMAGE_PATH); verify(viewModel).setFullImageId(IMAGE_ID); verify(binding).executePendingBindings(); } |
### Question:
LabelViewHolder extends RecyclerView.ViewHolder { void setData(LabelInfo label) { viewModel.setLabel(label); binding.executePendingBindings(); } LabelViewHolder(View itemView, ViewDataBinding binding, LabelViewModel viewModel); }### Answer:
@Test public void testSetData() { holder.setData(labelInfo); verify(viewModel).setLabel(labelInfo); verify(binding).executePendingBindings(); } |
### Question:
BindingConfig extends AbstractConfig { @Override public boolean validate() { boolean valid = true; if (StringUtils.isEmpty(getExchange())) { log.error("Invalid Exchange : Exchange must be provided for a binding"); valid = false; } if (StringUtils.isEmpty(getQueue())) { log.error("Invalid Queue : Queue must be provided for a binding"); valid = false; } if (valid) { log.info("Binding configuration validated successfully for Binding '{}'", this); } return valid; } @Override boolean validate(); Binding bind(Exchange exchange, Queue queue); }### Answer:
@Test public void bindingConfigValidationSuccessTest() { bindingConfig = BindingConfig.builder().exchange(exchaneg).queue(queue).routingKey(routingKey).build(); assertTrue(bindingConfig.validate()); assertThat(outputCapture.toString(), containsString(String.format("Binding configuration validated successfully for Binding '%s'", bindingConfig))); }
@Test public void bindingConfigWithoutExchnageAndValidationFailTest() { bindingConfig = BindingConfig.builder().exchange(null).queue(queue).routingKey(routingKey).build(); assertFalse(bindingConfig.validate()); assertThat(outputCapture.toString(), containsString(String.format("Invalid Exchange : Exchange must be provided for a binding"))); }
@Test public void bindingConfigWithoutQueueAndValidationFailTest() { bindingConfig = BindingConfig.builder().exchange(exchaneg).queue(null).routingKey(routingKey).build(); assertFalse(bindingConfig.validate()); assertThat(outputCapture.toString(), containsString(String.format("Invalid Queue : Queue must be provided for a binding"))); }
@Test public void bindingConfigNoExchangeAndNoQueueAndValidationFailTest() { bindingConfig = BindingConfig.builder().exchange(null).queue(null).routingKey(routingKey).build(); assertFalse(bindingConfig.validate()); assertThat(outputCapture.toString(), containsString(String.format("Invalid Exchange : Exchange must be provided for a binding"))); assertThat(outputCapture.toString(), containsString(String.format("Invalid Queue : Queue must be provided for a binding"))); } |
### Question:
QueueConfig extends AbstractConfig { public boolean validate() { if (StringUtils.isEmpty(getName())) { log.error("Invalid Queue Configuration : Name must be provided for a queue"); return false; } log.info("Queue configuration validated successfully for queue '{}'", getName()); return true; } boolean validate(); QueueConfig applyDefaultConfig(QueueConfig defaultQueueConfig); Queue buildQueue(QueueConfig defaultQueueConfig, DeadLetterConfig deadLetterConfig); Queue buildDeadLetterQueue(QueueConfig defaultQueueConfig, DeadLetterConfig deadLetterConfig); }### Answer:
@Test public void queueConfigWithNameAndValidationSuccessTest() { queueConfig = QueueConfig.builder().name(queueName).build(); assertTrue(queueConfig.validate()); assertThat(outputCapture.toString(), containsString(String.format("Queue configuration validated successfully for queue '%s'", queueName))); }
@Test public void queueConfigWithoutNameAndValidationFailTest() { queueConfig = QueueConfig.builder().build(); assertFalse(queueConfig.validate()); assertThat(outputCapture.toString(), containsString("Invalid Queue Configuration : Name must be provided for a queue")); } |
### Question:
QueueConfig extends AbstractConfig { public Queue buildDeadLetterQueue(QueueConfig defaultQueueConfig, DeadLetterConfig deadLetterConfig) { if (!isDefaultConfigApplied()) { applyDefaultConfig(defaultQueueConfig); } return new Queue(deadLetterConfig.createDeadLetterQueueName(getName()), getDurable(), getExclusive(), getAutoDelete(), getArguments()); } boolean validate(); QueueConfig applyDefaultConfig(QueueConfig defaultQueueConfig); Queue buildQueue(QueueConfig defaultQueueConfig, DeadLetterConfig deadLetterConfig); Queue buildDeadLetterQueue(QueueConfig defaultQueueConfig, DeadLetterConfig deadLetterConfig); }### Answer:
@Test public void createDeadLetterQueueWithDefaultConfigurationAppliedTest() { defaultQueueConfig = QueueConfig.builder().deadLetterEnabled(true).build(); queueConfig = QueueConfig.builder().name(queueName).build(); deadLetterConfig = DeadLetterConfig.builder().deadLetterExchange(ExchangeConfig.builder().name("dead-letter-exchange").build()) .queuePostfix(".dlq-new") .build(); expectedQueueConfig = QueueConfig.builder() .name(queueName + ".dlq-new").durable(false).autoDelete(false).exclusive(false).arguments(new HashMap<>()) .build(); Queue queue = queueConfig.buildDeadLetterQueue(defaultQueueConfig, deadLetterConfig); assertQueue(queue, expectedQueueConfig); } |
### Question:
DeadLetterConfig extends AbstractConfig { @Override public boolean validate() { log.info("Validating DeadLetterConfig..."); if (deadLetterExchange != null && deadLetterExchange.validate()) { log.info("DeadLetterConfig configuration validated successfully for deadLetterExchange '{}'", deadLetterExchange); return true; } log.error("Invalid DeadLetterConfig Configuration : Valid DeadLetterExchange must be provided for DeadLetterConfig"); return false; } String createDeadLetterQueueName(String queueName); @Override boolean validate(); }### Answer:
@Test public void invalidDeadLetterConfigWithoutExchange() { deadLetterConfig = DeadLetterConfig.builder() .deadLetterExchange(null) .queuePostfix(".dlq") .build(); assertFalse(deadLetterConfig.validate()); }
@Test public void invalidDeadLetterConfigWithoutExchangeName() { deadLetterConfig = DeadLetterConfig.builder() .deadLetterExchange(ExchangeConfig.builder().build()) .queuePostfix(".dlq") .build(); assertFalse(deadLetterConfig.validate()); } |
### Question:
ExchangeConfig extends AbstractConfig { public boolean validate() { if (StringUtils.isEmpty(getName())) { log.error("Invalid Exchange Configuration : Name must be provided for an exchange"); return false; } log.info("Exchange configuration validated successfully for exchange '{}'", getName()); return true; } boolean validate(); ExchangeConfig applyDefaultConfig(ExchangeConfig defaultExchangeConfig); AbstractExchange buildExchange(ExchangeConfig defaultExchangeConfig); }### Answer:
@Test public void exchangeConfigWithNameAndValidationSuccessTest() { exchangeConfig = ExchangeConfig.builder().name(exchangeName).build(); assertTrue(exchangeConfig.validate()); assertThat(outputCapture.toString(), containsString(String.format("Exchange configuration validated successfully for exchange '%s'", exchangeName))); }
@Test public void exchangeConfigWithoutNameAndValidationFailTest() { exchangeConfig = ExchangeConfig.builder().build(); assertFalse(exchangeConfig.validate()); assertThat(outputCapture.toString(), containsString(String.format("Invalid Exchange Configuration : Name must be provided for an exchange"))); } |
### Question:
ExchangeConfig extends AbstractConfig { public AbstractExchange buildExchange(ExchangeConfig defaultExchangeConfig) { if (!isDefaultConfigApplied()) { applyDefaultConfig(defaultExchangeConfig); } AbstractExchange exchange = new CustomExchange(getName(), getType().getValue(), getDurable(), getAutoDelete(), getArguments()); exchange.setInternal(getInternal()); exchange.setDelayed(getDelayed()); return exchange; } boolean validate(); ExchangeConfig applyDefaultConfig(ExchangeConfig defaultExchangeConfig); AbstractExchange buildExchange(ExchangeConfig defaultExchangeConfig); }### Answer:
@Test public void createExchangeWithDefaultConfigurationAppliedTest() { defaultExchangeConfig = ExchangeConfig.builder().build(); exchangeConfig = ExchangeConfig.builder().name(exchangeName).build(); expectedExchangeConfig = ExchangeConfig.builder() .name(exchangeName).type(ExchangeTypes.TOPIC).durable(false).autoDelete(false).delayed(false).internal(false).arguments(new HashMap<>()) .build(); AbstractExchange exchange = exchangeConfig.buildExchange(defaultExchangeConfig); assertExchange(exchange, expectedExchangeConfig); } |
### Question:
AutoReQueueScheduler { @Scheduled(cron = "${rabbitmq.auto-config.re-queue-config.cron}") public void autoReQueue() { log.info("Auto ReQueue Starting..."); String reQueueExchange = rabbitConfig.getReQueueConfig().getExchange().getName(); String reQueueRoutingKey = rabbitConfig.getReQueueConfig().getRoutingKey(); for (Map.Entry<String, QueueConfig> entry : rabbitConfig.getQueues().entrySet()) { if (BooleanUtils.isTrue(entry.getValue().getDeadLetterEnabled())) { ReQueueMessage reQueueMessage = ReQueueMessage.builder() .deadLetterQueue(rabbitConfig.getDeadLetterConfig().createDeadLetterQueueName(entry.getValue().getName())) .messageCount(messageCount) .build(); rabbitTemplate.convertAndSend(reQueueExchange, reQueueRoutingKey, reQueueMessage); } } log.info("Auto ReQueue completed..."); } @Scheduled(cron = "${rabbitmq.auto-config.re-queue-config.cron}") void autoReQueue(); }### Answer:
@Test public void autoReQueueTest() { autoReQueueScheduler.autoReQueue(); verify(rabbitTemplate, times(2)).convertAndSend(anyString(), anyString(), any(ReQueueMessage.class)); } |
### Question:
ReQueueConsumer { @RabbitListener(queues = "${rabbitmq.auto-config.re-queue-config.queue.name}") public void onMessage(ReQueueMessage reQueueMessage) { int count = 0; do { Message message = rabbitTemplate.receive(reQueueMessage.getDeadLetterQueue(), timeout); if (message == null) { break; } Map<String, Object> headers = message.getMessageProperties().getHeaders(); if (reQueuePolicy.canReQueue(message)) { String queueName = (String) headers.get("x-original-queue"); rabbitTemplate.send(queueName, message); } count++; } while (reQueueMessage.getMessageCount() < 0 || reQueueMessage.getMessageCount() > count); } @RabbitListener(queues = "${rabbitmq.auto-config.re-queue-config.queue.name}") void onMessage(ReQueueMessage reQueueMessage); }### Answer:
@Test public void reQueueMessageUntilTheMessageCount() { when(rabbitTemplate.receive(anyString(), anyLong())).thenReturn(message); reQueueConsumer.onMessage(reQueueMessage); verify(rabbitTemplate, times(2)).send(anyString(), any(Message.class)); }
@Test public void shouldNotReQueueIfTheMessageIsNull() { when(rabbitTemplate.receive(anyString(), anyLong())).thenReturn(null); reQueueConsumer.onMessage(reQueueMessage); verify(rabbitTemplate, times(0)).send(anyString(), any(Message.class)); } |
### Question:
ThresholdReQueuePolicy implements ReQueuePolicy { @Override public boolean canReQueue(Message message) { Map<String, Object> headers = message.getMessageProperties().getHeaders(); int requeueCount = 0; if (headers.containsKey(X_REQUEUE_COUNT)) { requeueCount = (int) headers.get(X_REQUEUE_COUNT); } if (threshold > requeueCount) { headers.put(X_REQUEUE_COUNT, ++requeueCount); return true; } return false; } @Override boolean canReQueue(Message message); }### Answer:
@Test public void shouldReQueueForAnyNewMessage() throws Exception { assertTrue(thresholdReQueuePolicy.canReQueue(message)); assertThat(message.getMessageProperties().getHeaders().get("x-requeue-count"), equalTo(1)); }
@Test public void shouldReQueueRequeueCountIsLessThanThreshold() throws Exception { message.getMessageProperties().getHeaders().put("x-requeue-count", 1); assertTrue(thresholdReQueuePolicy.canReQueue(message)); assertThat(message.getMessageProperties().getHeaders().get("x-requeue-count"), equalTo(2)); }
@Test public void shouldNotReQueueRequeueCountIsEqualToThreshold() throws Exception { message.getMessageProperties().getHeaders().put("x-requeue-count", 3); assertFalse(thresholdReQueuePolicy.canReQueue(message)); assertThat(message.getMessageProperties().getHeaders().get("x-requeue-count"), equalTo(3)); }
@Test public void shouldNotReQueueRequeueCountIsGreaterThanOrEqualToThreshold() throws Exception { message.getMessageProperties().getHeaders().put("x-requeue-count", 3); assertFalse(thresholdReQueuePolicy.canReQueue(message)); assertThat(message.getMessageProperties().getHeaders().get("x-requeue-count"), equalTo(3)); } |
### Question:
DefaultCorrelationDataPostProcessor implements CorrelationDataPostProcessor { @Override public CorrelationData postProcess(final Message message, CorrelationData correlationData) { CorrelationData resultCorrelationData = correlationData == null ? new CorrelationData() : correlationData; MessageProperties messageProperties = message.getMessageProperties(); if (correlationData != null && correlationData.getId() != null) { messageProperties.setCorrelationId(correlationData.getId()); } correlationPostProcessor.postProcessMessage(message); resultCorrelationData.setId(messageProperties.getCorrelationId()); return resultCorrelationData; } DefaultCorrelationDataPostProcessor(CorrelationPostProcessor correlationPostProcessor); @Override CorrelationData postProcess(final Message message, CorrelationData correlationData); }### Answer:
@Test public void postProcessWithCorrelationDataTest() { CorrelationData inputCorrelationData = new CorrelationData("my-correlation-id"); CorrelationData correlationData = defaultCorrelationDataPostProcessor.postProcess(message, inputCorrelationData); assertNotNull(message.getMessageProperties().getHeaders().get("correlation-id")); assertNotNull(correlationData); assertNotNull(correlationData.getId()); assertThat(message.getMessageProperties().getHeaders().get("correlation-id"), is(inputCorrelationData.getId())); assertThat(correlationData.getId(), is(inputCorrelationData.getId())); } |
### Question:
InfoHeaderMessagePostProcessor implements MessagePostProcessor { @Override public Message postProcessMessage(final Message message) { MessageProperties messageProperties = message.getMessageProperties(); headers.putIfAbsent("spring-application-name", getEnvironment().getProperty("spring.application.name", String.class)); headers.put("execution-time", new Date().toString()); messageProperties.getHeaders().putIfAbsent("info", headers); return message; } @Override Message postProcessMessage(final Message message); }### Answer:
@Test public void addInfoHeadersToMessage() { infoHeaderMessagePostProcessor.postProcessMessage(message); Map<String, Object> headers = (Map<String, Object>) message.getMessageProperties().getHeaders().get("info"); assertThat(headers.get("info-key"), is(equalTo("info-value"))); assertThat(headers.get("spring-application-name"), is(equalTo("my-application-name"))); assertNotNull(headers.get("execution-time")); }
@Test public void addDefaultHeadersToMessage() { infoHeaderMessagePostProcessor.getHeaders().clear(); infoHeaderMessagePostProcessor.postProcessMessage(message); Map<String, Object> headers = (Map<String, Object>) message.getMessageProperties().getHeaders().get("info"); assertThat(headers.get("spring-application-name"), is(equalTo("my-application-name"))); assertNotNull(headers.get("execution-time")); } |
### Question:
DefaultCorrelationPostProcessor implements CorrelationPostProcessor { @Override public Message postProcessMessage(final Message message) { MessageProperties messageProperties = message.getMessageProperties(); String correlationId = messageProperties.getCorrelationId(); if (correlationId == null) { correlationId = (tracer!=null && tracer.currentSpan()!=null)? tracer.currentSpan().context().traceIdString():UUID.randomUUID().toString(); messageProperties.setCorrelationId(correlationId); } messageProperties.getHeaders().put("correlation-id", correlationId); return message; } @Autowired(required = false) DefaultCorrelationPostProcessor(Tracer tracer); @Override Message postProcessMessage(final Message message); }### Answer:
@Test public void addNewCorrelationIdToHeaderIfMissingTest() { correlationPostProcessor.postProcessMessage(message); assertNotNull(message.getMessageProperties().getHeaders().get("correlation-id")); }
@Test public void addNewCorrelationIdFromTracerToHeaderIfMissingTest() { correlationPostProcessor.postProcessMessage(message); assertNotNull(message.getMessageProperties().getHeaders().get("correlation-id")); assertThat(message.getMessageProperties().getHeaders().get("correlation-id"), equalTo(tracer.currentSpan().context().traceIdString())); }
@Test public void addExistingCorrelationIdToHeaderIfPresentTest() { message.getMessageProperties().setCorrelationId("ExistingCorrelationId"); correlationPostProcessor.postProcessMessage(message); assertNotNull(message.getMessageProperties().getHeaders().get("correlation-id")); assertThat(message.getMessageProperties().getHeaders().get("correlation-id"), is(equalTo("ExistingCorrelationId"))); } |
### Question:
AnnouncementModule implements eu.cloud4soa.api.soa.AnnouncementModule { @Override public void removePaaSInstance(String paasInstanceUriId) throws SOAException { logger.debug("received paasInstanceUriId: "+paasInstanceUriId); logger.debug("paaSOfferingProfilesRepository.updatePaaSInstance(paaSInstance, null);"); try { paaSOfferingProfilesRepository.removePaaSInstance(paasInstanceUriId); } catch (RepositoryException ex) { throw new SOAException(Response.Status.INTERNAL_SERVER_ERROR, ex.getMessage()); } logger.debug("paaSInstance: "+ paasInstanceUriId +" removed"); } @Required void setRepositoryManager(RepositoryManager repositoryManager); @Required void setPaaSOfferingProfilesRepository(PaaSOfferingProfilesRepository paaSOfferingProfilesRepository); @Required void setUserProfilesRepository(UserProfilesRepository userProfilesRepository); @Override PaaSInstance getPaaSInstance(String paaSInstanceUriId); @Override String storePaaSInstance(PaaSInstance paaSInstance, String userInstanceUriId); @Override Response storeTurtlePaaSProfile(String paasProfile, String userInstanceUriId); @Override List<PaaSInstance> retrieveAllPaaSInstances(String userInstanceUriId); @Override void updatePaaSInstance(PaaSInstance paaSInstance); @Override void removePaaSInstance(String paasInstanceUriId); }### Answer:
@Ignore @Test public void TestRemovePaaSInstance() { try { announcementModule.removePaaSInstance(paaSInstance.getUriId()); } catch (SOAException ex) { Assert.fail("removePaaSInstance method has thrown an exception!"); } List<PaaSInstance> applications = null; try { applications = announcementModule.retrieveAllPaaSInstances(userInstance.getUriId()); } catch (SOAException ex) { Assert.fail("retrieveAllPaaSInstances method has thrown an exception!"); } Assert.assertTrue(applications.isEmpty()); } |
### Question:
PaaSOfferingRecommendation implements eu.cloud4soa.api.soa.PaaSOfferingRecommendation { @Override public FiveStarsRate getUserExperienceRate(String appURI) throws SOAException { logger.debug("Get User experience rate for appURI: " + appURI); return userExperienceRate.getUserExperienceRate(appURI); } @Required void setBreachRepository(BreachRepository breachRepository); @Required void setApplicationProfilesRepository(ApplicationProfilesRepository applicationProfilesRepository); @Required void setApplicationInstanceRepository(ApplicationInstanceRepository applicationInstanceRepository); @Required void setUserExperienceRate(UserExperienceRate userExperienceRate); @Override void storeUserExperienceRate(String appURI, FiveStarsRate rate); @Override void deleteUserExperienceRate(String appURI); @Override FiveStarsRate getUserExperienceRate(String appURI); @Override void updateUserExperienceRate(String appURI, String rate); @Override List<FiveStarsRate> getPaaSUserExperienceEvaluation(String paasURI); @Override float getAveragePaaSUserExperienceRate(String paasURI); @Override float getPaaSBreachesPerWeek(String paasURI); @Override float getPaaSBreachesPerMonth(String paasURI); @Override float getPaaSBreachesPerDay(String paasURI); }### Answer:
@Test public void testLoadExistingRateByAppUriId() throws Exception { FiveStarsRate targetRate; targetRate = paasOfferingRecommendation.getUserExperienceRate(APP2TEST_URIID); assertTrue( targetRate.getRate() == RATE1_VALUE); } |
### Question:
PaaSOfferingRecommendation implements eu.cloud4soa.api.soa.PaaSOfferingRecommendation { @Override public void deleteUserExperienceRate(String appURI) throws SOAException { logger.debug("Delete User experience rate for appURI: " + appURI); userExperienceRate.deleteUserExperienceRate(appURI); } @Required void setBreachRepository(BreachRepository breachRepository); @Required void setApplicationProfilesRepository(ApplicationProfilesRepository applicationProfilesRepository); @Required void setApplicationInstanceRepository(ApplicationInstanceRepository applicationInstanceRepository); @Required void setUserExperienceRate(UserExperienceRate userExperienceRate); @Override void storeUserExperienceRate(String appURI, FiveStarsRate rate); @Override void deleteUserExperienceRate(String appURI); @Override FiveStarsRate getUserExperienceRate(String appURI); @Override void updateUserExperienceRate(String appURI, String rate); @Override List<FiveStarsRate> getPaaSUserExperienceEvaluation(String paasURI); @Override float getAveragePaaSUserExperienceRate(String paasURI); @Override float getPaaSBreachesPerWeek(String paasURI); @Override float getPaaSBreachesPerMonth(String paasURI); @Override float getPaaSBreachesPerDay(String paasURI); }### Answer:
@Test public void testUserExperienceRateDelete() throws Exception { int ratesInTheDatabase; logger.debug( "counting the namber of rates in the database"); ratesInTheDatabase = userExperienceRateDao.retrieveAll().size(); logger.debug("Deleting one UserRate "); paasOfferingRecommendation.deleteUserExperienceRate( APP4TEST_URIID ); logger.debug( "Verifying the rate has been deleted"); assertTrue( "Database should contain one object less", userExperienceRateDao.retrieveAll().size() == (ratesInTheDatabase - 1) ); } |
### Question:
PaaSOfferingRecommendation implements eu.cloud4soa.api.soa.PaaSOfferingRecommendation { @Override public List<FiveStarsRate> getPaaSUserExperienceEvaluation(String paasURI) throws SOAException { logger.debug("Get PaaS User Experience Evaluation for paasURI: " + paasURI); return userExperienceRate.getPaasUserExperienceEvaluation(paasURI); } @Required void setBreachRepository(BreachRepository breachRepository); @Required void setApplicationProfilesRepository(ApplicationProfilesRepository applicationProfilesRepository); @Required void setApplicationInstanceRepository(ApplicationInstanceRepository applicationInstanceRepository); @Required void setUserExperienceRate(UserExperienceRate userExperienceRate); @Override void storeUserExperienceRate(String appURI, FiveStarsRate rate); @Override void deleteUserExperienceRate(String appURI); @Override FiveStarsRate getUserExperienceRate(String appURI); @Override void updateUserExperienceRate(String appURI, String rate); @Override List<FiveStarsRate> getPaaSUserExperienceEvaluation(String paasURI); @Override float getAveragePaaSUserExperienceRate(String paasURI); @Override float getPaaSBreachesPerWeek(String paasURI); @Override float getPaaSBreachesPerMonth(String paasURI); @Override float getPaaSBreachesPerDay(String paasURI); }### Answer:
@Test public void TestRetrieveAllPaasRates() throws Exception { List<FiveStarsRate> ratesPerPaas1; ratesPerPaas1 = paasOfferingRecommendation.getPaaSUserExperienceEvaluation( PAAS1_URIID ); assertTrue( ratesPerPaas1.size() == RATES_NUMBER_SET_BY_INIT ); } |
### Question:
PaaSOfferingDiscovery implements eu.cloud4soa.api.soa.PaaSOfferingDiscovery { @Override public PaaSProviderDetails getPaaSProviderDetails(String paaSInstanceUriId) { throw new UnsupportedOperationException("Not supported yet."); } @Required void setPaaSOfferingProfilesRepository(PaaSOfferingProfilesRepository paaSOfferingProfilesRepository); @Required void setApplicationProfilesRepository(ApplicationProfilesRepository applicationProfilesRepository); @Required void setSearchAndDiscoveryInterfaces(SearchAndDiscoveryInterfaces searchAndDiscoveryInterfaces); void setSlaModule(SLAModule slamodule); @Override MatchingPlatform searchForMatchingPlatform(String applicationInstanceUriId); @Override PaaSInstance searchForPaaS(String paaSInstanceUriId); @Override PaaSProviderDetails getPaaSProviderDetails(String paaSInstanceUriId); @Override String query(String sparql); @Override List<PaaSInstance> getAllAvailablePaaSInstances(); }### Answer:
@Ignore @Test public void TestGetPaaSProviderDetails() { PaaSProviderDetails details = paaSOfferingDiscovery.getPaaSProviderDetails(paaSInstance.getUriId()); Assert.assertNotNull(details); } |
### Question:
PaaSOfferingDiscovery implements eu.cloud4soa.api.soa.PaaSOfferingDiscovery { @Override public String query(String sparql) { throw new UnsupportedOperationException("Not supported yet."); } @Required void setPaaSOfferingProfilesRepository(PaaSOfferingProfilesRepository paaSOfferingProfilesRepository); @Required void setApplicationProfilesRepository(ApplicationProfilesRepository applicationProfilesRepository); @Required void setSearchAndDiscoveryInterfaces(SearchAndDiscoveryInterfaces searchAndDiscoveryInterfaces); void setSlaModule(SLAModule slamodule); @Override MatchingPlatform searchForMatchingPlatform(String applicationInstanceUriId); @Override PaaSInstance searchForPaaS(String paaSInstanceUriId); @Override PaaSProviderDetails getPaaSProviderDetails(String paaSInstanceUriId); @Override String query(String sparql); @Override List<PaaSInstance> getAllAvailablePaaSInstances(); }### Answer:
@Ignore @Test public void TestQuery() { String sparql = "select ?p where ?p rdf.type c4s.PaaSInstance"; String result = paaSOfferingDiscovery.query(sparql); Assert.assertTrue(result != null && !result.isEmpty()); } |
### Question:
RequestUtil { public static <T> boolean isValid(Request<T> request){ return isValid(request, true); } static boolean isValid(Request<T> request); static boolean isValid(Request<T> request, boolean validateSuperclass); static void infixPotentialDefaults(Request<T> request); static void infixPotentialDefaults(Request<T> request, Class<?> targetClazz, boolean infixPotentialValuesOfSuperClass); static String resolveResourcePath(Request<T> request); }### Answer:
@Test public void testIsValid(){ CreateDeploymentRequest createDeploymentRequest = new CreateDeploymentRequest(); Assert.assertFalse(RequestUtil.isValid(createDeploymentRequest)); createDeploymentRequest.setApplicationName("myApplication"); createDeploymentRequest.setDeploymentName("myDeployment"); Assert.assertFalse(RequestUtil.isValid(createDeploymentRequest)); CreateApplicationRequest createApplicationRequest = new CreateApplicationRequest(); Assert.assertFalse(RequestUtil.isValid(createApplicationRequest)); createApplicationRequest.setApplicationName("myApplication"); Assert.assertFalse(RequestUtil.isValid(createApplicationRequest)); createApplicationRequest.setLanguage("php"); Assert.assertFalse(RequestUtil.isValid(createApplicationRequest)); createApplicationRequest.setApiKey("kiasudzadh"); createApplicationRequest.setHash("asjdhaksjdhkdd"); Assert.assertTrue(RequestUtil.isValid(createApplicationRequest)); } |
### Question:
RequestUtil { public static <T> void infixPotentialDefaults(Request<T> request){ infixPotentialDefaults(request, request.getClass(), true); } static boolean isValid(Request<T> request); static boolean isValid(Request<T> request, boolean validateSuperclass); static void infixPotentialDefaults(Request<T> request); static void infixPotentialDefaults(Request<T> request, Class<?> targetClazz, boolean infixPotentialValuesOfSuperClass); static String resolveResourcePath(Request<T> request); }### Answer:
@Test public void testInfixPotentialDefault(){ CreateDeploymentRequest createDeploymentRequest = new CreateDeploymentRequest(); RequestUtil.infixPotentialDefaults(createDeploymentRequest); Assert.assertEquals("default", createDeploymentRequest.getDeploymentName()); createDeploymentRequest.setDeploymentName("anothervalue"); RequestUtil.infixPotentialDefaults(createDeploymentRequest); Assert.assertEquals("anothervalue", createDeploymentRequest.getDeploymentName()); } |
### Question:
EncryptionUtil { public static Credentials generateCredentials() throws NoSuchAlgorithmException { CustomerCredentials toUse = new CustomerCredentials(); toUse.setApiKey(convertToHex(randomSeed())); toUse.setSecretKey(convertToHex(randomSeed())); return toUse; } static Request<T> encipher(Request<T> request, Credentials credentials); static Credentials generateCredentials(); static String toSHA1(String unencrypted); static final String CIPHER; static final int SEEDSIZE; }### Answer:
@Test public void testGenerateCredentials() throws NoSuchAlgorithmException{ Credentials credentials = EncryptionUtil.generateCredentials(); Assert.assertNotNull(credentials); Assert.assertNotNull(credentials.getApiKey()); Assert.assertNotNull(credentials.getSecretKey()); Assert.assertFalse(credentials.getApiKey().isEmpty()); Assert.assertFalse(credentials.getSecretKey().isEmpty()); System.out.println(credentials.getApiKey()); System.out.println(credentials.getSecretKey()); } |
### Question:
MonitoringModule implements eu.cloud4soa.api.governance.MonitoringModule { @Override public void startMonitoring(String applicationUriId) { throw new UnsupportedOperationException("Not supported yet."); } void startMonitoringJob(ApplicationInstance applicationInstance); void stopMonitoring(String applicationUriId); IMonitoringJob getMonitoringJob(String applicationUriId); @SuppressWarnings("unchecked") List<IMonitoringStatistic> getMonitoringStatistics(String applicationUriId); @SuppressWarnings("unchecked") List<IMonitoringStatistic> getMonitoringStatisticsWhithinRange(String applicationUriId, Date start, Date end); @SuppressWarnings("unchecked") List<IMonitoringStatistic> getMonitoringStatisticsWhithinRangeLimited(String applicationUriId, Date start, Date end, int maxResults); List<IMonitoringMetric> getMonitoringMetricsWhithinRangeLimited(String applicationUriId, String metricKey, Date start, Date end, int maxResults); @Override void startMonitoring(String applicationUriId); }### Answer:
@Test public void testStartMonitoring() { String uriId=applicationInstance.getUriId(); Assert.assertNotNull(uriId); Assert.assertNotNull(monitoringModule); monitoringModule.startMonitoring(uriId); Assert.assertTrue(monitoringModule.getMonitoringStatistics(applicationInstance.getUriId()).size() > 0); } |
### Question:
AnnouncementModule implements eu.cloud4soa.api.soa.AnnouncementModule { @Override public void updatePaaSInstance(PaaSInstance paaSInstance) throws SOAException { logger.debug("received paaSInstance: "+paaSInstance); logger.debug("paaSOfferingProfilesRepository.updatePaaSInstance(paaSInstance, null);"); try { paaSOfferingProfilesRepository.updatePaaSInstance(paaSInstance, null); } catch (RepositoryException ex) { throw new SOAException(Response.Status.INTERNAL_SERVER_ERROR, ex.getMessage()); } logger.debug("paaSInstance: "+ paaSInstance +" updated"); } @Required void setRepositoryManager(RepositoryManager repositoryManager); @Required void setPaaSOfferingProfilesRepository(PaaSOfferingProfilesRepository paaSOfferingProfilesRepository); @Required void setUserProfilesRepository(UserProfilesRepository userProfilesRepository); @Override PaaSInstance getPaaSInstance(String paaSInstanceUriId); @Override String storePaaSInstance(PaaSInstance paaSInstance, String userInstanceUriId); @Override Response storeTurtlePaaSProfile(String paasProfile, String userInstanceUriId); @Override List<PaaSInstance> retrieveAllPaaSInstances(String userInstanceUriId); @Override void updatePaaSInstance(PaaSInstance paaSInstance); @Override void removePaaSInstance(String paasInstanceUriId); }### Answer:
@Ignore @Test public void TestUpdatePaaSInstance() { paaSInstance.setSupportedProgrammingLanguage("Python"); try { announcementModule.updatePaaSInstance(paaSInstance); } catch (SOAException ex) { Assert.fail("updatePaaSInstance method has thrown an exception!"); } } |
### Question:
AnnouncementModule implements eu.cloud4soa.api.soa.AnnouncementModule { @Override public List<PaaSInstance> retrieveAllPaaSInstances(String userInstanceUriId) throws SOAException { logger.debug("received userInstanceUriId: "+userInstanceUriId); logger.debug("paaSOfferingProfilesRepository.getAllAvailablePaaSInstances()"); List<PaaSInstance> retrievedPaaSInstances; try { retrievedPaaSInstances = paaSOfferingProfilesRepository.retrieveAllPaaSInstances(userInstanceUriId); } catch (RepositoryException ex) { throw new SOAException(Response.Status.INTERNAL_SERVER_ERROR, ex.getMessage()); } logger.debug("retrieved List<PaaSInstance>: "+retrievedPaaSInstances); return retrievedPaaSInstances; } @Required void setRepositoryManager(RepositoryManager repositoryManager); @Required void setPaaSOfferingProfilesRepository(PaaSOfferingProfilesRepository paaSOfferingProfilesRepository); @Required void setUserProfilesRepository(UserProfilesRepository userProfilesRepository); @Override PaaSInstance getPaaSInstance(String paaSInstanceUriId); @Override String storePaaSInstance(PaaSInstance paaSInstance, String userInstanceUriId); @Override Response storeTurtlePaaSProfile(String paasProfile, String userInstanceUriId); @Override List<PaaSInstance> retrieveAllPaaSInstances(String userInstanceUriId); @Override void updatePaaSInstance(PaaSInstance paaSInstance); @Override void removePaaSInstance(String paasInstanceUriId); }### Answer:
@Ignore @Test public void TestRetrieveAllApplicationProfiles() { List<PaaSInstance> applications = null; try { applications = announcementModule.retrieveAllPaaSInstances(userInstance.getUriId()); } catch (SOAException ex) { Assert.fail("retrieveAllPaaSInstances method has thrown an exception!"); } Assert.assertTrue(!applications.isEmpty()); } |
### Question:
Util { static String stripLeadingHyphens(String str) { if (str == null) { return null; } if (str.startsWith("--")) { return str.substring(2, str.length()); } else if (str.startsWith("-")) { return str.substring(1, str.length()); } return str; } }### Answer:
@Test public void testStripLeadingHyphens() { assertEquals("f", Util.stripLeadingHyphens("-f")); assertEquals("foo", Util.stripLeadingHyphens("--foo")); assertEquals("-foo", Util.stripLeadingHyphens("---foo")); assertNull(Util.stripLeadingHyphens(null)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.