method2testcases
stringlengths
118
3.08k
### Question: HttpConnection implements Connection { public Connection timeout(int millis) { req.timeout(millis); return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void timeout() { Connection con = HttpConnection.connect("http: assertEquals(30 * 1000, con.request().timeout()); con.timeout(1000); assertEquals(1000, con.request().timeout()); }
### Question: HttpConnection implements Connection { public Connection referrer(String referrer) { Validate.notNull(referrer, "Referrer must not be null"); req.header("Referer", referrer); return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void referrer() { Connection con = HttpConnection.connect("http: con.referrer("http: assertEquals("http: }
### Question: HttpConnection implements Connection { public Connection method(Method method) { req.method(method); return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void method() { Connection con = HttpConnection.connect("http: assertEquals(Connection.Method.GET, con.request().method()); con.method(Connection.Method.POST); assertEquals(Connection.Method.POST, con.request().method()); }
### Question: HttpConnection implements Connection { public Connection data(String key, String value) { req.data(KeyVal.create(key, value)); return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void data() { Connection con = HttpConnection.connect("http: con.data("Name", "Val", "Foo", "bar"); Collection<Connection.KeyVal> values = con.request().data(); Object[] data = values.toArray(); Connection.KeyVal one = (Connection.KeyVal) data[0]; Connection.KeyVal two = (Connection.KeyVal) data[1]; assertEquals("Name", one.key()); assertEquals("Val", one.value()); assertEquals("Foo", two.key()); assertEquals("bar", two.value()); }
### Question: IntegerListToStringFunction implements GetterFunction<List<Integer>, String> { @Nullable @Override public String apply(@Nullable List<Integer> input) { if (input == null) { return null; } if (input.size() == 0) { return ""; } StringBuilder builder = new StringBuilder(); builder.append(input.get(0)); for (int i = 1; i < input.size(); i++) { builder.append(SEPARATOR).append(input.get(i)); } return builder.toString(); } @Nullable @Override String apply(@Nullable List<Integer> input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("getX"); GetterInvoker invoker = FunctionalGetterInvoker.create("x", m); a.setX(Lists.newArrayList(1, 2, 3)); assertThat((String) invoker.invoke(a), is("1,2,3")); a.setX(null); assertThat(invoker.invoke(a), nullValue()); a.setX(new ArrayList<Integer>()); assertThat((String) invoker.invoke(a), is("")); }
### Question: HttpConnection implements Connection { public Connection cookie(String name, String value) { req.cookie(name, value); return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void cookie() { Connection con = HttpConnection.connect("http: con.cookie("Name", "Val"); assertEquals("Val", con.request().cookie("Name")); }
### Question: HttpConnection implements Connection { public Connection requestBody(String body) { req.requestBody(body); return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void requestBody() { Connection con = HttpConnection.connect("http: con.requestBody("foo"); assertEquals("foo", con.request().requestBody()); }
### Question: HttpConnection implements Connection { private static String encodeUrl(String url) { try { URL u = new URL(url); return encodeUrl(u).toExternalForm(); } catch (Exception e) { return url; } } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void encodeUrl() throws MalformedURLException { URL url1 = new URL("http: URL url2 = HttpConnection.encodeUrl(url1); assertEquals("http: }
### Question: StringUtil { public static String join(Collection strings, String sep) { return join(strings.iterator(), sep); } static String join(Collection strings, String sep); static String join(Iterator strings, String sep); static String padding(int width); static boolean isBlank(String string); static boolean isNumeric(String string); static boolean isWhitespace(int c); static boolean isActuallyWhitespace(int c); static String normaliseWhitespace(String string); static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading); static boolean in(String needle, String... haystack); static boolean inSorted(String needle, String[] haystack); static URL resolve(URL base, String relUrl); static String resolve(final String baseUrl, final String relUrl); static StringBuilder stringBuilder(); }### Answer: @Test public void join() { assertEquals("", StringUtil.join(Arrays.asList(""), " ")); assertEquals("one", StringUtil.join(Arrays.asList("one"), " ")); assertEquals("one two three", StringUtil.join(Arrays.asList("one", "two", "three"), " ")); }
### Question: StringUtil { public static String padding(int width) { if (width < 0) throw new IllegalArgumentException("width must be > 0"); if (width < padding.length) return padding[width]; char[] out = new char[width]; for (int i = 0; i < width; i++) out[i] = ' '; return String.valueOf(out); } static String join(Collection strings, String sep); static String join(Iterator strings, String sep); static String padding(int width); static boolean isBlank(String string); static boolean isNumeric(String string); static boolean isWhitespace(int c); static boolean isActuallyWhitespace(int c); static String normaliseWhitespace(String string); static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading); static boolean in(String needle, String... haystack); static boolean inSorted(String needle, String[] haystack); static URL resolve(URL base, String relUrl); static String resolve(final String baseUrl, final String relUrl); static StringBuilder stringBuilder(); }### Answer: @Test public void padding() { assertEquals("", StringUtil.padding(0)); assertEquals(" ", StringUtil.padding(1)); assertEquals(" ", StringUtil.padding(2)); assertEquals(" ", StringUtil.padding(15)); assertEquals(" ", StringUtil.padding(45)); }
### Question: StringUtil { public static boolean isBlank(String string) { if (string == null || string.length() == 0) return true; int l = string.length(); for (int i = 0; i < l; i++) { if (!StringUtil.isWhitespace(string.codePointAt(i))) return false; } return true; } static String join(Collection strings, String sep); static String join(Iterator strings, String sep); static String padding(int width); static boolean isBlank(String string); static boolean isNumeric(String string); static boolean isWhitespace(int c); static boolean isActuallyWhitespace(int c); static String normaliseWhitespace(String string); static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading); static boolean in(String needle, String... haystack); static boolean inSorted(String needle, String[] haystack); static URL resolve(URL base, String relUrl); static String resolve(final String baseUrl, final String relUrl); static StringBuilder stringBuilder(); }### Answer: @Test public void isBlank() { assertTrue(StringUtil.isBlank(null)); assertTrue(StringUtil.isBlank("")); assertTrue(StringUtil.isBlank(" ")); assertTrue(StringUtil.isBlank(" \r\n ")); assertFalse(StringUtil.isBlank("hello")); assertFalse(StringUtil.isBlank(" hello ")); }
### Question: StringUtil { public static boolean isNumeric(String string) { if (string == null || string.length() == 0) return false; int l = string.length(); for (int i = 0; i < l; i++) { if (!Character.isDigit(string.codePointAt(i))) return false; } return true; } static String join(Collection strings, String sep); static String join(Iterator strings, String sep); static String padding(int width); static boolean isBlank(String string); static boolean isNumeric(String string); static boolean isWhitespace(int c); static boolean isActuallyWhitespace(int c); static String normaliseWhitespace(String string); static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading); static boolean in(String needle, String... haystack); static boolean inSorted(String needle, String[] haystack); static URL resolve(URL base, String relUrl); static String resolve(final String baseUrl, final String relUrl); static StringBuilder stringBuilder(); }### Answer: @Test public void isNumeric() { assertFalse(StringUtil.isNumeric(null)); assertFalse(StringUtil.isNumeric(" ")); assertFalse(StringUtil.isNumeric("123 546")); assertFalse(StringUtil.isNumeric("hello")); assertFalse(StringUtil.isNumeric("123.334")); assertTrue(StringUtil.isNumeric("1")); assertTrue(StringUtil.isNumeric("1234")); }
### Question: StringUtil { public static boolean isWhitespace(int c){ return c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r'; } static String join(Collection strings, String sep); static String join(Iterator strings, String sep); static String padding(int width); static boolean isBlank(String string); static boolean isNumeric(String string); static boolean isWhitespace(int c); static boolean isActuallyWhitespace(int c); static String normaliseWhitespace(String string); static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading); static boolean in(String needle, String... haystack); static boolean inSorted(String needle, String[] haystack); static URL resolve(URL base, String relUrl); static String resolve(final String baseUrl, final String relUrl); static StringBuilder stringBuilder(); }### Answer: @Test public void isWhitespace() { assertTrue(StringUtil.isWhitespace('\t')); assertTrue(StringUtil.isWhitespace('\n')); assertTrue(StringUtil.isWhitespace('\r')); assertTrue(StringUtil.isWhitespace('\f')); assertTrue(StringUtil.isWhitespace(' ')); assertFalse(StringUtil.isWhitespace('\u00a0')); assertFalse(StringUtil.isWhitespace('\u2000')); assertFalse(StringUtil.isWhitespace('\u3000')); }
### Question: StringUtil { public static String normaliseWhitespace(String string) { StringBuilder sb = StringUtil.stringBuilder(); appendNormalisedWhitespace(sb, string, false); return sb.toString(); } static String join(Collection strings, String sep); static String join(Iterator strings, String sep); static String padding(int width); static boolean isBlank(String string); static boolean isNumeric(String string); static boolean isWhitespace(int c); static boolean isActuallyWhitespace(int c); static String normaliseWhitespace(String string); static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading); static boolean in(String needle, String... haystack); static boolean inSorted(String needle, String[] haystack); static URL resolve(URL base, String relUrl); static String resolve(final String baseUrl, final String relUrl); static StringBuilder stringBuilder(); }### Answer: @Test public void normaliseWhiteSpace() { assertEquals(" ", normaliseWhitespace(" \r \n \r\n")); assertEquals(" hello there ", normaliseWhitespace(" hello \r \n there \n")); assertEquals("hello", normaliseWhitespace("hello")); assertEquals("hello there", normaliseWhitespace("hello\nthere")); } @Test public void normaliseWhiteSpaceHandlesHighSurrogates() { String test71540chars = "\ud869\udeb2\u304b\u309a 1"; String test71540charsExpectedSingleWhitespace = "\ud869\udeb2\u304b\u309a 1"; assertEquals(test71540charsExpectedSingleWhitespace, normaliseWhitespace(test71540chars)); String extractedText = Jsoup.parse(test71540chars).text(); assertEquals(test71540charsExpectedSingleWhitespace, extractedText); }
### Question: IntegerToEnumFunction implements RuntimeSetterFunction<Integer, Enum> { @Nullable @Override public Enum apply(@Nullable Integer input, Type runtimeOutputType) { if (input == null) { return null; } Class<?> rawType = TypeToken.of(runtimeOutputType).getRawType(); EnumSet<?> es = cache.get(rawType); for (Enum<?> e : es) { if (e.ordinal() == input) { return e; } } throw new IllegalStateException("cant' trans Integer(" + input + ") to " + runtimeOutputType); } @Nullable @Override Enum apply(@Nullable Integer input, Type runtimeOutputType); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("setE", E.class); SetterInvoker invoker = FunctionalSetterInvoker.create("e", m); invoker.invoke(a, 2); assertThat(a.getE(), is(E.Z)); Method m2 = A.class.getDeclaredMethod("setE2", E2.class); SetterInvoker invoker2 = FunctionalSetterInvoker.create("e2", m2); invoker2.invoke(a, 2); assertThat(a.getE2(), is(E2.C)); }
### Question: StringUtil { public static URL resolve(URL base, String relUrl) throws MalformedURLException { if (relUrl.startsWith("?")) relUrl = base.getPath() + relUrl; if (relUrl.indexOf('.') == 0 && base.getFile().indexOf('/') != 0) { base = new URL(base.getProtocol(), base.getHost(), base.getPort(), "/" + base.getFile()); } return new URL(base, relUrl); } static String join(Collection strings, String sep); static String join(Iterator strings, String sep); static String padding(int width); static boolean isBlank(String string); static boolean isNumeric(String string); static boolean isWhitespace(int c); static boolean isActuallyWhitespace(int c); static String normaliseWhitespace(String string); static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading); static boolean in(String needle, String... haystack); static boolean inSorted(String needle, String[] haystack); static URL resolve(URL base, String relUrl); static String resolve(final String baseUrl, final String relUrl); static StringBuilder stringBuilder(); }### Answer: @Test public void resolvesRelativeUrls() { assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("https: assertEquals("http: assertEquals("https: assertEquals("https: assertEquals("https: assertEquals("https: assertEquals("https: assertEquals("", resolve("wrong", "also wrong")); assertEquals("ftp: assertEquals("ftp: assertEquals("ftp: }
### Question: StringToEnumFunction implements RuntimeSetterFunction<String, Enum> { @Nullable @Override public Enum apply(@Nullable String input, Type runtimeOutputType) { if (input == null) { return null; } Class rawType = TypeToken.of(runtimeOutputType).getRawType(); Enum r = Enum.valueOf(rawType, input); return r; } @Nullable @Override Enum apply(@Nullable String input, Type runtimeOutputType); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("setE", E.class); SetterInvoker invoker = FunctionalSetterInvoker.create("e", m); invoker.invoke(a, "Y"); assertThat(a.getE(), is(E.Y)); }
### Question: DataUtil { static String mimeBoundary() { final StringBuilder mime = new StringBuilder(boundaryLength); final Random rand = new Random(); for (int i = 0; i < boundaryLength; i++) { mime.append(mimeBoundaryChars[rand.nextInt(mimeBoundaryChars.length)]); } return mime.toString(); } private DataUtil(); static Document load(File in, String charsetName, String baseUri); static Document load(InputStream in, String charsetName, String baseUri); static Document load(InputStream in, String charsetName, String baseUri, Parser parser); static ByteBuffer readToByteBuffer(InputStream inStream, int maxSize); }### Answer: @Test public void generatesMimeBoundaries() { String m1 = DataUtil.mimeBoundary(); String m2 = DataUtil.mimeBoundary(); assertEquals(DataUtil.boundaryLength, m1.length()); assertEquals(DataUtil.boundaryLength, m2.length()); assertNotSame(m1, m2); }
### Question: EnumToStringFunction implements GetterFunction<Enum, String> { @Nullable @Override public String apply(@Nullable Enum input) { return input == null ? null : input.name(); } @Nullable @Override String apply(@Nullable Enum input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); a.setE(E.Y); Method m = A.class.getDeclaredMethod("getE"); GetterInvoker invoker = FunctionalGetterInvoker.create("e", m); String r = (String) invoker.invoke(a); assertThat(r, is("Y")); }
### Question: FixedOrderComparator implements Comparator<T>, Serializable { public boolean add(final T obj) { checkLocked(); final Integer position = map.put(obj, Integer.valueOf(counter++)); return position == null; } FixedOrderComparator(); FixedOrderComparator(final T... items); FixedOrderComparator(final List<T> items); boolean isLocked(); UnknownObjectBehavior getUnknownObjectBehavior(); void setUnknownObjectBehavior(final UnknownObjectBehavior unknownObjectBehavior); boolean add(final T obj); boolean addAsEqual(final T existingObj, final T newObj); @Override int compare(final T obj1, final T obj2); @Override int hashCode(); @Override boolean equals(final Object object); }### Answer: @Test public void testConstructorPlusAdd() { final FixedOrderComparator<String> comparator = new FixedOrderComparator<String>(); for (final String topCitie : topCities) { comparator.add(topCitie); } final String[] keys = topCities.clone(); assertComparatorYieldsOrder(keys, comparator); }
### Question: FixedOrderComparator implements Comparator<T>, Serializable { public boolean addAsEqual(final T existingObj, final T newObj) { checkLocked(); final Integer position = map.get(existingObj); if (position == null) { throw new IllegalArgumentException(existingObj + " not known to " + this); } final Integer result = map.put(newObj, position); return result == null; } FixedOrderComparator(); FixedOrderComparator(final T... items); FixedOrderComparator(final List<T> items); boolean isLocked(); UnknownObjectBehavior getUnknownObjectBehavior(); void setUnknownObjectBehavior(final UnknownObjectBehavior unknownObjectBehavior); boolean add(final T obj); boolean addAsEqual(final T existingObj, final T newObj); @Override int compare(final T obj1, final T obj2); @Override int hashCode(); @Override boolean equals(final Object object); }### Answer: @Test public void testAddAsEqual() { final FixedOrderComparator<String> comparator = new FixedOrderComparator<String>(topCities); comparator.addAsEqual("New York", "Minneapolis"); assertEquals(0, comparator.compare("New York", "Minneapolis")); assertEquals(-1, comparator.compare("Tokyo", "Minneapolis")); assertEquals(1, comparator.compare("Shanghai", "Minneapolis")); }
### Question: EnumToIntegerFunction implements GetterFunction<Enum, Integer> { @Nullable @Override public Integer apply(@Nullable Enum input) { return input == null ? null : input.ordinal(); } @Nullable @Override Integer apply(@Nullable Enum input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); a.setE(E.Y); Method m = A.class.getDeclaredMethod("getE"); GetterInvoker invoker = FunctionalGetterInvoker.create("e", m); Integer r = (Integer) invoker.invoke(a); assertThat(r, is(1)); }
### Question: TypeToken extends TypeCapture<T> implements Serializable { public static <T> TypeToken<T> of(Class<T> type) { return new SimpleTypeToken<T>(type); } protected TypeToken(); private TypeToken(Type type); static TypeToken<T> of(Class<T> type); static TypeToken<?> of(Type type); final Class<? super T> getRawType(); final Type getType(); final TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg); final TypeToken<?> resolveType(Type type); final boolean isAssignableFrom(TypeToken<?> type); final boolean isAssignableFrom(Type type); final boolean isArray(); final boolean isPrimitive(); final TypeToken<T> wrap(); @Nullable final TypeToken<?> getComponentType(); @Override boolean equals(@Nullable Object o); @Override int hashCode(); @Override String toString(); TypeToken<?> resolveFatherClass(Class<?> clazz); TokenTuple resolveFatherClassTuple(Class<?> clazz); }### Answer: @Test public void testOf() throws Exception { TypeToken<String> token = TypeToken.of(String.class); assertThat(token.getType().equals(String.class), is(true)); assertThat(token.getRawType().equals(String.class), is(true)); }
### Question: BagUtils { public static <E> Bag<E> synchronizedBag(final Bag<E> bag) { return SynchronizedBag.synchronizedBag(bag); } private BagUtils(); static Bag<E> synchronizedBag(final Bag<E> bag); static Bag<E> unmodifiableBag(final Bag<? extends E> bag); static Bag<E> predicatedBag(final Bag<E> bag, final Predicate<? super E> predicate); static Bag<E> transformingBag(final Bag<E> bag, final Transformer<? super E, ? extends E> transformer); static Bag<E> collectionBag(final Bag<E> bag); static SortedBag<E> synchronizedSortedBag(final SortedBag<E> bag); static SortedBag<E> unmodifiableSortedBag(final SortedBag<E> bag); static SortedBag<E> predicatedSortedBag(final SortedBag<E> bag, final Predicate<? super E> predicate); static SortedBag<E> transformingSortedBag(final SortedBag<E> bag, final Transformer<? super E, ? extends E> transformer); @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type static Bag<E> emptyBag(); @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type static SortedBag<E> emptySortedBag(); @SuppressWarnings("rawtypes") // OK, empty bag is compatible with any type static final Bag EMPTY_BAG; @SuppressWarnings("rawtypes") // OK, empty bag is compatible with any type static final Bag EMPTY_SORTED_BAG; }### Answer: @Test public void testSynchronizedBag() { Bag<Object> bag = BagUtils.synchronizedBag(new HashBag<Object>()); assertTrue("Returned object should be a SynchronizedBag.", bag instanceof SynchronizedBag); try { BagUtils.synchronizedBag(null); fail("Expecting NullPointerException for null bag."); } catch (final NullPointerException ex) { } }
### Question: BagUtils { public static <E> Bag<E> unmodifiableBag(final Bag<? extends E> bag) { return UnmodifiableBag.unmodifiableBag(bag); } private BagUtils(); static Bag<E> synchronizedBag(final Bag<E> bag); static Bag<E> unmodifiableBag(final Bag<? extends E> bag); static Bag<E> predicatedBag(final Bag<E> bag, final Predicate<? super E> predicate); static Bag<E> transformingBag(final Bag<E> bag, final Transformer<? super E, ? extends E> transformer); static Bag<E> collectionBag(final Bag<E> bag); static SortedBag<E> synchronizedSortedBag(final SortedBag<E> bag); static SortedBag<E> unmodifiableSortedBag(final SortedBag<E> bag); static SortedBag<E> predicatedSortedBag(final SortedBag<E> bag, final Predicate<? super E> predicate); static SortedBag<E> transformingSortedBag(final SortedBag<E> bag, final Transformer<? super E, ? extends E> transformer); @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type static Bag<E> emptyBag(); @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type static SortedBag<E> emptySortedBag(); @SuppressWarnings("rawtypes") // OK, empty bag is compatible with any type static final Bag EMPTY_BAG; @SuppressWarnings("rawtypes") // OK, empty bag is compatible with any type static final Bag EMPTY_SORTED_BAG; }### Answer: @Test public void testUnmodifiableBag() { Bag<Object> bag = BagUtils.unmodifiableBag(new HashBag<Object>()); assertTrue("Returned object should be an UnmodifiableBag.", bag instanceof UnmodifiableBag); try { BagUtils.unmodifiableBag(null); fail("Expecting NullPointerException for null bag."); } catch (final NullPointerException ex) { } assertSame("UnmodifiableBag shall not be decorated", bag, BagUtils.unmodifiableBag(bag)); }
### Question: BagUtils { public static <E> SortedBag<E> synchronizedSortedBag(final SortedBag<E> bag) { return SynchronizedSortedBag.synchronizedSortedBag(bag); } private BagUtils(); static Bag<E> synchronizedBag(final Bag<E> bag); static Bag<E> unmodifiableBag(final Bag<? extends E> bag); static Bag<E> predicatedBag(final Bag<E> bag, final Predicate<? super E> predicate); static Bag<E> transformingBag(final Bag<E> bag, final Transformer<? super E, ? extends E> transformer); static Bag<E> collectionBag(final Bag<E> bag); static SortedBag<E> synchronizedSortedBag(final SortedBag<E> bag); static SortedBag<E> unmodifiableSortedBag(final SortedBag<E> bag); static SortedBag<E> predicatedSortedBag(final SortedBag<E> bag, final Predicate<? super E> predicate); static SortedBag<E> transformingSortedBag(final SortedBag<E> bag, final Transformer<? super E, ? extends E> transformer); @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type static Bag<E> emptyBag(); @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type static SortedBag<E> emptySortedBag(); @SuppressWarnings("rawtypes") // OK, empty bag is compatible with any type static final Bag EMPTY_BAG; @SuppressWarnings("rawtypes") // OK, empty bag is compatible with any type static final Bag EMPTY_SORTED_BAG; }### Answer: @Test public void testSynchronizedSortedBag() { Bag<Object> bag = BagUtils.synchronizedSortedBag(new TreeBag<Object>()); assertTrue("Returned object should be a SynchronizedSortedBag.", bag instanceof SynchronizedSortedBag); try { BagUtils.synchronizedSortedBag(null); fail("Expecting NullPointerException for null bag."); } catch (final NullPointerException ex) { } }
### Question: TrieUtils { public static <K, V> Trie<K, V> unmodifiableTrie(final Trie<K, ? extends V> trie) { return UnmodifiableTrie.unmodifiableTrie(trie); } private TrieUtils(); static Trie<K, V> unmodifiableTrie(final Trie<K, ? extends V> trie); }### Answer: @Test public void testUnmodifiableTrie() { Trie<String, Object> trie = TrieUtils.unmodifiableTrie(new PatriciaTrie<Object>()); assertTrue("Returned object should be an UnmodifiableTrie.", trie instanceof UnmodifiableTrie); try { TrieUtils.unmodifiableTrie(null); fail("Expecting NullPointerException for null trie."); } catch (final NullPointerException ex) { } assertSame("UnmodifiableTrie shall not be decorated", trie, TrieUtils.unmodifiableTrie(trie)); }
### Question: QueueUtils { public static <E> Queue<E> unmodifiableQueue(final Queue<? extends E> queue) { return UnmodifiableQueue.unmodifiableQueue(queue); } private QueueUtils(); static Queue<E> unmodifiableQueue(final Queue<? extends E> queue); static Queue<E> predicatedQueue(final Queue<E> queue, final Predicate<? super E> predicate); static Queue<E> transformingQueue(final Queue<E> queue, final Transformer<? super E, ? extends E> transformer); @SuppressWarnings("unchecked") // OK, empty queue is compatible with any type static Queue<E> emptyQueue(); @SuppressWarnings("rawtypes") // OK, empty queue is compatible with any type static final Queue EMPTY_QUEUE; }### Answer: @Test public void testUnmodifiableQueue() { Queue<Object> queue = QueueUtils.unmodifiableQueue(new LinkedList<Object>()); assertTrue("Returned object should be an UnmodifiableQueue.", queue instanceof UnmodifiableQueue); try { QueueUtils.unmodifiableQueue(null); fail("Expecting NullPointerException for null queue."); } catch (final NullPointerException ex) { } assertSame("UnmodifiableQueue shall not be decorated", queue, QueueUtils.unmodifiableQueue(queue)); }
### Question: QueueUtils { public static <E> Queue<E> predicatedQueue(final Queue<E> queue, final Predicate<? super E> predicate) { return PredicatedQueue.predicatedQueue(queue, predicate); } private QueueUtils(); static Queue<E> unmodifiableQueue(final Queue<? extends E> queue); static Queue<E> predicatedQueue(final Queue<E> queue, final Predicate<? super E> predicate); static Queue<E> transformingQueue(final Queue<E> queue, final Transformer<? super E, ? extends E> transformer); @SuppressWarnings("unchecked") // OK, empty queue is compatible with any type static Queue<E> emptyQueue(); @SuppressWarnings("rawtypes") // OK, empty queue is compatible with any type static final Queue EMPTY_QUEUE; }### Answer: @Test public void testPredicatedQueue() { Queue<Object> queue = QueueUtils.predicatedQueue(new LinkedList<Object>(), truePredicate); assertTrue("Returned object should be a PredicatedQueue.", queue instanceof PredicatedQueue); try { QueueUtils.predicatedQueue(null, truePredicate); fail("Expecting NullPointerException for null queue."); } catch (final NullPointerException ex) { } try { QueueUtils.predicatedQueue(new LinkedList<Object>(), null); fail("Expecting NullPointerException for null predicate."); } catch (final NullPointerException ex) { } }
### Question: QueueUtils { public static <E> Queue<E> transformingQueue(final Queue<E> queue, final Transformer<? super E, ? extends E> transformer) { return TransformedQueue.transformingQueue(queue, transformer); } private QueueUtils(); static Queue<E> unmodifiableQueue(final Queue<? extends E> queue); static Queue<E> predicatedQueue(final Queue<E> queue, final Predicate<? super E> predicate); static Queue<E> transformingQueue(final Queue<E> queue, final Transformer<? super E, ? extends E> transformer); @SuppressWarnings("unchecked") // OK, empty queue is compatible with any type static Queue<E> emptyQueue(); @SuppressWarnings("rawtypes") // OK, empty queue is compatible with any type static final Queue EMPTY_QUEUE; }### Answer: @Test public void testTransformedQueue() { Queue<Object> queue = QueueUtils.transformingQueue(new LinkedList<Object>(), nopTransformer); assertTrue("Returned object should be an TransformedQueue.", queue instanceof TransformedQueue); try { QueueUtils.transformingQueue(null, nopTransformer); fail("Expecting NullPointerException for null queue."); } catch (final NullPointerException ex) { } try { QueueUtils.transformingQueue(new LinkedList<Object>(), null); fail("Expecting NullPointerException for null transformer."); } catch (final NullPointerException ex) { } }
### Question: QueueUtils { @SuppressWarnings("unchecked") public static <E> Queue<E> emptyQueue() { return (Queue<E>) EMPTY_QUEUE; } private QueueUtils(); static Queue<E> unmodifiableQueue(final Queue<? extends E> queue); static Queue<E> predicatedQueue(final Queue<E> queue, final Predicate<? super E> predicate); static Queue<E> transformingQueue(final Queue<E> queue, final Transformer<? super E, ? extends E> transformer); @SuppressWarnings("unchecked") // OK, empty queue is compatible with any type static Queue<E> emptyQueue(); @SuppressWarnings("rawtypes") // OK, empty queue is compatible with any type static final Queue EMPTY_QUEUE; }### Answer: @Test public void testEmptyQueue() { Queue<Object> queue = QueueUtils.emptyQueue(); assertTrue("Returned object should be an UnmodifiableQueue.", queue instanceof UnmodifiableQueue); assertTrue("Returned queue is not empty.", queue.isEmpty()); try { queue.add(new Object()); fail("Expecting UnsupportedOperationException for empty queue."); } catch (final UnsupportedOperationException ex) { } }
### Question: EnumerationUtils { public static <T> T get(final Enumeration<T> e, final int index) { int i = index; CollectionUtils.checkIndexBounds(i); while (e.hasMoreElements()) { i--; if (i == -1) { return e.nextElement(); } else { e.nextElement(); } } throw new IndexOutOfBoundsException("Entry does not exist: " + i); } private EnumerationUtils(); static T get(final Enumeration<T> e, final int index); static List<E> toList(final Enumeration<? extends E> enumeration); static List<String> toList(final StringTokenizer stringTokenizer); }### Answer: @Test public void getFromEnumeration() throws Exception { final Vector<String> vector = new Vector<String>(); vector.addElement("zero"); vector.addElement("one"); Enumeration<String> en = vector.elements(); assertEquals("zero", EnumerationUtils.get(en, 0)); en = vector.elements(); assertEquals("one", EnumerationUtils.get(en, 1)); try { EnumerationUtils.get(en, 3); fail("Expecting IndexOutOfBoundsException."); } catch (final IndexOutOfBoundsException e) { } assertTrue(!en.hasMoreElements()); }
### Question: BoundedIterator implements Iterator<E> { public void remove() { if (pos <= offset) { throw new IllegalStateException("remove() can not be called before calling next()"); } iterator.remove(); } BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max); boolean hasNext(); E next(); void remove(); }### Answer: @Test public void testRemoveWithoutCallingNext() { List<E> testListCopy = new ArrayList<E>(testList); Iterator<E> iter = new BoundedIterator<E>(testListCopy.iterator(), 1, 5); try { iter.remove(); fail("Expected IllegalStateException."); } catch (IllegalStateException ise) { } }
### Question: SkippingIterator extends AbstractIteratorDecorator<E> { @Override public E next() { final E next = super.next(); pos++; return next; } SkippingIterator(final Iterator<E> iterator, final long offset); @Override E next(); @Override void remove(); }### Answer: @Test public void testSkipping() { Iterator<E> iter = new SkippingIterator<E>(testList.iterator(), 2); assertTrue(iter.hasNext()); assertEquals("c", iter.next()); assertTrue(iter.hasNext()); assertEquals("d", iter.next()); assertTrue(iter.hasNext()); assertEquals("e", iter.next()); assertTrue(iter.hasNext()); assertEquals("f", iter.next()); assertTrue(iter.hasNext()); assertEquals("g", iter.next()); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { } } @Test public void testSameAsDecorated() { Iterator<E> iter = new SkippingIterator<E>(testList.iterator(), 0); assertTrue(iter.hasNext()); assertEquals("a", iter.next()); assertTrue(iter.hasNext()); assertEquals("b", iter.next()); assertTrue(iter.hasNext()); assertEquals("c", iter.next()); assertTrue(iter.hasNext()); assertEquals("d", iter.next()); assertTrue(iter.hasNext()); assertEquals("e", iter.next()); assertTrue(iter.hasNext()); assertEquals("f", iter.next()); assertTrue(iter.hasNext()); assertEquals("g", iter.next()); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { } } @Test public void testOffsetGreaterThanSize() { Iterator<E> iter = new SkippingIterator<E>(testList.iterator(), 10); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { } }
### Question: SkippingIterator extends AbstractIteratorDecorator<E> { @Override public void remove() { if (pos <= offset) { throw new IllegalStateException("remove() can not be called before calling next()"); } super.remove(); } SkippingIterator(final Iterator<E> iterator, final long offset); @Override E next(); @Override void remove(); }### Answer: @Test public void testRemoveWithoutCallingNext() { List<E> testListCopy = new ArrayList<E>(testList); Iterator<E> iter = new SkippingIterator<E>(testListCopy.iterator(), 1); try { iter.remove(); fail("Expected IllegalStateException."); } catch (IllegalStateException ise) { } }
### Question: PeekingIterator implements Iterator<E> { public boolean hasNext() { if (exhausted) { return false; } return slotFilled ? true : iterator.hasNext(); } PeekingIterator(final Iterator<? extends E> iterator); static PeekingIterator<E> peekingIterator(final Iterator<? extends E> iterator); boolean hasNext(); E peek(); E element(); E next(); void remove(); }### Answer: @Test public void testEmpty() { Iterator<E> it = makeEmptyIterator(); assertFalse(it.hasNext()); }
### Question: TypeToken extends TypeCapture<T> implements Serializable { public final TypeToken<?> resolveType(Type type) { TypeResolver resolver = typeResolver; if (resolver == null) { resolver = (typeResolver = TypeResolver.accordingTo(runtimeType)); } return of(resolver.resolveType(type)); } protected TypeToken(); private TypeToken(Type type); static TypeToken<T> of(Class<T> type); static TypeToken<?> of(Type type); final Class<? super T> getRawType(); final Type getType(); final TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg); final TypeToken<?> resolveType(Type type); final boolean isAssignableFrom(TypeToken<?> type); final boolean isAssignableFrom(Type type); final boolean isArray(); final boolean isPrimitive(); final TypeToken<T> wrap(); @Nullable final TypeToken<?> getComponentType(); @Override boolean equals(@Nullable Object o); @Override int hashCode(); @Override String toString(); TypeToken<?> resolveFatherClass(Class<?> clazz); TokenTuple resolveFatherClassTuple(Class<?> clazz); }### Answer: @Test public void testResolveType() throws Exception { TypeToken<HashMap<String, Integer>> mapToken = new TypeToken<HashMap<String, Integer>>() { }; TypeToken<?> entrySetToken = mapToken.resolveType(Map.class.getMethod("entrySet").getGenericReturnType()); assertThat(entrySetToken.toString(), equalTo("java.util.Set<java.util.Map.java.util.Map$Entry<java.lang.String, java.lang.Integer>>")); }
### Question: MultiMapUtils { @SuppressWarnings("unchecked") public static <K, V> MultiValuedMap<K, V> emptyIfNull(final MultiValuedMap<K, V> map) { return map == null ? EMPTY_MULTI_VALUED_MAP : map; } private MultiMapUtils(); @SuppressWarnings("unchecked") static MultiValuedMap<K, V> emptyMultiValuedMap(); @SuppressWarnings("unchecked") static MultiValuedMap<K, V> emptyIfNull(final MultiValuedMap<K, V> map); static boolean isEmpty(final MultiValuedMap<?, ?> map); static Collection<V> getCollection(final MultiValuedMap<K, V> map, final K key); static List<V> getValuesAsList(final MultiValuedMap<K, V> map, final K key); static Set<V> getValuesAsSet(final MultiValuedMap<K, V> map, final K key); static Bag<V> getValuesAsBag(final MultiValuedMap<K, V> map, final K key); static ListValuedMap<K, V> newListValuedHashMap(); static SetValuedMap<K, V> newSetValuedHashMap(); static MultiValuedMap<K, V> unmodifiableMultiValuedMap( final MultiValuedMap<? extends K, ? extends V> map); static MultiValuedMap<K, V> transformedMultiValuedMap(final MultiValuedMap<K, V> map, final Transformer<? super K, ? extends K> keyTransformer, final Transformer<? super V, ? extends V> valueTransformer); @SuppressWarnings({ "rawtypes", "unchecked" }) static final MultiValuedMap EMPTY_MULTI_VALUED_MAP; }### Answer: @Test public void testEmptyIfNull() { assertTrue(MultiMapUtils.emptyIfNull(null).isEmpty()); final MultiValuedMap<String, String> map = new ArrayListValuedHashMap<String, String>(); map.put("item", "value"); assertFalse(MultiMapUtils.emptyIfNull(map).isEmpty()); }
### Question: FactoryUtils { public static <T> Factory<T> exceptionFactory() { return ExceptionFactory.<T>exceptionFactory(); } private FactoryUtils(); static Factory<T> exceptionFactory(); static Factory<T> nullFactory(); static Factory<T> constantFactory(final T constantToReturn); static Factory<T> prototypeFactory(final T prototype); static Factory<T> instantiateFactory(final Class<T> classToInstantiate); static Factory<T> instantiateFactory(final Class<T> classToInstantiate, final Class<?>[] paramTypes, final Object[] args); }### Answer: @Test public void testExceptionFactory() { assertNotNull(FactoryUtils.exceptionFactory()); assertSame(FactoryUtils.exceptionFactory(), FactoryUtils.exceptionFactory()); try { FactoryUtils.exceptionFactory().create(); } catch (final FunctorException ex) { try { FactoryUtils.exceptionFactory().create(); } catch (final FunctorException ex2) { return; } } fail(); }
### Question: FactoryUtils { public static <T> Factory<T> nullFactory() { return ConstantFactory.<T>constantFactory(null); } private FactoryUtils(); static Factory<T> exceptionFactory(); static Factory<T> nullFactory(); static Factory<T> constantFactory(final T constantToReturn); static Factory<T> prototypeFactory(final T prototype); static Factory<T> instantiateFactory(final Class<T> classToInstantiate); static Factory<T> instantiateFactory(final Class<T> classToInstantiate, final Class<?>[] paramTypes, final Object[] args); }### Answer: @Test public void testNullFactory() { final Factory<Object> factory = FactoryUtils.nullFactory(); assertNotNull(factory); final Object created = factory.create(); assertNull(created); }
### Question: FactoryUtils { public static <T> Factory<T> constantFactory(final T constantToReturn) { return ConstantFactory.constantFactory(constantToReturn); } private FactoryUtils(); static Factory<T> exceptionFactory(); static Factory<T> nullFactory(); static Factory<T> constantFactory(final T constantToReturn); static Factory<T> prototypeFactory(final T prototype); static Factory<T> instantiateFactory(final Class<T> classToInstantiate); static Factory<T> instantiateFactory(final Class<T> classToInstantiate, final Class<?>[] paramTypes, final Object[] args); }### Answer: @Test public void testConstantFactoryNull() { final Factory<Object> factory = FactoryUtils.constantFactory(null); assertNotNull(factory); final Object created = factory.create(); assertNull(created); } @Test public void testConstantFactoryConstant() { final Integer constant = Integer.valueOf(9); final Factory<Integer> factory = FactoryUtils.constantFactory(constant); assertNotNull(factory); final Integer created = factory.create(); assertSame(constant, created); }
### Question: FactoryUtils { public static <T> Factory<T> prototypeFactory(final T prototype) { return PrototypeFactory.<T>prototypeFactory(prototype); } private FactoryUtils(); static Factory<T> exceptionFactory(); static Factory<T> nullFactory(); static Factory<T> constantFactory(final T constantToReturn); static Factory<T> prototypeFactory(final T prototype); static Factory<T> instantiateFactory(final Class<T> classToInstantiate); static Factory<T> instantiateFactory(final Class<T> classToInstantiate, final Class<?>[] paramTypes, final Object[] args); }### Answer: @Test public void testPrototypeFactoryNull() { assertSame(ConstantFactory.NULL_INSTANCE, FactoryUtils.prototypeFactory(null)); } @Test public void testPrototypeFactoryPublicCloneMethod() throws Exception { final Date proto = new Date(); final Factory<Date> factory = FactoryUtils.prototypeFactory(proto); assertNotNull(factory); final Date created = factory.create(); assertTrue(proto != created); assertEquals(proto, created); } @Test public void testPrototypeFactoryPublicCopyConstructor() throws Exception { final Mock1 proto = new Mock1(6); Factory<Object> factory = FactoryUtils.<Object>prototypeFactory(proto); assertNotNull(factory); final Object created = factory.create(); assertTrue(proto != created); assertEquals(proto, created); } @Test public void testPrototypeFactoryPublicSerialization() throws Exception { final Integer proto = Integer.valueOf(9); final Factory<Integer> factory = FactoryUtils.prototypeFactory(proto); assertNotNull(factory); final Integer created = factory.create(); assertTrue(proto != created); assertEquals(proto, created); } @Test public void testPrototypeFactoryPublicSerializationError() { final Mock2 proto = new Mock2(new Object()); final Factory<Object> factory = FactoryUtils.<Object>prototypeFactory(proto); assertNotNull(factory); try { factory.create(); } catch (final FunctorException ex) { assertTrue(ex.getCause() instanceof IOException); return; } fail(); } @Test public void testPrototypeFactoryPublicBad() { final Object proto = new Object(); try { FactoryUtils.prototypeFactory(proto); } catch (final IllegalArgumentException ex) { return; } fail(); }
### Question: FactoryUtils { public static <T> Factory<T> instantiateFactory(final Class<T> classToInstantiate) { return InstantiateFactory.instantiateFactory(classToInstantiate, null, null); } private FactoryUtils(); static Factory<T> exceptionFactory(); static Factory<T> nullFactory(); static Factory<T> constantFactory(final T constantToReturn); static Factory<T> prototypeFactory(final T prototype); static Factory<T> instantiateFactory(final Class<T> classToInstantiate); static Factory<T> instantiateFactory(final Class<T> classToInstantiate, final Class<?>[] paramTypes, final Object[] args); }### Answer: @Test(expected=NullPointerException.class) public void instantiateFactoryNull() { FactoryUtils.instantiateFactory(null); } @Test public void instantiateFactorySimple() { final Factory<Mock3> factory = FactoryUtils.instantiateFactory(Mock3.class); assertNotNull(factory); Mock3 created = factory.create(); assertEquals(0, created.getValue()); created = factory.create(); assertEquals(1, created.getValue()); } @Test(expected=IllegalArgumentException.class) public void instantiateFactoryMismatch() { FactoryUtils.instantiateFactory(Date.class, null, new Object[] {null}); } @Test(expected=IllegalArgumentException.class) public void instantiateFactoryNoConstructor() { FactoryUtils.instantiateFactory(Date.class, new Class[] {Long.class}, new Object[] {null}); } @Test public void instantiateFactoryComplex() { TimeZone.setDefault(TimeZone.getTimeZone("GMT")); final Factory<Date> factory = FactoryUtils.instantiateFactory(Date.class, new Class[] {Integer.TYPE, Integer.TYPE, Integer.TYPE}, new Object[] {Integer.valueOf(70), Integer.valueOf(0), Integer.valueOf(2)}); assertNotNull(factory); final Date created = factory.create(); assertEquals(new Date(1000 * 60 * 60 * 24), created); }
### Question: ComparatorUtils { public static Comparator<Boolean> booleanComparator(final boolean trueFirst) { return BooleanComparator.booleanComparator(trueFirst); } private ComparatorUtils(); @SuppressWarnings("unchecked") static Comparator<E> naturalComparator(); static Comparator<E> chainedComparator(final Comparator<E>... comparators); @SuppressWarnings("unchecked") static Comparator<E> chainedComparator(final Collection<Comparator<E>> comparators); static Comparator<E> reversedComparator(final Comparator<E> comparator); static Comparator<Boolean> booleanComparator(final boolean trueFirst); @SuppressWarnings("unchecked") static Comparator<E> nullLowComparator(Comparator<E> comparator); @SuppressWarnings("unchecked") static Comparator<E> nullHighComparator(Comparator<E> comparator); @SuppressWarnings("unchecked") static Comparator<I> transformedComparator(Comparator<O> comparator, final Transformer<? super I, ? extends O> transformer); @SuppressWarnings("unchecked") static E min(final E o1, final E o2, Comparator<E> comparator); @SuppressWarnings("unchecked") static E max(final E o1, final E o2, Comparator<E> comparator); @SuppressWarnings({ "rawtypes", "unchecked" }) // explicit type needed for Java 1.5 compilation static final Comparator NATURAL_COMPARATOR; }### Answer: @Test public void booleanComparator() { Comparator<Boolean> comp = ComparatorUtils.booleanComparator(true); assertTrue(comp.compare(Boolean.TRUE, Boolean.FALSE) < 0); assertTrue(comp.compare(Boolean.TRUE, Boolean.TRUE) == 0); assertTrue(comp.compare(Boolean.FALSE, Boolean.TRUE) > 0); comp = ComparatorUtils.booleanComparator(false); assertTrue(comp.compare(Boolean.TRUE, Boolean.FALSE) > 0); assertTrue(comp.compare(Boolean.TRUE, Boolean.TRUE) == 0); assertTrue(comp.compare(Boolean.FALSE, Boolean.TRUE) < 0); }
### Question: ComparatorUtils { public static <E> Comparator<E> chainedComparator(final Comparator<E>... comparators) { final ComparatorChain<E> chain = new ComparatorChain<E>(); for (final Comparator<E> comparator : comparators) { if (comparator == null) { throw new NullPointerException("Comparator cannot be null"); } chain.addComparator(comparator); } return chain; } private ComparatorUtils(); @SuppressWarnings("unchecked") static Comparator<E> naturalComparator(); static Comparator<E> chainedComparator(final Comparator<E>... comparators); @SuppressWarnings("unchecked") static Comparator<E> chainedComparator(final Collection<Comparator<E>> comparators); static Comparator<E> reversedComparator(final Comparator<E> comparator); static Comparator<Boolean> booleanComparator(final boolean trueFirst); @SuppressWarnings("unchecked") static Comparator<E> nullLowComparator(Comparator<E> comparator); @SuppressWarnings("unchecked") static Comparator<E> nullHighComparator(Comparator<E> comparator); @SuppressWarnings("unchecked") static Comparator<I> transformedComparator(Comparator<O> comparator, final Transformer<? super I, ? extends O> transformer); @SuppressWarnings("unchecked") static E min(final E o1, final E o2, Comparator<E> comparator); @SuppressWarnings("unchecked") static E max(final E o1, final E o2, Comparator<E> comparator); @SuppressWarnings({ "rawtypes", "unchecked" }) // explicit type needed for Java 1.5 compilation static final Comparator NATURAL_COMPARATOR; }### Answer: @Test public void chainedComparator() { Comparator<Integer> comp = ComparatorUtils.chainedComparator(ComparatorUtils.<Integer>naturalComparator(), ComparatorUtils.<Integer>naturalComparator()); assertTrue(comp.compare(1, 2) < 0); assertTrue(comp.compare(1, 1) == 0); assertTrue(comp.compare(2, 1) > 0); }
### Question: ComparatorUtils { @SuppressWarnings("unchecked") public static <E> Comparator<E> nullLowComparator(Comparator<E> comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } return new NullComparator<E>(comparator, false); } private ComparatorUtils(); @SuppressWarnings("unchecked") static Comparator<E> naturalComparator(); static Comparator<E> chainedComparator(final Comparator<E>... comparators); @SuppressWarnings("unchecked") static Comparator<E> chainedComparator(final Collection<Comparator<E>> comparators); static Comparator<E> reversedComparator(final Comparator<E> comparator); static Comparator<Boolean> booleanComparator(final boolean trueFirst); @SuppressWarnings("unchecked") static Comparator<E> nullLowComparator(Comparator<E> comparator); @SuppressWarnings("unchecked") static Comparator<E> nullHighComparator(Comparator<E> comparator); @SuppressWarnings("unchecked") static Comparator<I> transformedComparator(Comparator<O> comparator, final Transformer<? super I, ? extends O> transformer); @SuppressWarnings("unchecked") static E min(final E o1, final E o2, Comparator<E> comparator); @SuppressWarnings("unchecked") static E max(final E o1, final E o2, Comparator<E> comparator); @SuppressWarnings({ "rawtypes", "unchecked" }) // explicit type needed for Java 1.5 compilation static final Comparator NATURAL_COMPARATOR; }### Answer: @Test public void nullLowComparator() { Comparator<Integer> comp = ComparatorUtils.nullLowComparator(null); assertTrue(comp.compare(null, 10) < 0); assertTrue(comp.compare(null, null) == 0); assertTrue(comp.compare(10, null) > 0); }
### Question: ComparatorUtils { @SuppressWarnings("unchecked") public static <E> Comparator<E> nullHighComparator(Comparator<E> comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } return new NullComparator<E>(comparator, true); } private ComparatorUtils(); @SuppressWarnings("unchecked") static Comparator<E> naturalComparator(); static Comparator<E> chainedComparator(final Comparator<E>... comparators); @SuppressWarnings("unchecked") static Comparator<E> chainedComparator(final Collection<Comparator<E>> comparators); static Comparator<E> reversedComparator(final Comparator<E> comparator); static Comparator<Boolean> booleanComparator(final boolean trueFirst); @SuppressWarnings("unchecked") static Comparator<E> nullLowComparator(Comparator<E> comparator); @SuppressWarnings("unchecked") static Comparator<E> nullHighComparator(Comparator<E> comparator); @SuppressWarnings("unchecked") static Comparator<I> transformedComparator(Comparator<O> comparator, final Transformer<? super I, ? extends O> transformer); @SuppressWarnings("unchecked") static E min(final E o1, final E o2, Comparator<E> comparator); @SuppressWarnings("unchecked") static E max(final E o1, final E o2, Comparator<E> comparator); @SuppressWarnings({ "rawtypes", "unchecked" }) // explicit type needed for Java 1.5 compilation static final Comparator NATURAL_COMPARATOR; }### Answer: @Test public void nullHighComparator() { Comparator<Integer> comp = ComparatorUtils.nullHighComparator(null); assertTrue(comp.compare(null, 10) > 0); assertTrue(comp.compare(null, null) == 0); assertTrue(comp.compare(10, null) < 0); }
### Question: TypeToken extends TypeCapture<T> implements Serializable { Set<TypeToken<?>> getTypes() { Set<TypeToken<?>> tokens = new HashSet<TypeToken<?>>(); tokens.add(this); TypeToken<?> superclass = getGenericSuperclass(); if (superclass != null) { tokens.add(superclass); tokens.addAll(superclass.getTypes()); } List<TypeToken<?>> interfaces = getGenericInterfaces(); for (TypeToken<?> anInterface : interfaces) { tokens.add(anInterface); tokens.addAll(anInterface.getTypes()); } return tokens; } protected TypeToken(); private TypeToken(Type type); static TypeToken<T> of(Class<T> type); static TypeToken<?> of(Type type); final Class<? super T> getRawType(); final Type getType(); final TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg); final TypeToken<?> resolveType(Type type); final boolean isAssignableFrom(TypeToken<?> type); final boolean isAssignableFrom(Type type); final boolean isArray(); final boolean isPrimitive(); final TypeToken<T> wrap(); @Nullable final TypeToken<?> getComponentType(); @Override boolean equals(@Nullable Object o); @Override int hashCode(); @Override String toString(); TypeToken<?> resolveFatherClass(Class<?> clazz); TokenTuple resolveFatherClassTuple(Class<?> clazz); }### Answer: @Test public void testGetTypes() throws Exception { TypeToken<HashMap<String, Integer>> t = new TypeToken<HashMap<String, Integer>>() { }; Set<TypeToken<?>> types = t.getTypes(); assertThat(types.size(), equalTo(6)); types.contains(new TypeToken<Map<String, Integer>>() { }); types.contains(new TypeToken<HashMap<String, Integer>>() { }); types.contains(new TypeToken<AbstractMap<String, Integer>>() { }); types.contains(TypeToken.of(Cloneable.class)); types.contains(TypeToken.of(Serializable.class)); types.contains(TypeToken.of(Object.class)); }
### Question: LazySortedMap extends LazyMap<K,V> implements SortedMap<K,V> { public static <K, V> LazySortedMap<K, V> lazySortedMap(final SortedMap<K, V> map, final Factory<? extends V> factory) { return new LazySortedMap<K,V>(map, factory); } protected LazySortedMap(final SortedMap<K,V> map, final Factory<? extends V> factory); protected LazySortedMap(final SortedMap<K,V> map, final Transformer<? super K, ? extends V> factory); static LazySortedMap<K, V> lazySortedMap(final SortedMap<K, V> map, final Factory<? extends V> factory); static LazySortedMap<K, V> lazySortedMap(final SortedMap<K, V> map, final Transformer<? super K, ? extends V> factory); K firstKey(); K lastKey(); Comparator<? super K> comparator(); SortedMap<K,V> subMap(final K fromKey, final K toKey); SortedMap<K,V> headMap(final K toKey); SortedMap<K,V> tailMap(final K fromKey); }### Answer: @Test public void mapGet() { Map<Integer, Number> map = lazySortedMap(new TreeMap<Integer,Number>(), oneFactory); assertEquals(0, map.size()); final Number i1 = map.get(5); assertEquals(1, i1); assertEquals(1, map.size()); map = lazySortedMap(new TreeMap<Integer,Number>(), FactoryUtils.<Number>nullFactory()); final Number o = map.get(5); assertEquals(null,o); assertEquals(1, map.size()); }
### Question: LocalCacheHandler extends SimpleCacheHandler { public Object get(String key) { return get(key, null); } LocalCacheHandler(); LocalCacheHandler(Ticker ticker); Object get(String key); Map<String, Object> getBulk(Set<String> keys); @Override Object get(String key, Type type); @Override Map<String, Object> getBulk(Set<String> keys, Type type); @Override void set(String key, Object value, int exptimeSeconds); @Override void delete(String key); @Override void add(String key, Object value, int exptimeSeconds); }### Answer: @Test public void testGet() throws Exception { Ticker4Test t = new Ticker4Test(); LocalCacheHandler cache = new LocalCacheHandler(t); int seconds = 100; String key = "key"; String value = "value"; cache.set(key, value, seconds); assertThat((String) cache.get(key), equalTo(value)); t.addSeconds(seconds + 1); assertThat(cache.get(key), nullValue()); }
### Question: LocalCacheHandler extends SimpleCacheHandler { public Map<String, Object> getBulk(Set<String> keys) { return getBulk(keys, null); } LocalCacheHandler(); LocalCacheHandler(Ticker ticker); Object get(String key); Map<String, Object> getBulk(Set<String> keys); @Override Object get(String key, Type type); @Override Map<String, Object> getBulk(Set<String> keys, Type type); @Override void set(String key, Object value, int exptimeSeconds); @Override void delete(String key); @Override void add(String key, Object value, int exptimeSeconds); }### Answer: @Test public void testGetBulk() throws Exception { Ticker4Test t = new Ticker4Test(); LocalCacheHandler cache = new LocalCacheHandler(t); int seconds = 100; String key = "key"; String value = "value"; int seconds2 = 200; String key2 = "key2"; String value2 = "value2"; cache.set(key, value, seconds); cache.set(key2, value2, seconds2); Set<String> keys = Sets.newHashSet(key, key2); Map<String, Object> map = cache.getBulk(keys); assertThat(map.size(), equalTo(2)); assertThat((String) map.get(key), equalTo(value)); assertThat((String) map.get(key2), equalTo(value2)); t.addSeconds(seconds + 1); map = cache.getBulk(keys); assertThat(map.size(), equalTo(1)); assertThat((String) map.get(key2), equalTo(value2)); t.reset(); t.addSeconds(seconds2 + 1); map = cache.getBulk(keys); assertThat(map.size(), equalTo(0)); }
### Question: LocalCacheHandler extends SimpleCacheHandler { @Override public void delete(String key) { cache.remove(key); } LocalCacheHandler(); LocalCacheHandler(Ticker ticker); Object get(String key); Map<String, Object> getBulk(Set<String> keys); @Override Object get(String key, Type type); @Override Map<String, Object> getBulk(Set<String> keys, Type type); @Override void set(String key, Object value, int exptimeSeconds); @Override void delete(String key); @Override void add(String key, Object value, int exptimeSeconds); }### Answer: @Test public void testDelete() throws Exception { Ticker4Test t = new Ticker4Test(); LocalCacheHandler cache = new LocalCacheHandler(t); int seconds = 100; String key = "key"; String value = "value"; cache.set(key, value, seconds); assertThat((String) cache.get(key), equalTo(value)); cache.delete(key); assertThat(cache.get(key), nullValue()); }
### Question: LocalCacheHandler extends SimpleCacheHandler { @Override public void add(String key, Object value, int exptimeSeconds) { long now = ticker.read(); Entry entry = new Entry(value, now + TimeUnit.SECONDS.toNanos(exptimeSeconds)); cache.putIfAbsent(key, entry); } LocalCacheHandler(); LocalCacheHandler(Ticker ticker); Object get(String key); Map<String, Object> getBulk(Set<String> keys); @Override Object get(String key, Type type); @Override Map<String, Object> getBulk(Set<String> keys, Type type); @Override void set(String key, Object value, int exptimeSeconds); @Override void delete(String key); @Override void add(String key, Object value, int exptimeSeconds); }### Answer: @Test public void testAdd() throws Exception { Ticker4Test t = new Ticker4Test(); LocalCacheHandler cache = new LocalCacheHandler(t); int seconds = 100; String key = "key"; String value = "value"; int seconds2 = 200; String key2 = "key2"; String value2 = "value2"; cache.set(key, value, seconds); cache.add(key, value2, seconds); cache.add(key2, value2, seconds2); assertThat((String) cache.get(key), equalTo(value)); assertThat((String) cache.get(key2), equalTo(value2)); }
### Question: DynamicTokens { public static <E> TypeToken<Collection<E>> collectionToken(TypeToken<E> entityToken) { return new TypeToken<Collection<E>>() {} .where(new TypeParameter<E>() {}, entityToken); } static TypeToken<Collection<E>> collectionToken(TypeToken<E> entityToken); static TypeToken<List<E>> listToken(TypeToken<E> entityToken); }### Answer: @Test public void testCollectionToken() throws Exception { TypeToken<Collection<String>> token = DynamicTokens.collectionToken(TypeToken.of(String.class)); Type expectedType = DynamicTokensTest.class.getMethod("func").getGenericReturnType(); assertThat(token.getType(), equalTo(expectedType)); }
### Question: NullPredicate implements Predicate<T>, Serializable { @SuppressWarnings("unchecked") public static <T> Predicate<T> nullPredicate() { return (Predicate<T>) INSTANCE; } private NullPredicate(); @SuppressWarnings("unchecked") static Predicate<T> nullPredicate(); boolean evaluate(final T object); @SuppressWarnings("rawtypes") static final Predicate INSTANCE; }### Answer: @Test public void testNullPredicate() { assertSame(NullPredicate.nullPredicate(), NullPredicate.nullPredicate()); assertTrue(nullPredicate(), null); } @Test public void ensurePredicateCanBeTypedWithoutWarning() throws Exception { final Predicate<String> predicate = NullPredicate.nullPredicate(); assertFalse(predicate, cString); }
### Question: CatchAndRethrowClosure implements Closure<E> { public void execute(final E input) { try { executeAndThrow(input); } catch (final RuntimeException ex) { throw ex; } catch (final Throwable t) { throw new FunctorException(t); } } void execute(final E input); }### Answer: @Test public void testThrowingClosure() { Closure<Integer> closure = generateNoExceptionClosure(); try { closure.execute(Integer.valueOf(0)); } catch (final FunctorException ex) { Assert.fail(); } catch (final RuntimeException ex) { Assert.fail(); } closure = generateIOExceptionClosure(); try { closure.execute(Integer.valueOf(0)); Assert.fail(); } catch (final FunctorException ex) { Assert.assertTrue(ex.getCause() instanceof IOException); } catch (final RuntimeException ex) { Assert.fail(); } closure = generateNullPointerExceptionClosure(); try { closure.execute(Integer.valueOf(0)); Assert.fail(); } catch (final FunctorException ex) { Assert.fail(); } catch (final RuntimeException ex) { Assert.assertTrue(ex instanceof NullPointerException); } }
### Question: EqualPredicate implements Predicate<T>, Serializable { public static <T> Predicate<T> equalPredicate(final T object) { if (object == null) { return NullPredicate.nullPredicate(); } return new EqualPredicate<T>(object); } EqualPredicate(final T object); EqualPredicate(final T object, final Equator<T> equator); static Predicate<T> equalPredicate(final T object); static Predicate<T> equalPredicate(final T object, final Equator<T> equator); boolean evaluate(final T object); Object getValue(); }### Answer: @Test public void testNullArgumentEqualsNullPredicate() throws Exception { assertSame(nullPredicate(), equalPredicate(null)); } @Test public void objectFactoryUsesEqualsForTest() throws Exception { final Predicate<EqualsTestObject> predicate = equalPredicate(FALSE_OBJECT); assertFalse(predicate, FALSE_OBJECT); assertTrue(equalPredicate(TRUE_OBJECT), TRUE_OBJECT); } @SuppressWarnings("boxing") @Test public void testPredicateTypeCanBeSuperClassOfObject() throws Exception { final Predicate<Number> predicate = equalPredicate((Number) 4); assertTrue(predicate, 4); }
### Question: AllPredicate extends AbstractQuantifierPredicate<T> { public boolean evaluate(final T object) { for (final Predicate<? super T> iPredicate : iPredicates) { if (!iPredicate.evaluate(object)) { return false; } } return true; } AllPredicate(final Predicate<? super T>... predicates); static Predicate<T> allPredicate(final Predicate<? super T>... predicates); static Predicate<T> allPredicate(final Collection<? extends Predicate<? super T>> predicates); boolean evaluate(final T object); }### Answer: @SuppressWarnings({"unchecked"}) @Test public void emptyArrayToGetInstance() { assertTrue("empty array not true", getPredicateInstance(new Predicate[] {}).evaluate(null)); } @Test public void emptyCollectionToGetInstance() { final Predicate<Integer> allPredicate = getPredicateInstance( Collections.<Predicate<Integer>>emptyList()); assertTrue("empty collection not true", allPredicate.evaluate(getTestValue())); } @Test public void allTrue() { assertTrue("multiple true predicates evaluated to false", getPredicateInstance(true, true).evaluate(getTestValue())); assertTrue("multiple true predicates evaluated to false", getPredicateInstance(true, true, true).evaluate(getTestValue())); } @Test public void trueAndFalseCombined() { assertFalse("false predicate evaluated to true", getPredicateInstance(false, null).evaluate(getTestValue())); assertFalse("false predicate evaluated to true", getPredicateInstance(false, null, null).evaluate(getTestValue())); assertFalse("false predicate evaluated to true", getPredicateInstance(true, false, null).evaluate(getTestValue())); assertFalse("false predicate evaluated to true", getPredicateInstance(true, true, false).evaluate(getTestValue())); assertFalse("false predicate evaluated to true", getPredicateInstance(true, true, false, null).evaluate(getTestValue())); }
### Question: Charsets { public static Charset toCharset(final Charset charset) { return charset == null ? Charset.defaultCharset() : charset; } static Charset toCharset(final Charset charset); static Charset toCharset(final String charset); @Deprecated static final Charset ISO_8859_1; @Deprecated static final Charset US_ASCII; @Deprecated static final Charset UTF_16; @Deprecated static final Charset UTF_16BE; @Deprecated static final Charset UTF_16LE; @Deprecated static final Charset UTF_8; }### Answer: @Test public void testToCharset() { Assert.assertEquals(Charset.defaultCharset(), Charsets.toCharset((String) null)); Assert.assertEquals(Charset.defaultCharset(), Charsets.toCharset((Charset) null)); Assert.assertEquals(Charset.defaultCharset(), Charsets.toCharset(Charset.defaultCharset())); Assert.assertEquals(Charset.forName("UTF-8"), Charsets.toCharset(Charset.forName("UTF-8"))); }
### Question: StringEncoderComparator implements Comparator { @Override public int compare(final Object o1, final Object o2) { int compareCode = 0; try { @SuppressWarnings("unchecked") final Comparable<Comparable<?>> s1 = (Comparable<Comparable<?>>) this.stringEncoder.encode(o1); final Comparable<?> s2 = (Comparable<?>) this.stringEncoder.encode(o2); compareCode = s1.compareTo(s2); } catch (final EncoderException ee) { compareCode = 0; } return compareCode; } @Deprecated StringEncoderComparator(); StringEncoderComparator(final StringEncoder stringEncoder); @Override int compare(final Object o1, final Object o2); }### Answer: @Test public void testComparatorWithSoundex() throws Exception { final StringEncoderComparator sCompare = new StringEncoderComparator( new Soundex() ); assertTrue( "O'Brien and O'Brian didn't come out with " + "the same Soundex, something must be wrong here", 0 == sCompare.compare( "O'Brien", "O'Brian" ) ); } @Test public void testComparatorWithDoubleMetaphoneAndInvalidInput() throws Exception { final StringEncoderComparator sCompare = new StringEncoderComparator( new DoubleMetaphone() ); final int compare = sCompare.compare(new Double(3.0), Long.valueOf(3)); assertEquals( "Trying to compare objects that make no sense to the underlying encoder should return a zero compare code", 0, compare); }
### Question: B64 { static void b64from24bit(final byte b2, final byte b1, final byte b0, final int outLen, final StringBuilder buffer) { int w = ((b2 << 16) & 0x00ffffff) | ((b1 << 8) & 0x00ffff) | (b0 & 0xff); int n = outLen; while (n-- > 0) { buffer.append(B64T.charAt(w & 0x3f)); w >>= 6; } } }### Answer: @Test public void testB64from24bit() { final StringBuilder buffer = new StringBuilder(""); B64.b64from24bit((byte) 8, (byte) 16, (byte) 64, 2, buffer); B64.b64from24bit((byte) 7, (byte) 77, (byte) 120, 4, buffer); assertEquals("./spo/", buffer.toString()); }
### Question: MethodNameParser { public static MethodNameInfo parse(String str) { OrderUnit ou = parseOrderUnit(str); if (ou != null) { str = str.substring(0, str.length() - ou.getOrderStrSize()); } List<OpUnit> opUnits = new ArrayList<OpUnit>(); List<String> logics = new ArrayList<String>(); Pattern p = Pattern.compile(LOGIC_REGEX); Matcher m = p.matcher(str); int index = 0; while (m.find()) { opUnits.add(OpUnit.create(str.substring(index, m.start()))); logics.add(Strings.firstLetterToLowerCase(m.group())); index = m.end(); } opUnits.add(OpUnit.create(str.substring(index))); return new MethodNameInfo(opUnits, logics, ou); } static MethodNameInfo parse(String str); }### Answer: @Test public void parse() throws Exception { MethodNameInfo info = MethodNameParser.parse("EmailAddressAndLastnameLessThanOrIdOrderByUserIdDesc"); assertThat(info.getLogics(), equalTo(Arrays.asList("and", "or"))); OrderUnit ou = info.getOrderUnit(); assertThat(ou.getOrderType(), equalTo(OrderType.DESC)); assertThat(ou.getProperty(), equalTo("userId")); assertThat(ou.getOrderStrSize(), equalTo(17)); List<OpUnit> ous = info.getOpUnits(); assertThat(ous.size(), equalTo(3)); assertThat(ous.get(0).getOp(), equalTo((Op) new EqualsOp())); assertThat(ous.get(0).getProperty(), equalTo("emailAddress")); assertThat(ous.get(1).getOp(), equalTo((Op) new LessThanOp())); assertThat(ous.get(1).getProperty(), equalTo("lastname")); assertThat(ous.get(2).getOp(), equalTo((Op) new EqualsOp())); assertThat(ous.get(2).getProperty(), equalTo("id")); }
### Question: DynamicTokens { public static <E> TypeToken<List<E>> listToken(TypeToken<E> entityToken) { return new TypeToken<List<E>>() {} .where(new TypeParameter<E>() {}, entityToken); } static TypeToken<Collection<E>> collectionToken(TypeToken<E> entityToken); static TypeToken<List<E>> listToken(TypeToken<E> entityToken); }### Answer: @Test public void testListToken() throws Exception { TypeToken<List<String>> token = DynamicTokens.listToken(TypeToken.of(String.class)); Type expectedType = DynamicTokensTest.class.getMethod("func2").getGenericReturnType(); assertThat(token.getType(), equalTo(expectedType)); }
### Question: Crypt { public static String crypt(final byte[] keyBytes) { return crypt(keyBytes, null); } static String crypt(final byte[] keyBytes); static String crypt(final byte[] keyBytes, final String salt); static String crypt(final String key); static String crypt(final String key, final String salt); }### Answer: @Test public void testCrypt() { assertNotNull(new Crypt()); } @Test public void testDefaultCryptVariant() { assertTrue(Crypt.crypt("secret").startsWith("$6$")); assertTrue(Crypt.crypt("secret", null).startsWith("$6$")); } @Test public void testCryptWithBytes() { final byte[] keyBytes = new byte[] { 'b', 'y', 't', 'e' }; final String hash = Crypt.crypt(keyBytes); assertEquals(hash, Crypt.crypt("byte", hash)); } @Test(expected = IllegalArgumentException.class) public void testCryptWithEmptySalt() { Crypt.crypt("secret", ""); }
### Question: Md5Crypt { public static String md5Crypt(final byte[] keyBytes) { return md5Crypt(keyBytes, MD5_PREFIX + B64.getRandomSalt(8)); } static String apr1Crypt(final byte[] keyBytes); static String apr1Crypt(final byte[] keyBytes, String salt); static String apr1Crypt(final String keyBytes); static String apr1Crypt(final String keyBytes, final String salt); static String md5Crypt(final byte[] keyBytes); static String md5Crypt(final byte[] keyBytes, final String salt); static String md5Crypt(final byte[] keyBytes, final String salt, final String prefix); }### Answer: @Test public void testMd5CryptExplicitCall() { assertTrue(Md5Crypt.md5Crypt("secret".getBytes()).matches("^\\$1\\$[a-zA-Z0-9./]{0,8}\\$.{1,}$")); assertTrue(Md5Crypt.md5Crypt("secret".getBytes(), null).matches("^\\$1\\$[a-zA-Z0-9./]{0,8}\\$.{1,}$")); } @Test(expected = NullPointerException.class) public void testMd5CryptNullData() { Md5Crypt.md5Crypt((byte[]) null); } @Test(expected = IllegalArgumentException.class) public void testMd5CryptWithEmptySalt() { Md5Crypt.md5Crypt("secret".getBytes(), ""); }
### Question: StringUtils { public static byte[] getBytesIso8859_1(final String string) { return getBytes(string, Charsets.ISO_8859_1); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }### Answer: @Test public void testGetBytesIso8859_1() throws UnsupportedEncodingException { final String charsetName = "ISO-8859-1"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesIso8859_1(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); }
### Question: StringUtils { public static byte[] getBytesUsAscii(final String string) { return getBytes(string, Charsets.US_ASCII); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }### Answer: @Test public void testGetBytesUsAscii() throws UnsupportedEncodingException { final String charsetName = "US-ASCII"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUsAscii(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); }
### Question: StringUtils { public static byte[] getBytesUtf16(final String string) { return getBytes(string, Charsets.UTF_16); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }### Answer: @Test public void testGetBytesUtf16() throws UnsupportedEncodingException { final String charsetName = "UTF-16"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUtf16(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); }
### Question: MethodNameParser { @Nullable static OrderUnit parseOrderUnit(String str) { Pattern p = Pattern.compile(ORDER_BY_REGEX); Matcher m = p.matcher(str); if (m.find()) { String tailStr = Strings.firstLetterToLowerCase(str.substring(m.end() - 1)); int size = ORDER_BY.length() + tailStr.length(); String property; OrderType orderType; if (tailStr.endsWith(DESC)) { property = tailStr.substring(0, tailStr.length() - DESC.length()); orderType = OrderType.DESC; } else if (tailStr.endsWith(ASC)) { property = tailStr.substring(0, tailStr.length() - ASC.length()); orderType = OrderType.ASC; } else { property = tailStr; orderType = OrderType.NONE; } return new OrderUnit(property, orderType, size); } return null; } static MethodNameInfo parse(String str); }### Answer: @Test public void parseOrderUnit() throws Exception { OrderUnit ou = MethodNameParser.parseOrderUnit("AgeAndNameOrderByIdDesc"); assertThat(ou.getProperty(), equalTo("id")); assertThat(ou.getOrderType(), equalTo(OrderType.DESC)); assertThat(ou.getOrderStrSize(), equalTo("OrderByIdDesc".length())); ou = MethodNameParser.parseOrderUnit("AgeAndNameOrderByUserNameAsc"); assertThat(ou.getProperty(), equalTo("userName")); assertThat(ou.getOrderType(), equalTo(OrderType.ASC)); assertThat(ou.getOrderStrSize(), equalTo("OrderByUserNameAsc".length())); ou = MethodNameParser.parseOrderUnit("AgeAndNameOrderByAgeU"); assertThat(ou.getProperty(), equalTo("ageU")); assertThat(ou.getOrderType(), equalTo(OrderType.NONE)); assertThat(ou.getOrderStrSize(), equalTo("OrderByAgeU".length())); }
### Question: StringUtils { public static byte[] getBytesUtf16Be(final String string) { return getBytes(string, Charsets.UTF_16BE); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }### Answer: @Test public void testGetBytesUtf16Be() throws UnsupportedEncodingException { final String charsetName = "UTF-16BE"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUtf16Be(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); }
### Question: StringUtils { public static byte[] getBytesUtf16Le(final String string) { return getBytes(string, Charsets.UTF_16LE); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }### Answer: @Test public void testGetBytesUtf16Le() throws UnsupportedEncodingException { final String charsetName = "UTF-16LE"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUtf16Le(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); }
### Question: StringUtils { public static byte[] getBytesUtf8(final String string) { return getBytes(string, Charsets.UTF_8); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }### Answer: @Test public void testGetBytesUtf8() throws UnsupportedEncodingException { final String charsetName = "UTF-8"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUtf8(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); }
### Question: StringUtils { public static byte[] getBytesUnchecked(final String string, final String charsetName) { if (string == null) { return null; } try { return string.getBytes(charsetName); } catch (final UnsupportedEncodingException e) { throw StringUtils.newIllegalStateException(charsetName, e); } } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }### Answer: @Test public void testGetBytesUncheckedBadName() { try { StringUtils.getBytesUnchecked(STRING_FIXTURE, "UNKNOWN"); Assert.fail("Expected " + IllegalStateException.class.getName()); } catch (final IllegalStateException e) { } } @Test public void testGetBytesUncheckedNullInput() { Assert.assertNull(StringUtils.getBytesUnchecked(null, "UNKNOWN")); }
### Question: StringUtils { private static String newString(final byte[] bytes, final Charset charset) { return bytes == null ? null : new String(bytes, charset); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }### Answer: @Test public void testNewStringBadEnc() { try { StringUtils.newString(BYTES_FIXTURE, "UNKNOWN"); Assert.fail("Expected " + IllegalStateException.class.getName()); } catch (final IllegalStateException e) { } } @Test public void testNewStringNullInput() { Assert.assertNull(StringUtils.newString(null, "UNKNOWN")); }
### Question: StringUtils { public static String newStringIso8859_1(final byte[] bytes) { return new String(bytes, Charsets.ISO_8859_1); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }### Answer: @Test public void testNewStringIso8859_1() throws UnsupportedEncodingException { final String charsetName = "ISO-8859-1"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE, charsetName); final String actual = StringUtils.newStringIso8859_1(BYTES_FIXTURE); Assert.assertEquals(expected, actual); }
### Question: StringUtils { public static String newStringUsAscii(final byte[] bytes) { return new String(bytes, Charsets.US_ASCII); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }### Answer: @Test public void testNewStringUsAscii() throws UnsupportedEncodingException { final String charsetName = "US-ASCII"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE, charsetName); final String actual = StringUtils.newStringUsAscii(BYTES_FIXTURE); Assert.assertEquals(expected, actual); }
### Question: StringUtils { public static String newStringUtf16(final byte[] bytes) { return new String(bytes, Charsets.UTF_16); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }### Answer: @Test public void testNewStringUtf16() throws UnsupportedEncodingException { final String charsetName = "UTF-16"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE, charsetName); final String actual = StringUtils.newStringUtf16(BYTES_FIXTURE); Assert.assertEquals(expected, actual); }
### Question: LessThanOp extends Param1Op { @Override public String keyword() { return "LessThan"; } @Override String keyword(); @Override String operator(); }### Answer: @Test public void test() throws Exception { Op op = new LessThanOp(); assertThat(op.keyword(), equalTo("LessThan")); assertThat(op.paramCount(), equalTo(1)); assertThat(op.render("id", new String[] {":1"}), equalTo("id < :1")); }
### Question: StringUtils { public static String newStringUtf16Be(final byte[] bytes) { return new String(bytes, Charsets.UTF_16BE); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }### Answer: @Test public void testNewStringUtf16Be() throws UnsupportedEncodingException { final String charsetName = "UTF-16BE"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE_16BE, charsetName); final String actual = StringUtils.newStringUtf16Be(BYTES_FIXTURE_16BE); Assert.assertEquals(expected, actual); }
### Question: StringUtils { public static String newStringUtf16Le(final byte[] bytes) { return new String(bytes, Charsets.UTF_16LE); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }### Answer: @Test public void testNewStringUtf16Le() throws UnsupportedEncodingException { final String charsetName = "UTF-16LE"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE_16LE, charsetName); final String actual = StringUtils.newStringUtf16Le(BYTES_FIXTURE_16LE); Assert.assertEquals(expected, actual); }
### Question: StringUtils { public static String newStringUtf8(final byte[] bytes) { return newString(bytes, Charsets.UTF_8); } static boolean equals(final CharSequence cs1, final CharSequence cs2); static byte[] getBytesIso8859_1(final String string); static byte[] getBytesUnchecked(final String string, final String charsetName); static byte[] getBytesUsAscii(final String string); static byte[] getBytesUtf16(final String string); static byte[] getBytesUtf16Be(final String string); static byte[] getBytesUtf16Le(final String string); static byte[] getBytesUtf8(final String string); static String newString(final byte[] bytes, final String charsetName); static String newStringIso8859_1(final byte[] bytes); static String newStringUsAscii(final byte[] bytes); static String newStringUtf16(final byte[] bytes); static String newStringUtf16Be(final byte[] bytes); static String newStringUtf16Le(final byte[] bytes); static String newStringUtf8(final byte[] bytes); }### Answer: @Test public void testNewStringUtf8() throws UnsupportedEncodingException { final String charsetName = "UTF-8"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE, charsetName); final String actual = StringUtils.newStringUtf8(BYTES_FIXTURE); Assert.assertEquals(expected, actual); }
### Question: BaseNCodec implements BinaryEncoder, BinaryDecoder { protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength) { this(unencodedBlockSize, encodedBlockSize, lineLength, chunkSeparatorLength, PAD_DEFAULT); } protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength); protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength, final byte pad); @Override Object encode(final Object obj); String encodeToString(final byte[] pArray); String encodeAsString(final byte[] pArray); @Override Object decode(final Object obj); byte[] decode(final String pArray); @Override byte[] decode(final byte[] pArray); @Override byte[] encode(final byte[] pArray); boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad); boolean isInAlphabet(final String basen); long getEncodedLength(final byte[] pArray); static final int MIME_CHUNK_SIZE; static final int PEM_CHUNK_SIZE; }### Answer: @Test public void testBaseNCodec() { assertNotNull(codec); }
### Question: BaseNCodec implements BinaryEncoder, BinaryDecoder { protected static boolean isWhiteSpace(final byte byteToCheck) { switch (byteToCheck) { case ' ' : case '\n' : case '\r' : case '\t' : return true; default : return false; } } protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength); protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength, final byte pad); @Override Object encode(final Object obj); String encodeToString(final byte[] pArray); String encodeAsString(final byte[] pArray); @Override Object decode(final Object obj); byte[] decode(final String pArray); @Override byte[] decode(final byte[] pArray); @Override byte[] encode(final byte[] pArray); boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad); boolean isInAlphabet(final String basen); long getEncodedLength(final byte[] pArray); static final int MIME_CHUNK_SIZE; static final int PEM_CHUNK_SIZE; }### Answer: @Test public void testIsWhiteSpace() { assertTrue(BaseNCodec.isWhiteSpace((byte) ' ')); assertTrue(BaseNCodec.isWhiteSpace((byte) '\n')); assertTrue(BaseNCodec.isWhiteSpace((byte) '\r')); assertTrue(BaseNCodec.isWhiteSpace((byte) '\t')); }
### Question: BaseNCodec implements BinaryEncoder, BinaryDecoder { protected abstract boolean isInAlphabet(byte value); protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength); protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength, final byte pad); @Override Object encode(final Object obj); String encodeToString(final byte[] pArray); String encodeAsString(final byte[] pArray); @Override Object decode(final Object obj); byte[] decode(final String pArray); @Override byte[] decode(final byte[] pArray); @Override byte[] encode(final byte[] pArray); boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad); boolean isInAlphabet(final String basen); long getEncodedLength(final byte[] pArray); static final int MIME_CHUNK_SIZE; static final int PEM_CHUNK_SIZE; }### Answer: @Test public void testIsInAlphabetByte() { assertFalse(codec.isInAlphabet((byte) 0)); assertFalse(codec.isInAlphabet((byte) 'a')); assertTrue(codec.isInAlphabet((byte) 'O')); assertTrue(codec.isInAlphabet((byte) 'K')); } @Test public void testIsInAlphabetByteArrayBoolean() { assertTrue(codec.isInAlphabet(new byte[]{}, false)); assertTrue(codec.isInAlphabet(new byte[]{'O'}, false)); assertFalse(codec.isInAlphabet(new byte[]{'O',' '}, false)); assertFalse(codec.isInAlphabet(new byte[]{' '}, false)); assertTrue(codec.isInAlphabet(new byte[]{}, true)); assertTrue(codec.isInAlphabet(new byte[]{'O'}, true)); assertTrue(codec.isInAlphabet(new byte[]{'O',' '}, true)); assertTrue(codec.isInAlphabet(new byte[]{' '}, true)); } @Test public void testIsInAlphabetString() { assertTrue(codec.isInAlphabet("OK")); assertTrue(codec.isInAlphabet("O=K= \t\n\r")); }
### Question: BaseNCodec implements BinaryEncoder, BinaryDecoder { protected boolean containsAlphabetOrPad(final byte[] arrayOctet) { if (arrayOctet == null) { return false; } for (final byte element : arrayOctet) { if (pad == element || isInAlphabet(element)) { return true; } } return false; } protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength); protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength, final byte pad); @Override Object encode(final Object obj); String encodeToString(final byte[] pArray); String encodeAsString(final byte[] pArray); @Override Object decode(final Object obj); byte[] decode(final String pArray); @Override byte[] decode(final byte[] pArray); @Override byte[] encode(final byte[] pArray); boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad); boolean isInAlphabet(final String basen); long getEncodedLength(final byte[] pArray); static final int MIME_CHUNK_SIZE; static final int PEM_CHUNK_SIZE; }### Answer: @Test public void testContainsAlphabetOrPad() { assertFalse(codec.containsAlphabetOrPad(null)); assertFalse(codec.containsAlphabetOrPad(new byte[]{})); assertTrue(codec.containsAlphabetOrPad("OK".getBytes())); assertTrue(codec.containsAlphabetOrPad("OK ".getBytes())); assertFalse(codec.containsAlphabetOrPad("ok ".getBytes())); assertTrue(codec.containsAlphabetOrPad(new byte[]{codec.pad})); }
### Question: EqualsOp extends Param1Op { @Override public String keyword() { return "Equals"; } @Override String keyword(); @Override String operator(); }### Answer: @Test public void test() throws Exception { Op op = new EqualsOp(); assertThat(op.keyword(), equalTo("Equals")); assertThat(op.paramCount(), equalTo(1)); assertThat(op.render("id", new String[] {":1"}), equalTo("id = :1")); }
### Question: Base64 extends BaseNCodec { public static byte[] encodeInteger(final BigInteger bigInt) { if (bigInt == null) { throw new NullPointerException("encodeInteger called with null parameter"); } return encodeBase64(toIntegerBytes(bigInt), false); } Base64(); Base64(final boolean urlSafe); Base64(final int lineLength); Base64(final int lineLength, final byte[] lineSeparator); Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); boolean isUrlSafe(); @Deprecated static boolean isArrayByteBase64(final byte[] arrayOctet); static boolean isBase64(final byte octet); static boolean isBase64(final String base64); static boolean isBase64(final byte[] arrayOctet); static byte[] encodeBase64(final byte[] binaryData); static String encodeBase64String(final byte[] binaryData); static byte[] encodeBase64URLSafe(final byte[] binaryData); static String encodeBase64URLSafeString(final byte[] binaryData); static byte[] encodeBase64Chunked(final byte[] binaryData); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); static byte[] decodeBase64(final String base64String); static byte[] decodeBase64(final byte[] base64Data); static BigInteger decodeInteger(final byte[] pArray); static byte[] encodeInteger(final BigInteger bigInt); }### Answer: @Test public void testCodeIntegerNull() { try { Base64.encodeInteger(null); fail("Exception not thrown when passing in null to encodeInteger(BigInteger)"); } catch (final NullPointerException npe) { } catch (final Exception e) { fail("Incorrect Exception caught when passing in null to encodeInteger(BigInteger)"); } }
### Question: CustomQueryBuilder extends AbstractCustomBuilder { @Override public String buildSql() { String s1 = Joiner.on(", ").join(columns); return String.format(SQL_TEMPLATE, s1, tailOfSql); } CustomQueryBuilder(List<String> columns, String tailOfSql); @Override String buildSql(); }### Answer: @Test public void buildSql() throws Exception { List<String> columns = Lists.newArrayList("id2", "user_name", "user_age"); CustomQueryBuilder b = new CustomQueryBuilder(columns, "where id = :1"); assertThat(b.buildSql(), equalTo("select id2, user_name, user_age from #table where id = :1")); }
### Question: Base64 extends BaseNCodec { public boolean isUrlSafe() { return this.encodeTable == URL_SAFE_ENCODE_TABLE; } Base64(); Base64(final boolean urlSafe); Base64(final int lineLength); Base64(final int lineLength, final byte[] lineSeparator); Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); boolean isUrlSafe(); @Deprecated static boolean isArrayByteBase64(final byte[] arrayOctet); static boolean isBase64(final byte octet); static boolean isBase64(final String base64); static boolean isBase64(final byte[] arrayOctet); static byte[] encodeBase64(final byte[] binaryData); static String encodeBase64String(final byte[] binaryData); static byte[] encodeBase64URLSafe(final byte[] binaryData); static String encodeBase64URLSafeString(final byte[] binaryData); static byte[] encodeBase64Chunked(final byte[] binaryData); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); static byte[] decodeBase64(final String base64String); static byte[] decodeBase64(final byte[] base64Data); static BigInteger decodeInteger(final byte[] pArray); static byte[] encodeInteger(final BigInteger bigInt); }### Answer: @Test public void testIsUrlSafe() { final Base64 base64Standard = new Base64(false); final Base64 base64URLSafe = new Base64(true); assertFalse("Base64.isUrlSafe=false", base64Standard.isUrlSafe()); assertTrue("Base64.isUrlSafe=true", base64URLSafe.isUrlSafe()); final byte[] whiteSpace = {' ', '\n', '\r', '\t'}; assertTrue("Base64.isBase64(whiteSpace)=true", Base64.isBase64(whiteSpace)); }
### Question: CustomCountBuilder extends AbstractCustomBuilder { @Override public String buildSql() { return String.format(SQL_TEMPLATE, tailOfSql); } CustomCountBuilder(String tailOfSql); @Override String buildSql(); }### Answer: @Test public void buildSql() throws Exception { CustomCountBuilder b = new CustomCountBuilder("where id = :1"); assertThat(b.buildSql(), equalTo("select count(1) from #table where id = :1")); }
### Question: CustomDeleteBuilder extends AbstractCustomBuilder { @Override public String buildSql() { return String.format(SQL_TEMPLATE, tailOfSql); } CustomDeleteBuilder(String tailOfSql); @Override String buildSql(); }### Answer: @Test public void buildSql() throws Exception { CustomDeleteBuilder b = new CustomDeleteBuilder("where id = :1"); assertThat(b.buildSql(), equalTo("delete from #table where id = :1")); }
### Question: Hex implements BinaryEncoder, BinaryDecoder { @Override public String toString() { return super.toString() + "[charsetName=" + this.charset + "]"; } Hex(); Hex(final Charset charset); Hex(final String charsetName); static byte[] decodeHex(final char[] data); static char[] encodeHex(final byte[] data); static char[] encodeHex(final byte[] data, final boolean toLowerCase); static String encodeHexString(final byte[] data); @Override byte[] decode(final byte[] array); @Override Object decode(final Object object); @Override byte[] encode(final byte[] array); @Override Object encode(final Object object); Charset getCharset(); String getCharsetName(); @Override String toString(); static final Charset DEFAULT_CHARSET; static final String DEFAULT_CHARSET_NAME; }### Answer: @Test public void testCustomCharsetToString() { assertTrue(new Hex().toString().indexOf(Hex.DEFAULT_CHARSET_NAME) >= 0); }
### Question: Hex implements BinaryEncoder, BinaryDecoder { @Override public byte[] decode(final byte[] array) throws DecoderException { return decodeHex(new String(array, getCharset()).toCharArray()); } Hex(); Hex(final Charset charset); Hex(final String charsetName); static byte[] decodeHex(final char[] data); static char[] encodeHex(final byte[] data); static char[] encodeHex(final byte[] data, final boolean toLowerCase); static String encodeHexString(final byte[] data); @Override byte[] decode(final byte[] array); @Override Object decode(final Object object); @Override byte[] encode(final byte[] array); @Override Object encode(final Object object); Charset getCharset(); String getCharsetName(); @Override String toString(); static final Charset DEFAULT_CHARSET; static final String DEFAULT_CHARSET_NAME; }### Answer: @Test public void testDecodeArrayOddCharacters() { try { new Hex().decode(new byte[]{65}); fail("An exception wasn't thrown when trying to decode an odd number of characters"); } catch (final DecoderException e) { } } @Test public void testDecodeBadCharacterPos0() { try { new Hex().decode("q0"); fail("An exception wasn't thrown when trying to decode an illegal character"); } catch (final DecoderException e) { } } @Test public void testDecodeBadCharacterPos1() { try { new Hex().decode("0q"); fail("An exception wasn't thrown when trying to decode an illegal character"); } catch (final DecoderException e) { } } @Test public void testDecodeClassCastException() { try { new Hex().decode(new int[]{65}); fail("An exception wasn't thrown when trying to decode."); } catch (final DecoderException e) { } } @Test public void testDecodeStringOddCharacters() { try { new Hex().decode("6"); fail("An exception wasn't thrown when trying to decode an odd number of characters"); } catch (final DecoderException e) { } }
### Question: CommonGetBuilder extends AbstractCommonBuilder { @Override public String buildSql() { String s1 = Joiner.on(", ").join(columns); return isBatch ? String.format(BATCH_SQL_TEMPLATE, s1, columnId) : String.format(SQL_TEMPLATE, s1, columnId); } CommonGetBuilder(String colId, List<String> cols, boolean isBatch); @Override String buildSql(); }### Answer: @Test public void build() throws Exception { List<String> columns = Lists.newArrayList("id2", "user_name", "user_age"); CommonGetBuilder b = new CommonGetBuilder("id2", columns, false); assertThat(b.buildSql(), equalTo("select id2, user_name, user_age from #table where id2 = :1")); b = new CommonGetBuilder("id2", columns, true); assertThat(b.buildSql(), equalTo("select id2, user_name, user_age from #table where id2 in (:1)")); }
### Question: Hex implements BinaryEncoder, BinaryDecoder { @Override public byte[] encode(final byte[] array) { return encodeHexString(array).getBytes(this.getCharset()); } Hex(); Hex(final Charset charset); Hex(final String charsetName); static byte[] decodeHex(final char[] data); static char[] encodeHex(final byte[] data); static char[] encodeHex(final byte[] data, final boolean toLowerCase); static String encodeHexString(final byte[] data); @Override byte[] decode(final byte[] array); @Override Object decode(final Object object); @Override byte[] encode(final byte[] array); @Override Object encode(final Object object); Charset getCharset(); String getCharsetName(); @Override String toString(); static final Charset DEFAULT_CHARSET; static final String DEFAULT_CHARSET_NAME; }### Answer: @Test public void testEncodeClassCastException() { try { new Hex().encode(new int[]{65}); fail("An exception wasn't thrown when trying to encode."); } catch (final EncoderException e) { } }
### Question: CommonDeleteBuilder extends AbstractCommonBuilder { @Override public String buildSql() { return String.format(SQL_TEMPLATE, columnId); } CommonDeleteBuilder(String colId); @Override String buildSql(); }### Answer: @Test public void build() throws Exception { CommonDeleteBuilder b = new CommonDeleteBuilder("id2"); assertThat(b.buildSql(), equalTo("delete from #table where id2 = :1")); }
### Question: CommonUpdateBuilder extends AbstractCommonBuilder { @Override public String buildSql() { List<String> exps = new ArrayList<String>(); for (int i = 0; i < properties.size(); i++) { String exp = columns.get(i) + " = :" + properties.get(i); exps.add(exp); } String s1 = Joiner.on(", ").join(exps); String s2 = columnId + " = :" + propertyId; return String.format(SQL_TEMPLATE, s1, s2); } CommonUpdateBuilder(String propId, List<String> props, List<String> cols); @Override String buildSql(); }### Answer: @Test public void build() throws Exception { List<String> properties = Lists.newArrayList("id", "userName", "userAge"); List<String> columns = Lists.newArrayList("id", "user_name", "user_age"); CommonUpdateBuilder b = new CommonUpdateBuilder("id", properties, columns); assertThat(b.buildSql(), equalTo("update #table set user_name = :userName, user_age = :userAge where id = :id")); }
### Question: URLCodec implements BinaryEncoder, BinaryDecoder, StringEncoder, StringDecoder { public static final byte[] decodeUrl(final byte[] bytes) throws DecoderException { if (bytes == null) { return null; } final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for (int i = 0; i < bytes.length; i++) { final int b = bytes[i]; if (b == '+') { buffer.write(' '); } else if (b == ESCAPE_CHAR) { try { final int u = Utils.digit16(bytes[++i]); final int l = Utils.digit16(bytes[++i]); buffer.write((char) ((u << 4) + l)); } catch (final ArrayIndexOutOfBoundsException e) { throw new DecoderException("Invalid URL encoding: ", e); } } else { buffer.write(b); } } return buffer.toByteArray(); } URLCodec(); URLCodec(final String charset); static final byte[] encodeUrl(BitSet urlsafe, final byte[] bytes); static final byte[] decodeUrl(final byte[] bytes); @Override byte[] encode(final byte[] bytes); @Override byte[] decode(final byte[] bytes); String encode(final String str, final String charset); @Override String encode(final String str); String decode(final String str, final String charset); @Override String decode(final String str); @Override Object encode(final Object obj); @Override Object decode(final Object obj); String getDefaultCharset(); @Deprecated String getEncoding(); }### Answer: @Test public void testDecodeWithNullArray() throws Exception { final byte[] plain = null; final byte[] result = URLCodec.decodeUrl( plain ); assertEquals("Result should be null", null, result); }
### Question: QCodec extends RFC1522Codec implements StringEncoder, StringDecoder { public String encode(final String str, final Charset charset) throws EncoderException { if (str == null) { return null; } return encodeText(str, charset); } QCodec(); QCodec(final Charset charset); QCodec(final String charsetName); String encode(final String str, final Charset charset); String encode(final String str, final String charset); @Override String encode(final String str); @Override String decode(final String str); @Override Object encode(final Object obj); @Override Object decode(final Object obj); Charset getCharset(); String getDefaultCharset(); boolean isEncodeBlanks(); void setEncodeBlanks(final boolean b); }### Answer: @Test public void testEncodeStringWithNull() throws Exception { final QCodec qcodec = new QCodec(); final String test = null; final String result = qcodec.encode( test, "charset" ); assertEquals("Result should be null", null, result); } @Test public void testEncodeObjects() throws Exception { final QCodec qcodec = new QCodec(); final String plain = "1+1 = 2"; final String encoded = (String) qcodec.encode((Object) plain); assertEquals("Basic Q encoding test", "=?UTF-8?Q?1+1 =3D 2?=", encoded); final Object result = qcodec.encode((Object) null); assertEquals( "Encoding a null Object should return null", null, result); try { final Object dObj = new Double(3.0); qcodec.encode( dObj ); fail( "Trying to url encode a Double object should cause an exception."); } catch (final EncoderException ee) { } }
### Question: CommonAddBuilder extends AbstractCommonBuilder { @Override public String buildSql() { String s1 = Joiner.on(", ").join(columns); List<String> cps = new ArrayList<String>(); for (String prop : properties) { cps.add(":" + prop); } String s2 = Joiner.on(", ").join(cps); return String.format(SQL_TEMPLATE, s1, s2); } CommonAddBuilder(String propId, List<String> props, List<String> cols, boolean isAutoGenerateId); @Override String buildSql(); }### Answer: @Test public void build() throws Exception { List<String> properties = Lists.newArrayList("id", "name", "age"); List<String> columns = Lists.newArrayList("id2", "name2", "age2"); CommonAddBuilder b = new CommonAddBuilder("id", properties, columns, true); assertThat(b.buildSql(), equalTo("insert into #table(name2, age2) values(:name, :age)")); properties = Lists.newArrayList("id", "name", "age"); columns = Lists.newArrayList("id2", "name2", "age2"); b = new CommonAddBuilder("id", properties, columns, false); assertThat(b.buildSql(), equalTo("insert into #table(id2, name2, age2) values(:id, :name, :age)")); }