target stringlengths 20 113k | src_fm stringlengths 11 86.3k | src_fm_fc stringlengths 21 86.4k | src_fm_fc_co stringlengths 30 86.4k | src_fm_fc_ms stringlengths 42 86.8k | src_fm_fc_ms_ff stringlengths 43 86.8k |
|---|---|---|---|---|---|
@Test public void testCrc32() { long h = Crc32Util.getCrc32(String.valueOf("256")); ApiLogger.debug("Crc32UtilTest testCrc32 h:" + h); } | public static long getCrc32(byte[] b) { CRC32 crc = crc32Provider.get(); crc.reset(); crc.update(b); return crc.getValue(); } | Crc32Util { public static long getCrc32(byte[] b) { CRC32 crc = crc32Provider.get(); crc.reset(); crc.update(b); return crc.getValue(); } } | Crc32Util { public static long getCrc32(byte[] b) { CRC32 crc = crc32Provider.get(); crc.reset(); crc.update(b); return crc.getValue(); } } | Crc32Util { public static long getCrc32(byte[] b) { CRC32 crc = crc32Provider.get(); crc.reset(); crc.update(b); return crc.getValue(); } static long getCrc32(byte[] b); static long getCrc32(String str); static void main(String[] args); } | Crc32Util { public static long getCrc32(byte[] b) { CRC32 crc = crc32Provider.get(); crc.reset(); crc.update(b); return crc.getValue(); } static long getCrc32(byte[] b); static long getCrc32(String str); static void main(String[] args); } |
@Test public void testToRawIntArr(){ String[] inputArray1 = { "2", "2", "4", "6", "8", "15" }; int[] result = ArrayUtil.toRawIntArr(inputArray1); Assert.assertArrayEquals(new int[] { 2, 2, 4, 6, 8, 15 }, result); } | public static int[] toRawIntArr(String strArr[]) { int[] intArr = new int[strArr.length]; for (int i = 0; i < strArr.length; i++) { intArr[i] = Integer.parseInt(strArr[i]); } return intArr; } | ArrayUtil { public static int[] toRawIntArr(String strArr[]) { int[] intArr = new int[strArr.length]; for (int i = 0; i < strArr.length; i++) { intArr[i] = Integer.parseInt(strArr[i]); } return intArr; } } | ArrayUtil { public static int[] toRawIntArr(String strArr[]) { int[] intArr = new int[strArr.length]; for (int i = 0; i < strArr.length; i++) { intArr[i] = Integer.parseInt(strArr[i]); } return intArr; } private ArrayUtil(); } | ArrayUtil { public static int[] toRawIntArr(String strArr[]) { int[] intArr = new int[strArr.length]; for (int i = 0; i < strArr.length; i++) { intArr[i] = Integer.parseInt(strArr[i]); } return intArr; } private ArrayUtil(); static Long[] toLongArr(String[] strArr); static Long[] toLongArr(long[] longArr); static long... | ArrayUtil { public static int[] toRawIntArr(String strArr[]) { int[] intArr = new int[strArr.length]; for (int i = 0; i < strArr.length; i++) { intArr[i] = Integer.parseInt(strArr[i]); } return intArr; } private ArrayUtil(); static Long[] toLongArr(String[] strArr); static Long[] toLongArr(long[] longArr); static long... |
@Test public void testReverseCopy(){ long[] inputArray1 = { 2, 2, 4, 6, 8, 15 }; long[] result = ArrayUtil.reverseCopy(inputArray1, inputArray1.length); Assert.assertArrayEquals(new long[] { 15, 8, 6, 4, 2, 2 }, result); } | public static long[] reverseCopy(long[] original, int newLength) { long[] result = new long[newLength]; int originalLimit = original.length - newLength; for (int i = original.length - 1, resultIdx = 0; i >= originalLimit; i--) { result[resultIdx++] = original[i]; } return result; } | ArrayUtil { public static long[] reverseCopy(long[] original, int newLength) { long[] result = new long[newLength]; int originalLimit = original.length - newLength; for (int i = original.length - 1, resultIdx = 0; i >= originalLimit; i--) { result[resultIdx++] = original[i]; } return result; } } | ArrayUtil { public static long[] reverseCopy(long[] original, int newLength) { long[] result = new long[newLength]; int originalLimit = original.length - newLength; for (int i = original.length - 1, resultIdx = 0; i >= originalLimit; i--) { result[resultIdx++] = original[i]; } return result; } private ArrayUtil(); } | ArrayUtil { public static long[] reverseCopy(long[] original, int newLength) { long[] result = new long[newLength]; int originalLimit = original.length - newLength; for (int i = original.length - 1, resultIdx = 0; i >= originalLimit; i--) { result[resultIdx++] = original[i]; } return result; } private ArrayUtil(); sta... | ArrayUtil { public static long[] reverseCopy(long[] original, int newLength) { long[] result = new long[newLength]; int originalLimit = original.length - newLength; for (int i = original.length - 1, resultIdx = 0; i >= originalLimit; i--) { result[resultIdx++] = original[i]; } return result; } private ArrayUtil(); sta... |
@Test public void testSort() { long[] inputArray1 = { 2, 2, 4, 6, 8, 15 }; long[] inputArray2 = { 0, 0, 1, 3, 7, 9, 10, 11 }; long[] result = ArrayUtil.sort(inputArray1, inputArray2); Assert.assertArrayEquals(new long[] {0, 0, 1, 2, 2, 3, 4, 6, 7, 8, 9, 10, 11, 15}, result); result = ArrayUtil.sort(inputArray1, new lon... | public static long[] sort(long left[], long right[]) { long[] result = addTo(left, right); Arrays.sort(result); return result; } | ArrayUtil { public static long[] sort(long left[], long right[]) { long[] result = addTo(left, right); Arrays.sort(result); return result; } } | ArrayUtil { public static long[] sort(long left[], long right[]) { long[] result = addTo(left, right); Arrays.sort(result); return result; } private ArrayUtil(); } | ArrayUtil { public static long[] sort(long left[], long right[]) { long[] result = addTo(left, right); Arrays.sort(result); return result; } private ArrayUtil(); static Long[] toLongArr(String[] strArr); static Long[] toLongArr(long[] longArr); static long[] toRawLongArr(String[] strArr); static int[] toRawIntArr(Stri... | ArrayUtil { public static long[] sort(long left[], long right[]) { long[] result = addTo(left, right); Arrays.sort(result); return result; } private ArrayUtil(); static Long[] toLongArr(String[] strArr); static Long[] toLongArr(long[] longArr); static long[] toRawLongArr(String[] strArr); static int[] toRawIntArr(Stri... |
@Test public void testSortDesc() { long[] inputArray1 = { 2, 2, 4, 6, 8, 15 }; ArrayUtil.sortDesc(inputArray1); System.out.println(Arrays.toString(inputArray1)); Assert.assertArrayEquals(new long[] { 15, 8, 6, 4, 2, 2 }, inputArray1); } | public static void sortDesc(long[] a) { Arrays.sort(a); reverse(a); } | ArrayUtil { public static void sortDesc(long[] a) { Arrays.sort(a); reverse(a); } } | ArrayUtil { public static void sortDesc(long[] a) { Arrays.sort(a); reverse(a); } private ArrayUtil(); } | ArrayUtil { public static void sortDesc(long[] a) { Arrays.sort(a); reverse(a); } private ArrayUtil(); static Long[] toLongArr(String[] strArr); static Long[] toLongArr(long[] longArr); static long[] toRawLongArr(String[] strArr); static int[] toRawIntArr(String strArr[]); static long[] toLongArr(Collection<Long> ids)... | ArrayUtil { public static void sortDesc(long[] a) { Arrays.sort(a); reverse(a); } private ArrayUtil(); static Long[] toLongArr(String[] strArr); static Long[] toLongArr(long[] longArr); static long[] toRawLongArr(String[] strArr); static int[] toRawIntArr(String strArr[]); static long[] toLongArr(Collection<Long> ids)... |
@Test public void testAddToArrays(){ long[] array1 = { 2, 2, 4, 6, 8, 15 }; long id = 345; long[] result = ArrayUtil.addTo(array1, id); Assert.assertArrayEquals(new long[] { 2, 2, 4, 6, 8, 15, 345 }, result); } | public static long[] addTo(long[] left, long[] right){ if (left == null) { return ArrayUtils.clone(right); } else if (right == null) { return ArrayUtils.clone(left); } long[] result = new long[left.length + right.length]; int pos = 0; System.arraycopy(left, 0, result, pos, left.length); pos += left.length; System.array... | ArrayUtil { public static long[] addTo(long[] left, long[] right){ if (left == null) { return ArrayUtils.clone(right); } else if (right == null) { return ArrayUtils.clone(left); } long[] result = new long[left.length + right.length]; int pos = 0; System.arraycopy(left, 0, result, pos, left.length); pos += left.length; ... | ArrayUtil { public static long[] addTo(long[] left, long[] right){ if (left == null) { return ArrayUtils.clone(right); } else if (right == null) { return ArrayUtils.clone(left); } long[] result = new long[left.length + right.length]; int pos = 0; System.arraycopy(left, 0, result, pos, left.length); pos += left.length; ... | ArrayUtil { public static long[] addTo(long[] left, long[] right){ if (left == null) { return ArrayUtils.clone(right); } else if (right == null) { return ArrayUtils.clone(left); } long[] result = new long[left.length + right.length]; int pos = 0; System.arraycopy(left, 0, result, pos, left.length); pos += left.length; ... | ArrayUtil { public static long[] addTo(long[] left, long[] right){ if (left == null) { return ArrayUtils.clone(right); } else if (right == null) { return ArrayUtils.clone(left); } long[] result = new long[left.length + right.length]; int pos = 0; System.arraycopy(left, 0, result, pos, left.length); pos += left.length; ... |
@Test public void testAddToLimit() { long[] array1 = { 2, 2, 4, 6, 8, 15, 17 }; long id = 345; int limit = 10; long[] result = ArrayUtil.addTo(array1, id, limit); Assert.assertArrayEquals(new long[] { 2, 2, 4, 6, 8, 15, 17, 345 }, result); result = ArrayUtil.addTo(result, 4, limit); Assert.assertArrayEquals(new long[] ... | public static long[] addTo(long[] left, long[] right){ if (left == null) { return ArrayUtils.clone(right); } else if (right == null) { return ArrayUtils.clone(left); } long[] result = new long[left.length + right.length]; int pos = 0; System.arraycopy(left, 0, result, pos, left.length); pos += left.length; System.array... | ArrayUtil { public static long[] addTo(long[] left, long[] right){ if (left == null) { return ArrayUtils.clone(right); } else if (right == null) { return ArrayUtils.clone(left); } long[] result = new long[left.length + right.length]; int pos = 0; System.arraycopy(left, 0, result, pos, left.length); pos += left.length; ... | ArrayUtil { public static long[] addTo(long[] left, long[] right){ if (left == null) { return ArrayUtils.clone(right); } else if (right == null) { return ArrayUtils.clone(left); } long[] result = new long[left.length + right.length]; int pos = 0; System.arraycopy(left, 0, result, pos, left.length); pos += left.length; ... | ArrayUtil { public static long[] addTo(long[] left, long[] right){ if (left == null) { return ArrayUtils.clone(right); } else if (right == null) { return ArrayUtils.clone(left); } long[] result = new long[left.length + right.length]; int pos = 0; System.arraycopy(left, 0, result, pos, left.length); pos += left.length; ... | ArrayUtil { public static long[] addTo(long[] left, long[] right){ if (left == null) { return ArrayUtils.clone(right); } else if (right == null) { return ArrayUtils.clone(left); } long[] result = new long[left.length + right.length]; int pos = 0; System.arraycopy(left, 0, result, pos, left.length); pos += left.length; ... |
@Test public void testGetLimited(){ long[] array1 = { 1, 2, 4, 6, 8, 15, 17 }; long[] array2 = { 1, 2, 4, 6, 8, 15, 17, 18, 19, 20, 21}; long[] array3 = null; long[] array4 = {}; int limit = 10; long[] result = ArrayUtil.getLimited(array1, limit); Assert.assertArrayEquals(new long[] { 1, 2, 4, 6, 8, 15, 17}, result); r... | public static long[] getLimited(long[] arr, int limit) { if (arr == null) { return arr; } if (arr.length > limit) { long[] result = new long[limit]; System.arraycopy(arr, arr.length - limit, result, 0, limit); return result; } else { return arr; } } | ArrayUtil { public static long[] getLimited(long[] arr, int limit) { if (arr == null) { return arr; } if (arr.length > limit) { long[] result = new long[limit]; System.arraycopy(arr, arr.length - limit, result, 0, limit); return result; } else { return arr; } } } | ArrayUtil { public static long[] getLimited(long[] arr, int limit) { if (arr == null) { return arr; } if (arr.length > limit) { long[] result = new long[limit]; System.arraycopy(arr, arr.length - limit, result, 0, limit); return result; } else { return arr; } } private ArrayUtil(); } | ArrayUtil { public static long[] getLimited(long[] arr, int limit) { if (arr == null) { return arr; } if (arr.length > limit) { long[] result = new long[limit]; System.arraycopy(arr, arr.length - limit, result, 0, limit); return result; } else { return arr; } } private ArrayUtil(); static Long[] toLongArr(String[] str... | ArrayUtil { public static long[] getLimited(long[] arr, int limit) { if (arr == null) { return arr; } if (arr.length > limit) { long[] result = new long[limit]; System.arraycopy(arr, arr.length - limit, result, 0, limit); return result; } else { return arr; } } private ArrayUtil(); static Long[] toLongArr(String[] str... |
@Test public void testRemoveAll() { long[] sources = { 5, 9, 2, 8, 11, 7, 18, 10, 12, 3 }; long[] removes = { 5, 3 }; long[] results = ArrayUtil.removeAll(sources, removes); Assert.assertEquals(results.length, sources.length - removes.length); removes = new long[]{ 5, 3, 11, 10 }; results = ArrayUtil.removeAll(sources,... | public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> removeSet = new Ha... | ArrayUtil { public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> remove... | ArrayUtil { public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> remove... | ArrayUtil { public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> remove... | ArrayUtil { public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> remove... |
@Test public void testDelete() { String key = MemCacheUtil.toKey("123", "module.c"); MemCacheTemplate<String> memCacheTemplate = getMemCacheTemplate(); if (memCacheTemplate.set(key, "dsadsadsadsadas")) { String value = memCacheTemplate.get(key); Assert.assertEquals("dsadsadsadsadas", value); memCacheTemplate.delete(key... | @Override public boolean delete(String key) { boolean rs = delete(key, master); if (rs == false) { return rs; } if(slave != null){ delete(key, slave); } delete(key, masterL1List); delete(key, slaveL1List); return rs; } | MemCacheTemplate implements CacheAble<T> { @Override public boolean delete(String key) { boolean rs = delete(key, master); if (rs == false) { return rs; } if(slave != null){ delete(key, slave); } delete(key, masterL1List); delete(key, slaveL1List); return rs; } } | MemCacheTemplate implements CacheAble<T> { @Override public boolean delete(String key) { boolean rs = delete(key, master); if (rs == false) { return rs; } if(slave != null){ delete(key, slave); } delete(key, masterL1List); delete(key, slaveL1List); return rs; } } | MemCacheTemplate implements CacheAble<T> { @Override public boolean delete(String key) { boolean rs = delete(key, master); if (rs == false) { return rs; } if(slave != null){ delete(key, slave); } delete(key, masterL1List); delete(key, slaveL1List); return rs; } @Override T get(String key); @Override Map<String, T> get... | MemCacheTemplate implements CacheAble<T> { @Override public boolean delete(String key) { boolean rs = delete(key, master); if (rs == false) { return rs; } if(slave != null){ delete(key, slave); } delete(key, masterL1List); delete(key, slaveL1List); return rs; } @Override T get(String key); @Override Map<String, T> get... |
@Test public void testRemoveAllFor() { long init = 3000000000000000L; long[] sources = new long[10]; for (int i = 0; i < sources.length; i++) { sources[i] = init + i; } for (int i = 0; i < 10; i++) { HashSet<Long> removeSet = new HashSet<Long>(); for (int j = 0; j < i; j++) { removeSet.add(init + RandomUtils.nextInt(i)... | public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> removeSet = new Ha... | ArrayUtil { public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> remove... | ArrayUtil { public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> remove... | ArrayUtil { public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> remove... | ArrayUtil { public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> remove... |
@Test public void testRemoveAllSet() { long[] sources = { 5, 9, 2, 8, 11, 7, 18, 10, 12, 3 }; long[] removes = { 5, 3 }; Set<Long> removeSet = new HashSet<Long>(removes.length); for (long remove : removes) { removeSet.add(remove); } long[] results = ArrayUtil.removeAll(sources, removes); Assert.assertEquals(results.len... | public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> removeSet = new Ha... | ArrayUtil { public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> remove... | ArrayUtil { public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> remove... | ArrayUtil { public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> remove... | ArrayUtil { public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> remove... |
@Test public void testRemoveAllSetFor() { long init = 3000000000000000L; long[] sources = new long[10]; for (int i = 0; i < sources.length; i++) { sources[i] = init + i; } for (int i = 0; i < 10; i++) { HashSet<Long> removeSet = new HashSet<Long>(); for (int j = 0; j < i; j++) { removeSet.add(init + RandomUtils.nextInt... | public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> removeSet = new Ha... | ArrayUtil { public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> remove... | ArrayUtil { public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> remove... | ArrayUtil { public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> remove... | ArrayUtil { public static long[] removeAll(long[] sourceArray, long[] removeArray) { int sourceLength = sourceArray.length; int removeLength = removeArray.length; if (sourceLength == 0 || removeLength == 0) { return sourceArray; } long[] temp = new long[sourceLength]; int i = 0; if (removeLength > 2) { Set<Long> remove... |
@Test public void testConvertInt() { assertEquals(0, Util.convertInt("")); assertEquals(0, Util.convertInt("-")); assertEquals(12443, Util.convertInt("12443")); assertEquals(-12443, Util.convertInt("-12443")); assertEquals(Integer.MAX_VALUE, Util.convertInt(String.valueOf(Integer.MAX_VALUE))); assertEquals(Integer.MIN_... | public static int convertInt(Object obj) { return convertInt(obj, 0); } | Util { public static int convertInt(Object obj) { return convertInt(obj, 0); } } | Util { public static int convertInt(Object obj) { return convertInt(obj, 0); } } | Util { public static int convertInt(Object obj) { return convertInt(obj, 0); } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object obj,... | Util { public static int convertInt(Object obj) { return convertInt(obj, 0); } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object obj,... |
@Test public void testConvertLong() { assertEquals(0L, Util.convertLong("")); assertEquals(0L, Util.convertLong("-")); assertEquals(12443, Util.convertLong("12443")); assertEquals(-12443, Util.convertLong("-12443")); assertEquals(Long.MAX_VALUE, Util.convertLong(String.valueOf(Long.MAX_VALUE))); assertEquals(Long.MIN_V... | public static long convertLong(String src) { return convertLong(src, 0); } | Util { public static long convertLong(String src) { return convertLong(src, 0); } } | Util { public static long convertLong(String src) { return convertLong(src, 0); } } | Util { public static long convertLong(String src) { return convertLong(src, 0); } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object o... | Util { public static long convertLong(String src) { return convertLong(src, 0); } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object o... |
@Test public void testParseLong() { assertEquals(12443l,Util.convertLong("12443")); } | public static long convertLong(String src) { return convertLong(src, 0); } | Util { public static long convertLong(String src) { return convertLong(src, 0); } } | Util { public static long convertLong(String src) { return convertLong(src, 0); } } | Util { public static long convertLong(String src) { return convertLong(src, 0); } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object o... | Util { public static long convertLong(String src) { return convertLong(src, 0); } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object o... |
@Test public void testUrlEncoder() { assertEquals("%2C",Util.urlEncoder(",", "UTF-8")); } | public static String urlEncoder(String s, String charcoding) { if (s == null) return null; try { return URLEncoder.encode(s, charcoding); } catch (Exception e) { } return null; } | Util { public static String urlEncoder(String s, String charcoding) { if (s == null) return null; try { return URLEncoder.encode(s, charcoding); } catch (Exception e) { } return null; } } | Util { public static String urlEncoder(String s, String charcoding) { if (s == null) return null; try { return URLEncoder.encode(s, charcoding); } catch (Exception e) { } return null; } } | Util { public static String urlEncoder(String s, String charcoding) { if (s == null) return null; try { return URLEncoder.encode(s, charcoding); } catch (Exception e) { } return null; } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDo... | Util { public static String urlEncoder(String s, String charcoding) { if (s == null) return null; try { return URLEncoder.encode(s, charcoding); } catch (Exception e) { } return null; } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDo... |
@Test public void testUrlDecoder() { assertEquals(",",Util.urlDecoder("%2C", "UTF-8")); } | public static String urlDecoder(String s, String charcoding) { if (s == null) return null; try { return URLDecoder.decode(s, charcoding); } catch (Exception e) { } return null; } | Util { public static String urlDecoder(String s, String charcoding) { if (s == null) return null; try { return URLDecoder.decode(s, charcoding); } catch (Exception e) { } return null; } } | Util { public static String urlDecoder(String s, String charcoding) { if (s == null) return null; try { return URLDecoder.decode(s, charcoding); } catch (Exception e) { } return null; } } | Util { public static String urlDecoder(String s, String charcoding) { if (s == null) return null; try { return URLDecoder.decode(s, charcoding); } catch (Exception e) { } return null; } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDo... | Util { public static String urlDecoder(String s, String charcoding) { if (s == null) return null; try { return URLDecoder.decode(s, charcoding); } catch (Exception e) { } return null; } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDo... |
@Test public void testHtmlEscapeOnce() { String src = "&<span class=\"java\"/>"; String target = Util.htmlEscapeOnce(src); assertEquals("&amp;<span class="java"/>", target); } | public static String htmlEscapeOnce(String s) { if (StringUtils.isBlank(s)){ return s; } s = s.replaceAll("&", "&"); s = s.replaceAll("<", "<"); s = s.replaceAll(">", ">"); s = s.replaceAll("\"", """); return s; } | Util { public static String htmlEscapeOnce(String s) { if (StringUtils.isBlank(s)){ return s; } s = s.replaceAll("&", "&"); s = s.replaceAll("<", "<"); s = s.replaceAll(">", ">"); s = s.replaceAll("\"", """); return s; } } | Util { public static String htmlEscapeOnce(String s) { if (StringUtils.isBlank(s)){ return s; } s = s.replaceAll("&", "&"); s = s.replaceAll("<", "<"); s = s.replaceAll(">", ">"); s = s.replaceAll("\"", """); return s; } } | Util { public static String htmlEscapeOnce(String s) { if (StringUtils.isBlank(s)){ return s; } s = s.replaceAll("&", "&"); s = s.replaceAll("<", "<"); s = s.replaceAll(">", ">"); s = s.replaceAll("\"", """); return s; } static String toStr(byte[] data); static byte[] toBytes(String str); static double ... | Util { public static String htmlEscapeOnce(String s) { if (StringUtils.isBlank(s)){ return s; } s = s.replaceAll("&", "&"); s = s.replaceAll("<", "<"); s = s.replaceAll(">", ">"); s = s.replaceAll("\"", """); return s; } static String toStr(byte[] data); static byte[] toBytes(String str); static double ... |
@Test public void testHtmlUnEscapeOnce() { String src = "&amp;<span class="java"/>"; String target = Util.htmlUnEscapeOnce(src); assertEquals("&<span class=\"java\"/>", target); } | public static String htmlUnEscapeOnce(String s) { if (StringUtils.isBlank(s)){ return s; } s = s.replaceAll("&", "&"); s = s.replaceAll("<", "<"); s = s.replaceAll(">", ">"); s = s.replaceAll(""", "\""); return s; } | Util { public static String htmlUnEscapeOnce(String s) { if (StringUtils.isBlank(s)){ return s; } s = s.replaceAll("&", "&"); s = s.replaceAll("<", "<"); s = s.replaceAll(">", ">"); s = s.replaceAll(""", "\""); return s; } } | Util { public static String htmlUnEscapeOnce(String s) { if (StringUtils.isBlank(s)){ return s; } s = s.replaceAll("&", "&"); s = s.replaceAll("<", "<"); s = s.replaceAll(">", ">"); s = s.replaceAll(""", "\""); return s; } } | Util { public static String htmlUnEscapeOnce(String s) { if (StringUtils.isBlank(s)){ return s; } s = s.replaceAll("&", "&"); s = s.replaceAll("<", "<"); s = s.replaceAll(">", ">"); s = s.replaceAll(""", "\""); return s; } static String toStr(byte[] data); static byte[] toBytes(String str); static doubl... | Util { public static String htmlUnEscapeOnce(String s) { if (StringUtils.isBlank(s)){ return s; } s = s.replaceAll("&", "&"); s = s.replaceAll("<", "<"); s = s.replaceAll(">", ">"); s = s.replaceAll(""", "\""); return s; } static String toStr(byte[] data); static byte[] toBytes(String str); static doubl... |
@Test public void testCas() { String key = MemCacheUtil.toKey("123", "module.c"); MemCacheTemplate<String> memCacheTemplate = getMemCacheTemplate(); if (memCacheTemplate.set(key, "dsadsadsadsadas")) { CasValue<String> valueCas = memCacheTemplate.getCas(key); String value = (String) valueCas.getValue() + 0; valueCas.set... | @Override public boolean cas(String key, CasValue<T> casValue) { boolean result = cas(key, casValue, expireTime); if (result == false) { ApiLogger.warn("MemCacheTemplate cas key:" + key + ", result:" + result); } return result; } | MemCacheTemplate implements CacheAble<T> { @Override public boolean cas(String key, CasValue<T> casValue) { boolean result = cas(key, casValue, expireTime); if (result == false) { ApiLogger.warn("MemCacheTemplate cas key:" + key + ", result:" + result); } return result; } } | MemCacheTemplate implements CacheAble<T> { @Override public boolean cas(String key, CasValue<T> casValue) { boolean result = cas(key, casValue, expireTime); if (result == false) { ApiLogger.warn("MemCacheTemplate cas key:" + key + ", result:" + result); } return result; } } | MemCacheTemplate implements CacheAble<T> { @Override public boolean cas(String key, CasValue<T> casValue) { boolean result = cas(key, casValue, expireTime); if (result == false) { ApiLogger.warn("MemCacheTemplate cas key:" + key + ", result:" + result); } return result; } @Override T get(String key); @Override Map<Str... | MemCacheTemplate implements CacheAble<T> { @Override public boolean cas(String key, CasValue<T> casValue) { boolean result = cas(key, casValue, expireTime); if (result == false) { ApiLogger.warn("MemCacheTemplate cas key:" + key + ", result:" + result); } return result; } @Override T get(String key); @Override Map<Str... |
@Test public void testIsIp(){ org.junit.Assert.assertTrue(IpUtil.isIp("127.0.0.1")); org.junit.Assert.assertTrue(IpUtil.isIp("10.75.0.60")); org.junit.Assert.assertTrue(IpUtil.isIp("192.168.1.1")); org.junit.Assert.assertTrue(IpUtil.isIp("175.41.9.194")); } | public static boolean isIp(String in){ if(in==null){ return false; } return ipPattern.matcher(in).matches(); } | IpUtil { public static boolean isIp(String in){ if(in==null){ return false; } return ipPattern.matcher(in).matches(); } } | IpUtil { public static boolean isIp(String in){ if(in==null){ return false; } return ipPattern.matcher(in).matches(); } } | IpUtil { public static boolean isIp(String in){ if(in==null){ return false; } return ipPattern.matcher(in).matches(); } static String intToIp(int i); static int ipToInt(final String addr); static long ipToLong(final String addr); static String longToIp(long i); static boolean isIp(String in); static Map<String,String>... | IpUtil { public static boolean isIp(String in){ if(in==null){ return false; } return ipPattern.matcher(in).matches(); } static String intToIp(int i); static int ipToInt(final String addr); static long ipToLong(final String addr); static String longToIp(long i); static boolean isIp(String in); static Map<String,String>... |
@Test public void testIsIpFalse(){ org.junit.Assert.assertFalse(IpUtil.isIp("aaa")); org.junit.Assert.assertFalse(IpUtil.isIp("1000.75.0.60")); org.junit.Assert.assertFalse(IpUtil.isIp("192.168.1")); org.junit.Assert.assertFalse(IpUtil.isIp("175.41.9.a")); } | public static boolean isIp(String in){ if(in==null){ return false; } return ipPattern.matcher(in).matches(); } | IpUtil { public static boolean isIp(String in){ if(in==null){ return false; } return ipPattern.matcher(in).matches(); } } | IpUtil { public static boolean isIp(String in){ if(in==null){ return false; } return ipPattern.matcher(in).matches(); } } | IpUtil { public static boolean isIp(String in){ if(in==null){ return false; } return ipPattern.matcher(in).matches(); } static String intToIp(int i); static int ipToInt(final String addr); static long ipToLong(final String addr); static String longToIp(long i); static boolean isIp(String in); static Map<String,String>... | IpUtil { public static boolean isIp(String in){ if(in==null){ return false; } return ipPattern.matcher(in).matches(); } static String intToIp(int i); static int ipToInt(final String addr); static long ipToLong(final String addr); static String longToIp(long i); static boolean isIp(String in); static Map<String,String>... |
@Test public void testIPToInt(){ org.junit.Assert.assertEquals(2130706433,IpUtil.ipToInt("127.0.0.1")); org.junit.Assert.assertEquals(172687420,IpUtil.ipToInt("10.75.0.60")); org.junit.Assert.assertEquals(-1062731519,IpUtil.ipToInt("192.168.1.1")); org.junit.Assert.assertEquals(-1356265022,IpUtil.ipToInt("175.41.9.194"... | public static int ipToInt(final String addr) { final String[] addressBytes = addr.split("\\."); int ip = 0; for (int i = 0; i < 4; i++) { ip <<= 8; ip |= Integer.parseInt(addressBytes[i]); } return ip; } | IpUtil { public static int ipToInt(final String addr) { final String[] addressBytes = addr.split("\\."); int ip = 0; for (int i = 0; i < 4; i++) { ip <<= 8; ip |= Integer.parseInt(addressBytes[i]); } return ip; } } | IpUtil { public static int ipToInt(final String addr) { final String[] addressBytes = addr.split("\\."); int ip = 0; for (int i = 0; i < 4; i++) { ip <<= 8; ip |= Integer.parseInt(addressBytes[i]); } return ip; } } | IpUtil { public static int ipToInt(final String addr) { final String[] addressBytes = addr.split("\\."); int ip = 0; for (int i = 0; i < 4; i++) { ip <<= 8; ip |= Integer.parseInt(addressBytes[i]); } return ip; } static String intToIp(int i); static int ipToInt(final String addr); static long ipToLong(final String add... | IpUtil { public static int ipToInt(final String addr) { final String[] addressBytes = addr.split("\\."); int ip = 0; for (int i = 0; i < 4; i++) { ip <<= 8; ip |= Integer.parseInt(addressBytes[i]); } return ip; } static String intToIp(int i); static int ipToInt(final String addr); static long ipToLong(final String add... |
@Test public void testGetLocalIp(){ String localIp = IpUtil.getLocalIp(); System.out.println(localIp); org.junit.Assert.assertNotNull(localIp); } | public static String getLocalIp() { Map<String,String> ips = getLocalIps(); List<String> faceNames = new ArrayList<String>(ips.keySet()); Collections.sort(faceNames); for(String name:faceNames){ if("lo".equals(name)){ continue; } String ip = ips.get(name); if(!StringUtils.isBlank(ip)){ return ip; } } return "127.0.0.1"... | IpUtil { public static String getLocalIp() { Map<String,String> ips = getLocalIps(); List<String> faceNames = new ArrayList<String>(ips.keySet()); Collections.sort(faceNames); for(String name:faceNames){ if("lo".equals(name)){ continue; } String ip = ips.get(name); if(!StringUtils.isBlank(ip)){ return ip; } } return "1... | IpUtil { public static String getLocalIp() { Map<String,String> ips = getLocalIps(); List<String> faceNames = new ArrayList<String>(ips.keySet()); Collections.sort(faceNames); for(String name:faceNames){ if("lo".equals(name)){ continue; } String ip = ips.get(name); if(!StringUtils.isBlank(ip)){ return ip; } } return "1... | IpUtil { public static String getLocalIp() { Map<String,String> ips = getLocalIps(); List<String> faceNames = new ArrayList<String>(ips.keySet()); Collections.sort(faceNames); for(String name:faceNames){ if("lo".equals(name)){ continue; } String ip = ips.get(name); if(!StringUtils.isBlank(ip)){ return ip; } } return "1... | IpUtil { public static String getLocalIp() { Map<String,String> ips = getLocalIps(); List<String> faceNames = new ArrayList<String>(ips.keySet()); Collections.sort(faceNames); for(String name:faceNames){ if("lo".equals(name)){ continue; } String ip = ips.get(name); if(!StringUtils.isBlank(ip)){ return ip; } } return "1... |
@Test public void testGetRandomPort(){ int port = IpUtil.ramdomAvailablePort(); System.out.println(port); org.junit.Assert.assertTrue(port > 0 && port <65535); } | public static int ramdomAvailablePort(){ int port = 0; do{ port = (int) ((MAX_USER_PORT_NUMBER-MIN_USER_PORT_NUMBER) * Math.random())+MIN_USER_PORT_NUMBER; }while(!availablePort(port)); return port; } | IpUtil { public static int ramdomAvailablePort(){ int port = 0; do{ port = (int) ((MAX_USER_PORT_NUMBER-MIN_USER_PORT_NUMBER) * Math.random())+MIN_USER_PORT_NUMBER; }while(!availablePort(port)); return port; } } | IpUtil { public static int ramdomAvailablePort(){ int port = 0; do{ port = (int) ((MAX_USER_PORT_NUMBER-MIN_USER_PORT_NUMBER) * Math.random())+MIN_USER_PORT_NUMBER; }while(!availablePort(port)); return port; } } | IpUtil { public static int ramdomAvailablePort(){ int port = 0; do{ port = (int) ((MAX_USER_PORT_NUMBER-MIN_USER_PORT_NUMBER) * Math.random())+MIN_USER_PORT_NUMBER; }while(!availablePort(port)); return port; } static String intToIp(int i); static int ipToInt(final String addr); static long ipToLong(final String addr);... | IpUtil { public static int ramdomAvailablePort(){ int port = 0; do{ port = (int) ((MAX_USER_PORT_NUMBER-MIN_USER_PORT_NUMBER) * Math.random())+MIN_USER_PORT_NUMBER; }while(!availablePort(port)); return port; } static String intToIp(int i); static int ipToInt(final String addr); static long ipToLong(final String addr);... |
@Test public void testGetHashCrc32() { int hash = HashUtil.getHash(1821155363, 32, HashAlg.CRC32); Assert.assertEquals(12, hash); hash = HashUtil.getHash(1821155363, 128, HashAlg.CRC32); Assert.assertEquals(51, hash); } | public static int getHash(long id, int splitCount, String hashAlg) { return getHash(id, splitCount, hashAlg, NoneHash.NEW); } | HashUtil { public static int getHash(long id, int splitCount, String hashAlg) { return getHash(id, splitCount, hashAlg, NoneHash.NEW); } } | HashUtil { public static int getHash(long id, int splitCount, String hashAlg) { return getHash(id, splitCount, hashAlg, NoneHash.NEW); } } | HashUtil { public static int getHash(long id, int splitCount, String hashAlg) { return getHash(id, splitCount, hashAlg, NoneHash.NEW); } static int getHash(long id, int splitCount, String hashAlg); static int getHash(long id, int splitCount, String hashAlg, String noneHash); } | HashUtil { public static int getHash(long id, int splitCount, String hashAlg) { return getHash(id, splitCount, hashAlg, NoneHash.NEW); } static int getHash(long id, int splitCount, String hashAlg); static int getHash(long id, int splitCount, String hashAlg, String noneHash); } |
@Test public void testGetHashNone() { int hash = HashUtil.getHash(1821155363, 32, HashAlg.NONE); Assert.assertEquals(1, hash); hash = HashUtil.getHash(1821155363, 128, HashAlg.NONE); Assert.assertEquals(64, hash); } | public static int getHash(long id, int splitCount, String hashAlg) { return getHash(id, splitCount, hashAlg, NoneHash.NEW); } | HashUtil { public static int getHash(long id, int splitCount, String hashAlg) { return getHash(id, splitCount, hashAlg, NoneHash.NEW); } } | HashUtil { public static int getHash(long id, int splitCount, String hashAlg) { return getHash(id, splitCount, hashAlg, NoneHash.NEW); } } | HashUtil { public static int getHash(long id, int splitCount, String hashAlg) { return getHash(id, splitCount, hashAlg, NoneHash.NEW); } static int getHash(long id, int splitCount, String hashAlg); static int getHash(long id, int splitCount, String hashAlg, String noneHash); } | HashUtil { public static int getHash(long id, int splitCount, String hashAlg) { return getHash(id, splitCount, hashAlg, NoneHash.NEW); } static int getHash(long id, int splitCount, String hashAlg); static int getHash(long id, int splitCount, String hashAlg, String noneHash); } |
@Test public void testFormateDateTime() { assertEquals("2011-11-25 13:12:01", DateUtil.formateDateTime(new Date(1322197921282L))); Date currentTime = DateUtil.parseDateTime("2009-01-01 00:00:00", null); System.out.println(currentTime + ", " + (currentTime.getTime() / 1000)); currentTime = DateUtil.parseDateTime("2009-0... | public static String formateDateTime(Date date){ return dateTimeSdf.get().format(date); } | DateUtil { public static String formateDateTime(Date date){ return dateTimeSdf.get().format(date); } } | DateUtil { public static String formateDateTime(Date date){ return dateTimeSdf.get().format(date); } } | DateUtil { public static String formateDateTime(Date date){ return dateTimeSdf.get().format(date); } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime... | DateUtil { public static String formateDateTime(Date date){ return dateTimeSdf.get().format(date); } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime... |
@Test public void testParseDateTime() { System.out.println(new Date(515483463000L)); System.out.println(new Date(1356969600000L)); assertEquals(new Date(1325390268000L), DateUtil.parseDateTime("2012-01-01 11:57:48", null)); } | public static Date parseDateTime(String timeStr, Date defaultValue){ if(timeStr == null){ return defaultValue; } try { return dateTimeSdf.get().parse(timeStr); } catch (ParseException e) { return defaultValue; } } | DateUtil { public static Date parseDateTime(String timeStr, Date defaultValue){ if(timeStr == null){ return defaultValue; } try { return dateTimeSdf.get().parse(timeStr); } catch (ParseException e) { return defaultValue; } } } | DateUtil { public static Date parseDateTime(String timeStr, Date defaultValue){ if(timeStr == null){ return defaultValue; } try { return dateTimeSdf.get().parse(timeStr); } catch (ParseException e) { return defaultValue; } } } | DateUtil { public static Date parseDateTime(String timeStr, Date defaultValue){ if(timeStr == null){ return defaultValue; } try { return dateTimeSdf.get().parse(timeStr); } catch (ParseException e) { return defaultValue; } } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Da... | DateUtil { public static Date parseDateTime(String timeStr, Date defaultValue){ if(timeStr == null){ return defaultValue; } try { return dateTimeSdf.get().parse(timeStr); } catch (ParseException e) { return defaultValue; } } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Da... |
@Test public void testGetYearMonth() { Date date = DateUtil.parseDateTime("2012-01-01 11:57:48", null); assertEquals("12_01", DateUtil.getYearMonth(date)); date = DateUtil.parseDateTime("2012-12-01 00:00:00", null); ApiLogger.debug(date + ", " + date.getTime()); } | public static String getYearMonth(Date date){ return yearMonthSdf.get().format(date); } | DateUtil { public static String getYearMonth(Date date){ return yearMonthSdf.get().format(date); } } | DateUtil { public static String getYearMonth(Date date){ return yearMonthSdf.get().format(date); } } | DateUtil { public static String getYearMonth(Date date){ return yearMonthSdf.get().format(date); } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(S... | DateUtil { public static String getYearMonth(Date date){ return yearMonthSdf.get().format(date); } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(S... |
@Test public void testRequestUrl(){ ApiHttpClient client = new ApacheHttpClient(100, 1000, 1000, 1024*100); String result = client.get("http: ApiLogger.debug(result); Assert.assertTrue(!StringUtils.isBlank(result)); } | @Deprecated public String requestURL(String url, Map<String, ?> nameValues) { if(HttpManager.isBlockResource(url)){ debug("requestURL blockResource url="+url); return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); String result = null; try { long t = System.currentTimeMillis(); requestURL(url, nameVal... | ApacheHttpClient implements ApiHttpClient { @Deprecated public String requestURL(String url, Map<String, ?> nameValues) { if(HttpManager.isBlockResource(url)){ debug("requestURL blockResource url="+url); return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); String result = null; try { long t = System.... | ApacheHttpClient implements ApiHttpClient { @Deprecated public String requestURL(String url, Map<String, ?> nameValues) { if(HttpManager.isBlockResource(url)){ debug("requestURL blockResource url="+url); return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); String result = null; try { long t = System.... | ApacheHttpClient implements ApiHttpClient { @Deprecated public String requestURL(String url, Map<String, ?> nameValues) { if(HttpManager.isBlockResource(url)){ debug("requestURL blockResource url="+url); return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); String result = null; try { long t = System.... | ApacheHttpClient implements ApiHttpClient { @Deprecated public String requestURL(String url, Map<String, ?> nameValues) { if(HttpManager.isBlockResource(url)){ debug("requestURL blockResource url="+url); return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); String result = null; try { long t = System.... |
@Test public void testGetYearMonthDay() { assertEquals("11_11", DateUtil.getYearMonth(new Date(1322197921282L))); } | public static String getYearMonth(Date date){ return yearMonthSdf.get().format(date); } | DateUtil { public static String getYearMonth(Date date){ return yearMonthSdf.get().format(date); } } | DateUtil { public static String getYearMonth(Date date){ return yearMonthSdf.get().format(date); } } | DateUtil { public static String getYearMonth(Date date){ return yearMonthSdf.get().format(date); } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(S... | DateUtil { public static String getYearMonth(Date date){ return yearMonthSdf.get().format(date); } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(S... |
@Test public void testFormateYearMonthDay() { assertEquals("2011-11-25", DateUtil.formateYearMonthDay(new Date(1322197921282L))); } | public static String formateYearMonthDay(Date date){ return yearMonthDaySdf.get().format(date); } | DateUtil { public static String formateYearMonthDay(Date date){ return yearMonthDaySdf.get().format(date); } } | DateUtil { public static String formateYearMonthDay(Date date){ return yearMonthDaySdf.get().format(date); } } | DateUtil { public static String formateYearMonthDay(Date date){ return yearMonthDaySdf.get().format(date); } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parse... | DateUtil { public static String formateYearMonthDay(Date date){ return yearMonthDaySdf.get().format(date); } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parse... |
@Test public void testParseYearMonthDay() { assertEquals(new Date(1325347200000L), DateUtil.parseYearMonthDay("2012-01-01", null)); Date date = DateUtil.parseYearMonthDay("2012-12-01", null); ApiLogger.debug(date + ", " + date.getTime()); ApiLogger.debug(new Date(1000000000000L) + ", " + new Date(1000000000000L).getTim... | public static Date parseYearMonthDay(String timeStr, Date defaultValue){ if(timeStr == null){ return defaultValue; } try { return yearMonthDaySdf.get().parse(timeStr); } catch (ParseException e) { return defaultValue; } } | DateUtil { public static Date parseYearMonthDay(String timeStr, Date defaultValue){ if(timeStr == null){ return defaultValue; } try { return yearMonthDaySdf.get().parse(timeStr); } catch (ParseException e) { return defaultValue; } } } | DateUtil { public static Date parseYearMonthDay(String timeStr, Date defaultValue){ if(timeStr == null){ return defaultValue; } try { return yearMonthDaySdf.get().parse(timeStr); } catch (ParseException e) { return defaultValue; } } } | DateUtil { public static Date parseYearMonthDay(String timeStr, Date defaultValue){ if(timeStr == null){ return defaultValue; } try { return yearMonthDaySdf.get().parse(timeStr); } catch (ParseException e) { return defaultValue; } } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); s... | DateUtil { public static Date parseYearMonthDay(String timeStr, Date defaultValue){ if(timeStr == null){ return defaultValue; } try { return yearMonthDaySdf.get().parse(timeStr); } catch (ParseException e) { return defaultValue; } } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); s... |
@Test public void testGetFirstDayInMonth() { assertEquals(new Date(1320076800282L), DateUtil.getFirstDayInMonth(new Date(1322197921282L))); } | public static Date getFirstDayInMonth(Date date){ Calendar calendar = Calendar.getInstance(); if(date != null){ calendar.setTime(date); } calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); return calendar.getTime(); } | DateUtil { public static Date getFirstDayInMonth(Date date){ Calendar calendar = Calendar.getInstance(); if(date != null){ calendar.setTime(date); } calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); return calendar.getTime(... | DateUtil { public static Date getFirstDayInMonth(Date date){ Calendar calendar = Calendar.getInstance(); if(date != null){ calendar.setTime(date); } calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); return calendar.getTime(... | DateUtil { public static Date getFirstDayInMonth(Date date){ Calendar calendar = Calendar.getInstance(); if(date != null){ calendar.setTime(date); } calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); return calendar.getTime(... | DateUtil { public static Date getFirstDayInMonth(Date date){ Calendar calendar = Calendar.getInstance(); if(date != null){ calendar.setTime(date); } calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); return calendar.getTime(... |
@Test public void testGsCurrentMonth(){ assertEquals(true, DateUtil.isCurrentMonth(new Date())); assertEquals(false, DateUtil.isCurrentMonth(new Date(1322197921282L))); } | public static boolean isCurrentMonth(Date date){ if(date != null){ Calendar dest = Calendar.getInstance(); dest.setTime(date); Calendar now = Calendar.getInstance(); return now.get(Calendar.YEAR) == dest.get(Calendar.YEAR) && now.get(Calendar.MONTH) == dest.get(Calendar.MONTH); } return false; } | DateUtil { public static boolean isCurrentMonth(Date date){ if(date != null){ Calendar dest = Calendar.getInstance(); dest.setTime(date); Calendar now = Calendar.getInstance(); return now.get(Calendar.YEAR) == dest.get(Calendar.YEAR) && now.get(Calendar.MONTH) == dest.get(Calendar.MONTH); } return false; } } | DateUtil { public static boolean isCurrentMonth(Date date){ if(date != null){ Calendar dest = Calendar.getInstance(); dest.setTime(date); Calendar now = Calendar.getInstance(); return now.get(Calendar.YEAR) == dest.get(Calendar.YEAR) && now.get(Calendar.MONTH) == dest.get(Calendar.MONTH); } return false; } } | DateUtil { public static boolean isCurrentMonth(Date date){ if(date != null){ Calendar dest = Calendar.getInstance(); dest.setTime(date); Calendar now = Calendar.getInstance(); return now.get(Calendar.YEAR) == dest.get(Calendar.YEAR) && now.get(Calendar.MONTH) == dest.get(Calendar.MONTH); } return false; } static Stri... | DateUtil { public static boolean isCurrentMonth(Date date){ if(date != null){ Calendar dest = Calendar.getInstance(); dest.setTime(date); Calendar now = Calendar.getInstance(); return now.get(Calendar.YEAR) == dest.get(Calendar.YEAR) && now.get(Calendar.MONTH) == dest.get(Calendar.MONTH); } return false; } static Stri... |
@Test public void testStandardThreadExecutor(){ int minThread = 2; int maxThead = 10; StandardThreadExecutor executor = new StandardThreadExecutor(minThread,maxThead); for(int i=0;i<minThread;i++){ executor.submit(new SleepTask(10000)); } Assert.assertEquals(minThread,executor.getPoolSize()); for(int i=minThread;i<maxT... | public StandardThreadExecutor(){ this(DEFAULT_MIN_SPARE_THREADS,DEFAULT_MAX_THREADS); } | StandardThreadExecutor extends java.util.concurrent.AbstractExecutorService { public StandardThreadExecutor(){ this(DEFAULT_MIN_SPARE_THREADS,DEFAULT_MAX_THREADS); } } | StandardThreadExecutor extends java.util.concurrent.AbstractExecutorService { public StandardThreadExecutor(){ this(DEFAULT_MIN_SPARE_THREADS,DEFAULT_MAX_THREADS); } StandardThreadExecutor(); StandardThreadExecutor(int minSpareThreads,int maxThreads); StandardThreadExecutor(int minSpareThreads,int maxThreads,int task... | StandardThreadExecutor extends java.util.concurrent.AbstractExecutorService { public StandardThreadExecutor(){ this(DEFAULT_MIN_SPARE_THREADS,DEFAULT_MAX_THREADS); } StandardThreadExecutor(); StandardThreadExecutor(int minSpareThreads,int maxThreads); StandardThreadExecutor(int minSpareThreads,int maxThreads,int task... | StandardThreadExecutor extends java.util.concurrent.AbstractExecutorService { public StandardThreadExecutor(){ this(DEFAULT_MIN_SPARE_THREADS,DEFAULT_MAX_THREADS); } StandardThreadExecutor(); StandardThreadExecutor(int minSpareThreads,int maxThreads); StandardThreadExecutor(int minSpareThreads,int maxThreads,int task... |
@Test public void testJdkThreadExecutor(){ int minThread = 2; int maxThead = 10; ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(maxThead); ThreadPoolExecutor executor = new ThreadPoolExecutor(minThread,maxThead, 60, TimeUnit.SECONDS,queue,Executors.defaultThreadFactory()); for(int i=0;i<minThread... | public int getPoolSize() { return executor.getPoolSize(); } | StandardThreadExecutor extends java.util.concurrent.AbstractExecutorService { public int getPoolSize() { return executor.getPoolSize(); } } | StandardThreadExecutor extends java.util.concurrent.AbstractExecutorService { public int getPoolSize() { return executor.getPoolSize(); } StandardThreadExecutor(); StandardThreadExecutor(int minSpareThreads,int maxThreads); StandardThreadExecutor(int minSpareThreads,int maxThreads,int taskQueueCapacity); } | StandardThreadExecutor extends java.util.concurrent.AbstractExecutorService { public int getPoolSize() { return executor.getPoolSize(); } StandardThreadExecutor(); StandardThreadExecutor(int minSpareThreads,int maxThreads); StandardThreadExecutor(int minSpareThreads,int maxThreads,int taskQueueCapacity); void execute... | StandardThreadExecutor extends java.util.concurrent.AbstractExecutorService { public int getPoolSize() { return executor.getPoolSize(); } StandardThreadExecutor(); StandardThreadExecutor(int minSpareThreads,int maxThreads); StandardThreadExecutor(int minSpareThreads,int maxThreads,int taskQueueCapacity); void execute... |
@Test public void testGet(){ ApiHttpClient client = new ApacheHttpClient(100, 1000, 1000, 1024*100); String result = client.get("http: ApiLogger.debug(result); Assert.assertTrue(!StringUtils.isBlank(result)); } | @Override public String get(String url) { return get(url,DEFAULT_CHARSET); } | ApacheHttpClient implements ApiHttpClient { @Override public String get(String url) { return get(url,DEFAULT_CHARSET); } } | ApacheHttpClient implements ApiHttpClient { @Override public String get(String url) { return get(url,DEFAULT_CHARSET); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize,int minTh... | ApacheHttpClient implements ApiHttpClient { @Override public String get(String url) { return get(url,DEFAULT_CHARSET); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize,int minTh... | ApacheHttpClient implements ApiHttpClient { @Override public String get(String url) { return get(url,DEFAULT_CHARSET); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize,int minTh... |
@Test public void testPost(){ ApiHttpClient client = new ApacheHttpClient(100, 1000, 1000, 1024*100); String result = client.post("http: ApiLogger.debug(result); Assert.assertTrue(!StringUtils.isBlank(result)); } | @Override public String post(String url, Map<String, ?> nameValues) { return post(url,nameValues,DEFAULT_CHARSET); } | ApacheHttpClient implements ApiHttpClient { @Override public String post(String url, Map<String, ?> nameValues) { return post(url,nameValues,DEFAULT_CHARSET); } } | ApacheHttpClient implements ApiHttpClient { @Override public String post(String url, Map<String, ?> nameValues) { return post(url,nameValues,DEFAULT_CHARSET); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs... | ApacheHttpClient implements ApiHttpClient { @Override public String post(String url, Map<String, ?> nameValues) { return post(url,nameValues,DEFAULT_CHARSET); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs... | ApacheHttpClient implements ApiHttpClient { @Override public String post(String url, Map<String, ?> nameValues) { return post(url,nameValues,DEFAULT_CHARSET); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs... |
@Test public void testGetSlow(){ ApiHttpClient client = new ApacheHttpClient(100, 1000, 1000, 1024*100); String result = client.get("http: ApiLogger.debug(result); Assert.assertTrue(StringUtils.isBlank(result)); } | @Override public String get(String url) { return get(url,DEFAULT_CHARSET); } | ApacheHttpClient implements ApiHttpClient { @Override public String get(String url) { return get(url,DEFAULT_CHARSET); } } | ApacheHttpClient implements ApiHttpClient { @Override public String get(String url) { return get(url,DEFAULT_CHARSET); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize,int minTh... | ApacheHttpClient implements ApiHttpClient { @Override public String get(String url) { return get(url,DEFAULT_CHARSET); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize,int minTh... | ApacheHttpClient implements ApiHttpClient { @Override public String get(String url) { return get(url,DEFAULT_CHARSET); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize,int minTh... |
@Test public void testPostSlow(){ ApiHttpClient client = new ApacheHttpClient(100, 1000, 1000, 1024*100); String result = client.post("http: ApiLogger.debug(result); Assert.assertTrue(StringUtils.isBlank(result)); } | @Override public String post(String url, Map<String, ?> nameValues) { return post(url,nameValues,DEFAULT_CHARSET); } | ApacheHttpClient implements ApiHttpClient { @Override public String post(String url, Map<String, ?> nameValues) { return post(url,nameValues,DEFAULT_CHARSET); } } | ApacheHttpClient implements ApiHttpClient { @Override public String post(String url, Map<String, ?> nameValues) { return post(url,nameValues,DEFAULT_CHARSET); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs... | ApacheHttpClient implements ApiHttpClient { @Override public String post(String url, Map<String, ?> nameValues) { return post(url,nameValues,DEFAULT_CHARSET); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs... | ApacheHttpClient implements ApiHttpClient { @Override public String post(String url, Map<String, ?> nameValues) { return post(url,nameValues,DEFAULT_CHARSET); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs... |
@Test public void loginSuccess() throws Exception { String pass = "abc"; User user = sampleUser(1L); String token = StringUtils.getBasicAuth(user.getLogin(), pass); when(githubService.login(any())).thenReturn(successResponse(user)); when(userManager.startUserSession(any(), any())).thenReturn(null); viewModel.setUserNam... | public void login() { if (InputHelper.isEmpty(userName) || InputHelper.isEmpty(password)) { AlertUtils.showToastShortMessage(App.getInstance(), "Please input username and password!"); return; } String auth = StringUtils.getBasicAuth(userName, password); execute(true, RestHelper.createRemoteSourceMapper(githubService.lo... | LoginViewModel extends BaseViewModel { public void login() { if (InputHelper.isEmpty(userName) || InputHelper.isEmpty(password)) { AlertUtils.showToastShortMessage(App.getInstance(), "Please input username and password!"); return; } String auth = StringUtils.getBasicAuth(userName, password); execute(true, RestHelper.cr... | LoginViewModel extends BaseViewModel { public void login() { if (InputHelper.isEmpty(userName) || InputHelper.isEmpty(password)) { AlertUtils.showToastShortMessage(App.getInstance(), "Please input username and password!"); return; } String auth = StringUtils.getBasicAuth(userName, password); execute(true, RestHelper.cr... | LoginViewModel extends BaseViewModel { public void login() { if (InputHelper.isEmpty(userName) || InputHelper.isEmpty(password)) { AlertUtils.showToastShortMessage(App.getInstance(), "Please input username and password!"); return; } String auth = StringUtils.getBasicAuth(userName, password); execute(true, RestHelper.cr... | LoginViewModel extends BaseViewModel { public void login() { if (InputHelper.isEmpty(userName) || InputHelper.isEmpty(password)) { AlertUtils.showToastShortMessage(App.getInstance(), "Please input username and password!"); return; } String auth = StringUtils.getBasicAuth(userName, password); execute(true, RestHelper.cr... |
@Test public void loginError() throws Exception { when(githubService.login(any())).thenReturn(errorResponse(401, "blah blah")); viewModel.login(); verify(stateLiveData, times(1)).setValue(State.loading(null)); verify(stateLiveData, times(1)).setValue(State.error("blah blah")); verifyZeroInteractions(userManager); } | public void login() { if (InputHelper.isEmpty(userName) || InputHelper.isEmpty(password)) { AlertUtils.showToastShortMessage(App.getInstance(), "Please input username and password!"); return; } String auth = StringUtils.getBasicAuth(userName, password); execute(true, RestHelper.createRemoteSourceMapper(githubService.lo... | LoginViewModel extends BaseViewModel { public void login() { if (InputHelper.isEmpty(userName) || InputHelper.isEmpty(password)) { AlertUtils.showToastShortMessage(App.getInstance(), "Please input username and password!"); return; } String auth = StringUtils.getBasicAuth(userName, password); execute(true, RestHelper.cr... | LoginViewModel extends BaseViewModel { public void login() { if (InputHelper.isEmpty(userName) || InputHelper.isEmpty(password)) { AlertUtils.showToastShortMessage(App.getInstance(), "Please input username and password!"); return; } String auth = StringUtils.getBasicAuth(userName, password); execute(true, RestHelper.cr... | LoginViewModel extends BaseViewModel { public void login() { if (InputHelper.isEmpty(userName) || InputHelper.isEmpty(password)) { AlertUtils.showToastShortMessage(App.getInstance(), "Please input username and password!"); return; } String auth = StringUtils.getBasicAuth(userName, password); execute(true, RestHelper.cr... | LoginViewModel extends BaseViewModel { public void login() { if (InputHelper.isEmpty(userName) || InputHelper.isEmpty(password)) { AlertUtils.showToastShortMessage(App.getInstance(), "Please input username and password!"); return; } String auth = StringUtils.getBasicAuth(userName, password); execute(true, RestHelper.cr... |
@Test public void findOne() throws Exception { Girl girl = girlService.findOne(19); Assert.assertEquals(new Integer(14), girl.getAge()); } | public Girl findOne(Integer id) { return girlRepository.findOne(id); } | GirlService { public Girl findOne(Integer id) { return girlRepository.findOne(id); } } | GirlService { public Girl findOne(Integer id) { return girlRepository.findOne(id); } } | GirlService { public Girl findOne(Integer id) { return girlRepository.findOne(id); } @Transactional void insertTwo(); void getAge(Integer id); Girl findOne(Integer id); } | GirlService { public Girl findOne(Integer id) { return girlRepository.findOne(id); } @Transactional void insertTwo(); void getAge(Integer id); Girl findOne(Integer id); } |
@Test public void girlList() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/girls")) .andExpect(MockMvcResultMatchers.status().isOk()); } | @GetMapping(value = "/girls") public List<Girl> girlList() { logger.info("girlList"); return girlRepository.findAll(); } | GirlController { @GetMapping(value = "/girls") public List<Girl> girlList() { logger.info("girlList"); return girlRepository.findAll(); } } | GirlController { @GetMapping(value = "/girls") public List<Girl> girlList() { logger.info("girlList"); return girlRepository.findAll(); } } | GirlController { @GetMapping(value = "/girls") public List<Girl> girlList() { logger.info("girlList"); return girlRepository.findAll(); } @GetMapping(value = "/girls") List<Girl> girlList(); @PostMapping(value = "/girls") Object girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping(value = "/girl/{id}") ... | GirlController { @GetMapping(value = "/girls") public List<Girl> girlList() { logger.info("girlList"); return girlRepository.findAll(); } @GetMapping(value = "/girls") List<Girl> girlList(); @PostMapping(value = "/girls") Object girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping(value = "/girl/{id}") ... |
@Test public void tryGetDistributedLockTest() throws Exception { String key = "testDistributedLockKey"; String requestId = UUID.randomUUID().toString(); boolean getDistributedLockResult = RedisLockUtil.tryGetDistributedLock(JEDIS, key, requestId, 60 * 1000 * 60); System.out.println("getDistributedLockResult=" + getDist... | public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) { String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME_UNIT, expireTime); return LOCK_SUCCESS.equals(result); } | RedisLockUtil { public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) { String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME_UNIT, expireTime); return LOCK_SUCCESS.equals(result); } } | RedisLockUtil { public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) { String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME_UNIT, expireTime); return LOCK_SUCCESS.equals(result); } } | RedisLockUtil { public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) { String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME_UNIT, expireTime); return LOCK_SUCCESS.equals(result); } static boolean tryGetDistributedLock(Jedis jedis, St... | RedisLockUtil { public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) { String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME_UNIT, expireTime); return LOCK_SUCCESS.equals(result); } static boolean tryGetDistributedLock(Jedis jedis, St... |
@Test public void releaseDistributedLockTest() throws Exception { String key = "testDistributedLockKey"; String requestId = UUID.randomUUID().toString(); boolean releaseDistributedLockResult = RedisLockUtil.releaseDistributedLock(JEDIS, key, requestId); System.out.println("releaseDistributedLockResult=" + releaseDistri... | public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) { String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));... | RedisLockUtil { public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) { String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonL... | RedisLockUtil { public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) { String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonL... | RedisLockUtil { public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) { String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonL... | RedisLockUtil { public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) { String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonL... |
@Test public void get() throws UnsupportedEncodingException { GetUserRequest request = new GetUserRequest("/user/getUserList"); request.setUserId(1L); request.setUsername("李白"); String result = HttpUtil.get(request.composeUrl(baseUrl, request.getQueryParameters())); AbstractResponse response = JacksonUtil.readValue(res... | public static String get(String requestUrl) { HttpGet get = new HttpGet(requestUrl); return executeRequest(get, Charset.forName(DEFAULT_ENCODING)); } | HttpUtil { public static String get(String requestUrl) { HttpGet get = new HttpGet(requestUrl); return executeRequest(get, Charset.forName(DEFAULT_ENCODING)); } } | HttpUtil { public static String get(String requestUrl) { HttpGet get = new HttpGet(requestUrl); return executeRequest(get, Charset.forName(DEFAULT_ENCODING)); } } | HttpUtil { public static String get(String requestUrl) { HttpGet get = new HttpGet(requestUrl); return executeRequest(get, Charset.forName(DEFAULT_ENCODING)); } static String get(String requestUrl); static String post(String requestUrl, Object data, ContentType contentType); static String uploadFile(String requestUrl,... | HttpUtil { public static String get(String requestUrl) { HttpGet get = new HttpGet(requestUrl); return executeRequest(get, Charset.forName(DEFAULT_ENCODING)); } static String get(String requestUrl); static String post(String requestUrl, Object data, ContentType contentType); static String uploadFile(String requestUrl,... |
@Test public void postFormData() throws UnsupportedEncodingException { UpdateUserRequest request = new UpdateUserRequest("/user/updateUser"); request.setMethod(MethodTypeEnum.POST); request.setHttpContentType(ContentType.APPLICATION_FORM_URLENCODED); request.setUserId(1L); request.setUsername("李太白"); String result = Ht... | public static String post(String requestUrl, Object data, ContentType contentType) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } if (contentType == null) { throw new RuntimeException("contentType cann't be null"); } HttpPost post = new HttpPost(requestUrl); if (data... | HttpUtil { public static String post(String requestUrl, Object data, ContentType contentType) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } if (contentType == null) { throw new RuntimeException("contentType cann't be null"); } HttpPost post = new HttpPost(requestUrl... | HttpUtil { public static String post(String requestUrl, Object data, ContentType contentType) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } if (contentType == null) { throw new RuntimeException("contentType cann't be null"); } HttpPost post = new HttpPost(requestUrl... | HttpUtil { public static String post(String requestUrl, Object data, ContentType contentType) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } if (contentType == null) { throw new RuntimeException("contentType cann't be null"); } HttpPost post = new HttpPost(requestUrl... | HttpUtil { public static String post(String requestUrl, Object data, ContentType contentType) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } if (contentType == null) { throw new RuntimeException("contentType cann't be null"); } HttpPost post = new HttpPost(requestUrl... |
@Test public void postJsonObject() throws UnsupportedEncodingException { CreateUserRequest request = new CreateUserRequest("/user/createUser"); request.setMethod(MethodTypeEnum.POST); request.setHttpContentType(ContentType.APPLICATION_JSON); CreateUserRequest.CreateUserBody body = new CreateUserRequest.CreateUserBody()... | public static String post(String requestUrl, Object data, ContentType contentType) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } if (contentType == null) { throw new RuntimeException("contentType cann't be null"); } HttpPost post = new HttpPost(requestUrl); if (data... | HttpUtil { public static String post(String requestUrl, Object data, ContentType contentType) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } if (contentType == null) { throw new RuntimeException("contentType cann't be null"); } HttpPost post = new HttpPost(requestUrl... | HttpUtil { public static String post(String requestUrl, Object data, ContentType contentType) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } if (contentType == null) { throw new RuntimeException("contentType cann't be null"); } HttpPost post = new HttpPost(requestUrl... | HttpUtil { public static String post(String requestUrl, Object data, ContentType contentType) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } if (contentType == null) { throw new RuntimeException("contentType cann't be null"); } HttpPost post = new HttpPost(requestUrl... | HttpUtil { public static String post(String requestUrl, Object data, ContentType contentType) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } if (contentType == null) { throw new RuntimeException("contentType cann't be null"); } HttpPost post = new HttpPost(requestUrl... |
@Test public void uploadFile() throws UnsupportedEncodingException { UploadFileRequest request = new UploadFileRequest("/user/uploadFile"); request.setMethod(MethodTypeEnum.POST); request.setHttpContentType(ContentType.MULTIPART_FORM_DATA); UploadFileRequest.UploadFileBody body = new UploadFileRequest.UploadFileBody();... | public static String uploadFile(String requestUrl, Object data) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(Charset.forName(DEFAULT_ENCODING)); ContentType contentType = Con... | HttpUtil { public static String uploadFile(String requestUrl, Object data) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(Charset.forName(DEFAULT_ENCODING)); ContentType conten... | HttpUtil { public static String uploadFile(String requestUrl, Object data) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(Charset.forName(DEFAULT_ENCODING)); ContentType conten... | HttpUtil { public static String uploadFile(String requestUrl, Object data) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(Charset.forName(DEFAULT_ENCODING)); ContentType conten... | HttpUtil { public static String uploadFile(String requestUrl, Object data) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(Charset.forName(DEFAULT_ENCODING)); ContentType conten... |
@Test public void testGenerateThumbnail2Directory() throws IOException { String path = "D:\\workspace\\idea\\individual\\springboot-learn\\springboot-thumbnail\\image"; String[] files = new String[]{ "image/1.jpg", "image/2.jpg" }; List<String> list = ImageUtil.generateThumbnail2Directory(path, files); System.out.print... | public static List<String> generateThumbnail2Directory(String path, String... files) throws IOException { return generateThumbnail2Directory(DEFAULT_SCALE, path, files); } | ImageUtil { public static List<String> generateThumbnail2Directory(String path, String... files) throws IOException { return generateThumbnail2Directory(DEFAULT_SCALE, path, files); } } | ImageUtil { public static List<String> generateThumbnail2Directory(String path, String... files) throws IOException { return generateThumbnail2Directory(DEFAULT_SCALE, path, files); } } | ImageUtil { public static List<String> generateThumbnail2Directory(String path, String... files) throws IOException { return generateThumbnail2Directory(DEFAULT_SCALE, path, files); } static List<String> generateThumbnail2Directory(String path, String... files); static List<String> generateThumbnail2Directory(double s... | ImageUtil { public static List<String> generateThumbnail2Directory(String path, String... files) throws IOException { return generateThumbnail2Directory(DEFAULT_SCALE, path, files); } static List<String> generateThumbnail2Directory(String path, String... files); static List<String> generateThumbnail2Directory(double s... |
@Test public void testGenerateDirectoryThumbnail() throws IOException { String path = "D:\\workspace\\idea\\individual\\springboot-learn\\springboot-thumbnail\\image"; ImageUtil.generateDirectoryThumbnail(path); } | public static void generateDirectoryThumbnail(String pathname) throws IOException { generateDirectoryThumbnail(pathname, DEFAULT_SCALE); } | ImageUtil { public static void generateDirectoryThumbnail(String pathname) throws IOException { generateDirectoryThumbnail(pathname, DEFAULT_SCALE); } } | ImageUtil { public static void generateDirectoryThumbnail(String pathname) throws IOException { generateDirectoryThumbnail(pathname, DEFAULT_SCALE); } } | ImageUtil { public static void generateDirectoryThumbnail(String pathname) throws IOException { generateDirectoryThumbnail(pathname, DEFAULT_SCALE); } static List<String> generateThumbnail2Directory(String path, String... files); static List<String> generateThumbnail2Directory(double scale, String pathname, String... ... | ImageUtil { public static void generateDirectoryThumbnail(String pathname) throws IOException { generateDirectoryThumbnail(pathname, DEFAULT_SCALE); } static List<String> generateThumbnail2Directory(String path, String... files); static List<String> generateThumbnail2Directory(double scale, String pathname, String... ... |
@Test public void ensureArgsForMethodAccurate() throws NoSuchMethodException { List<String> inputStr = Arrays.asList("1", "nextMethod", "param", "param2"); Method testClass1234 = ReflTestClass.ReflSubClass.class.getMethod("get1234", int.class); List<String> out = ReflectionUtil.getArgsForMethod(inputStr, testClass1234)... | public static @NotNull List<String> getArgsForMethod(@NotNull List<String> args, @NotNull Method method) { if (args.size() == 0 && method.getParameterCount() == 0) { return Collections.emptyList(); } List<String> argsOut = new ArrayList<>(); if (args.size() < method.getParameterCount()) { argsOut.addAll(args); } else {... | ReflectionUtil { public static @NotNull List<String> getArgsForMethod(@NotNull List<String> args, @NotNull Method method) { if (args.size() == 0 && method.getParameterCount() == 0) { return Collections.emptyList(); } List<String> argsOut = new ArrayList<>(); if (args.size() < method.getParameterCount()) { argsOut.addAl... | ReflectionUtil { public static @NotNull List<String> getArgsForMethod(@NotNull List<String> args, @NotNull Method method) { if (args.size() == 0 && method.getParameterCount() == 0) { return Collections.emptyList(); } List<String> argsOut = new ArrayList<>(); if (args.size() < method.getParameterCount()) { argsOut.addAl... | ReflectionUtil { public static @NotNull List<String> getArgsForMethod(@NotNull List<String> args, @NotNull Method method) { if (args.size() == 0 && method.getParameterCount() == 0) { return Collections.emptyList(); } List<String> argsOut = new ArrayList<>(); if (args.size() < method.getParameterCount()) { argsOut.addAl... | ReflectionUtil { public static @NotNull List<String> getArgsForMethod(@NotNull List<String> args, @NotNull Method method) { if (args.size() == 0 && method.getParameterCount() == 0) { return Collections.emptyList(); } List<String> argsOut = new ArrayList<>(); if (args.size() < method.getParameterCount()) { argsOut.addAl... |
@Test public void ensurePolymorphicInput() throws InputException { Class[] requestedTypes = {AnEnum.class, AnEnum.class}; String[] inputArgs = {"VAL_1", "VAL_5"}; Object[] output = typeHandler.instantiateTypes(requestedTypes, Arrays.asList(inputArgs)); assertTrue(output[0] instanceof AnEnum); assertTrue(output[1] insta... | public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } | TypeHandler { public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } } | TypeHandler { public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } TypeHandler(Logger logger); } | TypeHandler { public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } TypeHandler(Logger logger); @Nullable String getOutputFor(@Nullable Object object); @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String>... | TypeHandler { public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } TypeHandler(Logger logger); @Nullable String getOutputFor(@Nullable Object object); @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String>... |
@Test public void ensureThrowsOnNoSuchIHandler() { Assertions.assertThrows(InputException.class, () -> { Class[] requestedType = {CASE_NEVER_WILL_BE_REGISTERED}; typeHandler.instantiateTypes(requestedType, Collections.singletonList("blah")); }); } | public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } | TypeHandler { public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } } | TypeHandler { public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } TypeHandler(Logger logger); } | TypeHandler { public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } TypeHandler(Logger logger); @Nullable String getOutputFor(@Nullable Object object); @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String>... | TypeHandler { public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } TypeHandler(Logger logger); @Nullable String getOutputFor(@Nullable Object object); @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String>... |
@Test public void ensureNullAlwaysAvailable() throws InputException { Object[] array = typeHandler.instantiateTypes(new Class[]{Object.class}, Collections.singletonList(TypeHandler.NULL_INSTANCE_KEYWORD)); Object instance = array[0]; assertNull(instance); } | public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } | TypeHandler { public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } } | TypeHandler { public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } TypeHandler(Logger logger); } | TypeHandler { public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } TypeHandler(Logger logger); @Nullable String getOutputFor(@Nullable Object object); @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String>... | TypeHandler { public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } TypeHandler(Logger logger); @Nullable String getOutputFor(@Nullable Object object); @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String>... |
@Test public void ensureNullInputGivesNullOutput() { String output = typeHandler.getOutputFor(null); assertNull(output); } | public @Nullable String getOutputFor(@Nullable Object object) { if (object == null) { return null; } OHandler handler = getOHandlerForClass(object.getClass()); if (handler != null) { return handler.getFormattedOutput(object); } else { return String.valueOf(object); } } | TypeHandler { public @Nullable String getOutputFor(@Nullable Object object) { if (object == null) { return null; } OHandler handler = getOHandlerForClass(object.getClass()); if (handler != null) { return handler.getFormattedOutput(object); } else { return String.valueOf(object); } } } | TypeHandler { public @Nullable String getOutputFor(@Nullable Object object) { if (object == null) { return null; } OHandler handler = getOHandlerForClass(object.getClass()); if (handler != null) { return handler.getFormattedOutput(object); } else { return String.valueOf(object); } } TypeHandler(Logger logger); } | TypeHandler { public @Nullable String getOutputFor(@Nullable Object object) { if (object == null) { return null; } OHandler handler = getOHandlerForClass(object.getClass()); if (handler != null) { return handler.getFormattedOutput(object); } else { return String.valueOf(object); } } TypeHandler(Logger logger); @Nullabl... | TypeHandler { public @Nullable String getOutputFor(@Nullable Object object) { if (object == null) { return null; } OHandler handler = getOHandlerForClass(object.getClass()); if (handler != null) { return handler.getFormattedOutput(object); } else { return String.valueOf(object); } } TypeHandler(Logger logger); @Nullabl... |
@Test public void ensureNoWhitespaceInMethodIds() throws NoSuchMethodException { Method method = ReflTestClass.class.getMethod("getSomeNumbers"); String id = ReflectionUtil.getMethodId(method); long whitespaceCount = id.chars() .filter(Character::isWhitespace) .count(); if (whitespaceCount != 0) { System.out.println("I... | public static @NotNull String getMethodId(Method method) { return getFormattedMethodSignature(method).replaceAll(" ", ""); } | ReflectionUtil { public static @NotNull String getMethodId(Method method) { return getFormattedMethodSignature(method).replaceAll(" ", ""); } } | ReflectionUtil { public static @NotNull String getMethodId(Method method) { return getFormattedMethodSignature(method).replaceAll(" ", ""); } } | ReflectionUtil { public static @NotNull String getMethodId(Method method) { return getFormattedMethodSignature(method).replaceAll(" ", ""); } static @NotNull List<String> getArgsForMethod(@NotNull List<String> args, @NotNull Method method); static @NotNull String getFormattedMethodSignature(Method method); static @Not... | ReflectionUtil { public static @NotNull String getMethodId(Method method) { return getFormattedMethodSignature(method).replaceAll(" ", ""); } static @NotNull List<String> getArgsForMethod(@NotNull List<String> args, @NotNull Method method); static @NotNull String getFormattedMethodSignature(Method method); static @Not... |
@Test public void validateArgsMismatchContent() throws NoSuchMethodException { BiConsumer<Method, String> validateBasics = (method, s) -> { s = s.toLowerCase(); assertTrue(s.contains(method.getName().toLowerCase())); assertTrue(s.contains(method.getReturnType().getSimpleName().toLowerCase())); assertTrue(s.contains(Str... | public static @NotNull String getArgMismatchString(Method method) { final String methodName = method.getName(); final Class<?> returnType = method.getReturnType(); final String returnTypeName = returnType.getSimpleName(); String returnInfo; if (returnType.equals(Void.TYPE)) { returnInfo = "returns void."; } else if (st... | ReflectionUtil { public static @NotNull String getArgMismatchString(Method method) { final String methodName = method.getName(); final Class<?> returnType = method.getReturnType(); final String returnTypeName = returnType.getSimpleName(); String returnInfo; if (returnType.equals(Void.TYPE)) { returnInfo = "returns void... | ReflectionUtil { public static @NotNull String getArgMismatchString(Method method) { final String methodName = method.getName(); final Class<?> returnType = method.getReturnType(); final String returnTypeName = returnType.getSimpleName(); String returnInfo; if (returnType.equals(Void.TYPE)) { returnInfo = "returns void... | ReflectionUtil { public static @NotNull String getArgMismatchString(Method method) { final String methodName = method.getName(); final Class<?> returnType = method.getReturnType(); final String returnTypeName = returnType.getSimpleName(); String returnInfo; if (returnType.equals(Void.TYPE)) { returnInfo = "returns void... | ReflectionUtil { public static @NotNull String getArgMismatchString(Method method) { final String methodName = method.getName(); final Class<?> returnType = method.getReturnType(); final String returnTypeName = returnType.getSimpleName(); String returnInfo; if (returnType.equals(Void.TYPE)) { returnInfo = "returns void... |
@Test public void testContainsMethods() { MethodMap methodmap = new MethodMap(TESTER); Set<Method> mappedMethods = methodmap.getAllMethods(); long missing = Arrays.stream(TESTER.getMethods()) .filter(m -> Modifier.isPublic(m.getModifiers())) .filter(m -> !mappedMethods.contains(m)) .peek(m -> System.out.println(m.getNa... | public @NotNull Set<Method> getAllMethods() { return new HashSet<>(backingMap.values()); } | MethodMap { public @NotNull Set<Method> getAllMethods() { return new HashSet<>(backingMap.values()); } } | MethodMap { public @NotNull Set<Method> getAllMethods() { return new HashSet<>(backingMap.values()); } private MethodMap(); MethodMap(@NotNull Class<?> clazz); } | MethodMap { public @NotNull Set<Method> getAllMethods() { return new HashSet<>(backingMap.values()); } private MethodMap(); MethodMap(@NotNull Class<?> clazz); @Nullable Method getById(String identifier); boolean containsId(String identifier); @NotNull Set<Method> getAllMethods(); @NotNull Set<String> getAllIds(); @... | MethodMap { public @NotNull Set<Method> getAllMethods() { return new HashSet<>(backingMap.values()); } private MethodMap(); MethodMap(@NotNull Class<?> clazz); @Nullable Method getById(String identifier); boolean containsId(String identifier); @NotNull Set<Method> getAllMethods(); @NotNull Set<String> getAllIds(); @... |
@Test public void testContainsIds() { MethodMap methodMap = new MethodMap(TESTER); Set<String> identifiers = methodMap.getAllIds(); long missing = Arrays.stream(TESTER.getMethods()) .filter(m -> Modifier.isPublic(m.getModifiers())) .map(ReflectionUtil::getMethodId) .filter(s -> !identifiers.contains(s)) .peek(s -> Syst... | public @NotNull Set<String> getAllIds() { return new HashSet<>(backingMap.keySet()); } | MethodMap { public @NotNull Set<String> getAllIds() { return new HashSet<>(backingMap.keySet()); } } | MethodMap { public @NotNull Set<String> getAllIds() { return new HashSet<>(backingMap.keySet()); } private MethodMap(); MethodMap(@NotNull Class<?> clazz); } | MethodMap { public @NotNull Set<String> getAllIds() { return new HashSet<>(backingMap.keySet()); } private MethodMap(); MethodMap(@NotNull Class<?> clazz); @Nullable Method getById(String identifier); boolean containsId(String identifier); @NotNull Set<Method> getAllMethods(); @NotNull Set<String> getAllIds(); @NotN... | MethodMap { public @NotNull Set<String> getAllIds() { return new HashSet<>(backingMap.keySet()); } private MethodMap(); MethodMap(@NotNull Class<?> clazz); @Nullable Method getById(String identifier); boolean containsId(String identifier); @NotNull Set<Method> getAllMethods(); @NotNull Set<String> getAllIds(); @NotN... |
@Test public void ensureHashcodes() { MethodMap map1 = new MethodMap(TESTER); MethodMap map2 = new MethodMap(TESTER); assertEquals(map1.hashCode(), map2.hashCode()); } | @Override public int hashCode() { return 67 * backingMap.hashCode(); } | MethodMap { @Override public int hashCode() { return 67 * backingMap.hashCode(); } } | MethodMap { @Override public int hashCode() { return 67 * backingMap.hashCode(); } private MethodMap(); MethodMap(@NotNull Class<?> clazz); } | MethodMap { @Override public int hashCode() { return 67 * backingMap.hashCode(); } private MethodMap(); MethodMap(@NotNull Class<?> clazz); @Nullable Method getById(String identifier); boolean containsId(String identifier); @NotNull Set<Method> getAllMethods(); @NotNull Set<String> getAllIds(); @NotNull Class<?> get... | MethodMap { @Override public int hashCode() { return 67 * backingMap.hashCode(); } private MethodMap(); MethodMap(@NotNull Class<?> clazz); @Nullable Method getById(String identifier); boolean containsId(String identifier); @NotNull Set<Method> getAllMethods(); @NotNull Set<String> getAllIds(); @NotNull Class<?> get... |
@Test public void simpleReflectTest() throws NoSuchMethodException, IllegalAccessException, InputException, InvocationTargetException { Method method = ReflTestClass.class.getMethod("getNumbersPlusParam", int.class); String methodName = ReflectionUtil.getMethodId(method); ReflTestClass instance = new ReflTestClass(1, 2... | void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0) { argsToSkip--; c... | ReflectionChain { void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0)... | ReflectionChain { void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0)... | ReflectionChain { void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0)... | ReflectionChain { void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0)... |
@Test public void chainReflectTest() throws NoSuchMethodException, IllegalAccessException, InputException, InvocationTargetException { Method subClassGet = ReflTestClass.class.getMethod("getSubClass"); String subClassGetterName = ReflectionUtil.getMethodId(subClassGet); Method subClassGetNum = ReflTestClass.ReflSubClas... | void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0) { argsToSkip--; c... | ReflectionChain { void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0)... | ReflectionChain { void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0)... | ReflectionChain { void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0)... | ReflectionChain { void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0)... |
@Test public void noSuchMethodTest() throws NoSuchMethodException, IllegalAccessException, InputException, InvocationTargetException { Method subClassGet = ReflTestClass.class.getMethod("getSubClass"); String subClassGetterName = ReflectionUtil.getMethodId(subClassGet); String methodThatDoesNotExist = "getPotatoes()"; ... | void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0) { argsToSkip--; c... | ReflectionChain { void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0)... | ReflectionChain { void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0)... | ReflectionChain { void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0)... | ReflectionChain { void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0)... |
@Test public void chainOnNullTest() throws NoSuchMethodException { Method alwaysReturnsNull = ReflTestClass.class.getMethod("alwaysReturnsNull"); String nullMethodName = ReflectionUtil.getMethodId(alwaysReturnsNull); ReflTestClass instance = new ReflTestClass(1, 2, 3); String[] input = new String[]{nullMethodName, "get... | void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0) { argsToSkip--; c... | ReflectionChain { void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0)... | ReflectionChain { void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0)... | ReflectionChain { void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0)... | ReflectionChain { void runChain() { MethodMap reflectionMap; Object currentInstance = initialInstance; ReflectionResult result = null; Object priorInstance; Method currentMethod; Object[] methodParameters; int argsToSkip = 0; for (int i = 0; i < input.size(); i++) { String currentArg = input.get(i); if (argsToSkip > 0)... |
@Test public void setup_withContext_hold() { FileDownloader.setup(application); Assert.assertEquals(application.getApplicationContext(), FileDownloadHelper.getAppContext()); } | public static void setup(Context context) { FileDownloadHelper.holdContext(context.getApplicationContext()); } | FileDownloader { public static void setup(Context context) { FileDownloadHelper.holdContext(context.getApplicationContext()); } } | FileDownloader { public static void setup(Context context) { FileDownloadHelper.holdContext(context.getApplicationContext()); } } | FileDownloader { public static void setup(Context context) { FileDownloadHelper.holdContext(context.getApplicationContext()); } static void setup(Context context); static DownloadMgrInitialParams.InitCustomMaker setupOnApplicationOnCreate(Application application); static void init(final Context context); static void i... | FileDownloader { public static void setup(Context context) { FileDownloadHelper.holdContext(context.getApplicationContext()); } static void setup(Context context); static DownloadMgrInitialParams.InitCustomMaker setupOnApplicationOnCreate(Application application); static void init(final Context context); static void i... |
@Test public void setupOnApplicationOnCreate_withContext_hold() { FileDownloader.setupOnApplicationOnCreate(application); Assert.assertEquals(application.getApplicationContext(), FileDownloadHelper.getAppContext()); } | public static DownloadMgrInitialParams.InitCustomMaker setupOnApplicationOnCreate(Application application) { final Context context = application.getApplicationContext(); FileDownloadHelper.holdContext(context); DownloadMgrInitialParams.InitCustomMaker customMaker = new DownloadMgrInitialParams.InitCustomMaker(); Custom... | FileDownloader { public static DownloadMgrInitialParams.InitCustomMaker setupOnApplicationOnCreate(Application application) { final Context context = application.getApplicationContext(); FileDownloadHelper.holdContext(context); DownloadMgrInitialParams.InitCustomMaker customMaker = new DownloadMgrInitialParams.InitCust... | FileDownloader { public static DownloadMgrInitialParams.InitCustomMaker setupOnApplicationOnCreate(Application application) { final Context context = application.getApplicationContext(); FileDownloadHelper.holdContext(context); DownloadMgrInitialParams.InitCustomMaker customMaker = new DownloadMgrInitialParams.InitCust... | FileDownloader { public static DownloadMgrInitialParams.InitCustomMaker setupOnApplicationOnCreate(Application application) { final Context context = application.getApplicationContext(); FileDownloadHelper.holdContext(context); DownloadMgrInitialParams.InitCustomMaker customMaker = new DownloadMgrInitialParams.InitCust... | FileDownloader { public static DownloadMgrInitialParams.InitCustomMaker setupOnApplicationOnCreate(Application application) { final Context context = application.getApplicationContext(); FileDownloadHelper.holdContext(context); DownloadMgrInitialParams.InitCustomMaker customMaker = new DownloadMgrInitialParams.InitCust... |
@Test public void run_withConnectFailed_retry() throws IOException, IllegalAccessException { when(mockConnectTask.connect()).thenThrow(mockIOException); downloadRunnable.run(); verify(mockCallback).onRetry(mockIOException, 0); } | @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); FileDownloadConnection connection = null; final long beginOffset = connectTask.getProfile().currentOffset; boolean isConnected = false; do { try { if (paused) { return; } isConnected = false; connection = connectTask.connect();... | DownloadRunnable implements Runnable { @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); FileDownloadConnection connection = null; final long beginOffset = connectTask.getProfile().currentOffset; boolean isConnected = false; do { try { if (paused) { return; } isConnected = fal... | DownloadRunnable implements Runnable { @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); FileDownloadConnection connection = null; final long beginOffset = connectTask.getProfile().currentOffset; boolean isConnected = false; do { try { if (paused) { return; } isConnected = fal... | DownloadRunnable implements Runnable { @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); FileDownloadConnection connection = null; final long beginOffset = connectTask.getProfile().currentOffset; boolean isConnected = false; do { try { if (paused) { return; } isConnected = fal... | DownloadRunnable implements Runnable { @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); FileDownloadConnection connection = null; final long beginOffset = connectTask.getProfile().currentOffset; boolean isConnected = false; do { try { if (paused) { return; } isConnected = fal... |
@Test public void run_responseCodeNotMet_error() throws IOException, IllegalAccessException { final FileDownloadConnection connection = mock(FileDownloadConnection.class); when(connection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_PRECON_FAILED); when(mockConnectTask.connect()).thenReturn(connection); downloa... | @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); FileDownloadConnection connection = null; final long beginOffset = connectTask.getProfile().currentOffset; boolean isConnected = false; do { try { if (paused) { return; } isConnected = false; connection = connectTask.connect();... | DownloadRunnable implements Runnable { @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); FileDownloadConnection connection = null; final long beginOffset = connectTask.getProfile().currentOffset; boolean isConnected = false; do { try { if (paused) { return; } isConnected = fal... | DownloadRunnable implements Runnable { @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); FileDownloadConnection connection = null; final long beginOffset = connectTask.getProfile().currentOffset; boolean isConnected = false; do { try { if (paused) { return; } isConnected = fal... | DownloadRunnable implements Runnable { @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); FileDownloadConnection connection = null; final long beginOffset = connectTask.getProfile().currentOffset; boolean isConnected = false; do { try { if (paused) { return; } isConnected = fal... | DownloadRunnable implements Runnable { @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); FileDownloadConnection connection = null; final long beginOffset = connectTask.getProfile().currentOffset; boolean isConnected = false; do { try { if (paused) { return; } isConnected = fal... |
@Test public void parseError_withInvalidRequestError_createsCorrectObject() { ErrorParser.StripeError parsedStripeError = ErrorParser.parseError(RAW_INVALID_REQUEST_ERROR); String errorMessage = "The Stripe API is only accessible over HTTPS. " + "Please see <https: assertEquals(errorMessage, parsedStripeError.message);... | @NonNull static StripeError parseError(String rawError) { StripeError stripeError = new StripeError(); try { JSONObject jsonError = new JSONObject(rawError); JSONObject errorObject = jsonError.getJSONObject(FIELD_ERROR); stripeError.charge = errorObject.optString(FIELD_CHARGE); stripeError.code = errorObject.optString(... | ErrorParser { @NonNull static StripeError parseError(String rawError) { StripeError stripeError = new StripeError(); try { JSONObject jsonError = new JSONObject(rawError); JSONObject errorObject = jsonError.getJSONObject(FIELD_ERROR); stripeError.charge = errorObject.optString(FIELD_CHARGE); stripeError.code = errorObj... | ErrorParser { @NonNull static StripeError parseError(String rawError) { StripeError stripeError = new StripeError(); try { JSONObject jsonError = new JSONObject(rawError); JSONObject errorObject = jsonError.getJSONObject(FIELD_ERROR); stripeError.charge = errorObject.optString(FIELD_CHARGE); stripeError.code = errorObj... | ErrorParser { @NonNull static StripeError parseError(String rawError) { StripeError stripeError = new StripeError(); try { JSONObject jsonError = new JSONObject(rawError); JSONObject errorObject = jsonError.getJSONObject(FIELD_ERROR); stripeError.charge = errorObject.optString(FIELD_CHARGE); stripeError.code = errorObj... | ErrorParser { @NonNull static StripeError parseError(String rawError) { StripeError stripeError = new StripeError(); try { JSONObject jsonError = new JSONObject(rawError); JSONObject errorObject = jsonError.getJSONObject(FIELD_ERROR); stripeError.charge = errorObject.optString(FIELD_CHARGE); stripeError.code = errorObj... |
@Test public void wholePositiveNumberShouldPassWithLeadingZero() { assertTrue(ModelUtils.isWholePositiveNumber("000")); } | static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } | ModelUtils { static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } } | ModelUtils { static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } } | ModelUtils { static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } } | ModelUtils { static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } } |
@Test public void wholePositiveNumberShouldFailIfNegative() { assertFalse(ModelUtils.isWholePositiveNumber("-1")); } | static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } | ModelUtils { static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } } | ModelUtils { static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } } | ModelUtils { static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } } | ModelUtils { static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } } |
@Test public void wholePositiveNumberShouldFailIfLetters() { assertFalse(ModelUtils.isWholePositiveNumber("1a")); } | static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } | ModelUtils { static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } } | ModelUtils { static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } } | ModelUtils { static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } } | ModelUtils { static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } } |
@Test public void normalizeSameCenturyShouldPass() { Calendar now = Calendar.getInstance(); int year = 1997; now.set(Calendar.YEAR, year); assertEquals(ModelUtils.normalizeYear(97, now), year); } | static int normalizeYear(int year, Calendar now) { if (year < 100 && year >= 0) { String currentYear = String.valueOf(now.get(Calendar.YEAR)); String prefix = currentYear.substring(0, currentYear.length() - 2); year = Integer.parseInt(String.format(Locale.US, "%s%02d", prefix, year)); } return year; } | ModelUtils { static int normalizeYear(int year, Calendar now) { if (year < 100 && year >= 0) { String currentYear = String.valueOf(now.get(Calendar.YEAR)); String prefix = currentYear.substring(0, currentYear.length() - 2); year = Integer.parseInt(String.format(Locale.US, "%s%02d", prefix, year)); } return year; } } | ModelUtils { static int normalizeYear(int year, Calendar now) { if (year < 100 && year >= 0) { String currentYear = String.valueOf(now.get(Calendar.YEAR)); String prefix = currentYear.substring(0, currentYear.length() - 2); year = Integer.parseInt(String.format(Locale.US, "%s%02d", prefix, year)); } return year; } } | ModelUtils { static int normalizeYear(int year, Calendar now) { if (year < 100 && year >= 0) { String currentYear = String.valueOf(now.get(Calendar.YEAR)); String prefix = currentYear.substring(0, currentYear.length() - 2); year = Integer.parseInt(String.format(Locale.US, "%s%02d", prefix, year)); } return year; } } | ModelUtils { static int normalizeYear(int year, Calendar now) { if (year < 100 && year >= 0) { String currentYear = String.valueOf(now.get(Calendar.YEAR)); String prefix = currentYear.substring(0, currentYear.length() - 2); year = Integer.parseInt(String.format(Locale.US, "%s%02d", prefix, year)); } return year; } } |
@Test public void normalizeDifferentCenturyShouldFail() { Calendar now = Calendar.getInstance(); int year = 1997; now.set(Calendar.YEAR, year); assertNotEquals(ModelUtils.normalizeYear(97, now), 2097); } | static int normalizeYear(int year, Calendar now) { if (year < 100 && year >= 0) { String currentYear = String.valueOf(now.get(Calendar.YEAR)); String prefix = currentYear.substring(0, currentYear.length() - 2); year = Integer.parseInt(String.format(Locale.US, "%s%02d", prefix, year)); } return year; } | ModelUtils { static int normalizeYear(int year, Calendar now) { if (year < 100 && year >= 0) { String currentYear = String.valueOf(now.get(Calendar.YEAR)); String prefix = currentYear.substring(0, currentYear.length() - 2); year = Integer.parseInt(String.format(Locale.US, "%s%02d", prefix, year)); } return year; } } | ModelUtils { static int normalizeYear(int year, Calendar now) { if (year < 100 && year >= 0) { String currentYear = String.valueOf(now.get(Calendar.YEAR)); String prefix = currentYear.substring(0, currentYear.length() - 2); year = Integer.parseInt(String.format(Locale.US, "%s%02d", prefix, year)); } return year; } } | ModelUtils { static int normalizeYear(int year, Calendar now) { if (year < 100 && year >= 0) { String currentYear = String.valueOf(now.get(Calendar.YEAR)); String prefix = currentYear.substring(0, currentYear.length() - 2); year = Integer.parseInt(String.format(Locale.US, "%s%02d", prefix, year)); } return year; } } | ModelUtils { static int normalizeYear(int year, Calendar now) { if (year < 100 && year >= 0) { String currentYear = String.valueOf(now.get(Calendar.YEAR)); String prefix = currentYear.substring(0, currentYear.length() - 2); year = Integer.parseInt(String.format(Locale.US, "%s%02d", prefix, year)); } return year; } } |
@Test public void fromJsonString_backToJson_createsIdenticalElement() { try { JSONObject rawConversion = new JSONObject(EXAMPLE_JSON_CODE_VERIFICATION); assertJsonEquals(rawConversion, mCodeVerification.toJson()); } catch (JSONException jsonException) { fail("Test Data failure: " + jsonException.getLocalizedMessage());... | @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); try{ jsonObject.put(FIELD_ATTEMPTS_REMAINING, mAttemptsRemaining); StripeJsonUtils.putStringIfNotNull(jsonObject, FIELD_STATUS, mStatus); } catch (JSONException ignored) { } return jsonObject; } | SourceCodeVerification extends StripeJsonModel { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); try{ jsonObject.put(FIELD_ATTEMPTS_REMAINING, mAttemptsRemaining); StripeJsonUtils.putStringIfNotNull(jsonObject, FIELD_STATUS, mStatus); } catch (JSONException ignored) { } return ... | SourceCodeVerification extends StripeJsonModel { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); try{ jsonObject.put(FIELD_ATTEMPTS_REMAINING, mAttemptsRemaining); StripeJsonUtils.putStringIfNotNull(jsonObject, FIELD_STATUS, mStatus); } catch (JSONException ignored) { } return ... | SourceCodeVerification extends StripeJsonModel { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); try{ jsonObject.put(FIELD_ATTEMPTS_REMAINING, mAttemptsRemaining); StripeJsonUtils.putStringIfNotNull(jsonObject, FIELD_STATUS, mStatus); } catch (JSONException ignored) { } return ... | SourceCodeVerification extends StripeJsonModel { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); try{ jsonObject.put(FIELD_ATTEMPTS_REMAINING, mAttemptsRemaining); StripeJsonUtils.putStringIfNotNull(jsonObject, FIELD_STATUS, mStatus); } catch (JSONException ignored) { } return ... |
@Test public void fromJsonString_toMap_createsExpectedMap() { assertMapEquals(EXAMPLE_MAP_CODE_VERIFICATION, mCodeVerification.toMap()); } | @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); hashMap.put(FIELD_ATTEMPTS_REMAINING, mAttemptsRemaining); if (mStatus != null) { hashMap.put(FIELD_STATUS, mStatus); } return hashMap; } | SourceCodeVerification extends StripeJsonModel { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); hashMap.put(FIELD_ATTEMPTS_REMAINING, mAttemptsRemaining); if (mStatus != null) { hashMap.put(FIELD_STATUS, mStatus); } return hashMap; } } | SourceCodeVerification extends StripeJsonModel { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); hashMap.put(FIELD_ATTEMPTS_REMAINING, mAttemptsRemaining); if (mStatus != null) { hashMap.put(FIELD_STATUS, mStatus); } return hashMap; } SourceCodeVerification(int att... | SourceCodeVerification extends StripeJsonModel { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); hashMap.put(FIELD_ATTEMPTS_REMAINING, mAttemptsRemaining); if (mStatus != null) { hashMap.put(FIELD_STATUS, mStatus); } return hashMap; } SourceCodeVerification(int att... | SourceCodeVerification extends StripeJsonModel { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); hashMap.put(FIELD_ATTEMPTS_REMAINING, mAttemptsRemaining); if (mStatus != null) { hashMap.put(FIELD_STATUS, mStatus); } return hashMap; } SourceCodeVerification(int att... |
@Test public void fromJsonString_backToJson_createsIdenticalElement() { try { JSONObject rawConversion = new JSONObject(EXAMPLE_JSON_RECEIVER); assertJsonEquals(rawConversion, mSourceReceiver.toJson()); } catch (JSONException jsonException) { fail("Test Data failure: " + jsonException.getLocalizedMessage()); } } | @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); StripeJsonUtils.putStringIfNotNull(jsonObject, FIELD_ADDRESS, mAddress); try { jsonObject.put(FIELD_AMOUNT_CHARGED, mAmountCharged); jsonObject.put(FIELD_AMOUNT_RECEIVED, mAmountReceived); jsonObject.put(FIELD_AMOUNT_RETURNED, mAm... | SourceReceiver extends StripeJsonModel { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); StripeJsonUtils.putStringIfNotNull(jsonObject, FIELD_ADDRESS, mAddress); try { jsonObject.put(FIELD_AMOUNT_CHARGED, mAmountCharged); jsonObject.put(FIELD_AMOUNT_RECEIVED, mAmountReceived); ... | SourceReceiver extends StripeJsonModel { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); StripeJsonUtils.putStringIfNotNull(jsonObject, FIELD_ADDRESS, mAddress); try { jsonObject.put(FIELD_AMOUNT_CHARGED, mAmountCharged); jsonObject.put(FIELD_AMOUNT_RECEIVED, mAmountReceived); ... | SourceReceiver extends StripeJsonModel { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); StripeJsonUtils.putStringIfNotNull(jsonObject, FIELD_ADDRESS, mAddress); try { jsonObject.put(FIELD_AMOUNT_CHARGED, mAmountCharged); jsonObject.put(FIELD_AMOUNT_RECEIVED, mAmountReceived); ... | SourceReceiver extends StripeJsonModel { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); StripeJsonUtils.putStringIfNotNull(jsonObject, FIELD_ADDRESS, mAddress); try { jsonObject.put(FIELD_AMOUNT_CHARGED, mAmountCharged); jsonObject.put(FIELD_AMOUNT_RECEIVED, mAmountReceived); ... |
@Test public void fromJsonString_toMap_createsExpectedMap() { assertMapEquals(EXAMPLE_MAP_RECEIVER, mSourceReceiver.toMap()); } | @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); if (!StripeTextUtils.isBlank(mAddress)) { hashMap.put(FIELD_ADDRESS, mAddress); } hashMap.put(FIELD_ADDRESS, mAddress); hashMap.put(FIELD_AMOUNT_CHARGED, mAmountCharged); hashMap.put(FIELD_AMOUNT_RECEIVED, mAmountRece... | SourceReceiver extends StripeJsonModel { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); if (!StripeTextUtils.isBlank(mAddress)) { hashMap.put(FIELD_ADDRESS, mAddress); } hashMap.put(FIELD_ADDRESS, mAddress); hashMap.put(FIELD_AMOUNT_CHARGED, mAmountCharged); hashM... | SourceReceiver extends StripeJsonModel { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); if (!StripeTextUtils.isBlank(mAddress)) { hashMap.put(FIELD_ADDRESS, mAddress); } hashMap.put(FIELD_ADDRESS, mAddress); hashMap.put(FIELD_AMOUNT_CHARGED, mAmountCharged); hashM... | SourceReceiver extends StripeJsonModel { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); if (!StripeTextUtils.isBlank(mAddress)) { hashMap.put(FIELD_ADDRESS, mAddress); } hashMap.put(FIELD_ADDRESS, mAddress); hashMap.put(FIELD_AMOUNT_CHARGED, mAmountCharged); hashM... | SourceReceiver extends StripeJsonModel { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); if (!StripeTextUtils.isBlank(mAddress)) { hashMap.put(FIELD_ADDRESS, mAddress); } hashMap.put(FIELD_ADDRESS, mAddress); hashMap.put(FIELD_AMOUNT_CHARGED, mAmountCharged); hashM... |
@Test public void jsonObjectToMapWithoutKeys_whenHasKeyInput_returnsMapOmittingKeys() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("a_key", "a_value"); jsonObject.put("b_key", "b_value"); jsonObject.put("c_key", "c_value"); jsonObject.put("d_key", "d_value"); } catch (JSONException unexpected) { fai... | @Nullable static Map<String, Object> jsonObjectToMapWithoutKeys( @Nullable JSONObject jsonObject, @Nullable Set<String> omitKeys) { if (jsonObject == null) { return null; } Set<String> keysToOmit = omitKeys == null ? new HashSet<String>() : omitKeys; Map<String, Object> map = new HashMap<>(); Iterator<String> keyIterat... | StripeSourceTypeModel extends StripeJsonModel { @Nullable static Map<String, Object> jsonObjectToMapWithoutKeys( @Nullable JSONObject jsonObject, @Nullable Set<String> omitKeys) { if (jsonObject == null) { return null; } Set<String> keysToOmit = omitKeys == null ? new HashSet<String>() : omitKeys; Map<String, Object> m... | StripeSourceTypeModel extends StripeJsonModel { @Nullable static Map<String, Object> jsonObjectToMapWithoutKeys( @Nullable JSONObject jsonObject, @Nullable Set<String> omitKeys) { if (jsonObject == null) { return null; } Set<String> keysToOmit = omitKeys == null ? new HashSet<String>() : omitKeys; Map<String, Object> m... | StripeSourceTypeModel extends StripeJsonModel { @Nullable static Map<String, Object> jsonObjectToMapWithoutKeys( @Nullable JSONObject jsonObject, @Nullable Set<String> omitKeys) { if (jsonObject == null) { return null; } Set<String> keysToOmit = omitKeys == null ? new HashSet<String>() : omitKeys; Map<String, Object> m... | StripeSourceTypeModel extends StripeJsonModel { @Nullable static Map<String, Object> jsonObjectToMapWithoutKeys( @Nullable JSONObject jsonObject, @Nullable Set<String> omitKeys) { if (jsonObject == null) { return null; } Set<String> keysToOmit = omitKeys == null ? new HashSet<String>() : omitKeys; Map<String, Object> m... |
@Test public void getString_whenFieldContainsRawNull_returnsNull() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("key", "null"); assertNull(StripeJsonUtils.getString(jsonObject, "key")); } catch (JSONException jex) { fail("No exception expected"); } } | @Nullable static String getString( @NonNull JSONObject jsonObject, @NonNull @Size(min = 1) String fieldName) throws JSONException { return nullIfNullOrEmpty(jsonObject.getString(fieldName)); } | StripeJsonUtils { @Nullable static String getString( @NonNull JSONObject jsonObject, @NonNull @Size(min = 1) String fieldName) throws JSONException { return nullIfNullOrEmpty(jsonObject.getString(fieldName)); } } | StripeJsonUtils { @Nullable static String getString( @NonNull JSONObject jsonObject, @NonNull @Size(min = 1) String fieldName) throws JSONException { return nullIfNullOrEmpty(jsonObject.getString(fieldName)); } } | StripeJsonUtils { @Nullable static String getString( @NonNull JSONObject jsonObject, @NonNull @Size(min = 1) String fieldName) throws JSONException { return nullIfNullOrEmpty(jsonObject.getString(fieldName)); } } | StripeJsonUtils { @Nullable static String getString( @NonNull JSONObject jsonObject, @NonNull @Size(min = 1) String fieldName) throws JSONException { return nullIfNullOrEmpty(jsonObject.getString(fieldName)); } } |
@Test public void jsonObjectToMapWithoutKeys_whenAllKeysGiven_returnsNull() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("a_key", "a_value"); jsonObject.put("b_key", "b_value"); } catch (JSONException unexpected) { fail("Unexpected error: " + unexpected.getLocalizedMessage()); } Set<String> omitKeys... | @Nullable static Map<String, Object> jsonObjectToMapWithoutKeys( @Nullable JSONObject jsonObject, @Nullable Set<String> omitKeys) { if (jsonObject == null) { return null; } Set<String> keysToOmit = omitKeys == null ? new HashSet<String>() : omitKeys; Map<String, Object> map = new HashMap<>(); Iterator<String> keyIterat... | StripeSourceTypeModel extends StripeJsonModel { @Nullable static Map<String, Object> jsonObjectToMapWithoutKeys( @Nullable JSONObject jsonObject, @Nullable Set<String> omitKeys) { if (jsonObject == null) { return null; } Set<String> keysToOmit = omitKeys == null ? new HashSet<String>() : omitKeys; Map<String, Object> m... | StripeSourceTypeModel extends StripeJsonModel { @Nullable static Map<String, Object> jsonObjectToMapWithoutKeys( @Nullable JSONObject jsonObject, @Nullable Set<String> omitKeys) { if (jsonObject == null) { return null; } Set<String> keysToOmit = omitKeys == null ? new HashSet<String>() : omitKeys; Map<String, Object> m... | StripeSourceTypeModel extends StripeJsonModel { @Nullable static Map<String, Object> jsonObjectToMapWithoutKeys( @Nullable JSONObject jsonObject, @Nullable Set<String> omitKeys) { if (jsonObject == null) { return null; } Set<String> keysToOmit = omitKeys == null ? new HashSet<String>() : omitKeys; Map<String, Object> m... | StripeSourceTypeModel extends StripeJsonModel { @Nullable static Map<String, Object> jsonObjectToMapWithoutKeys( @Nullable JSONObject jsonObject, @Nullable Set<String> omitKeys) { if (jsonObject == null) { return null; } Set<String> keysToOmit = omitKeys == null ? new HashSet<String>() : omitKeys; Map<String, Object> m... |
@Test public void jsonObjectToMapWithoutKeys_whenOtherKeysGiven_returnsFullMap() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("a_key", "a_value"); jsonObject.put("b_key", "b_value"); } catch (JSONException unexpected) { fail("Unexpected error: " + unexpected.getLocalizedMessage()); } Set<String> omi... | @Nullable static Map<String, Object> jsonObjectToMapWithoutKeys( @Nullable JSONObject jsonObject, @Nullable Set<String> omitKeys) { if (jsonObject == null) { return null; } Set<String> keysToOmit = omitKeys == null ? new HashSet<String>() : omitKeys; Map<String, Object> map = new HashMap<>(); Iterator<String> keyIterat... | StripeSourceTypeModel extends StripeJsonModel { @Nullable static Map<String, Object> jsonObjectToMapWithoutKeys( @Nullable JSONObject jsonObject, @Nullable Set<String> omitKeys) { if (jsonObject == null) { return null; } Set<String> keysToOmit = omitKeys == null ? new HashSet<String>() : omitKeys; Map<String, Object> m... | StripeSourceTypeModel extends StripeJsonModel { @Nullable static Map<String, Object> jsonObjectToMapWithoutKeys( @Nullable JSONObject jsonObject, @Nullable Set<String> omitKeys) { if (jsonObject == null) { return null; } Set<String> keysToOmit = omitKeys == null ? new HashSet<String>() : omitKeys; Map<String, Object> m... | StripeSourceTypeModel extends StripeJsonModel { @Nullable static Map<String, Object> jsonObjectToMapWithoutKeys( @Nullable JSONObject jsonObject, @Nullable Set<String> omitKeys) { if (jsonObject == null) { return null; } Set<String> keysToOmit = omitKeys == null ? new HashSet<String>() : omitKeys; Map<String, Object> m... | StripeSourceTypeModel extends StripeJsonModel { @Nullable static Map<String, Object> jsonObjectToMapWithoutKeys( @Nullable JSONObject jsonObject, @Nullable Set<String> omitKeys) { if (jsonObject == null) { return null; } Set<String> keysToOmit = omitKeys == null ? new HashSet<String>() : omitKeys; Map<String, Object> m... |
@Test public void putAdditionalFieldsIntoJsonObject_whenHasFields_putsThemIntoObject() { JSONObject jsonObject = new JSONObject(); Map<String, Object> additionalFields = new HashMap<>(); additionalFields.put("a_key", "a_value"); additionalFields.put("b_key", "b_value"); putAdditionalFieldsIntoJsonObject(jsonObject, add... | static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { try { if (additionalFields.get(key) != null) { js... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { t... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { t... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { t... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { t... |
@Test public void putAdditionalFieldsIntoJsonObject_whenHasDuplicateFields_putsThemIntoObject() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("a_key", "original"); } catch (JSONException unexpected) { fail("Unexpected exception: " + unexpected); } Map<String, Object> additionalFields = new HashMap<>(... | static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { try { if (additionalFields.get(key) != null) { js... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { t... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { t... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { t... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { t... |
@Test public void putAdditionalFieldsIntoJsonObject_whenNoFieldsArePassed_doesNothing() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("a", "a_value"); } catch (JSONException unexpected) { fail("Unexpected error: " + unexpected.getLocalizedMessage()); } Map<String, Object> emptyMap = new HashMap<>(); ... | static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { try { if (additionalFields.get(key) != null) { js... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { t... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { t... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { t... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { t... |
@Test public void putAdditionalFieldsIntoJsonObject_whenNullPassedInEitherArgument_doesNothing() { Map<String, Object> littleMap = new HashMap<String, Object>() {{ put("a", "a_value"); }}; JSONObject jsonObject = new JSONObject(); putAdditionalFieldsIntoJsonObject(null, littleMap); putAdditionalFieldsIntoJsonObject(jso... | static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { try { if (additionalFields.get(key) != null) { js... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { t... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { t... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { t... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { t... |
@Test public void putAdditionalFieldsIntoMap_whenGivenFields_putsThemIntoTheMap() { Map<String, Object> originalMap = new HashMap<String, Object>() {{ put("a", "a_val"); put("b", "b_val"); }}; Map<String, Object> extraMap = new HashMap<String, Object>() {{ put("c", 100); put("d", false); }}; putAdditionalFieldsIntoMap(... | static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, additionalFields.get(key)); } } | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, a... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, a... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, a... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, a... |
@Test public void putAdditionalFieldsIntoMap_whenGivenDuplicateFields_putsThemIntoTheMap() { Map<String, Object> originalMap = new HashMap<String, Object>() {{ put("a", "a_val"); put("b", "b_val"); }}; Map<String, Object> extraMap = new HashMap<String, Object>() {{ put("a", 100); put("d", false); }}; putAdditionalField... | static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, additionalFields.get(key)); } } | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, a... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, a... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, a... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, a... |
@Test public void putAdditionalFieldsIntoMap_whenGivenEmptyMap_doesNothing() { Map<String, Object> originalMap = new HashMap<String, Object>() {{ put("a", "a_val"); put("b", "b_val"); }}; Map<String, Object> emptyMap = new HashMap<>(); putAdditionalFieldsIntoMap(originalMap, emptyMap); assertEquals(2, originalMap.size(... | static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, additionalFields.get(key)); } } | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, a... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, a... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, a... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, a... |
@Test public void putAdditionalFieldsIntoMap_whenGivenNullForEitherInput_doesNothing() { Map<String, Object> littleMap = new HashMap<String, Object>() {{ put("a", "b"); }}; putAdditionalFieldsIntoMap(null, littleMap); putAdditionalFieldsIntoMap(littleMap, null); assertEquals(1, littleMap.size()); assertEquals("b", litt... | static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, additionalFields.get(key)); } } | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, a... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, a... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, a... | StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, a... |
@Test(expected = JSONException.class) public void getString_whenFieldNotPresent_throwsJsonException() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("key", "value"); StripeJsonUtils.getString(jsonObject, "differentKey"); fail("Expected an exception."); } | @Nullable static String getString( @NonNull JSONObject jsonObject, @NonNull @Size(min = 1) String fieldName) throws JSONException { return nullIfNullOrEmpty(jsonObject.getString(fieldName)); } | StripeJsonUtils { @Nullable static String getString( @NonNull JSONObject jsonObject, @NonNull @Size(min = 1) String fieldName) throws JSONException { return nullIfNullOrEmpty(jsonObject.getString(fieldName)); } } | StripeJsonUtils { @Nullable static String getString( @NonNull JSONObject jsonObject, @NonNull @Size(min = 1) String fieldName) throws JSONException { return nullIfNullOrEmpty(jsonObject.getString(fieldName)); } } | StripeJsonUtils { @Nullable static String getString( @NonNull JSONObject jsonObject, @NonNull @Size(min = 1) String fieldName) throws JSONException { return nullIfNullOrEmpty(jsonObject.getString(fieldName)); } } | StripeJsonUtils { @Nullable static String getString( @NonNull JSONObject jsonObject, @NonNull @Size(min = 1) String fieldName) throws JSONException { return nullIfNullOrEmpty(jsonObject.getString(fieldName)); } } |
@Test public void fromJsonString_backToJson_createsIdenticalElement() { try { JSONObject rawConversion = new JSONObject(EXAMPLE_JSON_SOURCE_WITHOUT_NULLS); JSONObject actualObject = mSource.toJson(); assertJsonEquals(rawConversion, actualObject); } catch (JSONException jsonException) { fail("Test Data failure: " + json... | @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); try { putStringIfNotNull(jsonObject, FIELD_ID, mId); jsonObject.put(FIELD_OBJECT, VALUE_SOURCE); jsonObject.put(FIELD_AMOUNT, mAmount); putStringIfNotNull(jsonObject, FIELD_CLIENT_SECRET, mClientSecret); putStripeJsonModelIfNotNul... | Source extends StripeJsonModel implements StripePaymentSource { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); try { putStringIfNotNull(jsonObject, FIELD_ID, mId); jsonObject.put(FIELD_OBJECT, VALUE_SOURCE); jsonObject.put(FIELD_AMOUNT, mAmount); putStringIfNotNull(jsonObject,... | Source extends StripeJsonModel implements StripePaymentSource { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); try { putStringIfNotNull(jsonObject, FIELD_ID, mId); jsonObject.put(FIELD_OBJECT, VALUE_SOURCE); jsonObject.put(FIELD_AMOUNT, mAmount); putStringIfNotNull(jsonObject,... | Source extends StripeJsonModel implements StripePaymentSource { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); try { putStringIfNotNull(jsonObject, FIELD_ID, mId); jsonObject.put(FIELD_OBJECT, VALUE_SOURCE); jsonObject.put(FIELD_AMOUNT, mAmount); putStringIfNotNull(jsonObject,... | Source extends StripeJsonModel implements StripePaymentSource { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); try { putStringIfNotNull(jsonObject, FIELD_ID, mId); jsonObject.put(FIELD_OBJECT, VALUE_SOURCE); jsonObject.put(FIELD_AMOUNT, mAmount); putStringIfNotNull(jsonObject,... |
@Test public void addNameAndVersion_whenApplicationContextIsNull_addsNoContextValues() { Context context = mock(Context.class); when(context.getApplicationContext()).thenReturn(null); Map<String, Object> paramsMap = new HashMap<>(); LoggingUtils.addNameAndVersion(paramsMap, context); assertEquals(LoggingUtils.NO_CONTEX... | static void addNameAndVersion( @NonNull Map<String, Object> paramsObject, @NonNull Context context) { Context applicationContext = context.getApplicationContext(); if (applicationContext != null && applicationContext.getPackageManager() != null) { try { PackageInfo info = applicationContext.getPackageManager().getPacka... | LoggingUtils { static void addNameAndVersion( @NonNull Map<String, Object> paramsObject, @NonNull Context context) { Context applicationContext = context.getApplicationContext(); if (applicationContext != null && applicationContext.getPackageManager() != null) { try { PackageInfo info = applicationContext.getPackageMan... | LoggingUtils { static void addNameAndVersion( @NonNull Map<String, Object> paramsObject, @NonNull Context context) { Context applicationContext = context.getApplicationContext(); if (applicationContext != null && applicationContext.getPackageManager() != null) { try { PackageInfo info = applicationContext.getPackageMan... | LoggingUtils { static void addNameAndVersion( @NonNull Map<String, Object> paramsObject, @NonNull Context context) { Context applicationContext = context.getApplicationContext(); if (applicationContext != null && applicationContext.getPackageManager() != null) { try { PackageInfo info = applicationContext.getPackageMan... | LoggingUtils { static void addNameAndVersion( @NonNull Map<String, Object> paramsObject, @NonNull Context context) { Context applicationContext = context.getApplicationContext(); if (applicationContext != null && applicationContext.getPackageManager() != null) { try { PackageInfo info = applicationContext.getPackageMan... |
@Test public void addNameAndVersion_whenPackageInfoNotFound_addsUnknownValues() { Context context = mock(Context.class); when(context.getApplicationContext()).thenReturn(context); final String dummyName = "dummy_name"; PackageManager manager = mock(PackageManager.class); when(context.getPackageManager()).thenReturn(man... | static void addNameAndVersion( @NonNull Map<String, Object> paramsObject, @NonNull Context context) { Context applicationContext = context.getApplicationContext(); if (applicationContext != null && applicationContext.getPackageManager() != null) { try { PackageInfo info = applicationContext.getPackageManager().getPacka... | LoggingUtils { static void addNameAndVersion( @NonNull Map<String, Object> paramsObject, @NonNull Context context) { Context applicationContext = context.getApplicationContext(); if (applicationContext != null && applicationContext.getPackageManager() != null) { try { PackageInfo info = applicationContext.getPackageMan... | LoggingUtils { static void addNameAndVersion( @NonNull Map<String, Object> paramsObject, @NonNull Context context) { Context applicationContext = context.getApplicationContext(); if (applicationContext != null && applicationContext.getPackageManager() != null) { try { PackageInfo info = applicationContext.getPackageMan... | LoggingUtils { static void addNameAndVersion( @NonNull Map<String, Object> paramsObject, @NonNull Context context) { Context applicationContext = context.getApplicationContext(); if (applicationContext != null && applicationContext.getPackageManager() != null) { try { PackageInfo info = applicationContext.getPackageMan... | LoggingUtils { static void addNameAndVersion( @NonNull Map<String, Object> paramsObject, @NonNull Context context) { Context applicationContext = context.getApplicationContext(); if (applicationContext != null && applicationContext.getPackageManager() != null) { try { PackageInfo info = applicationContext.getPackageMan... |
@Test public void getEventParamName_withTokenCreation_createsExpectedParameter() { final String expectedEventParam = "stripe_android.token_creation"; assertEquals(expectedEventParam, LoggingUtils.getEventParamName(LoggingUtils.EVENT_TOKEN_CREATION)); } | @NonNull static String getEventParamName(@NonNull @LoggingEventName String eventName) { return ANALYTICS_NAME + '.' + eventName; } | LoggingUtils { @NonNull static String getEventParamName(@NonNull @LoggingEventName String eventName) { return ANALYTICS_NAME + '.' + eventName; } } | LoggingUtils { @NonNull static String getEventParamName(@NonNull @LoggingEventName String eventName) { return ANALYTICS_NAME + '.' + eventName; } } | LoggingUtils { @NonNull static String getEventParamName(@NonNull @LoggingEventName String eventName) { return ANALYTICS_NAME + '.' + eventName; } } | LoggingUtils { @NonNull static String getEventParamName(@NonNull @LoggingEventName String eventName) { return ANALYTICS_NAME + '.' + eventName; } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.