src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
|---|---|
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; }
|
@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()); }
|
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; }
|
@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()); }
|
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); }
|
@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("")); }
|
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; }
|
@Test public void cookie() { Connection con = HttpConnection.connect("http: con.cookie("Name", "Val"); assertEquals("Val", con.request().cookie("Name")); }
|
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; }
|
@Test public void requestBody() { Connection con = HttpConnection.connect("http: con.requestBody("foo"); assertEquals("foo", con.request().requestBody()); }
|
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; }
|
@Test public void encodeUrl() throws MalformedURLException { URL url1 = new URL("http: URL url2 = HttpConnection.encodeUrl(url1); assertEquals("http: }
|
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(); }
|
@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"), " ")); }
|
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(); }
|
@Test public void padding() { assertEquals("", StringUtil.padding(0)); assertEquals(" ", StringUtil.padding(1)); assertEquals(" ", StringUtil.padding(2)); assertEquals(" ", StringUtil.padding(15)); assertEquals(" ", StringUtil.padding(45)); }
|
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(); }
|
@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 ")); }
|
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(); }
|
@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")); }
|
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(); }
|
@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')); }
|
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(); }
|
@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); }
|
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); }
|
@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)); }
|
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(); }
|
@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: }
|
W3CDom { public Document fromJsoup(org.jsoup.nodes.Document in) { Validate.notNull(in); DocumentBuilder builder; try { factory.setNamespaceAware(true); builder = factory.newDocumentBuilder(); Document out = builder.newDocument(); convert(in, out); return out; } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } } Document fromJsoup(org.jsoup.nodes.Document in); void convert(org.jsoup.nodes.Document in, Document out); String asString(Document doc); }
|
@Test public void namespacePreservation() throws IOException { File in = ParseTest.getFile("/htmltests/namespaces.xhtml"); org.jsoup.nodes.Document jsoupDoc; jsoupDoc = Jsoup.parse(in, "UTF-8"); Document doc; org.jsoup.helper.W3CDom jDom = new org.jsoup.helper.W3CDom(); doc = jDom.fromJsoup(jsoupDoc); Node htmlEl = doc.getChildNodes().item(0); assertEquals("http: assertEquals("html", htmlEl.getLocalName()); assertEquals("html", htmlEl.getNodeName()); Node epubTitle = htmlEl.getChildNodes().item(2).getChildNodes().item(3); assertEquals("http: assertEquals("title", epubTitle.getLocalName()); assertEquals("epub:title", epubTitle.getNodeName()); Node xSection = epubTitle.getNextSibling().getNextSibling(); assertEquals("urn:test", xSection.getNamespaceURI()); assertEquals("section", xSection.getLocalName()); assertEquals("x:section", xSection.getNodeName()); }
@Test public void handlesInvalidAttributeNames() { String html = "<html><head></head><body style=\"color: red\" \" name\"></body></html>"; org.jsoup.nodes.Document jsoupDoc; jsoupDoc = Jsoup.parse(html); Element body = jsoupDoc.select("body").first(); assertTrue(body.hasAttr("\"")); assertTrue(body.hasAttr("name\"")); Document w3Doc = new W3CDom().fromJsoup(jsoupDoc); }
@Test public void namespacePreservation() throws IOException { File in = ParseTest.getFile("/htmltests/namespaces.xhtml"); org.jsoup.nodes.Document jsoupDoc; jsoupDoc = Jsoup.parse(in, "UTF-8"); Document doc; W3CDom jDom = new W3CDom(); doc = jDom.fromJsoup(jsoupDoc); Node htmlEl = doc.getChildNodes().item(0); assertEquals("http: assertEquals("html", htmlEl.getLocalName()); assertEquals("html", htmlEl.getNodeName()); Node head = htmlEl.getFirstChild(); assertEquals("http: assertEquals("head", head.getLocalName()); assertEquals("head", head.getNodeName()); Node epubTitle = htmlEl.getChildNodes().item(2).getChildNodes().item(3); assertEquals("Check", epubTitle.getTextContent()); assertEquals("http: assertEquals("title", epubTitle.getLocalName()); assertEquals("epub:title", epubTitle.getNodeName()); Node xSection = epubTitle.getNextSibling().getNextSibling(); assertEquals("urn:test", xSection.getNamespaceURI()); assertEquals("section", xSection.getLocalName()); assertEquals("x:section", xSection.getNodeName()); Node svg = xSection.getNextSibling().getNextSibling(); assertEquals("http: assertEquals("svg", svg.getLocalName()); assertEquals("svg", svg.getNodeName()); Node path = svg.getChildNodes().item(1); assertEquals("http: assertEquals("path", path.getLocalName()); assertEquals("path", path.getNodeName()); Node clip = path.getChildNodes().item(1); assertEquals("http: assertEquals("clip", clip.getLocalName()); assertEquals("clip", clip.getNodeName()); assertEquals("456", clip.getTextContent()); Node picture = svg.getNextSibling().getNextSibling(); assertEquals("http: assertEquals("picture", picture.getLocalName()); assertEquals("picture", picture.getNodeName()); Node img = picture.getFirstChild(); assertEquals("http: assertEquals("img", img.getLocalName()); assertEquals("img", img.getNodeName()); }
@Test public void treatsUndeclaredNamespaceAsLocalName() { String html = "<fb:like>One</fb:like>"; org.jsoup.nodes.Document doc = Jsoup.parse(html); Document w3Doc = new W3CDom().fromJsoup(doc); Node htmlEl = w3Doc.getFirstChild(); assertNull(htmlEl.getNamespaceURI()); assertEquals("html", htmlEl.getLocalName()); assertEquals("html", htmlEl.getNodeName()); Node fb = htmlEl.getFirstChild().getNextSibling().getFirstChild(); assertNull(fb.getNamespaceURI()); assertEquals("like", fb.getLocalName()); assertEquals("fb:like", fb.getNodeName()); }
|
DataUtil { static String getCharsetFromContentType(String contentType) { if (contentType == null) return null; Matcher m = charsetPattern.matcher(contentType); if (m.find()) { String charset = m.group(1).trim(); charset = charset.replace("charset=", ""); return validateCharset(charset); } return null; } 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); }
|
@Test public void testCharset() { assertEquals("utf-8", DataUtil.getCharsetFromContentType("text/html;charset=utf-8 ")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html; charset=UTF-8")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=ISO-8859-1")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html")); assertEquals(null, DataUtil.getCharsetFromContentType(null)); assertEquals(null, DataUtil.getCharsetFromContentType("text/html;charset=Unknown")); }
@Test public void testQuotedCharset() { assertEquals("utf-8", DataUtil.getCharsetFromContentType("text/html; charset=\"utf-8\"")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html;charset=\"UTF-8\"")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=\"ISO-8859-1\"")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=\"Unsupported\"")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html; charset='UTF-8'")); }
@Test public void shouldNotThrowExceptionOnEmptyCharset() { assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=;")); }
@Test public void shouldSelectFirstCharsetOnWeirdMultileCharsetsInMetaTags() { assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=ISO-8859-1, charset=1251")); }
@Test public void shouldCorrectCharsetForDuplicateCharsetString() { assertEquals("iso-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=charset=iso-8859-1")); }
@Test public void shouldReturnNullForIllegalCharsetNames() { assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=$HJKDF§$/(")); }
|
DataUtil { static Document parseInputStream(InputStream input, String charsetName, String baseUri, Parser parser) throws IOException { if (input == null) return new Document(baseUri); if (!(input instanceof ConstrainableInputStream)) input = new ConstrainableInputStream(input, bufferSize, 0); Document doc = null; boolean fullyRead = false; input.mark(firstReadBufferSize); ByteBuffer firstBytes = readToByteBuffer(input, firstReadBufferSize - 1); fullyRead = input.read() == -1; input.reset(); BomCharset bomCharset = detectCharsetFromBom(firstBytes, charsetName); if (bomCharset != null) { charsetName = bomCharset.charset; input.skip(bomCharset.offset); } if (charsetName == null) { String docData = Charset.forName(defaultCharset).decode(firstBytes).toString(); doc = parser.parseInput(docData, baseUri); Elements metaElements = doc.select("meta[http-equiv=content-type], meta[charset]"); String foundCharset = null; for (Element meta : metaElements) { if (meta.hasAttr("http-equiv")) foundCharset = getCharsetFromContentType(meta.attr("content")); if (foundCharset == null && meta.hasAttr("charset")) foundCharset = meta.attr("charset"); if (foundCharset != null) break; } if (foundCharset == null && doc.childNodeSize() > 0 && doc.childNode(0) instanceof XmlDeclaration) { XmlDeclaration prolog = (XmlDeclaration) doc.childNode(0); if (prolog.name().equals("xml")) foundCharset = prolog.attr("encoding"); } foundCharset = validateCharset(foundCharset); if (foundCharset != null && !foundCharset.equalsIgnoreCase(defaultCharset)) { foundCharset = foundCharset.trim().replaceAll("[\"']", ""); charsetName = foundCharset; doc = null; } else if (!fullyRead) { doc = null; } } else { Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); } if (doc == null) { if (charsetName == null) charsetName = defaultCharset; BufferedReader reader = new BufferedReader(new InputStreamReader(input, charsetName), bufferSize); doc = parser.parseInput(reader, baseUri); doc.outputSettings().charset(charsetName); } input.close(); return doc; } 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); }
|
@Test public void discardsSpuriousByteOrderMark() throws IOException { String html = "\uFEFF<html><head><title>One</title></head><body>Two</body></html>"; Document doc = DataUtil.parseInputStream(stream(html), "UTF-8", "http: assertEquals("One", doc.head().text()); }
@Test public void discardsSpuriousByteOrderMarkWhenNoCharsetSet() throws IOException { String html = "\uFEFF<html><head><title>One</title></head><body>Two</body></html>"; Document doc = DataUtil.parseInputStream(stream(html), null, "http: assertEquals("One", doc.head().text()); assertEquals("UTF-8", doc.outputSettings().charset().displayName()); }
@Test public void wrongMetaCharsetFallback() throws IOException { String html = "<html><head><meta charset=iso-8></head><body></body></html>"; Document doc = DataUtil.parseInputStream(stream(html), null, "http: final String expected = "<html>\n" + " <head>\n" + " <meta charset=\"iso-8\">\n" + " </head>\n" + " <body></body>\n" + "</html>"; assertEquals(expected, doc.toString()); }
@Test public void secondMetaElementWithContentTypeContainsCharsetParameter() throws Exception { String html = "<html><head>" + "<meta http-equiv=\"Content-Type\" content=\"text/html\">" + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=euc-kr\">" + "</head><body>한국어</body></html>"; Document doc = DataUtil.parseInputStream(stream(html, "euc-kr"), null, "http: assertEquals("한국어", doc.body().text()); }
@Test public void firstMetaElementWithCharsetShouldBeUsedForDecoding() throws Exception { String html = "<html><head>" + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">" + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=koi8-u\">" + "</head><body>Übergrößenträger</body></html>"; Document doc = DataUtil.parseInputStream(stream(html, "iso-8859-1"), null, "http: assertEquals("Übergrößenträger", doc.body().text()); }
|
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); }
|
@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)); }
|
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); }
|
@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); }
|
ClosureUtils { public static <E> Closure<E> exceptionClosure() { return ExceptionClosure.<E>exceptionClosure(); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure,
final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes,
final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure,
final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures,
final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }
|
@Test public void testExceptionClosure() { assertNotNull(ClosureUtils.exceptionClosure()); assertSame(ClosureUtils.exceptionClosure(), ClosureUtils.exceptionClosure()); try { ClosureUtils.exceptionClosure().execute(null); } catch (final FunctorException ex) { try { ClosureUtils.exceptionClosure().execute(cString); } catch (final FunctorException ex2) { return; } } fail(); }
|
ClosureUtils { public static <E> Closure<E> nopClosure() { return NOPClosure.<E>nopClosure(); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure,
final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes,
final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure,
final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures,
final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }
|
@Test public void testNopClosure() { final StringBuilder buf = new StringBuilder("Hello"); ClosureUtils.nopClosure().execute(null); assertEquals("Hello", buf.toString()); ClosureUtils.nopClosure().execute("Hello"); assertEquals("Hello", buf.toString()); }
|
ClosureUtils { public static <E> Closure<E> invokerClosure(final String methodName) { return asClosure(InvokerTransformer.<E, Object>invokerTransformer(methodName)); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure,
final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes,
final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure,
final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures,
final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }
|
@Test public void testInvokeClosure() { StringBuffer buf = new StringBuffer("Hello"); ClosureUtils.invokerClosure("reverse").execute(buf); assertEquals("olleH", buf.toString()); buf = new StringBuffer("Hello"); ClosureUtils.invokerClosure("setLength", new Class[] {Integer.TYPE}, new Object[] {Integer.valueOf(2)}).execute(buf); assertEquals("He", buf.toString()); }
|
ClosureUtils { public static <E> Closure<E> forClosure(final int count, final Closure<? super E> closure) { return ForClosure.forClosure(count, closure); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure,
final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes,
final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure,
final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures,
final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }
|
@Test public void testForClosure() { final MockClosure<Object> cmd = new MockClosure<Object>(); ClosureUtils.forClosure(5, cmd).execute(null); assertEquals(5, cmd.count); assertSame(NOPClosure.INSTANCE, ClosureUtils.forClosure(0, new MockClosure<Object>())); assertSame(NOPClosure.INSTANCE, ClosureUtils.forClosure(-1, new MockClosure<Object>())); assertSame(NOPClosure.INSTANCE, ClosureUtils.forClosure(1, null)); assertSame(NOPClosure.INSTANCE, ClosureUtils.forClosure(3, null)); assertSame(cmd, ClosureUtils.forClosure(1, cmd)); }
|
ClosureUtils { public static <E> Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure) { return WhileClosure.<E>whileClosure(predicate, closure, false); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure,
final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes,
final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure,
final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures,
final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }
|
@Test public void testWhileClosure() { MockClosure<Object> cmd = new MockClosure<Object>(); ClosureUtils.whileClosure(FalsePredicate.falsePredicate(), cmd).execute(null); assertEquals(0, cmd.count); cmd = new MockClosure<Object>(); ClosureUtils.whileClosure(PredicateUtils.uniquePredicate(), cmd).execute(null); assertEquals(1, cmd.count); try { ClosureUtils.whileClosure(null, ClosureUtils.nopClosure()); fail(); } catch (final NullPointerException ex) {} try { ClosureUtils.whileClosure(FalsePredicate.falsePredicate(), null); fail(); } catch (final NullPointerException ex) {} try { ClosureUtils.whileClosure(null, null); fail(); } catch (final NullPointerException ex) {} }
|
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); }
|
@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")); }
|
ClosureUtils { public static <E> Closure<E> doWhileClosure(final Closure<? super E> closure, final Predicate<? super E> predicate) { return WhileClosure.<E>whileClosure(predicate, closure, true); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure,
final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes,
final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure,
final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures,
final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }
|
@Test public void testDoWhileClosure() { MockClosure<Object> cmd = new MockClosure<Object>(); ClosureUtils.doWhileClosure(cmd, FalsePredicate.falsePredicate()).execute(null); assertEquals(1, cmd.count); cmd = new MockClosure<Object>(); ClosureUtils.doWhileClosure(cmd, PredicateUtils.uniquePredicate()).execute(null); assertEquals(2, cmd.count); try { ClosureUtils.doWhileClosure(null, null); fail(); } catch (final NullPointerException ex) {} }
|
ClosureUtils { public static <E> Closure<E> chainedClosure(final Closure<? super E>... closures) { return ChainedClosure.chainedClosure(closures); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure,
final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes,
final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure,
final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures,
final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }
|
@Test @SuppressWarnings("unchecked") public void testChainedClosure() { MockClosure<Object> a = new MockClosure<Object>(); MockClosure<Object> b = new MockClosure<Object>(); ClosureUtils.chainedClosure(a, b).execute(null); assertEquals(1, a.count); assertEquals(1, b.count); a = new MockClosure<Object>(); b = new MockClosure<Object>(); ClosureUtils.<Object>chainedClosure(new Closure[] {a, b, a}).execute(null); assertEquals(2, a.count); assertEquals(1, b.count); a = new MockClosure<Object>(); b = new MockClosure<Object>(); Collection<Closure<Object>> coll = new ArrayList<Closure<Object>>(); coll.add(b); coll.add(a); coll.add(b); ClosureUtils.<Object>chainedClosure(coll).execute(null); assertEquals(1, a.count); assertEquals(2, b.count); assertSame(NOPClosure.INSTANCE, ClosureUtils.<Object>chainedClosure(new Closure[0])); assertSame(NOPClosure.INSTANCE, ClosureUtils.<Object>chainedClosure(Collections.<Closure<Object>>emptyList())); try { ClosureUtils.chainedClosure(null, null); fail(); } catch (final NullPointerException ex) {} try { ClosureUtils.<Object>chainedClosure((Closure[]) null); fail(); } catch (final NullPointerException ex) {} try { ClosureUtils.<Object>chainedClosure((Collection<Closure<Object>>) null); fail(); } catch (final NullPointerException ex) {} try { ClosureUtils.<Object>chainedClosure(new Closure[] {null, null}); fail(); } catch (final NullPointerException ex) {} try { coll = new ArrayList<Closure<Object>>(); coll.add(null); coll.add(null); ClosureUtils.chainedClosure(coll); fail(); } catch (final NullPointerException ex) {} }
|
ClosureUtils { public static <E> Closure<E> ifClosure(final Predicate<? super E> predicate, final Closure<? super E> trueClosure) { return IfClosure.<E>ifClosure(predicate, trueClosure); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure,
final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes,
final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure,
final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures,
final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }
|
@Test public void testIfClosure() { MockClosure<Object> a = new MockClosure<Object>(); MockClosure<Object> b = null; ClosureUtils.ifClosure(TruePredicate.truePredicate(), a).execute(null); assertEquals(1, a.count); a = new MockClosure<Object>(); ClosureUtils.ifClosure(FalsePredicate.<Object>falsePredicate(), a).execute(null); assertEquals(0, a.count); a = new MockClosure<Object>(); b = new MockClosure<Object>(); ClosureUtils.ifClosure(TruePredicate.<Object>truePredicate(), a, b).execute(null); assertEquals(1, a.count); assertEquals(0, b.count); a = new MockClosure<Object>(); b = new MockClosure<Object>(); ClosureUtils.ifClosure(FalsePredicate.<Object>falsePredicate(), a, b).execute(null); assertEquals(0, a.count); assertEquals(1, b.count); }
|
ClosureUtils { public static <E> Closure<E> switchClosure(final Predicate<? super E>[] predicates, final Closure<? super E>[] closures) { return SwitchClosure.<E>switchClosure(predicates, closures, null); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure,
final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes,
final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure,
final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures,
final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }
|
@Test @SuppressWarnings("unchecked") public void testSwitchClosure() { final MockClosure<String> a = new MockClosure<String>(); final MockClosure<String> b = new MockClosure<String>(); ClosureUtils.<String>switchClosure( new Predicate[] { EqualPredicate.equalPredicate("HELLO"), EqualPredicate.equalPredicate("THERE") }, new Closure[] { a, b }).execute("WELL"); assertEquals(0, a.count); assertEquals(0, b.count); a.reset(); b.reset(); ClosureUtils.<String>switchClosure( new Predicate[] { EqualPredicate.equalPredicate("HELLO"), EqualPredicate.equalPredicate("THERE") }, new Closure[] { a, b }).execute("HELLO"); assertEquals(1, a.count); assertEquals(0, b.count); a.reset(); b.reset(); final MockClosure<String> c = new MockClosure<String>(); ClosureUtils.<String>switchClosure( new Predicate[] { EqualPredicate.equalPredicate("HELLO"), EqualPredicate.equalPredicate("THERE") }, new Closure[] { a, b }, c).execute("WELL"); assertEquals(0, a.count); assertEquals(0, b.count); assertEquals(1, c.count); a.reset(); b.reset(); final Map<Predicate<String>, Closure<String>> map = new HashMap<Predicate<String>, Closure<String>>(); map.put(EqualPredicate.equalPredicate("HELLO"), a); map.put(EqualPredicate.equalPredicate("THERE"), b); ClosureUtils.<String>switchClosure(map).execute(null); assertEquals(0, a.count); assertEquals(0, b.count); a.reset(); b.reset(); map.clear(); map.put(EqualPredicate.equalPredicate("HELLO"), a); map.put(EqualPredicate.equalPredicate("THERE"), b); ClosureUtils.switchClosure(map).execute("THERE"); assertEquals(0, a.count); assertEquals(1, b.count); a.reset(); b.reset(); c.reset(); map.clear(); map.put(EqualPredicate.equalPredicate("HELLO"), a); map.put(EqualPredicate.equalPredicate("THERE"), b); map.put(null, c); ClosureUtils.switchClosure(map).execute("WELL"); assertEquals(0, a.count); assertEquals(0, b.count); assertEquals(1, c.count); assertEquals(NOPClosure.INSTANCE, ClosureUtils.<String>switchClosure(new Predicate[0], new Closure[0])); assertEquals(NOPClosure.INSTANCE, ClosureUtils.<String>switchClosure(new HashMap<Predicate<String>, Closure<String>>())); map.clear(); map.put(null, null); assertEquals(NOPClosure.INSTANCE, ClosureUtils.switchClosure(map)); try { ClosureUtils.switchClosure(null, null); fail(); } catch (final NullPointerException ex) {} try { ClosureUtils.<String>switchClosure((Predicate<String>[]) null, (Closure<String>[]) null); fail(); } catch (final NullPointerException ex) {} try { ClosureUtils.<String>switchClosure((Map<Predicate<String>, Closure<String>>) null); fail(); } catch (final NullPointerException ex) {} try { ClosureUtils.<String>switchClosure(new Predicate[2], new Closure[2]); fail(); } catch (final NullPointerException ex) {} try { ClosureUtils.<String>switchClosure( new Predicate[] { TruePredicate.<String>truePredicate() }, new Closure[] { a, b }); fail(); } catch (final IllegalArgumentException ex) {} }
|
ClosureUtils { @SuppressWarnings("unchecked") public static <E> Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures) { if (objectsAndClosures == null) { throw new NullPointerException("The object and closure map must not be null"); } final Closure<? super E> def = objectsAndClosures.remove(null); final int size = objectsAndClosures.size(); final Closure<? super E>[] trs = new Closure[size]; final Predicate<E>[] preds = new Predicate[size]; int i = 0; for (final Map.Entry<? extends E, Closure<E>> entry : objectsAndClosures.entrySet()) { preds[i] = EqualPredicate.<E>equalPredicate(entry.getKey()); trs[i] = entry.getValue(); i++; } return ClosureUtils.<E>switchClosure(preds, trs, def); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure,
final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes,
final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate,
final Closure<? super E> trueClosure,
final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates,
final Closure<? super E>[] closures,
final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }
|
@Test public void testSwitchMapClosure() { final MockClosure<String> a = new MockClosure<String>(); final MockClosure<String> b = new MockClosure<String>(); final Map<String, Closure<String>> map = new HashMap<String, Closure<String>>(); map.put("HELLO", a); map.put("THERE", b); ClosureUtils.switchMapClosure(map).execute(null); assertEquals(0, a.count); assertEquals(0, b.count); a.reset(); b.reset(); map.clear(); map.put("HELLO", a); map.put("THERE", b); ClosureUtils.switchMapClosure(map).execute("THERE"); assertEquals(0, a.count); assertEquals(1, b.count); a.reset(); b.reset(); map.clear(); final MockClosure<String> c = new MockClosure<String>(); map.put("HELLO", a); map.put("THERE", b); map.put(null, c); ClosureUtils.switchMapClosure(map).execute("WELL"); assertEquals(0, a.count); assertEquals(0, b.count); assertEquals(1, c.count); assertEquals(NOPClosure.INSTANCE, ClosureUtils.switchMapClosure(new HashMap<String, Closure<String>>())); try { ClosureUtils.switchMapClosure(null); fail(); } catch (final NullPointerException ex) {} }
|
ComparatorChain implements Comparator<E>, Serializable { @Override public int compare(final E o1, final E o2) throws UnsupportedOperationException { if (isLocked == false) { checkChainIntegrity(); isLocked = true; } final Iterator<Comparator<E>> comparators = comparatorChain.iterator(); for (int comparatorIndex = 0; comparators.hasNext(); ++comparatorIndex) { final Comparator<? super E> comparator = comparators.next(); int retval = comparator.compare(o1,o2); if (retval != 0) { if (orderingBits.get(comparatorIndex) == true) { if (retval > 0) { retval = -1; } else { retval = 1; } } return retval; } } return 0; } ComparatorChain(); ComparatorChain(final Comparator<E> comparator); ComparatorChain(final Comparator<E> comparator, final boolean reverse); ComparatorChain(final List<Comparator<E>> list); ComparatorChain(final List<Comparator<E>> list, final BitSet bits); void addComparator(final Comparator<E> comparator); void addComparator(final Comparator<E> comparator, final boolean reverse); void setComparator(final int index, final Comparator<E> comparator); void setComparator(final int index, final Comparator<E> comparator, final boolean reverse); void setForwardSort(final int index); void setReverseSort(final int index); int size(); boolean isLocked(); @Override int compare(final E o1, final E o2); @Override int hashCode(); @Override boolean equals(final Object object); }
|
@Test public void testBadNoopComparatorChain() { final ComparatorChain<Integer> chain = new ComparatorChain<Integer>(); final Integer i1 = Integer.valueOf(4); final Integer i2 = Integer.valueOf(6); try { chain.compare(i1,i2); fail("An exception should be thrown when a chain contains zero comparators."); } catch (final UnsupportedOperationException e) { } }
@Test public void testListComparatorChain() { final List<Comparator<Integer>> list = new LinkedList<Comparator<Integer>>(); list.add(new ComparableComparator<Integer>()); final ComparatorChain<Integer> chain = new ComparatorChain<Integer>(list); final Integer i1 = Integer.valueOf(4); final Integer i2 = Integer.valueOf(6); final int correctValue = i1.compareTo(i2); assertTrue("Comparison returns the right order", chain.compare(i1, i2) == correctValue); }
@Test public void testBadListComparatorChain() { final List<Comparator<Integer>> list = new LinkedList<Comparator<Integer>>(); final ComparatorChain<Integer> chain = new ComparatorChain<Integer>(list); final Integer i1 = Integer.valueOf(4); final Integer i2 = Integer.valueOf(6); try { chain.compare(i1, i2); fail("An exception should be thrown when a chain contains zero comparators."); } catch (final UnsupportedOperationException e) { } }
|
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); }
|
@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); }
|
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); }
|
@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")); }
|
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); }
|
@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)); }
|
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); }
|
@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)); }
|
SplitMapUtils { @SuppressWarnings("unchecked") public static <K, V> IterableMap<K, V> readableMap(final Get<K, V> get) { if (get == null) { throw new NullPointerException("Get must not be null"); } if (get instanceof Map) { return get instanceof IterableMap ? ((IterableMap<K, V>) get) : MapUtils.iterableMap((Map<K, V>) get); } return new WrappedGet<K, V>(get); } private SplitMapUtils(); @SuppressWarnings("unchecked") static IterableMap<K, V> readableMap(final Get<K, V> get); @SuppressWarnings("unchecked") static Map<K, V> writableMap(final Put<K, V> put); }
|
@Test public void testReadableMap() { final IterableMap<String, Integer> map = SplitMapUtils.readableMap(transformedMap); for (int i = 0; i < 10; i++) { assertFalse(map.containsValue(String.valueOf(i))); assertEquals(i, map.get(String.valueOf(i)).intValue()); } final MapIterator<String, Integer> it = map.mapIterator(); while (it.hasNext()) { final String k = it.next(); assertEquals(k, it.getKey()); assertEquals(Integer.valueOf(k), it.getValue()); } assertTrue(map instanceof Unmodifiable); int sz = map.size(); attemptPutOperation(new Runnable() { public void run() { map.clear(); } }); assertEquals(sz, map.size()); attemptPutOperation(new Runnable() { public void run() { map.put("foo", 100); } }); final HashMap<String, Integer> m = new HashMap<String, Integer>(); m.put("foo", 100); m.put("bar", 200); m.put("baz", 300); attemptPutOperation(new Runnable() { public void run() { map.putAll(m); } }); final IterableMap<String, Integer> other = SplitMapUtils.readableMap(transformedMap); assertEquals(other, map); assertEquals(other.hashCode(), map.hashCode()); for (int i = 0; i < 10; i++) { assertEquals(i, map.remove(String.valueOf(i)).intValue()); assertEquals(--sz, map.size()); } assertTrue(map.isEmpty()); assertSame(map, SplitMapUtils.readableMap(map)); }
@Test public void testAlreadyReadableMap() { final HashedMap<String, Integer> hashedMap = new HashedMap<String, Integer>(); assertSame(hashedMap, SplitMapUtils.readableMap(hashedMap)); }
|
SplitMapUtils { @SuppressWarnings("unchecked") public static <K, V> Map<K, V> writableMap(final Put<K, V> put) { if (put == null) { throw new NullPointerException("Put must not be null"); } if (put instanceof Map) { return (Map<K, V>) put; } return new WrappedPut<K, V>(put); } private SplitMapUtils(); @SuppressWarnings("unchecked") static IterableMap<K, V> readableMap(final Get<K, V> get); @SuppressWarnings("unchecked") static Map<K, V> writableMap(final Put<K, V> put); }
|
@Test @SuppressWarnings("unchecked") public void testWritableMap() { final Map<String, String> map = SplitMapUtils.writableMap(transformedMap); attemptGetOperation(new Runnable() { public void run() { map.get(null); } }); attemptGetOperation(new Runnable() { public void run() { map.entrySet(); } }); attemptGetOperation(new Runnable() { public void run() { map.keySet(); } }); attemptGetOperation(new Runnable() { public void run() { map.values(); } }); attemptGetOperation(new Runnable() { public void run() { map.size(); } }); attemptGetOperation(new Runnable() { public void run() { map.isEmpty(); } }); attemptGetOperation(new Runnable() { public void run() { map.containsKey(null); } }); attemptGetOperation(new Runnable() { public void run() { map.containsValue(null); } }); attemptGetOperation(new Runnable() { public void run() { map.remove(null); } }); final Map<String, String> other = SplitMapUtils.writableMap(transformedMap); assertEquals(other, map); assertEquals(other.hashCode(), map.hashCode()); int sz = backingMap.size(); assertFalse(backingMap.containsKey("foo")); map.put("new", "66"); assertEquals(++sz, backingMap.size()); final Map<String, String> more = new HashMap<String, String>(); more.put("foo", "77"); more.put("bar", "88"); more.put("baz", "99"); map.putAll(more); assertEquals(sz + more.size(), backingMap.size()); map.clear(); assertTrue(backingMap.isEmpty()); assertSame(map, SplitMapUtils.writableMap((Put<String, String>) map)); }
@Test public void testAlreadyWritableMap() { final HashedMap<String, String> hashedMap = new HashedMap<String, String>(); assertSame(hashedMap, SplitMapUtils.writableMap(hashedMap)); }
|
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; }
|
@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) { } }
|
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; }
|
@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)); }
|
BagUtils { public static <E> Bag<E> predicatedBag(final Bag<E> bag, final Predicate<? super E> predicate) { return PredicatedBag.predicatedBag(bag, predicate); } 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; }
|
@Test public void testPredicatedBag() { Bag<Object> bag = BagUtils.predicatedBag(new HashBag<Object>(), truePredicate); assertTrue("Returned object should be a PredicatedBag.", bag instanceof PredicatedBag); try { BagUtils.predicatedBag(null,truePredicate); fail("Expecting NullPointerException for null bag."); } catch (final NullPointerException ex) { } try { BagUtils.predicatedBag(new HashBag<Object>(), null); fail("Expecting NullPointerException for null predicate."); } catch (final NullPointerException ex) { } }
|
BagUtils { public static <E> Bag<E> transformingBag(final Bag<E> bag, final Transformer<? super E, ? extends E> transformer) { return TransformedBag.transformingBag(bag, transformer); } 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; }
|
@Test public void testTransformedBag() { Bag<Object> bag = BagUtils.transformingBag(new HashBag<Object>(), nopTransformer); assertTrue("Returned object should be an TransformedBag.", bag instanceof TransformedBag); try { BagUtils.transformingBag(null, nopTransformer); fail("Expecting NullPointerException for null bag."); } catch (final NullPointerException ex) { } try { BagUtils.transformingBag(new HashBag<Object>(), null); fail("Expecting NullPointerException for null transformer."); } catch (final NullPointerException ex) { } }
|
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; }
|
@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) { } }
|
BagUtils { public static <E> SortedBag<E> unmodifiableSortedBag(final SortedBag<E> bag) { return UnmodifiableSortedBag.unmodifiableSortedBag(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; }
|
@Test public void testUnmodifiableSortedBag() { SortedBag<Object> bag = BagUtils.unmodifiableSortedBag(new TreeBag<Object>()); assertTrue("Returned object should be an UnmodifiableSortedBag.", bag instanceof UnmodifiableSortedBag); try { BagUtils.unmodifiableSortedBag(null); fail("Expecting NullPointerException for null bag."); } catch (final NullPointerException ex) { } assertSame("UnmodifiableSortedBag shall not be decorated", bag, BagUtils.unmodifiableSortedBag(bag)); }
|
Methods { static Type resolveType(Type type, TypeToken<?> daoTypeToken) { return genericTypeToken.isAssignableFrom(daoTypeToken) ? daoTypeToken.resolveType(type).getType() : type; } static MethodDescriptor getMethodDescriptor(Class<?> daoClass, Method method, boolean isUseActualParamName); static List<Method> listMethods(Class<?> clazz); }
|
@Test public void testResolveType() throws Exception { TypeToken<?> daoTypeToken = TypeToken.of(SubDao.class); Method m = SubDao.class.getMethod("add", Object.class); Type type = Methods.fixAndResolveType(m.getGenericReturnType(), daoTypeToken); assertThat(type, equalTo((Type) void.class)); type = Methods.fixAndResolveType(m.getGenericParameterTypes()[0], daoTypeToken); assertThat(type, equalTo((Type) String.class)); m = SubDao.class.getMethod("add", Collection.class); type = Methods.fixAndResolveType(m.getGenericReturnType(), daoTypeToken); assertThat(TypeToken.of(type).getRawType(), equalTo((Type) int[].class)); type = Methods.fixAndResolveType(m.getGenericParameterTypes()[0], daoTypeToken); assertThat(type, equalTo((new TypeToken<Collection<String>>(){}.getType()))); m = SubDao.class.getMethod("findOne", Object.class); type = Methods.fixAndResolveType(m.getGenericReturnType(), daoTypeToken); assertThat(type, equalTo((Type) String.class)); type = Methods.fixAndResolveType(m.getGenericParameterTypes()[0], daoTypeToken); assertThat(type, equalTo((Type) Integer.class)); m = SubDao.class.getMethod("findAll", List.class); type = Methods.fixAndResolveType(m.getGenericReturnType(), daoTypeToken); assertThat(type, equalTo((new TypeToken<List<String>>(){}.getType()))); type = Methods.fixAndResolveType(m.getGenericParameterTypes()[0], daoTypeToken); assertThat(type, equalTo((new TypeToken<List<Integer>>(){}.getType()))); m = SubDao.class.getMethod("update", Object.class); type = Methods.fixAndResolveType(m.getGenericReturnType(), daoTypeToken); assertThat(type, equalTo((Type) int.class)); type = Methods.fixAndResolveType(m.getGenericParameterTypes()[0], daoTypeToken); assertThat(type, equalTo((Type) String.class)); m = SubDao.class.getMethod("update", Collection.class); type = Methods.fixAndResolveType(m.getGenericReturnType(), daoTypeToken); assertThat(TypeToken.of(type).getRawType(), equalTo((Type) int[].class)); type = Methods.fixAndResolveType(m.getGenericParameterTypes()[0], daoTypeToken); assertThat(type, equalTo((new TypeToken<Collection<String>>(){}.getType()))); m = SubDao.class.getMethod("delete", Object.class); type = Methods.fixAndResolveType(m.getGenericReturnType(), daoTypeToken); assertThat(type, equalTo((Type) int.class)); type = Methods.fixAndResolveType(m.getGenericParameterTypes()[0], daoTypeToken); assertThat(type, equalTo((Type) Integer.class)); m = SubDao.class.getMethod("getDate", List.class); type = Methods.fixAndResolveType(m.getGenericReturnType(), daoTypeToken); assertThat(type, equalTo((Type) Date.class)); type = Methods.fixAndResolveType(m.getGenericParameterTypes()[0], daoTypeToken); assertThat(type, equalTo((new TypeToken<List<String>>(){}.getType()))); }
|
BagUtils { public static <E> SortedBag<E> predicatedSortedBag(final SortedBag<E> bag, final Predicate<? super E> predicate) { return PredicatedSortedBag.predicatedSortedBag(bag, predicate); } 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; }
|
@Test public void testPredicatedSortedBag() { Bag<Object> bag = BagUtils.predicatedSortedBag(new TreeBag<Object>(), truePredicate); assertTrue("Returned object should be a PredicatedSortedBag.", bag instanceof PredicatedSortedBag); try { BagUtils.predicatedSortedBag(null, truePredicate); fail("Expecting NullPointerException for null bag."); } catch (final NullPointerException ex) { } try { BagUtils.predicatedSortedBag(new TreeBag<Object>(), null); fail("Expecting NullPointerException for null predicate."); } catch (final NullPointerException ex) { } }
|
BagUtils { public static <E> SortedBag<E> transformingSortedBag(final SortedBag<E> bag, final Transformer<? super E, ? extends E> transformer) { return TransformedSortedBag.transformingSortedBag(bag, transformer); } 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; }
|
@Test public void testTransformedSortedBag() { Bag<Object> bag = BagUtils.transformingSortedBag(new TreeBag<Object>(), nopTransformer); assertTrue("Returned object should be an TransformedSortedBag", bag instanceof TransformedSortedBag); try { BagUtils.transformingSortedBag(null, nopTransformer); fail("Expecting NullPointerException for null bag."); } catch (final NullPointerException ex) { } try { BagUtils.transformingSortedBag(new TreeBag<Object>(), null); fail("Expecting NullPointerException for null transformer."); } catch (final NullPointerException ex) { } }
|
IterableUtils { public static <E> void forEach(final Iterable<E> iterable, final Closure<? super E> closure) { IteratorUtils.forEach(emptyIteratorIfNull(iterable), closure); } @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type static Iterable<E> emptyIterable(); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c,
final Iterable<? extends E> d); static Iterable<E> chainedIterable(final Iterable<? extends E>... iterables); static Iterable<E> collatedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> collatedIterable(final Comparator<? super E> comparator,
final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> filteredIterable(final Iterable<E> iterable,
final Predicate<? super E> predicate); static Iterable<E> boundedIterable(final Iterable<E> iterable, final long maxSize); static Iterable<E> loopingIterable(final Iterable<E> iterable); static Iterable<E> reversedIterable(final Iterable<E> iterable); static Iterable<E> skippingIterable(final Iterable<E> iterable, final long elementsToSkip); static Iterable<O> transformedIterable(final Iterable<I> iterable,
final Transformer<? super I, ? extends O> transformer); static Iterable<E> uniqueIterable(final Iterable<E> iterable); static Iterable<E> unmodifiableIterable(final Iterable<E> iterable); static Iterable<E> zippingIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> zippingIterable(final Iterable<? extends E> first,
final Iterable<? extends E>... others); static Iterable<E> emptyIfNull(final Iterable<E> iterable); static void forEach(final Iterable<E> iterable, final Closure<? super E> closure); static E forEachButLast(final Iterable<E> iterable, final Closure<? super E> closure); static E find(final Iterable<E> iterable, final Predicate<? super E> predicate); static int indexOf(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAll(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAny(final Iterable<E> iterable, final Predicate<? super E> predicate); static long countMatches(final Iterable<E> input, final Predicate<? super E> predicate); static boolean isEmpty(final Iterable<?> iterable); static boolean contains(final Iterable<E> iterable, final Object object); static boolean contains(final Iterable<? extends E> iterable, final E object,
final Equator<? super E> equator); static int frequency(final Iterable<E> iterable, final T obj); static T get(final Iterable<T> iterable, final int index); static int size(final Iterable<?> iterable); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O> predicate); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O>... predicates); static List<R> partition(final Iterable<? extends O> iterable,
final Factory<R> partitionFactory, final Predicate<? super O>... predicates); static List<E> toList(final Iterable<E> iterable); static String toString(final Iterable<E> iterable); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer,
final String delimiter,
final String prefix,
final String suffix); }
|
@Test public void forEach() { final List<Integer> listA = new ArrayList<Integer>(); listA.add(1); final List<Integer> listB = new ArrayList<Integer>(); listB.add(2); final Closure<List<Integer>> testClosure = ClosureUtils.invokerClosure("clear"); final Collection<List<Integer>> col = new ArrayList<List<Integer>>(); col.add(listA); col.add(listB); IterableUtils.forEach(col, testClosure); assertTrue(listA.isEmpty() && listB.isEmpty()); try { IterableUtils.forEach(col, null); fail("expecting NullPointerException"); } catch (NullPointerException npe) { } IterableUtils.forEach(null, testClosure); col.add(null); IterableUtils.forEach(col, testClosure); }
@Test(expected = FunctorException.class) public void forEachFailure() { final Closure<String> testClosure = ClosureUtils.invokerClosure("clear"); final Collection<String> col = new ArrayList<String>(); col.add("x"); IterableUtils.forEach(col, testClosure); }
|
IterableUtils { public static <E> E forEachButLast(final Iterable<E> iterable, final Closure<? super E> closure) { return IteratorUtils.forEachButLast(emptyIteratorIfNull(iterable), closure); } @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type static Iterable<E> emptyIterable(); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c,
final Iterable<? extends E> d); static Iterable<E> chainedIterable(final Iterable<? extends E>... iterables); static Iterable<E> collatedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> collatedIterable(final Comparator<? super E> comparator,
final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> filteredIterable(final Iterable<E> iterable,
final Predicate<? super E> predicate); static Iterable<E> boundedIterable(final Iterable<E> iterable, final long maxSize); static Iterable<E> loopingIterable(final Iterable<E> iterable); static Iterable<E> reversedIterable(final Iterable<E> iterable); static Iterable<E> skippingIterable(final Iterable<E> iterable, final long elementsToSkip); static Iterable<O> transformedIterable(final Iterable<I> iterable,
final Transformer<? super I, ? extends O> transformer); static Iterable<E> uniqueIterable(final Iterable<E> iterable); static Iterable<E> unmodifiableIterable(final Iterable<E> iterable); static Iterable<E> zippingIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> zippingIterable(final Iterable<? extends E> first,
final Iterable<? extends E>... others); static Iterable<E> emptyIfNull(final Iterable<E> iterable); static void forEach(final Iterable<E> iterable, final Closure<? super E> closure); static E forEachButLast(final Iterable<E> iterable, final Closure<? super E> closure); static E find(final Iterable<E> iterable, final Predicate<? super E> predicate); static int indexOf(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAll(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAny(final Iterable<E> iterable, final Predicate<? super E> predicate); static long countMatches(final Iterable<E> input, final Predicate<? super E> predicate); static boolean isEmpty(final Iterable<?> iterable); static boolean contains(final Iterable<E> iterable, final Object object); static boolean contains(final Iterable<? extends E> iterable, final E object,
final Equator<? super E> equator); static int frequency(final Iterable<E> iterable, final T obj); static T get(final Iterable<T> iterable, final int index); static int size(final Iterable<?> iterable); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O> predicate); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O>... predicates); static List<R> partition(final Iterable<? extends O> iterable,
final Factory<R> partitionFactory, final Predicate<? super O>... predicates); static List<E> toList(final Iterable<E> iterable); static String toString(final Iterable<E> iterable); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer,
final String delimiter,
final String prefix,
final String suffix); }
|
@Test public void forEachButLast() { final List<Integer> listA = new ArrayList<Integer>(); listA.add(1); final List<Integer> listB = new ArrayList<Integer>(); listB.add(2); final Closure<List<Integer>> testClosure = ClosureUtils.invokerClosure("clear"); final Collection<List<Integer>> col = new ArrayList<List<Integer>>(); col.add(listA); col.add(listB); List<Integer> last = IterableUtils.forEachButLast(col, testClosure); assertTrue(listA.isEmpty() && !listB.isEmpty()); assertSame(listB, last); try { IterableUtils.forEachButLast(col, null); fail("expecting NullPointerException"); } catch (NullPointerException npe) { } IterableUtils.forEachButLast(null, testClosure); col.add(null); col.add(null); last = IterableUtils.forEachButLast(col, testClosure); assertNull(last); }
|
IterableUtils { public static <E> boolean contains(final Iterable<E> iterable, final Object object) { if (iterable instanceof Collection<?>) { return ((Collection<E>) iterable).contains(object); } else { return IteratorUtils.contains(emptyIteratorIfNull(iterable), object); } } @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type static Iterable<E> emptyIterable(); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c,
final Iterable<? extends E> d); static Iterable<E> chainedIterable(final Iterable<? extends E>... iterables); static Iterable<E> collatedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> collatedIterable(final Comparator<? super E> comparator,
final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> filteredIterable(final Iterable<E> iterable,
final Predicate<? super E> predicate); static Iterable<E> boundedIterable(final Iterable<E> iterable, final long maxSize); static Iterable<E> loopingIterable(final Iterable<E> iterable); static Iterable<E> reversedIterable(final Iterable<E> iterable); static Iterable<E> skippingIterable(final Iterable<E> iterable, final long elementsToSkip); static Iterable<O> transformedIterable(final Iterable<I> iterable,
final Transformer<? super I, ? extends O> transformer); static Iterable<E> uniqueIterable(final Iterable<E> iterable); static Iterable<E> unmodifiableIterable(final Iterable<E> iterable); static Iterable<E> zippingIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> zippingIterable(final Iterable<? extends E> first,
final Iterable<? extends E>... others); static Iterable<E> emptyIfNull(final Iterable<E> iterable); static void forEach(final Iterable<E> iterable, final Closure<? super E> closure); static E forEachButLast(final Iterable<E> iterable, final Closure<? super E> closure); static E find(final Iterable<E> iterable, final Predicate<? super E> predicate); static int indexOf(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAll(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAny(final Iterable<E> iterable, final Predicate<? super E> predicate); static long countMatches(final Iterable<E> input, final Predicate<? super E> predicate); static boolean isEmpty(final Iterable<?> iterable); static boolean contains(final Iterable<E> iterable, final Object object); static boolean contains(final Iterable<? extends E> iterable, final E object,
final Equator<? super E> equator); static int frequency(final Iterable<E> iterable, final T obj); static T get(final Iterable<T> iterable, final int index); static int size(final Iterable<?> iterable); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O> predicate); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O>... predicates); static List<R> partition(final Iterable<? extends O> iterable,
final Factory<R> partitionFactory, final Predicate<? super O>... predicates); static List<E> toList(final Iterable<E> iterable); static String toString(final Iterable<E> iterable); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer,
final String delimiter,
final String prefix,
final String suffix); }
|
@Test public void containsWithEquator() { final List<String> base = new ArrayList<String>(); base.add("AC"); base.add("BB"); base.add("CA"); final Equator<String> secondLetterEquator = new Equator<String>() { @Override public boolean equate(String o1, String o2) { return o1.charAt(1) == o2.charAt(1); } @Override public int hash(String o) { return o.charAt(1); } }; assertFalse(base.contains("CC")); assertTrue(IterableUtils.contains(base, "AC", secondLetterEquator)); assertTrue(IterableUtils.contains(base, "CC", secondLetterEquator)); assertFalse(IterableUtils.contains(base, "CX", secondLetterEquator)); assertFalse(IterableUtils.contains(null, null, secondLetterEquator)); try { IterableUtils.contains(base, "AC", null); fail("expecting NullPointerException"); } catch (final NullPointerException npe) { } }
|
IterableUtils { public static <E, T extends E> int frequency(final Iterable<E> iterable, final T obj) { if (iterable instanceof Set<?>) { return ((Set<E>) iterable).contains(obj) ? 1 : 0; } if (iterable instanceof Bag<?>) { return ((Bag<E>) iterable).getCount(obj); } return size(filteredIterable(emptyIfNull(iterable), EqualPredicate.<E>equalPredicate(obj))); } @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type static Iterable<E> emptyIterable(); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c,
final Iterable<? extends E> d); static Iterable<E> chainedIterable(final Iterable<? extends E>... iterables); static Iterable<E> collatedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> collatedIterable(final Comparator<? super E> comparator,
final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> filteredIterable(final Iterable<E> iterable,
final Predicate<? super E> predicate); static Iterable<E> boundedIterable(final Iterable<E> iterable, final long maxSize); static Iterable<E> loopingIterable(final Iterable<E> iterable); static Iterable<E> reversedIterable(final Iterable<E> iterable); static Iterable<E> skippingIterable(final Iterable<E> iterable, final long elementsToSkip); static Iterable<O> transformedIterable(final Iterable<I> iterable,
final Transformer<? super I, ? extends O> transformer); static Iterable<E> uniqueIterable(final Iterable<E> iterable); static Iterable<E> unmodifiableIterable(final Iterable<E> iterable); static Iterable<E> zippingIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> zippingIterable(final Iterable<? extends E> first,
final Iterable<? extends E>... others); static Iterable<E> emptyIfNull(final Iterable<E> iterable); static void forEach(final Iterable<E> iterable, final Closure<? super E> closure); static E forEachButLast(final Iterable<E> iterable, final Closure<? super E> closure); static E find(final Iterable<E> iterable, final Predicate<? super E> predicate); static int indexOf(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAll(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAny(final Iterable<E> iterable, final Predicate<? super E> predicate); static long countMatches(final Iterable<E> input, final Predicate<? super E> predicate); static boolean isEmpty(final Iterable<?> iterable); static boolean contains(final Iterable<E> iterable, final Object object); static boolean contains(final Iterable<? extends E> iterable, final E object,
final Equator<? super E> equator); static int frequency(final Iterable<E> iterable, final T obj); static T get(final Iterable<T> iterable, final int index); static int size(final Iterable<?> iterable); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O> predicate); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O>... predicates); static List<R> partition(final Iterable<? extends O> iterable,
final Factory<R> partitionFactory, final Predicate<? super O>... predicates); static List<E> toList(final Iterable<E> iterable); static String toString(final Iterable<E> iterable); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer,
final String delimiter,
final String prefix,
final String suffix); }
|
@Test public void frequency() { assertEquals(0, IterableUtils.frequency(null, 1)); assertEquals(1, IterableUtils.frequency(iterableA, 1)); assertEquals(2, IterableUtils.frequency(iterableA, 2)); assertEquals(3, IterableUtils.frequency(iterableA, 3)); assertEquals(4, IterableUtils.frequency(iterableA, 4)); assertEquals(0, IterableUtils.frequency(iterableA, 5)); assertEquals(0, IterableUtils.frequency(iterableB, 1L)); assertEquals(4, IterableUtils.frequency(iterableB, 2L)); assertEquals(3, IterableUtils.frequency(iterableB, 3L)); assertEquals(2, IterableUtils.frequency(iterableB, 4L)); assertEquals(1, IterableUtils.frequency(iterableB, 5L)); Iterable<Number> iterableIntAsNumber = Arrays.<Number>asList(1, 2, 3, 4, 5); Iterable<Number> iterableLongAsNumber = Arrays.<Number>asList(1L, 2L, 3L, 4L, 5L); assertEquals(0, IterableUtils.frequency(iterableIntAsNumber, 2L)); assertEquals(0, IterableUtils.frequency(iterableLongAsNumber, 2)); final Set<String> set = new HashSet<String>(); set.add("A"); set.add("C"); set.add("E"); set.add("E"); assertEquals(1, IterableUtils.frequency(set, "A")); assertEquals(0, IterableUtils.frequency(set, "B")); assertEquals(1, IterableUtils.frequency(set, "C")); assertEquals(0, IterableUtils.frequency(set, "D")); assertEquals(1, IterableUtils.frequency(set, "E")); final Bag<String> bag = new HashBag<String>(); bag.add("A", 3); bag.add("C"); bag.add("E"); bag.add("E"); assertEquals(3, IterableUtils.frequency(bag, "A")); assertEquals(0, IterableUtils.frequency(bag, "B")); assertEquals(1, IterableUtils.frequency(bag, "C")); assertEquals(0, IterableUtils.frequency(bag, "D")); assertEquals(2, IterableUtils.frequency(bag, "E")); }
@Test public void frequencyOfNull() { final List<String> list = new ArrayList<String>(); assertEquals(0, IterableUtils.frequency(list, null)); list.add("A"); assertEquals(0, IterableUtils.frequency(list, null)); list.add(null); assertEquals(1, IterableUtils.frequency(list, null)); list.add("B"); assertEquals(1, IterableUtils.frequency(list, null)); list.add(null); assertEquals(2, IterableUtils.frequency(list, null)); list.add("B"); assertEquals(2, IterableUtils.frequency(list, null)); list.add(null); assertEquals(3, IterableUtils.frequency(list, null)); }
|
IterableUtils { public static <E> E find(final Iterable<E> iterable, final Predicate<? super E> predicate) { return IteratorUtils.find(emptyIteratorIfNull(iterable), predicate); } @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type static Iterable<E> emptyIterable(); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c,
final Iterable<? extends E> d); static Iterable<E> chainedIterable(final Iterable<? extends E>... iterables); static Iterable<E> collatedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> collatedIterable(final Comparator<? super E> comparator,
final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> filteredIterable(final Iterable<E> iterable,
final Predicate<? super E> predicate); static Iterable<E> boundedIterable(final Iterable<E> iterable, final long maxSize); static Iterable<E> loopingIterable(final Iterable<E> iterable); static Iterable<E> reversedIterable(final Iterable<E> iterable); static Iterable<E> skippingIterable(final Iterable<E> iterable, final long elementsToSkip); static Iterable<O> transformedIterable(final Iterable<I> iterable,
final Transformer<? super I, ? extends O> transformer); static Iterable<E> uniqueIterable(final Iterable<E> iterable); static Iterable<E> unmodifiableIterable(final Iterable<E> iterable); static Iterable<E> zippingIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> zippingIterable(final Iterable<? extends E> first,
final Iterable<? extends E>... others); static Iterable<E> emptyIfNull(final Iterable<E> iterable); static void forEach(final Iterable<E> iterable, final Closure<? super E> closure); static E forEachButLast(final Iterable<E> iterable, final Closure<? super E> closure); static E find(final Iterable<E> iterable, final Predicate<? super E> predicate); static int indexOf(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAll(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAny(final Iterable<E> iterable, final Predicate<? super E> predicate); static long countMatches(final Iterable<E> input, final Predicate<? super E> predicate); static boolean isEmpty(final Iterable<?> iterable); static boolean contains(final Iterable<E> iterable, final Object object); static boolean contains(final Iterable<? extends E> iterable, final E object,
final Equator<? super E> equator); static int frequency(final Iterable<E> iterable, final T obj); static T get(final Iterable<T> iterable, final int index); static int size(final Iterable<?> iterable); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O> predicate); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O>... predicates); static List<R> partition(final Iterable<? extends O> iterable,
final Factory<R> partitionFactory, final Predicate<? super O>... predicates); static List<E> toList(final Iterable<E> iterable); static String toString(final Iterable<E> iterable); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer,
final String delimiter,
final String prefix,
final String suffix); }
|
@Test public void find() { Predicate<Number> testPredicate = equalPredicate((Number) 4); Integer test = IterableUtils.find(iterableA, testPredicate); assertTrue(test.equals(4)); testPredicate = equalPredicate((Number) 45); test = IterableUtils.find(iterableA, testPredicate); assertTrue(test == null); assertNull(IterableUtils.find(null,testPredicate)); try { assertNull(IterableUtils.find(iterableA, null)); fail("expecting NullPointerException"); } catch (final NullPointerException npe) { } }
|
IterableUtils { public static <E> int indexOf(final Iterable<E> iterable, final Predicate<? super E> predicate) { return IteratorUtils.indexOf(emptyIteratorIfNull(iterable), predicate); } @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type static Iterable<E> emptyIterable(); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c,
final Iterable<? extends E> d); static Iterable<E> chainedIterable(final Iterable<? extends E>... iterables); static Iterable<E> collatedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> collatedIterable(final Comparator<? super E> comparator,
final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> filteredIterable(final Iterable<E> iterable,
final Predicate<? super E> predicate); static Iterable<E> boundedIterable(final Iterable<E> iterable, final long maxSize); static Iterable<E> loopingIterable(final Iterable<E> iterable); static Iterable<E> reversedIterable(final Iterable<E> iterable); static Iterable<E> skippingIterable(final Iterable<E> iterable, final long elementsToSkip); static Iterable<O> transformedIterable(final Iterable<I> iterable,
final Transformer<? super I, ? extends O> transformer); static Iterable<E> uniqueIterable(final Iterable<E> iterable); static Iterable<E> unmodifiableIterable(final Iterable<E> iterable); static Iterable<E> zippingIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> zippingIterable(final Iterable<? extends E> first,
final Iterable<? extends E>... others); static Iterable<E> emptyIfNull(final Iterable<E> iterable); static void forEach(final Iterable<E> iterable, final Closure<? super E> closure); static E forEachButLast(final Iterable<E> iterable, final Closure<? super E> closure); static E find(final Iterable<E> iterable, final Predicate<? super E> predicate); static int indexOf(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAll(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAny(final Iterable<E> iterable, final Predicate<? super E> predicate); static long countMatches(final Iterable<E> input, final Predicate<? super E> predicate); static boolean isEmpty(final Iterable<?> iterable); static boolean contains(final Iterable<E> iterable, final Object object); static boolean contains(final Iterable<? extends E> iterable, final E object,
final Equator<? super E> equator); static int frequency(final Iterable<E> iterable, final T obj); static T get(final Iterable<T> iterable, final int index); static int size(final Iterable<?> iterable); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O> predicate); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O>... predicates); static List<R> partition(final Iterable<? extends O> iterable,
final Factory<R> partitionFactory, final Predicate<? super O>... predicates); static List<E> toList(final Iterable<E> iterable); static String toString(final Iterable<E> iterable); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer,
final String delimiter,
final String prefix,
final String suffix); }
|
@Test public void indexOf() { Predicate<Number> testPredicate = equalPredicate((Number) 4); int index = IterableUtils.indexOf(iterableA, testPredicate); assertEquals(6, index); testPredicate = equalPredicate((Number) 45); index = IterableUtils.indexOf(iterableA, testPredicate); assertEquals(-1, index); assertEquals(-1, IterableUtils.indexOf(null, testPredicate)); try { assertNull(IterableUtils.indexOf(iterableA, null)); fail("expecting NullPointerException"); } catch (final NullPointerException npe) { } }
|
InvocationInterceptorChain { public void intercept(BoundSql boundSql, InvocationContext context, DataSource dataSource) { if (interceptorChain.getInterceptors() != null) { List<Object> parameterValues = context.getParameterValues(); List<Parameter> parameters = new ArrayList<Parameter>(parameterValues.size()); for (int i = 0; i < parameterValues.size(); i++) { ParameterDescriptor pd = parameterDescriptors.get(i); parameters.add(new Parameter(pd, parameterValues.get(i))); } interceptorChain.intercept(boundSql, parameters, sqlType, dataSource); } } InvocationInterceptorChain(InterceptorChain interceptorChain,
List<ParameterDescriptor> parameterDescriptors,
SQLType sqlType); void intercept(BoundSql boundSql, InvocationContext context, DataSource dataSource); }
|
@Test public void testIntercept() throws Exception { final String sql = "select * from user where id=? and name=?"; BoundSql boundSql = new BoundSql(sql); boundSql.addArg(1); boundSql.addArg("ash"); final User user = new User(); user.setId(100); user.setName("lucy"); InterceptorChain ic = new InterceptorChain(); ic.addInterceptor(new Interceptor() { @Override public void intercept(BoundSql boundSql, List<Parameter> parameters, SQLType sqlType, DataSource dataSource) { assertThat(boundSql.getSql(), equalTo(sql)); assertThat(boundSql.getArgs(), equalTo(boundSql.getArgs())); assertThat(boundSql.getTypeHandlers(), equalTo(boundSql.getTypeHandlers())); assertThat((User) parameters.get(0).getValue(), equalTo(user)); assertThat(sqlType, equalTo(SQLType.SELECT)); } }); List<Annotation> empty = Collections.emptyList(); TypeToken<User> t = new TypeToken<User>() { }; ParameterDescriptor p = ParameterDescriptor.create(0, t.getType(), empty, "1"); List<ParameterDescriptor> pds = Arrays.asList(p); InvocationInterceptorChain iic = new InvocationInterceptorChain(ic, pds, SQLType.SELECT); InvocationContextFactory f = InvocationContextFactory.create(DefaultParameterContext.create(pds)); InvocationContext ctx = f.newInvocationContext(new Object[]{user}); iic.intercept(boundSql, ctx, null); }
|
IterableUtils { public static <E> long countMatches(final Iterable<E> input, final Predicate<? super E> predicate) { if (predicate == null) { throw new NullPointerException("Predicate must not be null."); } return size(filteredIterable(emptyIfNull(input), predicate)); } @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type static Iterable<E> emptyIterable(); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c,
final Iterable<? extends E> d); static Iterable<E> chainedIterable(final Iterable<? extends E>... iterables); static Iterable<E> collatedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> collatedIterable(final Comparator<? super E> comparator,
final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> filteredIterable(final Iterable<E> iterable,
final Predicate<? super E> predicate); static Iterable<E> boundedIterable(final Iterable<E> iterable, final long maxSize); static Iterable<E> loopingIterable(final Iterable<E> iterable); static Iterable<E> reversedIterable(final Iterable<E> iterable); static Iterable<E> skippingIterable(final Iterable<E> iterable, final long elementsToSkip); static Iterable<O> transformedIterable(final Iterable<I> iterable,
final Transformer<? super I, ? extends O> transformer); static Iterable<E> uniqueIterable(final Iterable<E> iterable); static Iterable<E> unmodifiableIterable(final Iterable<E> iterable); static Iterable<E> zippingIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> zippingIterable(final Iterable<? extends E> first,
final Iterable<? extends E>... others); static Iterable<E> emptyIfNull(final Iterable<E> iterable); static void forEach(final Iterable<E> iterable, final Closure<? super E> closure); static E forEachButLast(final Iterable<E> iterable, final Closure<? super E> closure); static E find(final Iterable<E> iterable, final Predicate<? super E> predicate); static int indexOf(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAll(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAny(final Iterable<E> iterable, final Predicate<? super E> predicate); static long countMatches(final Iterable<E> input, final Predicate<? super E> predicate); static boolean isEmpty(final Iterable<?> iterable); static boolean contains(final Iterable<E> iterable, final Object object); static boolean contains(final Iterable<? extends E> iterable, final E object,
final Equator<? super E> equator); static int frequency(final Iterable<E> iterable, final T obj); static T get(final Iterable<T> iterable, final int index); static int size(final Iterable<?> iterable); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O> predicate); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O>... predicates); static List<R> partition(final Iterable<? extends O> iterable,
final Factory<R> partitionFactory, final Predicate<? super O>... predicates); static List<E> toList(final Iterable<E> iterable); static String toString(final Iterable<E> iterable); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer,
final String delimiter,
final String prefix,
final String suffix); }
|
@Test public void countMatches() { assertEquals(4, IterableUtils.countMatches(iterableB, EQUALS_TWO)); assertEquals(0, IterableUtils.countMatches(null, EQUALS_TWO)); try { assertEquals(0, IterableUtils.countMatches(iterableA, null)); fail("predicate must not be null"); } catch (NullPointerException ex) { } try { assertEquals(0, IterableUtils.countMatches(null, null)); fail("predicate must not be null"); } catch (NullPointerException ex) { } }
|
IterableUtils { public static <E> boolean matchesAny(final Iterable<E> iterable, final Predicate<? super E> predicate) { return IteratorUtils.matchesAny(emptyIteratorIfNull(iterable), predicate); } @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type static Iterable<E> emptyIterable(); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c,
final Iterable<? extends E> d); static Iterable<E> chainedIterable(final Iterable<? extends E>... iterables); static Iterable<E> collatedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> collatedIterable(final Comparator<? super E> comparator,
final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> filteredIterable(final Iterable<E> iterable,
final Predicate<? super E> predicate); static Iterable<E> boundedIterable(final Iterable<E> iterable, final long maxSize); static Iterable<E> loopingIterable(final Iterable<E> iterable); static Iterable<E> reversedIterable(final Iterable<E> iterable); static Iterable<E> skippingIterable(final Iterable<E> iterable, final long elementsToSkip); static Iterable<O> transformedIterable(final Iterable<I> iterable,
final Transformer<? super I, ? extends O> transformer); static Iterable<E> uniqueIterable(final Iterable<E> iterable); static Iterable<E> unmodifiableIterable(final Iterable<E> iterable); static Iterable<E> zippingIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> zippingIterable(final Iterable<? extends E> first,
final Iterable<? extends E>... others); static Iterable<E> emptyIfNull(final Iterable<E> iterable); static void forEach(final Iterable<E> iterable, final Closure<? super E> closure); static E forEachButLast(final Iterable<E> iterable, final Closure<? super E> closure); static E find(final Iterable<E> iterable, final Predicate<? super E> predicate); static int indexOf(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAll(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAny(final Iterable<E> iterable, final Predicate<? super E> predicate); static long countMatches(final Iterable<E> input, final Predicate<? super E> predicate); static boolean isEmpty(final Iterable<?> iterable); static boolean contains(final Iterable<E> iterable, final Object object); static boolean contains(final Iterable<? extends E> iterable, final E object,
final Equator<? super E> equator); static int frequency(final Iterable<E> iterable, final T obj); static T get(final Iterable<T> iterable, final int index); static int size(final Iterable<?> iterable); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O> predicate); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O>... predicates); static List<R> partition(final Iterable<? extends O> iterable,
final Factory<R> partitionFactory, final Predicate<? super O>... predicates); static List<E> toList(final Iterable<E> iterable); static String toString(final Iterable<E> iterable); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer,
final String delimiter,
final String prefix,
final String suffix); }
|
@Test public void matchesAny() { final List<Integer> list = new ArrayList<Integer>(); try { assertFalse(IterableUtils.matchesAny(null, null)); fail("predicate must not be null"); } catch (NullPointerException ex) { } try { assertFalse(IterableUtils.matchesAny(list, null)); fail("predicate must not be null"); } catch (NullPointerException ex) { } assertFalse(IterableUtils.matchesAny(null, EQUALS_TWO)); assertFalse(IterableUtils.matchesAny(list, EQUALS_TWO)); list.add(1); list.add(3); list.add(4); assertFalse(IterableUtils.matchesAny(list, EQUALS_TWO)); list.add(2); assertEquals(true, IterableUtils.matchesAny(list, EQUALS_TWO)); }
|
IterableUtils { public static <E> boolean matchesAll(final Iterable<E> iterable, final Predicate<? super E> predicate) { return IteratorUtils.matchesAll(emptyIteratorIfNull(iterable), predicate); } @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type static Iterable<E> emptyIterable(); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c,
final Iterable<? extends E> d); static Iterable<E> chainedIterable(final Iterable<? extends E>... iterables); static Iterable<E> collatedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> collatedIterable(final Comparator<? super E> comparator,
final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> filteredIterable(final Iterable<E> iterable,
final Predicate<? super E> predicate); static Iterable<E> boundedIterable(final Iterable<E> iterable, final long maxSize); static Iterable<E> loopingIterable(final Iterable<E> iterable); static Iterable<E> reversedIterable(final Iterable<E> iterable); static Iterable<E> skippingIterable(final Iterable<E> iterable, final long elementsToSkip); static Iterable<O> transformedIterable(final Iterable<I> iterable,
final Transformer<? super I, ? extends O> transformer); static Iterable<E> uniqueIterable(final Iterable<E> iterable); static Iterable<E> unmodifiableIterable(final Iterable<E> iterable); static Iterable<E> zippingIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> zippingIterable(final Iterable<? extends E> first,
final Iterable<? extends E>... others); static Iterable<E> emptyIfNull(final Iterable<E> iterable); static void forEach(final Iterable<E> iterable, final Closure<? super E> closure); static E forEachButLast(final Iterable<E> iterable, final Closure<? super E> closure); static E find(final Iterable<E> iterable, final Predicate<? super E> predicate); static int indexOf(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAll(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAny(final Iterable<E> iterable, final Predicate<? super E> predicate); static long countMatches(final Iterable<E> input, final Predicate<? super E> predicate); static boolean isEmpty(final Iterable<?> iterable); static boolean contains(final Iterable<E> iterable, final Object object); static boolean contains(final Iterable<? extends E> iterable, final E object,
final Equator<? super E> equator); static int frequency(final Iterable<E> iterable, final T obj); static T get(final Iterable<T> iterable, final int index); static int size(final Iterable<?> iterable); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O> predicate); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O>... predicates); static List<R> partition(final Iterable<? extends O> iterable,
final Factory<R> partitionFactory, final Predicate<? super O>... predicates); static List<E> toList(final Iterable<E> iterable); static String toString(final Iterable<E> iterable); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer,
final String delimiter,
final String prefix,
final String suffix); }
|
@Test public void matchesAll() { try { assertFalse(IterableUtils.matchesAll(null, null)); fail("predicate must not be null"); } catch (NullPointerException ex) { } try { assertFalse(IterableUtils.matchesAll(iterableA, null)); fail("predicate must not be null"); } catch (NullPointerException ex) { } Predicate<Integer> lessThanFive = new Predicate<Integer>() { @Override public boolean evaluate(Integer object) { return object < 5; } }; assertTrue(IterableUtils.matchesAll(iterableA, lessThanFive)); Predicate<Integer> lessThanFour = new Predicate<Integer>() { @Override public boolean evaluate(Integer object) { return object < 4; } }; assertFalse(IterableUtils.matchesAll(iterableA, lessThanFour)); assertTrue(IterableUtils.matchesAll(null, lessThanFour)); assertTrue(IterableUtils.matchesAll(emptyIterable, lessThanFour)); }
|
IterableUtils { public static <T> T get(final Iterable<T> iterable, final int index) { CollectionUtils.checkIndexBounds(index); if (iterable instanceof List<?>) { return ((List<T>) iterable).get(index); } return IteratorUtils.get(emptyIteratorIfNull(iterable), index); } @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type static Iterable<E> emptyIterable(); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c,
final Iterable<? extends E> d); static Iterable<E> chainedIterable(final Iterable<? extends E>... iterables); static Iterable<E> collatedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> collatedIterable(final Comparator<? super E> comparator,
final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> filteredIterable(final Iterable<E> iterable,
final Predicate<? super E> predicate); static Iterable<E> boundedIterable(final Iterable<E> iterable, final long maxSize); static Iterable<E> loopingIterable(final Iterable<E> iterable); static Iterable<E> reversedIterable(final Iterable<E> iterable); static Iterable<E> skippingIterable(final Iterable<E> iterable, final long elementsToSkip); static Iterable<O> transformedIterable(final Iterable<I> iterable,
final Transformer<? super I, ? extends O> transformer); static Iterable<E> uniqueIterable(final Iterable<E> iterable); static Iterable<E> unmodifiableIterable(final Iterable<E> iterable); static Iterable<E> zippingIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> zippingIterable(final Iterable<? extends E> first,
final Iterable<? extends E>... others); static Iterable<E> emptyIfNull(final Iterable<E> iterable); static void forEach(final Iterable<E> iterable, final Closure<? super E> closure); static E forEachButLast(final Iterable<E> iterable, final Closure<? super E> closure); static E find(final Iterable<E> iterable, final Predicate<? super E> predicate); static int indexOf(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAll(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAny(final Iterable<E> iterable, final Predicate<? super E> predicate); static long countMatches(final Iterable<E> input, final Predicate<? super E> predicate); static boolean isEmpty(final Iterable<?> iterable); static boolean contains(final Iterable<E> iterable, final Object object); static boolean contains(final Iterable<? extends E> iterable, final E object,
final Equator<? super E> equator); static int frequency(final Iterable<E> iterable, final T obj); static T get(final Iterable<T> iterable, final int index); static int size(final Iterable<?> iterable); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O> predicate); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O>... predicates); static List<R> partition(final Iterable<? extends O> iterable,
final Factory<R> partitionFactory, final Predicate<? super O>... predicates); static List<E> toList(final Iterable<E> iterable); static String toString(final Iterable<E> iterable); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer,
final String delimiter,
final String prefix,
final String suffix); }
|
@Test(expected = IndexOutOfBoundsException.class) public void getFromIterable() throws Exception { final Bag<String> bag = new HashBag<String>(); bag.add("element", 1); assertEquals("element", IterableUtils.get(bag, 0)); IterableUtils.get(bag, 1); }
|
IterableUtils { public static <O> List<List<O>> partition(final Iterable<? extends O> iterable, final Predicate<? super O> predicate) { if (predicate == null) { throw new NullPointerException("Predicate must not be null."); } @SuppressWarnings({ "unchecked", "rawtypes" }) final Factory<List<O>> factory = FactoryUtils.instantiateFactory((Class) ArrayList.class); @SuppressWarnings("unchecked") final Predicate<? super O>[] predicates = new Predicate[] { predicate }; return partition(iterable, factory, predicates); } @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type static Iterable<E> emptyIterable(); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c,
final Iterable<? extends E> d); static Iterable<E> chainedIterable(final Iterable<? extends E>... iterables); static Iterable<E> collatedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> collatedIterable(final Comparator<? super E> comparator,
final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> filteredIterable(final Iterable<E> iterable,
final Predicate<? super E> predicate); static Iterable<E> boundedIterable(final Iterable<E> iterable, final long maxSize); static Iterable<E> loopingIterable(final Iterable<E> iterable); static Iterable<E> reversedIterable(final Iterable<E> iterable); static Iterable<E> skippingIterable(final Iterable<E> iterable, final long elementsToSkip); static Iterable<O> transformedIterable(final Iterable<I> iterable,
final Transformer<? super I, ? extends O> transformer); static Iterable<E> uniqueIterable(final Iterable<E> iterable); static Iterable<E> unmodifiableIterable(final Iterable<E> iterable); static Iterable<E> zippingIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> zippingIterable(final Iterable<? extends E> first,
final Iterable<? extends E>... others); static Iterable<E> emptyIfNull(final Iterable<E> iterable); static void forEach(final Iterable<E> iterable, final Closure<? super E> closure); static E forEachButLast(final Iterable<E> iterable, final Closure<? super E> closure); static E find(final Iterable<E> iterable, final Predicate<? super E> predicate); static int indexOf(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAll(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAny(final Iterable<E> iterable, final Predicate<? super E> predicate); static long countMatches(final Iterable<E> input, final Predicate<? super E> predicate); static boolean isEmpty(final Iterable<?> iterable); static boolean contains(final Iterable<E> iterable, final Object object); static boolean contains(final Iterable<? extends E> iterable, final E object,
final Equator<? super E> equator); static int frequency(final Iterable<E> iterable, final T obj); static T get(final Iterable<T> iterable, final int index); static int size(final Iterable<?> iterable); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O> predicate); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O>... predicates); static List<R> partition(final Iterable<? extends O> iterable,
final Factory<R> partitionFactory, final Predicate<? super O>... predicates); static List<E> toList(final Iterable<E> iterable); static String toString(final Iterable<E> iterable); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer,
final String delimiter,
final String prefix,
final String suffix); }
|
@SuppressWarnings("unchecked") @Test public void partition() { List<Integer> input = new ArrayList<Integer>(); input.add(1); input.add(2); input.add(3); input.add(4); List<List<Integer>> partitions = IterableUtils.partition(input, EQUALS_TWO); assertEquals(2, partitions.size()); Collection<Integer> partition = partitions.get(0); assertEquals(1, partition.size()); assertEquals(2, CollectionUtils.extractSingleton(partition).intValue()); Integer[] expected = {1, 3, 4}; partition = partitions.get(1); Assert.assertArrayEquals(expected, partition.toArray()); partitions = IterableUtils.partition((List<Integer>) null, EQUALS_TWO); assertEquals(2, partitions.size()); assertTrue(partitions.get(0).isEmpty()); assertTrue(partitions.get(1).isEmpty()); partitions = IterableUtils.partition(input); assertEquals(1, partitions.size()); assertEquals(input, partitions.get(0)); try { IterableUtils.partition(input, (Predicate<Integer>) null); fail("expecting NullPointerException"); } catch (NullPointerException npe) { } }
|
IterableUtils { public static <E> String toString(final Iterable<E> iterable) { return IteratorUtils.toString(emptyIteratorIfNull(iterable)); } @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type static Iterable<E> emptyIterable(); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c); @SuppressWarnings("unchecked") static Iterable<E> chainedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b,
final Iterable<? extends E> c,
final Iterable<? extends E> d); static Iterable<E> chainedIterable(final Iterable<? extends E>... iterables); static Iterable<E> collatedIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> collatedIterable(final Comparator<? super E> comparator,
final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> filteredIterable(final Iterable<E> iterable,
final Predicate<? super E> predicate); static Iterable<E> boundedIterable(final Iterable<E> iterable, final long maxSize); static Iterable<E> loopingIterable(final Iterable<E> iterable); static Iterable<E> reversedIterable(final Iterable<E> iterable); static Iterable<E> skippingIterable(final Iterable<E> iterable, final long elementsToSkip); static Iterable<O> transformedIterable(final Iterable<I> iterable,
final Transformer<? super I, ? extends O> transformer); static Iterable<E> uniqueIterable(final Iterable<E> iterable); static Iterable<E> unmodifiableIterable(final Iterable<E> iterable); static Iterable<E> zippingIterable(final Iterable<? extends E> a,
final Iterable<? extends E> b); static Iterable<E> zippingIterable(final Iterable<? extends E> first,
final Iterable<? extends E>... others); static Iterable<E> emptyIfNull(final Iterable<E> iterable); static void forEach(final Iterable<E> iterable, final Closure<? super E> closure); static E forEachButLast(final Iterable<E> iterable, final Closure<? super E> closure); static E find(final Iterable<E> iterable, final Predicate<? super E> predicate); static int indexOf(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAll(final Iterable<E> iterable, final Predicate<? super E> predicate); static boolean matchesAny(final Iterable<E> iterable, final Predicate<? super E> predicate); static long countMatches(final Iterable<E> input, final Predicate<? super E> predicate); static boolean isEmpty(final Iterable<?> iterable); static boolean contains(final Iterable<E> iterable, final Object object); static boolean contains(final Iterable<? extends E> iterable, final E object,
final Equator<? super E> equator); static int frequency(final Iterable<E> iterable, final T obj); static T get(final Iterable<T> iterable, final int index); static int size(final Iterable<?> iterable); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O> predicate); static List<List<O>> partition(final Iterable<? extends O> iterable,
final Predicate<? super O>... predicates); static List<R> partition(final Iterable<? extends O> iterable,
final Factory<R> partitionFactory, final Predicate<? super O>... predicates); static List<E> toList(final Iterable<E> iterable); static String toString(final Iterable<E> iterable); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer); static String toString(final Iterable<E> iterable,
final Transformer<? super E, String> transformer,
final String delimiter,
final String prefix,
final String suffix); }
|
@Test public void testToString() { String result = IterableUtils.toString(iterableA); assertEquals("[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]", result); result = IterableUtils.toString(new ArrayList<Integer>()); assertEquals("[]", result); result = IterableUtils.toString(null); assertEquals("[]", result); result = IterableUtils.toString(iterableA, new Transformer<Integer, String>() { @Override public String transform(Integer input) { return new Integer(input * 2).toString(); } }); assertEquals("[2, 4, 4, 6, 6, 6, 8, 8, 8, 8]", result); result = IterableUtils.toString(new ArrayList<Integer>(), new Transformer<Integer, String>() { @Override public String transform(Integer input) { fail("not supposed to reach here"); return ""; } }); assertEquals("[]", result); result = IterableUtils.toString(null, new Transformer<Integer, String>() { @Override public String transform(Integer input) { fail("not supposed to reach here"); return ""; } }); assertEquals("[]", result); }
@Test public void testToStringDelimiter() { Transformer<Integer, String> transformer = new Transformer<Integer, String>() { @Override public String transform(Integer input) { return new Integer(input * 2).toString(); } }; String result = IterableUtils.toString(iterableA, transformer, "", "", ""); assertEquals("2446668888", result); result = IterableUtils.toString(iterableA, transformer, ",", "", ""); assertEquals("2,4,4,6,6,6,8,8,8,8", result); result = IterableUtils.toString(iterableA, transformer, "", "[", "]"); assertEquals("[2446668888]", result); result = IterableUtils.toString(iterableA, transformer, ",", "[", "]"); assertEquals("[2,4,4,6,6,6,8,8,8,8]", result); result = IterableUtils.toString(iterableA, transformer, ",", "[[", "]]"); assertEquals("[[2,4,4,6,6,6,8,8,8,8]]", result); result = IterableUtils.toString(iterableA, transformer, ",,", "[", "]"); assertEquals("[2,,4,,4,,6,,6,,6,,8,,8,,8,,8]", result); result = IterableUtils.toString(iterableA, transformer, ",,", "((", "))"); assertEquals("((2,,4,,4,,6,,6,,6,,8,,8,,8,,8))", result); result = IterableUtils.toString(new ArrayList<Integer>(), transformer, "", "(", ")"); assertEquals("()", result); result = IterableUtils.toString(new ArrayList<Integer>(), transformer, "", "", ""); assertEquals("", result); }
@Test public void testToStringWithNullArguments() { String result = IterableUtils.toString(null, new Transformer<Integer, String>() { @Override public String transform(Integer input) { fail("not supposed to reach here"); return ""; } }, "", "(", ")"); assertEquals("()", result); try { IterableUtils.toString(new ArrayList<Integer>(), null, "", "(", ")"); fail("expecting NullPointerException"); } catch (final NullPointerException ex) { } try { IterableUtils.toString(new ArrayList<Integer>(), new Transformer<Integer, String>() { @Override public String transform(Integer input) { fail("not supposed to reach here"); return ""; } }, null, "(", ")"); fail("expecting NullPointerException"); } catch (final NullPointerException ex) { } try { IterableUtils.toString(new ArrayList<Integer>(), new Transformer<Integer, String>() { @Override public String transform(Integer input) { fail("not supposed to reach here"); return ""; } }, "", null, ")"); fail("expecting NullPointerException"); } catch (final NullPointerException ex) { } try { IterableUtils.toString(new ArrayList<Integer>(), new Transformer<Integer, String>() { @Override public String transform(Integer input) { fail("not supposed to reach here"); return ""; } }, "", "(", null); fail("expecting NullPointerException"); } catch (final NullPointerException ex) { } }
|
SequencesComparator { public EditScript<T> getScript() { final EditScript<T> script = new EditScript<T>(); buildScript(0, sequence1.size(), 0, sequence2.size(), script); return script; } SequencesComparator(final List<T> sequence1, final List<T> sequence2); SequencesComparator(final List<T> sequence1, final List<T> sequence2, final Equator<? super T> equator); EditScript<T> getScript(); }
|
@Test public void testLength() { for (int i = 0; i < before.size(); ++i) { final SequencesComparator<Character> comparator = new SequencesComparator<Character>(sequence(before.get(i)), sequence(after.get(i))); Assert.assertEquals(length[i], comparator.getScript().getModifications()); } }
@Test public void testExecution() { final ExecutionVisitor<Character> ev = new ExecutionVisitor<Character>(); for (int i = 0; i < before.size(); ++i) { ev.setList(sequence(before.get(i))); new SequencesComparator<Character>(sequence(before.get(i)), sequence(after.get(i))).getScript().visit(ev); Assert.assertEquals(after.get(i), ev.getString()); } }
@Test public void testMinimal() { final String[] shadokAlph = new String[] { new String("GA"), new String("BU"), new String("ZO"), new String("MEU") }; final List<String> sentenceBefore = new ArrayList<String>(); final List<String> sentenceAfter = new ArrayList<String>(); sentenceBefore.add(shadokAlph[0]); sentenceBefore.add(shadokAlph[2]); sentenceBefore.add(shadokAlph[3]); sentenceBefore.add(shadokAlph[1]); sentenceBefore.add(shadokAlph[0]); sentenceBefore.add(shadokAlph[0]); sentenceBefore.add(shadokAlph[2]); sentenceBefore.add(shadokAlph[1]); sentenceBefore.add(shadokAlph[3]); sentenceBefore.add(shadokAlph[0]); sentenceBefore.add(shadokAlph[2]); sentenceBefore.add(shadokAlph[1]); sentenceBefore.add(shadokAlph[3]); sentenceBefore.add(shadokAlph[2]); sentenceBefore.add(shadokAlph[2]); sentenceBefore.add(shadokAlph[0]); sentenceBefore.add(shadokAlph[1]); sentenceBefore.add(shadokAlph[3]); sentenceBefore.add(shadokAlph[0]); sentenceBefore.add(shadokAlph[3]); final Random random = new Random(4564634237452342L); for (int nbCom = 0; nbCom <= 40; nbCom+=5) { sentenceAfter.clear(); sentenceAfter.addAll(sentenceBefore); for (int i = 0; i<nbCom; i++) { if (random.nextInt(2) == 0) { sentenceAfter.add(random.nextInt(sentenceAfter.size() + 1), shadokAlph[random.nextInt(4)]); } else { sentenceAfter.remove(random.nextInt(sentenceAfter.size())); } } final SequencesComparator<String> comparator = new SequencesComparator<String>(sentenceBefore, sentenceAfter); Assert.assertTrue(comparator.getScript().getModifications() <= nbCom); } }
@Test public void testShadok() { final int lgMax = 5; final String[] shadokAlph = new String[] { new String("GA"), new String("BU"), new String("ZO"), new String("MEU") }; List<List<String>> shadokSentences = new ArrayList<List<String>>(); for (int lg=0; lg<lgMax; ++lg) { final List<List<String>> newTab = new ArrayList<List<String>>(); newTab.add(new ArrayList<String>()); for (final String element : shadokAlph) { for (final List<String> sentence : shadokSentences) { final List<String> newSentence = new ArrayList<String>(sentence); newSentence.add(element); newTab.add(newSentence); } } shadokSentences = newTab; } final ExecutionVisitor<String> ev = new ExecutionVisitor<String>(); for (int i = 0; i < shadokSentences.size(); ++i) { for (List<String> shadokSentence : shadokSentences) { ev.setList(shadokSentences.get(i)); new SequencesComparator<String>(shadokSentences.get(i), shadokSentence).getScript().visit(ev); final StringBuilder concat = new StringBuilder(); for (final String s : shadokSentence) { concat.append(s); } Assert.assertEquals(concat.toString(), ev.getString()); } } }
|
BatchUpdateOperator extends AbstractOperator { @Override public Object execute(Object[] values, InvocationStat stat) { Iterables iterables = getIterables(values); if (iterables.isEmpty()) { return transformer.transform(new int[]{}); } Map<DataSource, Group> gorupMap = new HashMap<DataSource, Group>(); int t = 0; for (Object obj : iterables) { InvocationContext context = invocationContextFactory.newInvocationContext(new Object[]{obj}); group(context, gorupMap, t++); } int[] ints = executeDb(gorupMap, t, stat); return transformer.transform(ints); } BatchUpdateOperator(ASTRootNode rootNode, MethodDescriptor md, Config config); @Override Object execute(Object[] values, InvocationStat stat); }
|
@Test public void testExecuteReturnVoid() throws Exception { TypeToken<List<User>> pt = new TypeToken<List<User>>() { }; TypeToken<Void> rt = TypeToken.of(void.class); String srcSql = "update user set name=:1.name where id=:1.id"; AbstractOperator operator = getOperator(pt, rt, srcSql); final int[] expectedInts = new int[]{1, 2}; operator.setJdbcOperations(new JdbcOperationsAdapter() { @Override public int[] batchUpdate(DataSource ds, List<BoundSql> boundSqls) { String sql = boundSqls.get(0).getSql(); String descSql = "update user set name=? where id=?"; assertThat(sql, equalTo(descSql)); assertThat(boundSqls.size(), equalTo(2)); assertThat(boundSqls.get(0).getArgs().get(0), equalTo((Object) "ash")); assertThat(boundSqls.get(0).getArgs().get(1), equalTo((Object) 100)); assertThat(boundSqls.get(1).getArgs().get(0), equalTo((Object) "lucy")); assertThat(boundSqls.get(1).getArgs().get(1), equalTo((Object) 200)); return expectedInts; } }); List<User> users = Arrays.asList(new User(100, "ash"), new User(200, "lucy")); Object actual = operator.execute(new Object[]{users}, InvocationStat.create()); assertThat(actual, nullValue()); }
@Test public void testExecuteReturnInt() throws Exception { TypeToken<List<User>> pt = new TypeToken<List<User>>() { }; TypeToken<Integer> rt = TypeToken.of(int.class); String srcSql = "update user set name=:1.name where id=:1.id"; AbstractOperator operator = getOperator(pt, rt, srcSql); final int[] expectedInts = new int[]{1, 2}; operator.setJdbcOperations(new JdbcOperationsAdapter() { @Override public int[] batchUpdate(DataSource ds, List<BoundSql> boundSqls) { String sql = boundSqls.get(0).getSql(); String descSql = "update user set name=? where id=?"; assertThat(sql, equalTo(descSql)); assertThat(boundSqls.size(), equalTo(2)); assertThat(boundSqls.get(0).getArgs().get(0), equalTo((Object) "ash")); assertThat(boundSqls.get(0).getArgs().get(1), equalTo((Object) 100)); assertThat(boundSqls.get(1).getArgs().get(0), equalTo((Object) "lucy")); assertThat(boundSqls.get(1).getArgs().get(1), equalTo((Object) 200)); return expectedInts; } }); List<User> users = Arrays.asList(new User(100, "ash"), new User(200, "lucy")); int actual = (Integer) operator.execute(new Object[]{users}, InvocationStat.create()); assertThat(actual, is(3)); }
@Test public void testExecuteReturnIntArray() throws Exception { TypeToken<List<User>> pt = new TypeToken<List<User>>() { }; TypeToken<int[]> rt = TypeToken.of(int[].class); String srcSql = "update user set name=:1.name where id=:1.id"; AbstractOperator operator = getOperator(pt, rt, srcSql); final int[] expectedInts = new int[]{1, 2}; operator.setJdbcOperations(new JdbcOperationsAdapter() { @Override public int[] batchUpdate(DataSource ds, List<BoundSql> boundSqls) { String sql = boundSqls.get(0).getSql(); String descSql = "update user set name=? where id=?"; assertThat(sql, equalTo(descSql)); assertThat(boundSqls.size(), equalTo(2)); assertThat(boundSqls.get(0).getArgs().get(0), equalTo((Object) "ash")); assertThat(boundSqls.get(0).getArgs().get(1), equalTo((Object) 100)); assertThat(boundSqls.get(1).getArgs().get(0), equalTo((Object) "lucy")); assertThat(boundSqls.get(1).getArgs().get(1), equalTo((Object) 200)); return expectedInts; } }); List<User> users = Arrays.asList(new User(100, "ash"), new User(200, "lucy")); int[] actualInts = (int[]) operator.execute(new Object[]{users}, InvocationStat.create()); assertThat(Arrays.toString(actualInts), equalTo(Arrays.toString(expectedInts))); }
@Test public void testExecuteReturnIntegerArray() throws Exception { TypeToken<List<User>> pt = new TypeToken<List<User>>() { }; TypeToken<Integer[]> rt = TypeToken.of(Integer[].class); String srcSql = "update user set name=:1.name where id=:1.id"; AbstractOperator operator = getOperator(pt, rt, srcSql); final int[] expectedInts = new int[]{1, 2}; operator.setJdbcOperations(new JdbcOperationsAdapter() { @Override public int[] batchUpdate(DataSource ds, List<BoundSql> boundSqls) { String sql = boundSqls.get(0).getSql(); String descSql = "update user set name=? where id=?"; assertThat(sql, equalTo(descSql)); assertThat(boundSqls.size(), equalTo(2)); assertThat(boundSqls.get(0).getArgs().get(0), equalTo((Object) "ash")); assertThat(boundSqls.get(0).getArgs().get(1), equalTo((Object) 100)); assertThat(boundSqls.get(1).getArgs().get(0), equalTo((Object) "lucy")); assertThat(boundSqls.get(1).getArgs().get(1), equalTo((Object) 200)); return expectedInts; } }); List<User> users = Arrays.asList(new User(100, "ash"), new User(200, "lucy")); Integer[] actualInts = (Integer[]) operator.execute(new Object[]{users}, InvocationStat.create()); assertThat(Arrays.toString(actualInts), equalTo(Arrays.toString(expectedInts))); }
@Test public void testExecuteMulti() throws Exception { TypeToken<List<User>> pt = new TypeToken<List<User>>() { }; TypeToken<int[]> rt = TypeToken.of(int[].class); String srcSql = "update #table set name=:1.name where id=:1.id"; AbstractOperator operator = getOperator2(pt, rt, srcSql); operator.setJdbcOperations(new JdbcOperationsAdapter() { @Override public int[] batchUpdate(DataSource ds, List<BoundSql> boundSqls) throws DataAccessException { if (boundSqls.size() == 3) { List<String> descSqls = Arrays.asList( "update user_30 set name=? where id=?", "update user_10 set name=? where id=?", "update user_20 set name=? where id=?"); List<String> sqls = new ArrayList<String>(); for (BoundSql boundSql : boundSqls) { sqls.add(boundSql.getSql()); } assertThat(sqls, equalTo(descSqls)); assertThat(boundSqls.size(), equalTo(3)); assertThat(boundSqls.get(0).getArgs().get(0), equalTo((Object) "ash")); assertThat(boundSqls.get(0).getArgs().get(1), equalTo((Object) 30)); assertThat(boundSqls.get(1).getArgs().get(0), equalTo((Object) "lily")); assertThat(boundSqls.get(1).getArgs().get(1), equalTo((Object) 10)); assertThat(boundSqls.get(2).getArgs().get(0), equalTo((Object) "gill")); assertThat(boundSqls.get(2).getArgs().get(1), equalTo((Object) 20)); return new int[] {3, 1, 2}; } else if (boundSqls.size() == 2) { List<String> descSqls = Arrays.asList( "update user_60 set name=? where id=?", "update user_55 set name=? where id=?"); List<String> sqls = new ArrayList<String>(); for (BoundSql boundSql : boundSqls) { sqls.add(boundSql.getSql()); } assertThat(sqls, equalTo(descSqls)); assertThat(boundSqls.size(), equalTo(2)); assertThat(boundSqls.get(0).getArgs().get(0), equalTo((Object) "lucy")); assertThat(boundSqls.get(0).getArgs().get(1), equalTo((Object) 60)); assertThat(boundSqls.get(1).getArgs().get(0), equalTo((Object) "liu")); assertThat(boundSqls.get(1).getArgs().get(1), equalTo((Object) 55)); return new int[] {6, 5}; } else { throw new IllegalStateException(); } } }); List<User> users = Arrays.asList( new User(30, "ash"), new User(60, "lucy"), new User(10, "lily"), new User(20, "gill"), new User(55, "liu")); int[] actualInts = (int[]) operator.execute(new Object[]{users}, InvocationStat.create()); assertThat(Arrays.toString(actualInts), equalTo(Arrays.toString(new int[]{3, 6, 1, 2, 5}))); }
@Test public void testStatsCounter() throws Exception { TypeToken<List<User>> pt = new TypeToken<List<User>>() { }; TypeToken<int[]> rt = TypeToken.of(int[].class); String srcSql = "update user set name=:1.name where id=:1.id"; AbstractOperator operator = getOperator(pt, rt, srcSql); operator.setJdbcOperations(new JdbcOperationsAdapter() { @Override public int[] batchUpdate(DataSource ds, List<BoundSql> boundSqls) { String descSql = "update user set name=? where id=?"; assertThat(boundSqls.get(0).getSql(), equalTo(descSql)); assertThat(boundSqls.size(), equalTo(2)); assertThat(boundSqls.get(0).getArgs().get(0), equalTo((Object) "ash")); assertThat(boundSqls.get(0).getArgs().get(1), equalTo((Object) 100)); assertThat(boundSqls.get(1).getArgs().get(0), equalTo((Object) "lucy")); assertThat(boundSqls.get(1).getArgs().get(1), equalTo((Object) 200)); return new int[]{9, 7}; } }); List<User> users = Arrays.asList(new User(100, "ash"), new User(200, "lucy")); InvocationStat stat = InvocationStat.create(); operator.execute(new Object[]{users}, stat); assertThat(stat.getDatabaseExecuteSuccessCount(), equalTo(1L)); operator.execute(new Object[]{users}, stat); assertThat(stat.getDatabaseExecuteSuccessCount(), equalTo(2L)); operator.setJdbcOperations(new JdbcOperationsAdapter()); try { operator.execute(new Object[]{users}, stat); } catch (UnsupportedOperationException e) { } assertThat(stat.getDatabaseExecuteExceptionCount(), equalTo(1L)); try { operator.execute(new Object[]{users}, stat); } catch (UnsupportedOperationException e) { } assertThat(stat.getDatabaseExecuteExceptionCount(), equalTo(2L)); }
@Test public void testExecuteReturnTypeError() throws Exception { thrown.expect(DescriptionException.class); thrown.expectMessage("the return type of batch update expected one of " + "[void, int, int[], Void, Integer, Integer[]] but class java.lang.String"); TypeToken<List<User>> pt = new TypeToken<List<User>>() { }; TypeToken<String> rt = TypeToken.of(String.class); String srcSql = "update user set name=:1.name where id=:1.id"; AbstractOperator operator = getOperator(pt, rt, srcSql); final int[] expectedInts = new int[]{1, 2}; operator.setJdbcOperations(new JdbcOperationsAdapter() { @Override public int[] batchUpdate(DataSource ds, List<BoundSql> boundSqls) { String descSql = "update user set name=? where id=?"; assertThat(boundSqls.get(0).getSql(), equalTo(descSql)); assertThat(boundSqls.size(), equalTo(2)); assertThat(boundSqls.get(0).getArgs().get(0), equalTo((Object) "ash")); assertThat(boundSqls.get(0).getArgs().get(1), equalTo((Object) 100)); assertThat(boundSqls.get(1).getArgs().get(0), equalTo((Object) "lucy")); assertThat(boundSqls.get(1).getArgs().get(1), equalTo((Object) 200)); return expectedInts; } }); List<User> users = Arrays.asList(new User(100, "ash"), new User(200, "lucy")); operator.execute(new Object[]{users}, InvocationStat.create()); }
|
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); }
|
@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)); }
|
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; }
|
@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)); }
|
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; }
|
@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) { } }
|
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; }
|
@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) { } }
|
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; }
|
@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) { } }
|
EnumerationUtils { public static <E> List<E> toList(final Enumeration<? extends E> enumeration) { return IteratorUtils.toList(new EnumerationIterator<E>(enumeration)); } 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); }
|
@Test public void testToListWithStringTokenizer() { final List<String> expectedList1 = new ArrayList<String>(); final StringTokenizer st = new StringTokenizer(TO_LIST_FIXTURE); while (st.hasMoreTokens()) { expectedList1.add(st.nextToken()); } final List<String> expectedList2 = new ArrayList<String>(); expectedList2.add("this"); expectedList2.add("is"); expectedList2.add("a"); expectedList2.add("test"); final List<String> actualList = EnumerationUtils.toList(new StringTokenizer(TO_LIST_FIXTURE)); assertEquals(expectedList1, expectedList2); assertEquals(expectedList1, actualList); assertEquals(expectedList2, actualList); }
@Test public void testToListWithHashtable() { final Hashtable<String, Integer> expected = new Hashtable<String, Integer>(); expected.put("one", Integer.valueOf(1)); expected.put("two", Integer.valueOf(2)); expected.put("three", Integer.valueOf(3)); final List<Integer> actualEltList = EnumerationUtils.toList(expected.elements()); assertEquals(expected.size(), actualEltList.size()); assertTrue(actualEltList.contains(Integer.valueOf(1))); assertTrue(actualEltList.contains(Integer.valueOf(2))); assertTrue(actualEltList.contains(Integer.valueOf(3))); final List<Integer> expectedEltList = new ArrayList<Integer>(); expectedEltList.add(Integer.valueOf(1)); expectedEltList.add(Integer.valueOf(2)); expectedEltList.add(Integer.valueOf(3)); assertTrue(actualEltList.containsAll(expectedEltList)); final List<String> actualKeyList = EnumerationUtils.toList(expected.keys()); assertEquals(expected.size(), actualEltList.size()); assertTrue(actualKeyList.contains("one")); assertTrue(actualKeyList.contains("two")); assertTrue(actualKeyList.contains("three")); final List<String> expectedKeyList = new ArrayList<String>(); expectedKeyList.add("one"); expectedKeyList.add("two"); expectedKeyList.add("three"); assertTrue(actualKeyList.containsAll(expectedKeyList)); }
|
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); }
|
@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()); }
|
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(); }
|
@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) { } }
|
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(); }
|
@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) { } }
|
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(); }
|
@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) { } }
|
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(); }
|
@Test public void testEmpty() { Iterator<E> it = makeEmptyIterator(); assertFalse(it.hasNext()); }
|
MapUtils { public static <K, V> IterableMap<K, V> predicatedMap(final Map<K, V> map, final Predicate<? super K> keyPred, final Predicate<? super V> valuePred) { return PredicatedMap.predicatedMap(map, keyPred, valuePred); } private MapUtils(); static V getObject(final Map<? super K, V> map, final K key); static String getString(final Map<? super K, ?> map, final K key); static Boolean getBoolean(final Map<? super K, ?> map, final K key); static Number getNumber(final Map<? super K, ?> map, final K key); static Byte getByte(final Map<? super K, ?> map, final K key); static Short getShort(final Map<? super K, ?> map, final K key); static Integer getInteger(final Map<? super K, ?> map, final K key); static Long getLong(final Map<? super K, ?> map, final K key); static Float getFloat(final Map<? super K, ?> map, final K key); static Double getDouble(final Map<? super K, ?> map, final K key); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key); static V getObject(final Map<K, V> map, final K key, final V defaultValue); static String getString(final Map<? super K, ?> map, final K key, final String defaultValue); static Boolean getBoolean(final Map<? super K, ?> map, final K key, final Boolean defaultValue); static Number getNumber(final Map<? super K, ?> map, final K key, final Number defaultValue); static Byte getByte(final Map<? super K, ?> map, final K key, final Byte defaultValue); static Short getShort(final Map<? super K, ?> map, final K key, final Short defaultValue); static Integer getInteger(final Map<? super K, ?> map, final K key, final Integer defaultValue); static Long getLong(final Map<? super K, ?> map, final K key, final Long defaultValue); static Float getFloat(final Map<? super K, ?> map, final K key, final Float defaultValue); static Double getDouble(final Map<? super K, ?> map, final K key, final Double defaultValue); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key, final Map<?, ?> defaultValue); static boolean getBooleanValue(final Map<? super K, ?> map, final K key); static byte getByteValue(final Map<? super K, ?> map, final K key); static short getShortValue(final Map<? super K, ?> map, final K key); static int getIntValue(final Map<? super K, ?> map, final K key); static long getLongValue(final Map<? super K, ?> map, final K key); static float getFloatValue(final Map<? super K, ?> map, final K key); static double getDoubleValue(final Map<? super K, ?> map, final K key); static boolean getBooleanValue(final Map<? super K, ?> map, final K key, final boolean defaultValue); static byte getByteValue(final Map<? super K, ?> map, final K key, final byte defaultValue); static short getShortValue(final Map<? super K, ?> map, final K key, final short defaultValue); static int getIntValue(final Map<? super K, ?> map, final K key, final int defaultValue); static long getLongValue(final Map<? super K, ?> map, final K key, final long defaultValue); static float getFloatValue(final Map<? super K, ?> map, final K key, final float defaultValue); static double getDoubleValue(final Map<? super K, ?> map, final K key, final double defaultValue); static Properties toProperties(final Map<K, V> map); static Map<String, Object> toMap(final ResourceBundle resourceBundle); static void verbosePrint(final PrintStream out, final Object label, final Map<?, ?> map); static void debugPrint(final PrintStream out, final Object label, final Map<?, ?> map); static Map<V, K> invertMap(final Map<K, V> map); static void safeAddToMap(final Map<? super K, Object> map, final K key, final Object value); @SuppressWarnings("unchecked") // As per Javadoc throws CCE for invalid array contents static Map<K, V> putAll(final Map<K, V> map, final Object[] array); static Map<K,V> emptyIfNull(final Map<K,V> map); static boolean isEmpty(final Map<?,?> map); static boolean isNotEmpty(final Map<?,?> map); static Map<K, V> synchronizedMap(final Map<K, V> map); static Map<K, V> unmodifiableMap(final Map<? extends K, ? extends V> map); static IterableMap<K, V> predicatedMap(final Map<K, V> map, final Predicate<? super K> keyPred,
final Predicate<? super V> valuePred); static IterableMap<K, V> transformedMap(final Map<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static IterableMap<K, V> fixedSizeMap(final Map<K, V> map); static IterableMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory); static IterableMap<K, V> lazyMap(final Map<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static OrderedMap<K, V> orderedMap(final Map<K, V> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, ? super Collection<V>> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Class<C> collectionClass); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Factory<C> collectionFactory); static SortedMap<K, V> synchronizedSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> unmodifiableSortedMap(final SortedMap<K, ? extends V> map); static SortedMap<K, V> predicatedSortedMap(final SortedMap<K, V> map,
final Predicate<? super K> keyPred, final Predicate<? super V> valuePred); static SortedMap<K, V> transformedSortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static SortedMap<K, V> fixedSizeSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map, final Factory<? extends V> factory); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static void populateMap(final Map<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final Map<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static IterableMap<K, V> iterableMap(final Map<K, V> map); static IterableSortedMap<K, V> iterableSortedMap(final SortedMap<K, V> sortedMap); @SuppressWarnings("rawtypes")
static final SortedMap EMPTY_SORTED_MAP; }
|
@Test public void testPredicatedMap() { final Predicate<Object> p = getPredicate(); Map<Object, Object> map = MapUtils.predicatedMap(new HashMap<Object, Object>(), p, p); assertTrue("returned object should be a PredicatedMap", map instanceof PredicatedMap); try { MapUtils.predicatedMap(null, p, p); fail("Expecting NullPointerException for null map."); } catch (final NullPointerException e) { } }
|
MapUtils { public static <K, V> IterableMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory) { return LazyMap.lazyMap(map, factory); } private MapUtils(); static V getObject(final Map<? super K, V> map, final K key); static String getString(final Map<? super K, ?> map, final K key); static Boolean getBoolean(final Map<? super K, ?> map, final K key); static Number getNumber(final Map<? super K, ?> map, final K key); static Byte getByte(final Map<? super K, ?> map, final K key); static Short getShort(final Map<? super K, ?> map, final K key); static Integer getInteger(final Map<? super K, ?> map, final K key); static Long getLong(final Map<? super K, ?> map, final K key); static Float getFloat(final Map<? super K, ?> map, final K key); static Double getDouble(final Map<? super K, ?> map, final K key); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key); static V getObject(final Map<K, V> map, final K key, final V defaultValue); static String getString(final Map<? super K, ?> map, final K key, final String defaultValue); static Boolean getBoolean(final Map<? super K, ?> map, final K key, final Boolean defaultValue); static Number getNumber(final Map<? super K, ?> map, final K key, final Number defaultValue); static Byte getByte(final Map<? super K, ?> map, final K key, final Byte defaultValue); static Short getShort(final Map<? super K, ?> map, final K key, final Short defaultValue); static Integer getInteger(final Map<? super K, ?> map, final K key, final Integer defaultValue); static Long getLong(final Map<? super K, ?> map, final K key, final Long defaultValue); static Float getFloat(final Map<? super K, ?> map, final K key, final Float defaultValue); static Double getDouble(final Map<? super K, ?> map, final K key, final Double defaultValue); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key, final Map<?, ?> defaultValue); static boolean getBooleanValue(final Map<? super K, ?> map, final K key); static byte getByteValue(final Map<? super K, ?> map, final K key); static short getShortValue(final Map<? super K, ?> map, final K key); static int getIntValue(final Map<? super K, ?> map, final K key); static long getLongValue(final Map<? super K, ?> map, final K key); static float getFloatValue(final Map<? super K, ?> map, final K key); static double getDoubleValue(final Map<? super K, ?> map, final K key); static boolean getBooleanValue(final Map<? super K, ?> map, final K key, final boolean defaultValue); static byte getByteValue(final Map<? super K, ?> map, final K key, final byte defaultValue); static short getShortValue(final Map<? super K, ?> map, final K key, final short defaultValue); static int getIntValue(final Map<? super K, ?> map, final K key, final int defaultValue); static long getLongValue(final Map<? super K, ?> map, final K key, final long defaultValue); static float getFloatValue(final Map<? super K, ?> map, final K key, final float defaultValue); static double getDoubleValue(final Map<? super K, ?> map, final K key, final double defaultValue); static Properties toProperties(final Map<K, V> map); static Map<String, Object> toMap(final ResourceBundle resourceBundle); static void verbosePrint(final PrintStream out, final Object label, final Map<?, ?> map); static void debugPrint(final PrintStream out, final Object label, final Map<?, ?> map); static Map<V, K> invertMap(final Map<K, V> map); static void safeAddToMap(final Map<? super K, Object> map, final K key, final Object value); @SuppressWarnings("unchecked") // As per Javadoc throws CCE for invalid array contents static Map<K, V> putAll(final Map<K, V> map, final Object[] array); static Map<K,V> emptyIfNull(final Map<K,V> map); static boolean isEmpty(final Map<?,?> map); static boolean isNotEmpty(final Map<?,?> map); static Map<K, V> synchronizedMap(final Map<K, V> map); static Map<K, V> unmodifiableMap(final Map<? extends K, ? extends V> map); static IterableMap<K, V> predicatedMap(final Map<K, V> map, final Predicate<? super K> keyPred,
final Predicate<? super V> valuePred); static IterableMap<K, V> transformedMap(final Map<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static IterableMap<K, V> fixedSizeMap(final Map<K, V> map); static IterableMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory); static IterableMap<K, V> lazyMap(final Map<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static OrderedMap<K, V> orderedMap(final Map<K, V> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, ? super Collection<V>> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Class<C> collectionClass); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Factory<C> collectionFactory); static SortedMap<K, V> synchronizedSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> unmodifiableSortedMap(final SortedMap<K, ? extends V> map); static SortedMap<K, V> predicatedSortedMap(final SortedMap<K, V> map,
final Predicate<? super K> keyPred, final Predicate<? super V> valuePred); static SortedMap<K, V> transformedSortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static SortedMap<K, V> fixedSizeSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map, final Factory<? extends V> factory); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static void populateMap(final Map<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final Map<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static IterableMap<K, V> iterableMap(final Map<K, V> map); static IterableSortedMap<K, V> iterableSortedMap(final SortedMap<K, V> sortedMap); @SuppressWarnings("rawtypes")
static final SortedMap EMPTY_SORTED_MAP; }
|
@Test public void testLazyMapFactory() { final Factory<Integer> factory = FactoryUtils.constantFactory(Integer.valueOf(5)); Map<Object, Object> map = MapUtils.lazyMap(new HashMap<Object, Object>(), factory); assertTrue(map instanceof LazyMap); try { map = MapUtils.lazyMap(new HashMap<Object, Object>(), (Factory<Object>) null); fail("Expecting NullPointerException for null factory"); } catch (final NullPointerException e) { } try { map = MapUtils.lazyMap((Map<Object, Object>) null, factory); fail("Expecting NullPointerException for null map"); } catch (final NullPointerException e) { } final Transformer<Object, Integer> transformer = TransformerUtils.asTransformer(factory); map = MapUtils.lazyMap(new HashMap<Object, Object>(), transformer); assertTrue(map instanceof LazyMap); try { map = MapUtils.lazyMap(new HashMap<Object, Object>(), (Transformer<Object, Object>) null); fail("Expecting NullPointerException for null transformer"); } catch (final NullPointerException e) { } try { map = MapUtils.lazyMap((Map<Object, Object>) null, transformer); fail("Expecting NullPointerException for null map"); } catch (final NullPointerException e) { } }
@Test public void testLazyMapTransformer() { final Map<Object, Object> map = MapUtils.lazyMap(new HashMap<Object, Object>(), new Transformer<Object, Object>() { public Object transform(final Object mapKey) { if (mapKey instanceof String) { return Integer.valueOf((String) mapKey); } return null; } }); assertEquals(0, map.size()); final Integer i1 = (Integer) map.get("5"); assertEquals(Integer.valueOf(5), i1); assertEquals(1, map.size()); final Integer i2 = (Integer) map.get(new String(new char[] {'5'})); assertEquals(Integer.valueOf(5), i2); assertEquals(1, map.size()); assertSame(i1, i2); }
|
MapUtils { public static <K, V> Map<V, K> invertMap(final Map<K, V> map) { final Map<V, K> out = new HashMap<V, K>(map.size()); for (final Entry<K, V> entry : map.entrySet()) { out.put(entry.getValue(), entry.getKey()); } return out; } private MapUtils(); static V getObject(final Map<? super K, V> map, final K key); static String getString(final Map<? super K, ?> map, final K key); static Boolean getBoolean(final Map<? super K, ?> map, final K key); static Number getNumber(final Map<? super K, ?> map, final K key); static Byte getByte(final Map<? super K, ?> map, final K key); static Short getShort(final Map<? super K, ?> map, final K key); static Integer getInteger(final Map<? super K, ?> map, final K key); static Long getLong(final Map<? super K, ?> map, final K key); static Float getFloat(final Map<? super K, ?> map, final K key); static Double getDouble(final Map<? super K, ?> map, final K key); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key); static V getObject(final Map<K, V> map, final K key, final V defaultValue); static String getString(final Map<? super K, ?> map, final K key, final String defaultValue); static Boolean getBoolean(final Map<? super K, ?> map, final K key, final Boolean defaultValue); static Number getNumber(final Map<? super K, ?> map, final K key, final Number defaultValue); static Byte getByte(final Map<? super K, ?> map, final K key, final Byte defaultValue); static Short getShort(final Map<? super K, ?> map, final K key, final Short defaultValue); static Integer getInteger(final Map<? super K, ?> map, final K key, final Integer defaultValue); static Long getLong(final Map<? super K, ?> map, final K key, final Long defaultValue); static Float getFloat(final Map<? super K, ?> map, final K key, final Float defaultValue); static Double getDouble(final Map<? super K, ?> map, final K key, final Double defaultValue); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key, final Map<?, ?> defaultValue); static boolean getBooleanValue(final Map<? super K, ?> map, final K key); static byte getByteValue(final Map<? super K, ?> map, final K key); static short getShortValue(final Map<? super K, ?> map, final K key); static int getIntValue(final Map<? super K, ?> map, final K key); static long getLongValue(final Map<? super K, ?> map, final K key); static float getFloatValue(final Map<? super K, ?> map, final K key); static double getDoubleValue(final Map<? super K, ?> map, final K key); static boolean getBooleanValue(final Map<? super K, ?> map, final K key, final boolean defaultValue); static byte getByteValue(final Map<? super K, ?> map, final K key, final byte defaultValue); static short getShortValue(final Map<? super K, ?> map, final K key, final short defaultValue); static int getIntValue(final Map<? super K, ?> map, final K key, final int defaultValue); static long getLongValue(final Map<? super K, ?> map, final K key, final long defaultValue); static float getFloatValue(final Map<? super K, ?> map, final K key, final float defaultValue); static double getDoubleValue(final Map<? super K, ?> map, final K key, final double defaultValue); static Properties toProperties(final Map<K, V> map); static Map<String, Object> toMap(final ResourceBundle resourceBundle); static void verbosePrint(final PrintStream out, final Object label, final Map<?, ?> map); static void debugPrint(final PrintStream out, final Object label, final Map<?, ?> map); static Map<V, K> invertMap(final Map<K, V> map); static void safeAddToMap(final Map<? super K, Object> map, final K key, final Object value); @SuppressWarnings("unchecked") // As per Javadoc throws CCE for invalid array contents static Map<K, V> putAll(final Map<K, V> map, final Object[] array); static Map<K,V> emptyIfNull(final Map<K,V> map); static boolean isEmpty(final Map<?,?> map); static boolean isNotEmpty(final Map<?,?> map); static Map<K, V> synchronizedMap(final Map<K, V> map); static Map<K, V> unmodifiableMap(final Map<? extends K, ? extends V> map); static IterableMap<K, V> predicatedMap(final Map<K, V> map, final Predicate<? super K> keyPred,
final Predicate<? super V> valuePred); static IterableMap<K, V> transformedMap(final Map<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static IterableMap<K, V> fixedSizeMap(final Map<K, V> map); static IterableMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory); static IterableMap<K, V> lazyMap(final Map<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static OrderedMap<K, V> orderedMap(final Map<K, V> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, ? super Collection<V>> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Class<C> collectionClass); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Factory<C> collectionFactory); static SortedMap<K, V> synchronizedSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> unmodifiableSortedMap(final SortedMap<K, ? extends V> map); static SortedMap<K, V> predicatedSortedMap(final SortedMap<K, V> map,
final Predicate<? super K> keyPred, final Predicate<? super V> valuePred); static SortedMap<K, V> transformedSortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static SortedMap<K, V> fixedSizeSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map, final Factory<? extends V> factory); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static void populateMap(final Map<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final Map<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static IterableMap<K, V> iterableMap(final Map<K, V> map); static IterableSortedMap<K, V> iterableSortedMap(final SortedMap<K, V> sortedMap); @SuppressWarnings("rawtypes")
static final SortedMap EMPTY_SORTED_MAP; }
|
@Test public void testInvertMap() { final Map<String, String> in = new HashMap<String, String>(5, 1); in.put("1", "A"); in.put("2", "B"); in.put("3", "C"); in.put("4", "D"); in.put("5", "E"); final Set<String> inKeySet = new HashSet<String>(in.keySet()); final Set<String> inValSet = new HashSet<String>(in.values()); final Map<String, String> out = MapUtils.invertMap(in); final Set<String> outKeySet = new HashSet<String>(out.keySet()); final Set<String> outValSet = new HashSet<String>(out.values()); assertTrue( inKeySet.equals( outValSet )); assertTrue( inValSet.equals( outKeySet )); assertEquals( "1", out.get("A")); assertEquals( "2", out.get("B")); assertEquals( "3", out.get("C")); assertEquals( "4", out.get("D")); assertEquals( "5", out.get("E")); }
|
MapUtils { @SuppressWarnings("unchecked") public static <K, V> Map<K, V> putAll(final Map<K, V> map, final Object[] array) { if (map == null) { throw new NullPointerException("The map must not be null"); } if (array == null || array.length == 0) { return map; } final Object obj = array[0]; if (obj instanceof Map.Entry) { for (final Object element : array) { final Map.Entry<K, V> entry = (Map.Entry<K, V>) element; map.put(entry.getKey(), entry.getValue()); } } else if (obj instanceof KeyValue) { for (final Object element : array) { final KeyValue<K, V> keyval = (KeyValue<K, V>) element; map.put(keyval.getKey(), keyval.getValue()); } } else if (obj instanceof Object[]) { for (int i = 0; i < array.length; i++) { final Object[] sub = (Object[]) array[i]; if (sub == null || sub.length < 2) { throw new IllegalArgumentException("Invalid array element: " + i); } map.put((K) sub[0], (V) sub[1]); } } else { for (int i = 0; i < array.length - 1;) { map.put((K) array[i++], (V) array[i++]); } } return map; } private MapUtils(); static V getObject(final Map<? super K, V> map, final K key); static String getString(final Map<? super K, ?> map, final K key); static Boolean getBoolean(final Map<? super K, ?> map, final K key); static Number getNumber(final Map<? super K, ?> map, final K key); static Byte getByte(final Map<? super K, ?> map, final K key); static Short getShort(final Map<? super K, ?> map, final K key); static Integer getInteger(final Map<? super K, ?> map, final K key); static Long getLong(final Map<? super K, ?> map, final K key); static Float getFloat(final Map<? super K, ?> map, final K key); static Double getDouble(final Map<? super K, ?> map, final K key); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key); static V getObject(final Map<K, V> map, final K key, final V defaultValue); static String getString(final Map<? super K, ?> map, final K key, final String defaultValue); static Boolean getBoolean(final Map<? super K, ?> map, final K key, final Boolean defaultValue); static Number getNumber(final Map<? super K, ?> map, final K key, final Number defaultValue); static Byte getByte(final Map<? super K, ?> map, final K key, final Byte defaultValue); static Short getShort(final Map<? super K, ?> map, final K key, final Short defaultValue); static Integer getInteger(final Map<? super K, ?> map, final K key, final Integer defaultValue); static Long getLong(final Map<? super K, ?> map, final K key, final Long defaultValue); static Float getFloat(final Map<? super K, ?> map, final K key, final Float defaultValue); static Double getDouble(final Map<? super K, ?> map, final K key, final Double defaultValue); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key, final Map<?, ?> defaultValue); static boolean getBooleanValue(final Map<? super K, ?> map, final K key); static byte getByteValue(final Map<? super K, ?> map, final K key); static short getShortValue(final Map<? super K, ?> map, final K key); static int getIntValue(final Map<? super K, ?> map, final K key); static long getLongValue(final Map<? super K, ?> map, final K key); static float getFloatValue(final Map<? super K, ?> map, final K key); static double getDoubleValue(final Map<? super K, ?> map, final K key); static boolean getBooleanValue(final Map<? super K, ?> map, final K key, final boolean defaultValue); static byte getByteValue(final Map<? super K, ?> map, final K key, final byte defaultValue); static short getShortValue(final Map<? super K, ?> map, final K key, final short defaultValue); static int getIntValue(final Map<? super K, ?> map, final K key, final int defaultValue); static long getLongValue(final Map<? super K, ?> map, final K key, final long defaultValue); static float getFloatValue(final Map<? super K, ?> map, final K key, final float defaultValue); static double getDoubleValue(final Map<? super K, ?> map, final K key, final double defaultValue); static Properties toProperties(final Map<K, V> map); static Map<String, Object> toMap(final ResourceBundle resourceBundle); static void verbosePrint(final PrintStream out, final Object label, final Map<?, ?> map); static void debugPrint(final PrintStream out, final Object label, final Map<?, ?> map); static Map<V, K> invertMap(final Map<K, V> map); static void safeAddToMap(final Map<? super K, Object> map, final K key, final Object value); @SuppressWarnings("unchecked") // As per Javadoc throws CCE for invalid array contents static Map<K, V> putAll(final Map<K, V> map, final Object[] array); static Map<K,V> emptyIfNull(final Map<K,V> map); static boolean isEmpty(final Map<?,?> map); static boolean isNotEmpty(final Map<?,?> map); static Map<K, V> synchronizedMap(final Map<K, V> map); static Map<K, V> unmodifiableMap(final Map<? extends K, ? extends V> map); static IterableMap<K, V> predicatedMap(final Map<K, V> map, final Predicate<? super K> keyPred,
final Predicate<? super V> valuePred); static IterableMap<K, V> transformedMap(final Map<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static IterableMap<K, V> fixedSizeMap(final Map<K, V> map); static IterableMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory); static IterableMap<K, V> lazyMap(final Map<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static OrderedMap<K, V> orderedMap(final Map<K, V> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, ? super Collection<V>> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Class<C> collectionClass); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Factory<C> collectionFactory); static SortedMap<K, V> synchronizedSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> unmodifiableSortedMap(final SortedMap<K, ? extends V> map); static SortedMap<K, V> predicatedSortedMap(final SortedMap<K, V> map,
final Predicate<? super K> keyPred, final Predicate<? super V> valuePred); static SortedMap<K, V> transformedSortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static SortedMap<K, V> fixedSizeSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map, final Factory<? extends V> factory); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static void populateMap(final Map<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final Map<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static IterableMap<K, V> iterableMap(final Map<K, V> map); static IterableSortedMap<K, V> iterableSortedMap(final SortedMap<K, V> sortedMap); @SuppressWarnings("rawtypes")
static final SortedMap EMPTY_SORTED_MAP; }
|
@Test public void testPutAll_Map_array() { try { MapUtils.putAll(null, null); fail(); } catch (final NullPointerException ex) {} try { MapUtils.putAll(null, new Object[0]); fail(); } catch (final NullPointerException ex) {} Map<String, String> test = MapUtils.putAll(new HashMap<String, String>(), new String[0]); assertEquals(0, test.size()); test = MapUtils.putAll(new HashMap<String, String>(), new String[][] { {"RED", "#FF0000"}, {"GREEN", "#00FF00"}, {"BLUE", "#0000FF"} }); assertEquals(true, test.containsKey("RED")); assertEquals("#FF0000", test.get("RED")); assertEquals(true, test.containsKey("GREEN")); assertEquals("#00FF00", test.get("GREEN")); assertEquals(true, test.containsKey("BLUE")); assertEquals("#0000FF", test.get("BLUE")); assertEquals(3, test.size()); try { MapUtils.putAll(new HashMap<String, String>(), new String[][] { {"RED", "#FF0000"}, null, {"BLUE", "#0000FF"} }); fail(); } catch (final IllegalArgumentException ex) {} try { MapUtils.putAll(new HashMap<String, String>(), new String[][] { {"RED", "#FF0000"}, {"GREEN"}, {"BLUE", "#0000FF"} }); fail(); } catch (final IllegalArgumentException ex) {} try { MapUtils.putAll(new HashMap<String, String>(), new String[][] { {"RED", "#FF0000"}, {}, {"BLUE", "#0000FF"} }); fail(); } catch (final IllegalArgumentException ex) {} test = MapUtils.putAll(new HashMap<String, String>(), new String[] { "RED", "#FF0000", "GREEN", "#00FF00", "BLUE", "#0000FF" }); assertEquals(true, test.containsKey("RED")); assertEquals("#FF0000", test.get("RED")); assertEquals(true, test.containsKey("GREEN")); assertEquals("#00FF00", test.get("GREEN")); assertEquals(true, test.containsKey("BLUE")); assertEquals("#0000FF", test.get("BLUE")); assertEquals(3, test.size()); test = MapUtils.putAll(new HashMap<String, String>(), new String[] { "RED", "#FF0000", "GREEN", "#00FF00", "BLUE", "#0000FF", "PURPLE" }); assertEquals(true, test.containsKey("RED")); assertEquals("#FF0000", test.get("RED")); assertEquals(true, test.containsKey("GREEN")); assertEquals("#00FF00", test.get("GREEN")); assertEquals(true, test.containsKey("BLUE")); assertEquals("#0000FF", test.get("BLUE")); assertEquals(3, test.size()); test = MapUtils.putAll(new HashMap<String, String>(), new Object[] { new DefaultMapEntry<String, String>("RED", "#FF0000"), new DefaultMapEntry<String, String>("GREEN", "#00FF00"), new DefaultMapEntry<String, String>("BLUE", "#0000FF") }); assertEquals(true, test.containsKey("RED")); assertEquals("#FF0000", test.get("RED")); assertEquals(true, test.containsKey("GREEN")); assertEquals("#00FF00", test.get("GREEN")); assertEquals(true, test.containsKey("BLUE")); assertEquals("#0000FF", test.get("BLUE")); assertEquals(3, test.size()); test = MapUtils.putAll(new HashMap<String, String>(), new Object[] { new DefaultKeyValue<String, String>("RED", "#FF0000"), new DefaultKeyValue<String, String>("GREEN", "#00FF00"), new DefaultKeyValue<String, String>("BLUE", "#0000FF") }); assertEquals(true, test.containsKey("RED")); assertEquals("#FF0000", test.get("RED")); assertEquals(true, test.containsKey("GREEN")); assertEquals("#00FF00", test.get("GREEN")); assertEquals(true, test.containsKey("BLUE")); assertEquals("#0000FF", test.get("BLUE")); assertEquals(3, test.size()); }
|
MapUtils { public static Map<String, Object> toMap(final ResourceBundle resourceBundle) { final Enumeration<String> enumeration = resourceBundle.getKeys(); final Map<String, Object> map = new HashMap<String, Object>(); while (enumeration.hasMoreElements()) { final String key = enumeration.nextElement(); final Object value = resourceBundle.getObject(key); map.put(key, value); } return map; } private MapUtils(); static V getObject(final Map<? super K, V> map, final K key); static String getString(final Map<? super K, ?> map, final K key); static Boolean getBoolean(final Map<? super K, ?> map, final K key); static Number getNumber(final Map<? super K, ?> map, final K key); static Byte getByte(final Map<? super K, ?> map, final K key); static Short getShort(final Map<? super K, ?> map, final K key); static Integer getInteger(final Map<? super K, ?> map, final K key); static Long getLong(final Map<? super K, ?> map, final K key); static Float getFloat(final Map<? super K, ?> map, final K key); static Double getDouble(final Map<? super K, ?> map, final K key); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key); static V getObject(final Map<K, V> map, final K key, final V defaultValue); static String getString(final Map<? super K, ?> map, final K key, final String defaultValue); static Boolean getBoolean(final Map<? super K, ?> map, final K key, final Boolean defaultValue); static Number getNumber(final Map<? super K, ?> map, final K key, final Number defaultValue); static Byte getByte(final Map<? super K, ?> map, final K key, final Byte defaultValue); static Short getShort(final Map<? super K, ?> map, final K key, final Short defaultValue); static Integer getInteger(final Map<? super K, ?> map, final K key, final Integer defaultValue); static Long getLong(final Map<? super K, ?> map, final K key, final Long defaultValue); static Float getFloat(final Map<? super K, ?> map, final K key, final Float defaultValue); static Double getDouble(final Map<? super K, ?> map, final K key, final Double defaultValue); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key, final Map<?, ?> defaultValue); static boolean getBooleanValue(final Map<? super K, ?> map, final K key); static byte getByteValue(final Map<? super K, ?> map, final K key); static short getShortValue(final Map<? super K, ?> map, final K key); static int getIntValue(final Map<? super K, ?> map, final K key); static long getLongValue(final Map<? super K, ?> map, final K key); static float getFloatValue(final Map<? super K, ?> map, final K key); static double getDoubleValue(final Map<? super K, ?> map, final K key); static boolean getBooleanValue(final Map<? super K, ?> map, final K key, final boolean defaultValue); static byte getByteValue(final Map<? super K, ?> map, final K key, final byte defaultValue); static short getShortValue(final Map<? super K, ?> map, final K key, final short defaultValue); static int getIntValue(final Map<? super K, ?> map, final K key, final int defaultValue); static long getLongValue(final Map<? super K, ?> map, final K key, final long defaultValue); static float getFloatValue(final Map<? super K, ?> map, final K key, final float defaultValue); static double getDoubleValue(final Map<? super K, ?> map, final K key, final double defaultValue); static Properties toProperties(final Map<K, V> map); static Map<String, Object> toMap(final ResourceBundle resourceBundle); static void verbosePrint(final PrintStream out, final Object label, final Map<?, ?> map); static void debugPrint(final PrintStream out, final Object label, final Map<?, ?> map); static Map<V, K> invertMap(final Map<K, V> map); static void safeAddToMap(final Map<? super K, Object> map, final K key, final Object value); @SuppressWarnings("unchecked") // As per Javadoc throws CCE for invalid array contents static Map<K, V> putAll(final Map<K, V> map, final Object[] array); static Map<K,V> emptyIfNull(final Map<K,V> map); static boolean isEmpty(final Map<?,?> map); static boolean isNotEmpty(final Map<?,?> map); static Map<K, V> synchronizedMap(final Map<K, V> map); static Map<K, V> unmodifiableMap(final Map<? extends K, ? extends V> map); static IterableMap<K, V> predicatedMap(final Map<K, V> map, final Predicate<? super K> keyPred,
final Predicate<? super V> valuePred); static IterableMap<K, V> transformedMap(final Map<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static IterableMap<K, V> fixedSizeMap(final Map<K, V> map); static IterableMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory); static IterableMap<K, V> lazyMap(final Map<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static OrderedMap<K, V> orderedMap(final Map<K, V> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, ? super Collection<V>> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Class<C> collectionClass); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Factory<C> collectionFactory); static SortedMap<K, V> synchronizedSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> unmodifiableSortedMap(final SortedMap<K, ? extends V> map); static SortedMap<K, V> predicatedSortedMap(final SortedMap<K, V> map,
final Predicate<? super K> keyPred, final Predicate<? super V> valuePred); static SortedMap<K, V> transformedSortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static SortedMap<K, V> fixedSizeSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map, final Factory<? extends V> factory); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static void populateMap(final Map<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final Map<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static IterableMap<K, V> iterableMap(final Map<K, V> map); static IterableSortedMap<K, V> iterableSortedMap(final SortedMap<K, V> sortedMap); @SuppressWarnings("rawtypes")
static final SortedMap EMPTY_SORTED_MAP; }
|
@Test public void testConvertResourceBundle() { final Map<String, String> in = new HashMap<String, String>( 5 , 1 ); in.put("1", "A"); in.put("2", "B"); in.put("3", "C"); in.put("4", "D"); in.put("5", "E"); final ResourceBundle b = new ListResourceBundle() { @Override public Object[][] getContents() { final Object[][] contents = new Object[ in.size() ][2]; final Iterator<String> i = in.keySet().iterator(); int n = 0; while ( i.hasNext() ) { final Object key = i.next(); final Object val = in.get( key ); contents[ n ][ 0 ] = key; contents[ n ][ 1 ] = val; ++n; } return contents; } }; final Map<String, Object> out = MapUtils.toMap(b); assertTrue( in.equals(out)); }
|
MapUtils { public static void debugPrint(final PrintStream out, final Object label, final Map<?, ?> map) { verbosePrintInternal(out, label, map, new ArrayDeque<Map<?, ?>>(), true); } private MapUtils(); static V getObject(final Map<? super K, V> map, final K key); static String getString(final Map<? super K, ?> map, final K key); static Boolean getBoolean(final Map<? super K, ?> map, final K key); static Number getNumber(final Map<? super K, ?> map, final K key); static Byte getByte(final Map<? super K, ?> map, final K key); static Short getShort(final Map<? super K, ?> map, final K key); static Integer getInteger(final Map<? super K, ?> map, final K key); static Long getLong(final Map<? super K, ?> map, final K key); static Float getFloat(final Map<? super K, ?> map, final K key); static Double getDouble(final Map<? super K, ?> map, final K key); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key); static V getObject(final Map<K, V> map, final K key, final V defaultValue); static String getString(final Map<? super K, ?> map, final K key, final String defaultValue); static Boolean getBoolean(final Map<? super K, ?> map, final K key, final Boolean defaultValue); static Number getNumber(final Map<? super K, ?> map, final K key, final Number defaultValue); static Byte getByte(final Map<? super K, ?> map, final K key, final Byte defaultValue); static Short getShort(final Map<? super K, ?> map, final K key, final Short defaultValue); static Integer getInteger(final Map<? super K, ?> map, final K key, final Integer defaultValue); static Long getLong(final Map<? super K, ?> map, final K key, final Long defaultValue); static Float getFloat(final Map<? super K, ?> map, final K key, final Float defaultValue); static Double getDouble(final Map<? super K, ?> map, final K key, final Double defaultValue); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key, final Map<?, ?> defaultValue); static boolean getBooleanValue(final Map<? super K, ?> map, final K key); static byte getByteValue(final Map<? super K, ?> map, final K key); static short getShortValue(final Map<? super K, ?> map, final K key); static int getIntValue(final Map<? super K, ?> map, final K key); static long getLongValue(final Map<? super K, ?> map, final K key); static float getFloatValue(final Map<? super K, ?> map, final K key); static double getDoubleValue(final Map<? super K, ?> map, final K key); static boolean getBooleanValue(final Map<? super K, ?> map, final K key, final boolean defaultValue); static byte getByteValue(final Map<? super K, ?> map, final K key, final byte defaultValue); static short getShortValue(final Map<? super K, ?> map, final K key, final short defaultValue); static int getIntValue(final Map<? super K, ?> map, final K key, final int defaultValue); static long getLongValue(final Map<? super K, ?> map, final K key, final long defaultValue); static float getFloatValue(final Map<? super K, ?> map, final K key, final float defaultValue); static double getDoubleValue(final Map<? super K, ?> map, final K key, final double defaultValue); static Properties toProperties(final Map<K, V> map); static Map<String, Object> toMap(final ResourceBundle resourceBundle); static void verbosePrint(final PrintStream out, final Object label, final Map<?, ?> map); static void debugPrint(final PrintStream out, final Object label, final Map<?, ?> map); static Map<V, K> invertMap(final Map<K, V> map); static void safeAddToMap(final Map<? super K, Object> map, final K key, final Object value); @SuppressWarnings("unchecked") // As per Javadoc throws CCE for invalid array contents static Map<K, V> putAll(final Map<K, V> map, final Object[] array); static Map<K,V> emptyIfNull(final Map<K,V> map); static boolean isEmpty(final Map<?,?> map); static boolean isNotEmpty(final Map<?,?> map); static Map<K, V> synchronizedMap(final Map<K, V> map); static Map<K, V> unmodifiableMap(final Map<? extends K, ? extends V> map); static IterableMap<K, V> predicatedMap(final Map<K, V> map, final Predicate<? super K> keyPred,
final Predicate<? super V> valuePred); static IterableMap<K, V> transformedMap(final Map<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static IterableMap<K, V> fixedSizeMap(final Map<K, V> map); static IterableMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory); static IterableMap<K, V> lazyMap(final Map<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static OrderedMap<K, V> orderedMap(final Map<K, V> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, ? super Collection<V>> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Class<C> collectionClass); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Factory<C> collectionFactory); static SortedMap<K, V> synchronizedSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> unmodifiableSortedMap(final SortedMap<K, ? extends V> map); static SortedMap<K, V> predicatedSortedMap(final SortedMap<K, V> map,
final Predicate<? super K> keyPred, final Predicate<? super V> valuePred); static SortedMap<K, V> transformedSortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static SortedMap<K, V> fixedSizeSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map, final Factory<? extends V> factory); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static void populateMap(final Map<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final Map<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static IterableMap<K, V> iterableMap(final Map<K, V> map); static IterableSortedMap<K, V> iterableSortedMap(final SortedMap<K, V> sortedMap); @SuppressWarnings("rawtypes")
static final SortedMap EMPTY_SORTED_MAP; }
|
@Test public void testDebugAndVerbosePrintCasting() { final Map<Integer, String> inner = new HashMap<Integer, String>(2, 1); inner.put(2, "B"); inner.put(3, "C"); final Map<Integer, Object> outer = new HashMap<Integer, Object>(2, 1); outer.put(0, inner); outer.put(1, "A"); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); try { MapUtils.debugPrint(outPrint, "Print Map", outer); } catch (final ClassCastException e) { fail("No Casting should be occurring!"); } }
@Test public void testDebugPrintNullLabel() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String INDENT = " "; final Map<Integer, String> map = new TreeMap<Integer, String>(); map.put(2, "B"); map.put(3, "C"); map.put(4, null); outPrint.println("{"); outPrint.println(INDENT + "2 = B " + String.class.getName()); outPrint.println(INDENT + "3 = C " + String.class.getName()); outPrint.println(INDENT + "4 = null"); outPrint.println("} " + TreeMap.class.getName()); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.debugPrint(outPrint, null, map); assertEquals(EXPECTED_OUT, out.toString()); }
@Test public void testDebugPrintNullLabelAndMap() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); outPrint.println("null"); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.debugPrint(outPrint, null, null); assertEquals(EXPECTED_OUT, out.toString()); }
@Test public void testDebugPrintNullStream() { try { MapUtils.debugPrint(null, "Map", new HashMap<Object, Object>()); fail("Should generate NullPointerException"); } catch (final NullPointerException expected) { } }
@Test public void testDebugPrintNullKey() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String INDENT = " "; final Map<Object, String> map = new HashMap<Object, String>(); map.put(null, "A"); outPrint.println("{"); outPrint.println(INDENT + "null = A " + String.class.getName()); outPrint.println("} " + HashMap.class.getName()); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.debugPrint(outPrint, null, map); assertEquals(EXPECTED_OUT, out.toString()); }
@Test public void testDebugPrintNullKeyToMap1() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String INDENT = " "; final Map<Object, Map<?, ?>> map = new HashMap<Object, Map<?, ?>>(); map.put(null, map); outPrint.println("{"); outPrint.println(INDENT + "null = (this Map) " + HashMap.class.getName()); outPrint.println("} " + HashMap.class.getName()); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.debugPrint(outPrint, null, map); assertEquals(EXPECTED_OUT, out.toString()); }
@Test public void testDebugPrintNullKeyToMap2() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String INDENT = " "; final Map<Object, Object> map = new HashMap<Object, Object>(); final Map<Object, Object> map2= new HashMap<Object, Object>(); map.put(null, map2); map2.put("2", "B"); outPrint.println("{"); outPrint.println(INDENT + "null = "); outPrint.println(INDENT + "{"); outPrint.println(INDENT + INDENT + "2 = B " + String.class.getName()); outPrint.println(INDENT + "} " + HashMap.class.getName()); outPrint.println("} " + HashMap.class.getName()); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.debugPrint(outPrint, null, map); assertEquals(EXPECTED_OUT, out.toString()); }
@Test public void testDebugPrint() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String LABEL = "Print Map"; final String INDENT = " "; outPrint.println(LABEL + " = "); outPrint.println("{"); outPrint.println(INDENT + "0 = A " + String.class.getName()); outPrint.println(INDENT + "1 = "); outPrint.println(INDENT + "{"); outPrint.println(INDENT + INDENT + "2 = B " + String.class.getName()); outPrint.println(INDENT + INDENT + "3 = C " + String.class.getName()); outPrint.println(INDENT + "} " + TreeMap.class.getName()); outPrint.println(INDENT + "7 = (this Map) " + TreeMap.class.getName()); outPrint.println("} " + TreeMap.class.getName()); final String EXPECTED_OUT = out.toString(); out.reset(); final Map<Integer, String> inner = new TreeMap<Integer, String>(); inner.put(2, "B"); inner.put(3, "C"); final Map<Integer, Object> outer = new TreeMap<Integer, Object>(); outer.put(1, inner); outer.put(0, "A"); outer.put(7, outer); MapUtils.debugPrint(outPrint, "Print Map", outer); assertEquals(EXPECTED_OUT, out.toString()); }
@Test public void testDebugPrintSelfReference() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String LABEL = "Print Map"; final String INDENT = " "; final Map<Integer, Object> grandfather = new TreeMap<Integer, Object>(); final Map<Integer, Object> father = new TreeMap<Integer, Object>(); final Map<Integer, Object> son = new TreeMap<Integer, Object>(); grandfather.put(0, "A"); grandfather.put(1, father); father.put(2, "B"); father.put(3, grandfather); father.put(4, son); son.put(5, "C"); son.put(6, grandfather); son.put(7, father); outPrint.println(LABEL + " = "); outPrint.println("{"); outPrint.println(INDENT + "0 = A " + String.class.getName()); outPrint.println(INDENT + "1 = "); outPrint.println(INDENT + "{"); outPrint.println(INDENT + INDENT + "2 = B " + String.class.getName()); outPrint.println(INDENT + INDENT + "3 = (ancestor[0] Map) " + TreeMap.class.getName()); outPrint.println(INDENT + INDENT + "4 = "); outPrint.println(INDENT + INDENT + "{"); outPrint.println(INDENT + INDENT + INDENT + "5 = C " + String.class.getName()); outPrint.println(INDENT + INDENT + INDENT + "6 = (ancestor[1] Map) " + TreeMap.class.getName()); outPrint.println(INDENT + INDENT + INDENT + "7 = (ancestor[0] Map) " + TreeMap.class.getName()); outPrint.println(INDENT + INDENT + "} " + TreeMap.class.getName()); outPrint.println(INDENT + "} " + TreeMap.class.getName()); outPrint.println("} " + TreeMap.class.getName()); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.debugPrint(outPrint, "Print Map", grandfather); assertEquals(EXPECTED_OUT, out.toString()); }
|
MapUtils { public static void verbosePrint(final PrintStream out, final Object label, final Map<?, ?> map) { verbosePrintInternal(out, label, map, new ArrayDeque<Map<?, ?>>(), false); } private MapUtils(); static V getObject(final Map<? super K, V> map, final K key); static String getString(final Map<? super K, ?> map, final K key); static Boolean getBoolean(final Map<? super K, ?> map, final K key); static Number getNumber(final Map<? super K, ?> map, final K key); static Byte getByte(final Map<? super K, ?> map, final K key); static Short getShort(final Map<? super K, ?> map, final K key); static Integer getInteger(final Map<? super K, ?> map, final K key); static Long getLong(final Map<? super K, ?> map, final K key); static Float getFloat(final Map<? super K, ?> map, final K key); static Double getDouble(final Map<? super K, ?> map, final K key); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key); static V getObject(final Map<K, V> map, final K key, final V defaultValue); static String getString(final Map<? super K, ?> map, final K key, final String defaultValue); static Boolean getBoolean(final Map<? super K, ?> map, final K key, final Boolean defaultValue); static Number getNumber(final Map<? super K, ?> map, final K key, final Number defaultValue); static Byte getByte(final Map<? super K, ?> map, final K key, final Byte defaultValue); static Short getShort(final Map<? super K, ?> map, final K key, final Short defaultValue); static Integer getInteger(final Map<? super K, ?> map, final K key, final Integer defaultValue); static Long getLong(final Map<? super K, ?> map, final K key, final Long defaultValue); static Float getFloat(final Map<? super K, ?> map, final K key, final Float defaultValue); static Double getDouble(final Map<? super K, ?> map, final K key, final Double defaultValue); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key, final Map<?, ?> defaultValue); static boolean getBooleanValue(final Map<? super K, ?> map, final K key); static byte getByteValue(final Map<? super K, ?> map, final K key); static short getShortValue(final Map<? super K, ?> map, final K key); static int getIntValue(final Map<? super K, ?> map, final K key); static long getLongValue(final Map<? super K, ?> map, final K key); static float getFloatValue(final Map<? super K, ?> map, final K key); static double getDoubleValue(final Map<? super K, ?> map, final K key); static boolean getBooleanValue(final Map<? super K, ?> map, final K key, final boolean defaultValue); static byte getByteValue(final Map<? super K, ?> map, final K key, final byte defaultValue); static short getShortValue(final Map<? super K, ?> map, final K key, final short defaultValue); static int getIntValue(final Map<? super K, ?> map, final K key, final int defaultValue); static long getLongValue(final Map<? super K, ?> map, final K key, final long defaultValue); static float getFloatValue(final Map<? super K, ?> map, final K key, final float defaultValue); static double getDoubleValue(final Map<? super K, ?> map, final K key, final double defaultValue); static Properties toProperties(final Map<K, V> map); static Map<String, Object> toMap(final ResourceBundle resourceBundle); static void verbosePrint(final PrintStream out, final Object label, final Map<?, ?> map); static void debugPrint(final PrintStream out, final Object label, final Map<?, ?> map); static Map<V, K> invertMap(final Map<K, V> map); static void safeAddToMap(final Map<? super K, Object> map, final K key, final Object value); @SuppressWarnings("unchecked") // As per Javadoc throws CCE for invalid array contents static Map<K, V> putAll(final Map<K, V> map, final Object[] array); static Map<K,V> emptyIfNull(final Map<K,V> map); static boolean isEmpty(final Map<?,?> map); static boolean isNotEmpty(final Map<?,?> map); static Map<K, V> synchronizedMap(final Map<K, V> map); static Map<K, V> unmodifiableMap(final Map<? extends K, ? extends V> map); static IterableMap<K, V> predicatedMap(final Map<K, V> map, final Predicate<? super K> keyPred,
final Predicate<? super V> valuePred); static IterableMap<K, V> transformedMap(final Map<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static IterableMap<K, V> fixedSizeMap(final Map<K, V> map); static IterableMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory); static IterableMap<K, V> lazyMap(final Map<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static OrderedMap<K, V> orderedMap(final Map<K, V> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, ? super Collection<V>> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Class<C> collectionClass); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Factory<C> collectionFactory); static SortedMap<K, V> synchronizedSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> unmodifiableSortedMap(final SortedMap<K, ? extends V> map); static SortedMap<K, V> predicatedSortedMap(final SortedMap<K, V> map,
final Predicate<? super K> keyPred, final Predicate<? super V> valuePred); static SortedMap<K, V> transformedSortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static SortedMap<K, V> fixedSizeSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map, final Factory<? extends V> factory); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static void populateMap(final Map<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final Map<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static IterableMap<K, V> iterableMap(final Map<K, V> map); static IterableSortedMap<K, V> iterableSortedMap(final SortedMap<K, V> sortedMap); @SuppressWarnings("rawtypes")
static final SortedMap EMPTY_SORTED_MAP; }
|
@Test public void testVerbosePrintNullLabel() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String INDENT = " "; final Map<Integer, String> map = new TreeMap<Integer, String>(); map.put(2, "B"); map.put(3, "C"); map.put(4, null); outPrint.println("{"); outPrint.println(INDENT + "2 = B"); outPrint.println(INDENT + "3 = C"); outPrint.println(INDENT + "4 = null"); outPrint.println("}"); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.verbosePrint(outPrint, null, map); assertEquals(EXPECTED_OUT, out.toString()); }
@Test public void testVerbosePrintNullLabelAndMap() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); outPrint.println("null"); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.verbosePrint(outPrint, null, null); assertEquals(EXPECTED_OUT, out.toString()); }
@Test public void testVerbosePrintNullStream() { try { MapUtils.verbosePrint(null, "Map", new HashMap<Object, Object>()); fail("Should generate NullPointerException"); } catch (final NullPointerException expected) { } }
@Test public void testVerbosePrintNullKey() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String INDENT = " "; final Map<Object, String> map = new HashMap<Object, String>(); map.put(null, "A"); outPrint.println("{"); outPrint.println(INDENT + "null = A"); outPrint.println("}"); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.verbosePrint(outPrint, null, map); assertEquals(EXPECTED_OUT, out.toString()); }
@Test public void testVerbosePrintNullKeyToMap1() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String INDENT = " "; final Map<Object, Map<?, ?>> map = new HashMap<Object, Map<?, ?>>(); map.put(null, map); outPrint.println("{"); outPrint.println(INDENT + "null = (this Map)"); outPrint.println("}"); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.verbosePrint(outPrint, null, map); assertEquals(EXPECTED_OUT, out.toString()); }
@Test public void testVerbosePrintNullKeyToMap2() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String INDENT = " "; final Map<Object, Object> map = new HashMap<Object, Object>(); final Map<Object, Object> map2= new HashMap<Object, Object>(); map.put(null, map2); map2.put("2", "B"); outPrint.println("{"); outPrint.println(INDENT + "null = "); outPrint.println(INDENT + "{"); outPrint.println(INDENT + INDENT + "2 = B"); outPrint.println(INDENT + "}"); outPrint.println("}"); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.verbosePrint(outPrint, null, map); assertEquals(EXPECTED_OUT, out.toString()); }
@Test public void testVerbosePrint() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String LABEL = "Print Map"; final String INDENT = " "; outPrint.println(LABEL + " = "); outPrint.println("{"); outPrint.println(INDENT + "0 = A"); outPrint.println(INDENT + "1 = "); outPrint.println(INDENT + "{"); outPrint.println(INDENT + INDENT + "2 = B"); outPrint.println(INDENT + INDENT + "3 = C"); outPrint.println(INDENT + "}"); outPrint.println(INDENT + "7 = (this Map)"); outPrint.println("}"); final String EXPECTED_OUT = out.toString(); out.reset(); final Map<Integer, String> inner = new TreeMap<Integer, String>(); inner.put(2, "B"); inner.put(3, "C"); final Map<Integer, Object> outer = new TreeMap<Integer, Object>(); outer.put(1, inner); outer.put(0, "A"); outer.put(7, outer); MapUtils.verbosePrint(outPrint, "Print Map", outer); assertEquals(EXPECTED_OUT, out.toString()); }
@Test public void testVerbosePrintSelfReference() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); final String LABEL = "Print Map"; final String INDENT = " "; final Map<Integer, Object> grandfather = new TreeMap<Integer, Object>(); final Map<Integer, Object> father = new TreeMap<Integer, Object>(); final Map<Integer, Object> son = new TreeMap<Integer, Object>(); grandfather.put(0, "A"); grandfather.put(1, father); father.put(2, "B"); father.put(3, grandfather); father.put(4, son); son.put(5, "C"); son.put(6, grandfather); son.put(7, father); outPrint.println(LABEL + " = "); outPrint.println("{"); outPrint.println(INDENT + "0 = A"); outPrint.println(INDENT + "1 = "); outPrint.println(INDENT + "{"); outPrint.println(INDENT + INDENT + "2 = B"); outPrint.println(INDENT + INDENT + "3 = (ancestor[0] Map)"); outPrint.println(INDENT + INDENT + "4 = "); outPrint.println(INDENT + INDENT + "{"); outPrint.println(INDENT + INDENT + INDENT + "5 = C"); outPrint.println(INDENT + INDENT + INDENT + "6 = (ancestor[1] Map)"); outPrint.println(INDENT + INDENT + INDENT + "7 = (ancestor[0] Map)"); outPrint.println(INDENT + INDENT + "}"); outPrint.println(INDENT + "}"); outPrint.println("}"); final String EXPECTED_OUT = out.toString(); out.reset(); MapUtils.verbosePrint(outPrint, "Print Map", grandfather); assertEquals(EXPECTED_OUT, out.toString()); }
|
MapUtils { public static <K,V> Map<K,V> emptyIfNull(final Map<K,V> map) { return map == null ? Collections.<K,V>emptyMap() : map; } private MapUtils(); static V getObject(final Map<? super K, V> map, final K key); static String getString(final Map<? super K, ?> map, final K key); static Boolean getBoolean(final Map<? super K, ?> map, final K key); static Number getNumber(final Map<? super K, ?> map, final K key); static Byte getByte(final Map<? super K, ?> map, final K key); static Short getShort(final Map<? super K, ?> map, final K key); static Integer getInteger(final Map<? super K, ?> map, final K key); static Long getLong(final Map<? super K, ?> map, final K key); static Float getFloat(final Map<? super K, ?> map, final K key); static Double getDouble(final Map<? super K, ?> map, final K key); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key); static V getObject(final Map<K, V> map, final K key, final V defaultValue); static String getString(final Map<? super K, ?> map, final K key, final String defaultValue); static Boolean getBoolean(final Map<? super K, ?> map, final K key, final Boolean defaultValue); static Number getNumber(final Map<? super K, ?> map, final K key, final Number defaultValue); static Byte getByte(final Map<? super K, ?> map, final K key, final Byte defaultValue); static Short getShort(final Map<? super K, ?> map, final K key, final Short defaultValue); static Integer getInteger(final Map<? super K, ?> map, final K key, final Integer defaultValue); static Long getLong(final Map<? super K, ?> map, final K key, final Long defaultValue); static Float getFloat(final Map<? super K, ?> map, final K key, final Float defaultValue); static Double getDouble(final Map<? super K, ?> map, final K key, final Double defaultValue); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key, final Map<?, ?> defaultValue); static boolean getBooleanValue(final Map<? super K, ?> map, final K key); static byte getByteValue(final Map<? super K, ?> map, final K key); static short getShortValue(final Map<? super K, ?> map, final K key); static int getIntValue(final Map<? super K, ?> map, final K key); static long getLongValue(final Map<? super K, ?> map, final K key); static float getFloatValue(final Map<? super K, ?> map, final K key); static double getDoubleValue(final Map<? super K, ?> map, final K key); static boolean getBooleanValue(final Map<? super K, ?> map, final K key, final boolean defaultValue); static byte getByteValue(final Map<? super K, ?> map, final K key, final byte defaultValue); static short getShortValue(final Map<? super K, ?> map, final K key, final short defaultValue); static int getIntValue(final Map<? super K, ?> map, final K key, final int defaultValue); static long getLongValue(final Map<? super K, ?> map, final K key, final long defaultValue); static float getFloatValue(final Map<? super K, ?> map, final K key, final float defaultValue); static double getDoubleValue(final Map<? super K, ?> map, final K key, final double defaultValue); static Properties toProperties(final Map<K, V> map); static Map<String, Object> toMap(final ResourceBundle resourceBundle); static void verbosePrint(final PrintStream out, final Object label, final Map<?, ?> map); static void debugPrint(final PrintStream out, final Object label, final Map<?, ?> map); static Map<V, K> invertMap(final Map<K, V> map); static void safeAddToMap(final Map<? super K, Object> map, final K key, final Object value); @SuppressWarnings("unchecked") // As per Javadoc throws CCE for invalid array contents static Map<K, V> putAll(final Map<K, V> map, final Object[] array); static Map<K,V> emptyIfNull(final Map<K,V> map); static boolean isEmpty(final Map<?,?> map); static boolean isNotEmpty(final Map<?,?> map); static Map<K, V> synchronizedMap(final Map<K, V> map); static Map<K, V> unmodifiableMap(final Map<? extends K, ? extends V> map); static IterableMap<K, V> predicatedMap(final Map<K, V> map, final Predicate<? super K> keyPred,
final Predicate<? super V> valuePred); static IterableMap<K, V> transformedMap(final Map<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static IterableMap<K, V> fixedSizeMap(final Map<K, V> map); static IterableMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory); static IterableMap<K, V> lazyMap(final Map<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static OrderedMap<K, V> orderedMap(final Map<K, V> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, ? super Collection<V>> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Class<C> collectionClass); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Factory<C> collectionFactory); static SortedMap<K, V> synchronizedSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> unmodifiableSortedMap(final SortedMap<K, ? extends V> map); static SortedMap<K, V> predicatedSortedMap(final SortedMap<K, V> map,
final Predicate<? super K> keyPred, final Predicate<? super V> valuePred); static SortedMap<K, V> transformedSortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static SortedMap<K, V> fixedSizeSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map, final Factory<? extends V> factory); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static void populateMap(final Map<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final Map<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static IterableMap<K, V> iterableMap(final Map<K, V> map); static IterableSortedMap<K, V> iterableSortedMap(final SortedMap<K, V> sortedMap); @SuppressWarnings("rawtypes")
static final SortedMap EMPTY_SORTED_MAP; }
|
@Test public void testEmptyIfNull() { assertTrue(MapUtils.emptyIfNull(null).isEmpty()); final Map<Long, Long> map = new HashMap<Long, Long>(); assertSame(map, MapUtils.emptyIfNull(map)); }
|
MapUtils { public static boolean isEmpty(final Map<?,?> map) { return map == null || map.isEmpty(); } private MapUtils(); static V getObject(final Map<? super K, V> map, final K key); static String getString(final Map<? super K, ?> map, final K key); static Boolean getBoolean(final Map<? super K, ?> map, final K key); static Number getNumber(final Map<? super K, ?> map, final K key); static Byte getByte(final Map<? super K, ?> map, final K key); static Short getShort(final Map<? super K, ?> map, final K key); static Integer getInteger(final Map<? super K, ?> map, final K key); static Long getLong(final Map<? super K, ?> map, final K key); static Float getFloat(final Map<? super K, ?> map, final K key); static Double getDouble(final Map<? super K, ?> map, final K key); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key); static V getObject(final Map<K, V> map, final K key, final V defaultValue); static String getString(final Map<? super K, ?> map, final K key, final String defaultValue); static Boolean getBoolean(final Map<? super K, ?> map, final K key, final Boolean defaultValue); static Number getNumber(final Map<? super K, ?> map, final K key, final Number defaultValue); static Byte getByte(final Map<? super K, ?> map, final K key, final Byte defaultValue); static Short getShort(final Map<? super K, ?> map, final K key, final Short defaultValue); static Integer getInteger(final Map<? super K, ?> map, final K key, final Integer defaultValue); static Long getLong(final Map<? super K, ?> map, final K key, final Long defaultValue); static Float getFloat(final Map<? super K, ?> map, final K key, final Float defaultValue); static Double getDouble(final Map<? super K, ?> map, final K key, final Double defaultValue); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key, final Map<?, ?> defaultValue); static boolean getBooleanValue(final Map<? super K, ?> map, final K key); static byte getByteValue(final Map<? super K, ?> map, final K key); static short getShortValue(final Map<? super K, ?> map, final K key); static int getIntValue(final Map<? super K, ?> map, final K key); static long getLongValue(final Map<? super K, ?> map, final K key); static float getFloatValue(final Map<? super K, ?> map, final K key); static double getDoubleValue(final Map<? super K, ?> map, final K key); static boolean getBooleanValue(final Map<? super K, ?> map, final K key, final boolean defaultValue); static byte getByteValue(final Map<? super K, ?> map, final K key, final byte defaultValue); static short getShortValue(final Map<? super K, ?> map, final K key, final short defaultValue); static int getIntValue(final Map<? super K, ?> map, final K key, final int defaultValue); static long getLongValue(final Map<? super K, ?> map, final K key, final long defaultValue); static float getFloatValue(final Map<? super K, ?> map, final K key, final float defaultValue); static double getDoubleValue(final Map<? super K, ?> map, final K key, final double defaultValue); static Properties toProperties(final Map<K, V> map); static Map<String, Object> toMap(final ResourceBundle resourceBundle); static void verbosePrint(final PrintStream out, final Object label, final Map<?, ?> map); static void debugPrint(final PrintStream out, final Object label, final Map<?, ?> map); static Map<V, K> invertMap(final Map<K, V> map); static void safeAddToMap(final Map<? super K, Object> map, final K key, final Object value); @SuppressWarnings("unchecked") // As per Javadoc throws CCE for invalid array contents static Map<K, V> putAll(final Map<K, V> map, final Object[] array); static Map<K,V> emptyIfNull(final Map<K,V> map); static boolean isEmpty(final Map<?,?> map); static boolean isNotEmpty(final Map<?,?> map); static Map<K, V> synchronizedMap(final Map<K, V> map); static Map<K, V> unmodifiableMap(final Map<? extends K, ? extends V> map); static IterableMap<K, V> predicatedMap(final Map<K, V> map, final Predicate<? super K> keyPred,
final Predicate<? super V> valuePred); static IterableMap<K, V> transformedMap(final Map<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static IterableMap<K, V> fixedSizeMap(final Map<K, V> map); static IterableMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory); static IterableMap<K, V> lazyMap(final Map<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static OrderedMap<K, V> orderedMap(final Map<K, V> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, ? super Collection<V>> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Class<C> collectionClass); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Factory<C> collectionFactory); static SortedMap<K, V> synchronizedSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> unmodifiableSortedMap(final SortedMap<K, ? extends V> map); static SortedMap<K, V> predicatedSortedMap(final SortedMap<K, V> map,
final Predicate<? super K> keyPred, final Predicate<? super V> valuePred); static SortedMap<K, V> transformedSortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static SortedMap<K, V> fixedSizeSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map, final Factory<? extends V> factory); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static void populateMap(final Map<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final Map<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static IterableMap<K, V> iterableMap(final Map<K, V> map); static IterableSortedMap<K, V> iterableSortedMap(final SortedMap<K, V> sortedMap); @SuppressWarnings("rawtypes")
static final SortedMap EMPTY_SORTED_MAP; }
|
@Test public void testIsEmptyWithEmptyMap() { final Map<Object, Object> map = new HashMap<Object, Object>(); assertEquals(true, MapUtils.isEmpty(map)); }
@Test public void testIsEmptyWithNonEmptyMap() { final Map<String, String> map = new HashMap<String, String>(); map.put("item", "value"); assertEquals(false, MapUtils.isEmpty(map)); }
@Test public void testIsEmptyWithNull() { final Map<Object, Object> map = null; assertEquals(true, MapUtils.isEmpty(map)); }
|
MapUtils { public static boolean isNotEmpty(final Map<?,?> map) { return !MapUtils.isEmpty(map); } private MapUtils(); static V getObject(final Map<? super K, V> map, final K key); static String getString(final Map<? super K, ?> map, final K key); static Boolean getBoolean(final Map<? super K, ?> map, final K key); static Number getNumber(final Map<? super K, ?> map, final K key); static Byte getByte(final Map<? super K, ?> map, final K key); static Short getShort(final Map<? super K, ?> map, final K key); static Integer getInteger(final Map<? super K, ?> map, final K key); static Long getLong(final Map<? super K, ?> map, final K key); static Float getFloat(final Map<? super K, ?> map, final K key); static Double getDouble(final Map<? super K, ?> map, final K key); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key); static V getObject(final Map<K, V> map, final K key, final V defaultValue); static String getString(final Map<? super K, ?> map, final K key, final String defaultValue); static Boolean getBoolean(final Map<? super K, ?> map, final K key, final Boolean defaultValue); static Number getNumber(final Map<? super K, ?> map, final K key, final Number defaultValue); static Byte getByte(final Map<? super K, ?> map, final K key, final Byte defaultValue); static Short getShort(final Map<? super K, ?> map, final K key, final Short defaultValue); static Integer getInteger(final Map<? super K, ?> map, final K key, final Integer defaultValue); static Long getLong(final Map<? super K, ?> map, final K key, final Long defaultValue); static Float getFloat(final Map<? super K, ?> map, final K key, final Float defaultValue); static Double getDouble(final Map<? super K, ?> map, final K key, final Double defaultValue); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key, final Map<?, ?> defaultValue); static boolean getBooleanValue(final Map<? super K, ?> map, final K key); static byte getByteValue(final Map<? super K, ?> map, final K key); static short getShortValue(final Map<? super K, ?> map, final K key); static int getIntValue(final Map<? super K, ?> map, final K key); static long getLongValue(final Map<? super K, ?> map, final K key); static float getFloatValue(final Map<? super K, ?> map, final K key); static double getDoubleValue(final Map<? super K, ?> map, final K key); static boolean getBooleanValue(final Map<? super K, ?> map, final K key, final boolean defaultValue); static byte getByteValue(final Map<? super K, ?> map, final K key, final byte defaultValue); static short getShortValue(final Map<? super K, ?> map, final K key, final short defaultValue); static int getIntValue(final Map<? super K, ?> map, final K key, final int defaultValue); static long getLongValue(final Map<? super K, ?> map, final K key, final long defaultValue); static float getFloatValue(final Map<? super K, ?> map, final K key, final float defaultValue); static double getDoubleValue(final Map<? super K, ?> map, final K key, final double defaultValue); static Properties toProperties(final Map<K, V> map); static Map<String, Object> toMap(final ResourceBundle resourceBundle); static void verbosePrint(final PrintStream out, final Object label, final Map<?, ?> map); static void debugPrint(final PrintStream out, final Object label, final Map<?, ?> map); static Map<V, K> invertMap(final Map<K, V> map); static void safeAddToMap(final Map<? super K, Object> map, final K key, final Object value); @SuppressWarnings("unchecked") // As per Javadoc throws CCE for invalid array contents static Map<K, V> putAll(final Map<K, V> map, final Object[] array); static Map<K,V> emptyIfNull(final Map<K,V> map); static boolean isEmpty(final Map<?,?> map); static boolean isNotEmpty(final Map<?,?> map); static Map<K, V> synchronizedMap(final Map<K, V> map); static Map<K, V> unmodifiableMap(final Map<? extends K, ? extends V> map); static IterableMap<K, V> predicatedMap(final Map<K, V> map, final Predicate<? super K> keyPred,
final Predicate<? super V> valuePred); static IterableMap<K, V> transformedMap(final Map<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static IterableMap<K, V> fixedSizeMap(final Map<K, V> map); static IterableMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory); static IterableMap<K, V> lazyMap(final Map<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static OrderedMap<K, V> orderedMap(final Map<K, V> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, ? super Collection<V>> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Class<C> collectionClass); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Factory<C> collectionFactory); static SortedMap<K, V> synchronizedSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> unmodifiableSortedMap(final SortedMap<K, ? extends V> map); static SortedMap<K, V> predicatedSortedMap(final SortedMap<K, V> map,
final Predicate<? super K> keyPred, final Predicate<? super V> valuePred); static SortedMap<K, V> transformedSortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static SortedMap<K, V> fixedSizeSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map, final Factory<? extends V> factory); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static void populateMap(final Map<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final Map<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static IterableMap<K, V> iterableMap(final Map<K, V> map); static IterableSortedMap<K, V> iterableSortedMap(final SortedMap<K, V> sortedMap); @SuppressWarnings("rawtypes")
static final SortedMap EMPTY_SORTED_MAP; }
|
@Test public void testIsNotEmptyWithEmptyMap() { final Map<Object, Object> map = new HashMap<Object, Object>(); assertEquals(false, MapUtils.isNotEmpty(map)); }
@Test public void testIsNotEmptyWithNonEmptyMap() { final Map<String, String> map = new HashMap<String, String>(); map.put("item", "value"); assertEquals(true, MapUtils.isNotEmpty(map)); }
@Test public void testIsNotEmptyWithNull() { final Map<Object, Object> map = null; assertEquals(false, MapUtils.isNotEmpty(map)); }
|
MapUtils { public static <K, V> void populateMap(final Map<K, V> map, final Iterable<? extends V> elements, final Transformer<V, K> keyTransformer) { populateMap(map, elements, keyTransformer, TransformerUtils.<V>nopTransformer()); } private MapUtils(); static V getObject(final Map<? super K, V> map, final K key); static String getString(final Map<? super K, ?> map, final K key); static Boolean getBoolean(final Map<? super K, ?> map, final K key); static Number getNumber(final Map<? super K, ?> map, final K key); static Byte getByte(final Map<? super K, ?> map, final K key); static Short getShort(final Map<? super K, ?> map, final K key); static Integer getInteger(final Map<? super K, ?> map, final K key); static Long getLong(final Map<? super K, ?> map, final K key); static Float getFloat(final Map<? super K, ?> map, final K key); static Double getDouble(final Map<? super K, ?> map, final K key); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key); static V getObject(final Map<K, V> map, final K key, final V defaultValue); static String getString(final Map<? super K, ?> map, final K key, final String defaultValue); static Boolean getBoolean(final Map<? super K, ?> map, final K key, final Boolean defaultValue); static Number getNumber(final Map<? super K, ?> map, final K key, final Number defaultValue); static Byte getByte(final Map<? super K, ?> map, final K key, final Byte defaultValue); static Short getShort(final Map<? super K, ?> map, final K key, final Short defaultValue); static Integer getInteger(final Map<? super K, ?> map, final K key, final Integer defaultValue); static Long getLong(final Map<? super K, ?> map, final K key, final Long defaultValue); static Float getFloat(final Map<? super K, ?> map, final K key, final Float defaultValue); static Double getDouble(final Map<? super K, ?> map, final K key, final Double defaultValue); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key, final Map<?, ?> defaultValue); static boolean getBooleanValue(final Map<? super K, ?> map, final K key); static byte getByteValue(final Map<? super K, ?> map, final K key); static short getShortValue(final Map<? super K, ?> map, final K key); static int getIntValue(final Map<? super K, ?> map, final K key); static long getLongValue(final Map<? super K, ?> map, final K key); static float getFloatValue(final Map<? super K, ?> map, final K key); static double getDoubleValue(final Map<? super K, ?> map, final K key); static boolean getBooleanValue(final Map<? super K, ?> map, final K key, final boolean defaultValue); static byte getByteValue(final Map<? super K, ?> map, final K key, final byte defaultValue); static short getShortValue(final Map<? super K, ?> map, final K key, final short defaultValue); static int getIntValue(final Map<? super K, ?> map, final K key, final int defaultValue); static long getLongValue(final Map<? super K, ?> map, final K key, final long defaultValue); static float getFloatValue(final Map<? super K, ?> map, final K key, final float defaultValue); static double getDoubleValue(final Map<? super K, ?> map, final K key, final double defaultValue); static Properties toProperties(final Map<K, V> map); static Map<String, Object> toMap(final ResourceBundle resourceBundle); static void verbosePrint(final PrintStream out, final Object label, final Map<?, ?> map); static void debugPrint(final PrintStream out, final Object label, final Map<?, ?> map); static Map<V, K> invertMap(final Map<K, V> map); static void safeAddToMap(final Map<? super K, Object> map, final K key, final Object value); @SuppressWarnings("unchecked") // As per Javadoc throws CCE for invalid array contents static Map<K, V> putAll(final Map<K, V> map, final Object[] array); static Map<K,V> emptyIfNull(final Map<K,V> map); static boolean isEmpty(final Map<?,?> map); static boolean isNotEmpty(final Map<?,?> map); static Map<K, V> synchronizedMap(final Map<K, V> map); static Map<K, V> unmodifiableMap(final Map<? extends K, ? extends V> map); static IterableMap<K, V> predicatedMap(final Map<K, V> map, final Predicate<? super K> keyPred,
final Predicate<? super V> valuePred); static IterableMap<K, V> transformedMap(final Map<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static IterableMap<K, V> fixedSizeMap(final Map<K, V> map); static IterableMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory); static IterableMap<K, V> lazyMap(final Map<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static OrderedMap<K, V> orderedMap(final Map<K, V> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, ? super Collection<V>> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Class<C> collectionClass); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Factory<C> collectionFactory); static SortedMap<K, V> synchronizedSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> unmodifiableSortedMap(final SortedMap<K, ? extends V> map); static SortedMap<K, V> predicatedSortedMap(final SortedMap<K, V> map,
final Predicate<? super K> keyPred, final Predicate<? super V> valuePred); static SortedMap<K, V> transformedSortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static SortedMap<K, V> fixedSizeSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map, final Factory<? extends V> factory); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static void populateMap(final Map<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final Map<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static IterableMap<K, V> iterableMap(final Map<K, V> map); static IterableSortedMap<K, V> iterableSortedMap(final SortedMap<K, V> sortedMap); @SuppressWarnings("rawtypes")
static final SortedMap EMPTY_SORTED_MAP; }
|
@Test public void testPopulateMap() { final List<String> list = new ArrayList<String>(); list.add("1"); list.add("3"); list.add("5"); list.add("7"); list.add("2"); list.add("4"); list.add("6"); Map<Object, Object> map = new HashMap<Object, Object>(); MapUtils.populateMap(map, list, TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(list.size(), map.size()); for (int i = 0; i < list.size(); i++) { assertEquals(true, map.containsKey(Integer.valueOf(list.get(i)))); assertEquals(false, map.containsKey(list.get(i))); assertEquals(true, map.containsValue(list.get(i))); assertEquals(list.get(i), map.get(Integer.valueOf(list.get(i)))); } map = new HashMap<Object, Object>(); MapUtils.populateMap(map, list, TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER, TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(list.size(), map.size()); for (int i = 0; i < list.size(); i++) { assertEquals(true, map.containsKey(Integer.valueOf(list.get(i)))); assertEquals(false, map.containsKey(list.get(i))); assertEquals(true, map.containsValue(Integer.valueOf(list.get(i)))); assertEquals(Integer.valueOf(list.get(i)), map.get(Integer.valueOf(list.get(i)))); } }
|
MapUtils { public static <K, V> IterableMap<K, V> iterableMap(final Map<K, V> map) { if (map == null) { throw new NullPointerException("Map must not be null"); } return map instanceof IterableMap ? (IterableMap<K, V>) map : new AbstractMapDecorator<K, V>(map) {}; } private MapUtils(); static V getObject(final Map<? super K, V> map, final K key); static String getString(final Map<? super K, ?> map, final K key); static Boolean getBoolean(final Map<? super K, ?> map, final K key); static Number getNumber(final Map<? super K, ?> map, final K key); static Byte getByte(final Map<? super K, ?> map, final K key); static Short getShort(final Map<? super K, ?> map, final K key); static Integer getInteger(final Map<? super K, ?> map, final K key); static Long getLong(final Map<? super K, ?> map, final K key); static Float getFloat(final Map<? super K, ?> map, final K key); static Double getDouble(final Map<? super K, ?> map, final K key); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key); static V getObject(final Map<K, V> map, final K key, final V defaultValue); static String getString(final Map<? super K, ?> map, final K key, final String defaultValue); static Boolean getBoolean(final Map<? super K, ?> map, final K key, final Boolean defaultValue); static Number getNumber(final Map<? super K, ?> map, final K key, final Number defaultValue); static Byte getByte(final Map<? super K, ?> map, final K key, final Byte defaultValue); static Short getShort(final Map<? super K, ?> map, final K key, final Short defaultValue); static Integer getInteger(final Map<? super K, ?> map, final K key, final Integer defaultValue); static Long getLong(final Map<? super K, ?> map, final K key, final Long defaultValue); static Float getFloat(final Map<? super K, ?> map, final K key, final Float defaultValue); static Double getDouble(final Map<? super K, ?> map, final K key, final Double defaultValue); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key, final Map<?, ?> defaultValue); static boolean getBooleanValue(final Map<? super K, ?> map, final K key); static byte getByteValue(final Map<? super K, ?> map, final K key); static short getShortValue(final Map<? super K, ?> map, final K key); static int getIntValue(final Map<? super K, ?> map, final K key); static long getLongValue(final Map<? super K, ?> map, final K key); static float getFloatValue(final Map<? super K, ?> map, final K key); static double getDoubleValue(final Map<? super K, ?> map, final K key); static boolean getBooleanValue(final Map<? super K, ?> map, final K key, final boolean defaultValue); static byte getByteValue(final Map<? super K, ?> map, final K key, final byte defaultValue); static short getShortValue(final Map<? super K, ?> map, final K key, final short defaultValue); static int getIntValue(final Map<? super K, ?> map, final K key, final int defaultValue); static long getLongValue(final Map<? super K, ?> map, final K key, final long defaultValue); static float getFloatValue(final Map<? super K, ?> map, final K key, final float defaultValue); static double getDoubleValue(final Map<? super K, ?> map, final K key, final double defaultValue); static Properties toProperties(final Map<K, V> map); static Map<String, Object> toMap(final ResourceBundle resourceBundle); static void verbosePrint(final PrintStream out, final Object label, final Map<?, ?> map); static void debugPrint(final PrintStream out, final Object label, final Map<?, ?> map); static Map<V, K> invertMap(final Map<K, V> map); static void safeAddToMap(final Map<? super K, Object> map, final K key, final Object value); @SuppressWarnings("unchecked") // As per Javadoc throws CCE for invalid array contents static Map<K, V> putAll(final Map<K, V> map, final Object[] array); static Map<K,V> emptyIfNull(final Map<K,V> map); static boolean isEmpty(final Map<?,?> map); static boolean isNotEmpty(final Map<?,?> map); static Map<K, V> synchronizedMap(final Map<K, V> map); static Map<K, V> unmodifiableMap(final Map<? extends K, ? extends V> map); static IterableMap<K, V> predicatedMap(final Map<K, V> map, final Predicate<? super K> keyPred,
final Predicate<? super V> valuePred); static IterableMap<K, V> transformedMap(final Map<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static IterableMap<K, V> fixedSizeMap(final Map<K, V> map); static IterableMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory); static IterableMap<K, V> lazyMap(final Map<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static OrderedMap<K, V> orderedMap(final Map<K, V> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, ? super Collection<V>> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Class<C> collectionClass); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Factory<C> collectionFactory); static SortedMap<K, V> synchronizedSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> unmodifiableSortedMap(final SortedMap<K, ? extends V> map); static SortedMap<K, V> predicatedSortedMap(final SortedMap<K, V> map,
final Predicate<? super K> keyPred, final Predicate<? super V> valuePred); static SortedMap<K, V> transformedSortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static SortedMap<K, V> fixedSizeSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map, final Factory<? extends V> factory); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static void populateMap(final Map<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final Map<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static IterableMap<K, V> iterableMap(final Map<K, V> map); static IterableSortedMap<K, V> iterableSortedMap(final SortedMap<K, V> sortedMap); @SuppressWarnings("rawtypes")
static final SortedMap EMPTY_SORTED_MAP; }
|
@Test public void testIterableMap() { try { MapUtils.iterableMap(null); fail("Should throw NullPointerException"); } catch (final NullPointerException e) { } final HashMap<String, String> map = new HashMap<String, String>(); map.put("foo", "foov"); map.put("bar", "barv"); map.put("baz", "bazv"); final IterableMap<String, String> iMap = MapUtils.iterableMap(map); assertEquals(map, iMap); assertNotSame(map, iMap); final HashedMap<String, String> hMap = new HashedMap<String, String>(map); assertSame(hMap, MapUtils.iterableMap(hMap)); }
|
MapUtils { public static <K, V> IterableSortedMap<K, V> iterableSortedMap(final SortedMap<K, V> sortedMap) { if (sortedMap == null) { throw new NullPointerException("Map must not be null"); } return sortedMap instanceof IterableSortedMap ? (IterableSortedMap<K, V>) sortedMap : new AbstractSortedMapDecorator<K, V>(sortedMap) {}; } private MapUtils(); static V getObject(final Map<? super K, V> map, final K key); static String getString(final Map<? super K, ?> map, final K key); static Boolean getBoolean(final Map<? super K, ?> map, final K key); static Number getNumber(final Map<? super K, ?> map, final K key); static Byte getByte(final Map<? super K, ?> map, final K key); static Short getShort(final Map<? super K, ?> map, final K key); static Integer getInteger(final Map<? super K, ?> map, final K key); static Long getLong(final Map<? super K, ?> map, final K key); static Float getFloat(final Map<? super K, ?> map, final K key); static Double getDouble(final Map<? super K, ?> map, final K key); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key); static V getObject(final Map<K, V> map, final K key, final V defaultValue); static String getString(final Map<? super K, ?> map, final K key, final String defaultValue); static Boolean getBoolean(final Map<? super K, ?> map, final K key, final Boolean defaultValue); static Number getNumber(final Map<? super K, ?> map, final K key, final Number defaultValue); static Byte getByte(final Map<? super K, ?> map, final K key, final Byte defaultValue); static Short getShort(final Map<? super K, ?> map, final K key, final Short defaultValue); static Integer getInteger(final Map<? super K, ?> map, final K key, final Integer defaultValue); static Long getLong(final Map<? super K, ?> map, final K key, final Long defaultValue); static Float getFloat(final Map<? super K, ?> map, final K key, final Float defaultValue); static Double getDouble(final Map<? super K, ?> map, final K key, final Double defaultValue); static Map<?, ?> getMap(final Map<? super K, ?> map, final K key, final Map<?, ?> defaultValue); static boolean getBooleanValue(final Map<? super K, ?> map, final K key); static byte getByteValue(final Map<? super K, ?> map, final K key); static short getShortValue(final Map<? super K, ?> map, final K key); static int getIntValue(final Map<? super K, ?> map, final K key); static long getLongValue(final Map<? super K, ?> map, final K key); static float getFloatValue(final Map<? super K, ?> map, final K key); static double getDoubleValue(final Map<? super K, ?> map, final K key); static boolean getBooleanValue(final Map<? super K, ?> map, final K key, final boolean defaultValue); static byte getByteValue(final Map<? super K, ?> map, final K key, final byte defaultValue); static short getShortValue(final Map<? super K, ?> map, final K key, final short defaultValue); static int getIntValue(final Map<? super K, ?> map, final K key, final int defaultValue); static long getLongValue(final Map<? super K, ?> map, final K key, final long defaultValue); static float getFloatValue(final Map<? super K, ?> map, final K key, final float defaultValue); static double getDoubleValue(final Map<? super K, ?> map, final K key, final double defaultValue); static Properties toProperties(final Map<K, V> map); static Map<String, Object> toMap(final ResourceBundle resourceBundle); static void verbosePrint(final PrintStream out, final Object label, final Map<?, ?> map); static void debugPrint(final PrintStream out, final Object label, final Map<?, ?> map); static Map<V, K> invertMap(final Map<K, V> map); static void safeAddToMap(final Map<? super K, Object> map, final K key, final Object value); @SuppressWarnings("unchecked") // As per Javadoc throws CCE for invalid array contents static Map<K, V> putAll(final Map<K, V> map, final Object[] array); static Map<K,V> emptyIfNull(final Map<K,V> map); static boolean isEmpty(final Map<?,?> map); static boolean isNotEmpty(final Map<?,?> map); static Map<K, V> synchronizedMap(final Map<K, V> map); static Map<K, V> unmodifiableMap(final Map<? extends K, ? extends V> map); static IterableMap<K, V> predicatedMap(final Map<K, V> map, final Predicate<? super K> keyPred,
final Predicate<? super V> valuePred); static IterableMap<K, V> transformedMap(final Map<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static IterableMap<K, V> fixedSizeMap(final Map<K, V> map); static IterableMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory); static IterableMap<K, V> lazyMap(final Map<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static OrderedMap<K, V> orderedMap(final Map<K, V> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, ? super Collection<V>> map); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Class<C> collectionClass); @Deprecated static MultiValueMap<K, V> multiValueMap(final Map<K, C> map,
final Factory<C> collectionFactory); static SortedMap<K, V> synchronizedSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> unmodifiableSortedMap(final SortedMap<K, ? extends V> map); static SortedMap<K, V> predicatedSortedMap(final SortedMap<K, V> map,
final Predicate<? super K> keyPred, final Predicate<? super V> valuePred); static SortedMap<K, V> transformedSortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends K> keyTransformer,
final Transformer<? super V, ? extends V> valueTransformer); static SortedMap<K, V> fixedSizeSortedMap(final SortedMap<K, V> map); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map, final Factory<? extends V> factory); static SortedMap<K, V> lazySortedMap(final SortedMap<K, V> map,
final Transformer<? super K, ? extends V> transformerFactory); static void populateMap(final Map<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final Map<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends V> elements,
final Transformer<V, K> keyTransformer); static void populateMap(final MultiMap<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer); static IterableMap<K, V> iterableMap(final Map<K, V> map); static IterableSortedMap<K, V> iterableSortedMap(final SortedMap<K, V> sortedMap); @SuppressWarnings("rawtypes")
static final SortedMap EMPTY_SORTED_MAP; }
|
@Test public void testIterableSortedMap() { try { MapUtils.iterableSortedMap(null); fail("Should throw NullPointerException"); } catch (final NullPointerException e) { } final TreeMap<String, String> map = new TreeMap<String, String>(); map.put("foo", "foov"); map.put("bar", "barv"); map.put("baz", "bazv"); final IterableSortedMap<String, String> iMap = MapUtils.iterableSortedMap(map); assertEquals(map, iMap); assertNotSame(map, iMap); assertSame(iMap, MapUtils.iterableMap(iMap)); }
|
ListUtils { public static <E> List<E> intersection(final List<? extends E> list1, final List<? extends E> list2) { final List<E> result = new ArrayList<E>(); List<? extends E> smaller = list1; List<? extends E> larger = list2; if (list1.size() > list2.size()) { smaller = list2; larger = list1; } final HashSet<E> hashSet = new HashSet<E>(smaller); for (final E e : larger) { if (hashSet.contains(e)) { result.add(e); hashSet.remove(e); } } return result; } private ListUtils(); static List<T> emptyIfNull(final List<T> list); static List<T> defaultIfNull(final List<T> list, final List<T> defaultList); static List<E> intersection(final List<? extends E> list1, final List<? extends E> list2); static List<E> subtract(final List<E> list1, final List<? extends E> list2); static List<E> sum(final List<? extends E> list1, final List<? extends E> list2); static List<E> union(final List<? extends E> list1, final List<? extends E> list2); static List<E> select(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static List<E> selectRejected(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static boolean isEqualList(final Collection<?> list1, final Collection<?> list2); static int hashCodeForList(final Collection<?> list); static List<E> retainAll(final Collection<E> collection, final Collection<?> retain); static List<E> removeAll(final Collection<E> collection, final Collection<?> remove); static List<E> synchronizedList(final List<E> list); static List<E> unmodifiableList(final List<? extends E> list); static List<E> predicatedList(final List<E> list, final Predicate<E> predicate); static List<E> transformedList(final List<E> list,
final Transformer<? super E, ? extends E> transformer); static List<E> lazyList(final List<E> list, final Factory<? extends E> factory); static List<E> fixedSizeList(final List<E> list); static int indexOf(final List<E> list, final Predicate<E> predicate); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b,
final Equator<? super E> equator); static String longestCommonSubsequence(final CharSequence a, final CharSequence b); static List<List<T>> partition(final List<T> list, final int size); }
|
@Test public void testIntersectNonEmptyWithEmptyList() { final List<String> empty = Collections.<String>emptyList(); assertTrue("result not empty", ListUtils.intersection(empty, fullList).isEmpty()); }
@Test public void testIntersectEmptyWithEmptyList() { final List<?> empty = Collections.EMPTY_LIST; assertTrue("result not empty", ListUtils.intersection(empty, empty).isEmpty()); }
@Test public void testIntersectNonEmptySubset() { final List<String> other = new ArrayList<String>(fullList); assertNotNull(other.remove(0)); assertNotNull(other.remove(1)); assertEquals(other, ListUtils.intersection(fullList, other)); }
@Test public void testIntersectListWithNoOverlapAndDifferentTypes() { @SuppressWarnings("boxing") final List<Integer> other = Arrays.asList(1, 23); assertTrue(ListUtils.intersection(fullList, other).isEmpty()); }
@Test public void testIntersectListWithSelf() { assertEquals(fullList, ListUtils.intersection(fullList, fullList)); }
@Test public void testIntersectionOrderInsensitivity() { final List<String> one = new ArrayList<String>(); final List<String> two = new ArrayList<String>(); one.add("a"); one.add("b"); two.add("a"); two.add("a"); two.add("b"); two.add("b"); assertEquals(ListUtils.intersection(one,two),ListUtils.intersection(two, one)); }
|
ListUtils { public static <E> List<E> predicatedList(final List<E> list, final Predicate<E> predicate) { return PredicatedList.predicatedList(list, predicate); } private ListUtils(); static List<T> emptyIfNull(final List<T> list); static List<T> defaultIfNull(final List<T> list, final List<T> defaultList); static List<E> intersection(final List<? extends E> list1, final List<? extends E> list2); static List<E> subtract(final List<E> list1, final List<? extends E> list2); static List<E> sum(final List<? extends E> list1, final List<? extends E> list2); static List<E> union(final List<? extends E> list1, final List<? extends E> list2); static List<E> select(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static List<E> selectRejected(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static boolean isEqualList(final Collection<?> list1, final Collection<?> list2); static int hashCodeForList(final Collection<?> list); static List<E> retainAll(final Collection<E> collection, final Collection<?> retain); static List<E> removeAll(final Collection<E> collection, final Collection<?> remove); static List<E> synchronizedList(final List<E> list); static List<E> unmodifiableList(final List<? extends E> list); static List<E> predicatedList(final List<E> list, final Predicate<E> predicate); static List<E> transformedList(final List<E> list,
final Transformer<? super E, ? extends E> transformer); static List<E> lazyList(final List<E> list, final Factory<? extends E> factory); static List<E> fixedSizeList(final List<E> list); static int indexOf(final List<E> list, final Predicate<E> predicate); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b,
final Equator<? super E> equator); static String longestCommonSubsequence(final CharSequence a, final CharSequence b); static List<List<T>> partition(final List<T> list, final int size); }
|
@Test public void testPredicatedList() { final Predicate<Object> predicate = new Predicate<Object>() { public boolean evaluate(final Object o) { return o instanceof String; } }; List<Object> list = ListUtils.predicatedList(new ArrayList<Object>(), predicate); assertTrue("returned object should be a PredicatedList", list instanceof PredicatedList); try { ListUtils.predicatedList(new ArrayList<Object>(), null); fail("Expecting IllegalArgumentException for null predicate."); } catch (final NullPointerException ex) { } try { ListUtils.predicatedList(null, predicate); fail("Expecting IllegalArgumentException for null list."); } catch (final NullPointerException ex) { } }
|
ListUtils { public static <E> List<E> lazyList(final List<E> list, final Factory<? extends E> factory) { return LazyList.lazyList(list, factory); } private ListUtils(); static List<T> emptyIfNull(final List<T> list); static List<T> defaultIfNull(final List<T> list, final List<T> defaultList); static List<E> intersection(final List<? extends E> list1, final List<? extends E> list2); static List<E> subtract(final List<E> list1, final List<? extends E> list2); static List<E> sum(final List<? extends E> list1, final List<? extends E> list2); static List<E> union(final List<? extends E> list1, final List<? extends E> list2); static List<E> select(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static List<E> selectRejected(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static boolean isEqualList(final Collection<?> list1, final Collection<?> list2); static int hashCodeForList(final Collection<?> list); static List<E> retainAll(final Collection<E> collection, final Collection<?> retain); static List<E> removeAll(final Collection<E> collection, final Collection<?> remove); static List<E> synchronizedList(final List<E> list); static List<E> unmodifiableList(final List<? extends E> list); static List<E> predicatedList(final List<E> list, final Predicate<E> predicate); static List<E> transformedList(final List<E> list,
final Transformer<? super E, ? extends E> transformer); static List<E> lazyList(final List<E> list, final Factory<? extends E> factory); static List<E> fixedSizeList(final List<E> list); static int indexOf(final List<E> list, final Predicate<E> predicate); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b,
final Equator<? super E> equator); static String longestCommonSubsequence(final CharSequence a, final CharSequence b); static List<List<T>> partition(final List<T> list, final int size); }
|
@Test public void testLazyList() { final List<Integer> list = ListUtils.lazyList(new ArrayList<Integer>(), new Factory<Integer>() { private int index; public Integer create() { index++; return Integer.valueOf(index); } }); assertNotNull(list.get(5)); assertEquals(6, list.size()); assertNotNull(list.get(5)); assertEquals(6, list.size()); }
|
ListUtils { public static <T> List<T> emptyIfNull(final List<T> list) { return list == null ? Collections.<T>emptyList() : list; } private ListUtils(); static List<T> emptyIfNull(final List<T> list); static List<T> defaultIfNull(final List<T> list, final List<T> defaultList); static List<E> intersection(final List<? extends E> list1, final List<? extends E> list2); static List<E> subtract(final List<E> list1, final List<? extends E> list2); static List<E> sum(final List<? extends E> list1, final List<? extends E> list2); static List<E> union(final List<? extends E> list1, final List<? extends E> list2); static List<E> select(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static List<E> selectRejected(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static boolean isEqualList(final Collection<?> list1, final Collection<?> list2); static int hashCodeForList(final Collection<?> list); static List<E> retainAll(final Collection<E> collection, final Collection<?> retain); static List<E> removeAll(final Collection<E> collection, final Collection<?> remove); static List<E> synchronizedList(final List<E> list); static List<E> unmodifiableList(final List<? extends E> list); static List<E> predicatedList(final List<E> list, final Predicate<E> predicate); static List<E> transformedList(final List<E> list,
final Transformer<? super E, ? extends E> transformer); static List<E> lazyList(final List<E> list, final Factory<? extends E> factory); static List<E> fixedSizeList(final List<E> list); static int indexOf(final List<E> list, final Predicate<E> predicate); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b,
final Equator<? super E> equator); static String longestCommonSubsequence(final CharSequence a, final CharSequence b); static List<List<T>> partition(final List<T> list, final int size); }
|
@Test public void testEmptyIfNull() { assertTrue(ListUtils.emptyIfNull(null).isEmpty()); final List<Long> list = new ArrayList<Long>(); assertSame(list, ListUtils.emptyIfNull(list)); }
|
ListUtils { public static <T> List<T> defaultIfNull(final List<T> list, final List<T> defaultList) { return list == null ? defaultList : list; } private ListUtils(); static List<T> emptyIfNull(final List<T> list); static List<T> defaultIfNull(final List<T> list, final List<T> defaultList); static List<E> intersection(final List<? extends E> list1, final List<? extends E> list2); static List<E> subtract(final List<E> list1, final List<? extends E> list2); static List<E> sum(final List<? extends E> list1, final List<? extends E> list2); static List<E> union(final List<? extends E> list1, final List<? extends E> list2); static List<E> select(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static List<E> selectRejected(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static boolean isEqualList(final Collection<?> list1, final Collection<?> list2); static int hashCodeForList(final Collection<?> list); static List<E> retainAll(final Collection<E> collection, final Collection<?> retain); static List<E> removeAll(final Collection<E> collection, final Collection<?> remove); static List<E> synchronizedList(final List<E> list); static List<E> unmodifiableList(final List<? extends E> list); static List<E> predicatedList(final List<E> list, final Predicate<E> predicate); static List<E> transformedList(final List<E> list,
final Transformer<? super E, ? extends E> transformer); static List<E> lazyList(final List<E> list, final Factory<? extends E> factory); static List<E> fixedSizeList(final List<E> list); static int indexOf(final List<E> list, final Predicate<E> predicate); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b,
final Equator<? super E> equator); static String longestCommonSubsequence(final CharSequence a, final CharSequence b); static List<List<T>> partition(final List<T> list, final int size); }
|
@Test public void testDefaultIfNull() { assertTrue(ListUtils.defaultIfNull(null, Collections.emptyList()).isEmpty()); final List<Long> list = new ArrayList<Long>(); assertSame(list, ListUtils.defaultIfNull(list, Collections.<Long>emptyList())); }
|
ListUtils { public static boolean isEqualList(final Collection<?> list1, final Collection<?> list2) { if (list1 == list2) { return true; } if (list1 == null || list2 == null || list1.size() != list2.size()) { return false; } final Iterator<?> it1 = list1.iterator(); final Iterator<?> it2 = list2.iterator(); Object obj1 = null; Object obj2 = null; while (it1.hasNext() && it2.hasNext()) { obj1 = it1.next(); obj2 = it2.next(); if (!(obj1 == null ? obj2 == null : obj1.equals(obj2))) { return false; } } return !(it1.hasNext() || it2.hasNext()); } private ListUtils(); static List<T> emptyIfNull(final List<T> list); static List<T> defaultIfNull(final List<T> list, final List<T> defaultList); static List<E> intersection(final List<? extends E> list1, final List<? extends E> list2); static List<E> subtract(final List<E> list1, final List<? extends E> list2); static List<E> sum(final List<? extends E> list1, final List<? extends E> list2); static List<E> union(final List<? extends E> list1, final List<? extends E> list2); static List<E> select(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static List<E> selectRejected(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static boolean isEqualList(final Collection<?> list1, final Collection<?> list2); static int hashCodeForList(final Collection<?> list); static List<E> retainAll(final Collection<E> collection, final Collection<?> retain); static List<E> removeAll(final Collection<E> collection, final Collection<?> remove); static List<E> synchronizedList(final List<E> list); static List<E> unmodifiableList(final List<? extends E> list); static List<E> predicatedList(final List<E> list, final Predicate<E> predicate); static List<E> transformedList(final List<E> list,
final Transformer<? super E, ? extends E> transformer); static List<E> lazyList(final List<E> list, final Factory<? extends E> factory); static List<E> fixedSizeList(final List<E> list); static int indexOf(final List<E> list, final Predicate<E> predicate); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b,
final Equator<? super E> equator); static String longestCommonSubsequence(final CharSequence a, final CharSequence b); static List<List<T>> partition(final List<T> list, final int size); }
|
@Test public void testEquals() { final Collection<String> data = Arrays.asList("a", "b", "c"); final List<String> a = new ArrayList<String>( data ); final List<String> b = new ArrayList<String>( data ); assertEquals(true, a.equals(b)); assertEquals(true, ListUtils.isEqualList(a, b)); a.clear(); assertEquals(false, ListUtils.isEqualList(a, b)); assertEquals(false, ListUtils.isEqualList(a, null)); assertEquals(false, ListUtils.isEqualList(null, b)); assertEquals(true, ListUtils.isEqualList(null, null)); }
|
ListUtils { public static int hashCodeForList(final Collection<?> list) { if (list == null) { return 0; } int hashCode = 1; final Iterator<?> it = list.iterator(); while (it.hasNext()) { final Object obj = it.next(); hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode()); } return hashCode; } private ListUtils(); static List<T> emptyIfNull(final List<T> list); static List<T> defaultIfNull(final List<T> list, final List<T> defaultList); static List<E> intersection(final List<? extends E> list1, final List<? extends E> list2); static List<E> subtract(final List<E> list1, final List<? extends E> list2); static List<E> sum(final List<? extends E> list1, final List<? extends E> list2); static List<E> union(final List<? extends E> list1, final List<? extends E> list2); static List<E> select(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static List<E> selectRejected(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static boolean isEqualList(final Collection<?> list1, final Collection<?> list2); static int hashCodeForList(final Collection<?> list); static List<E> retainAll(final Collection<E> collection, final Collection<?> retain); static List<E> removeAll(final Collection<E> collection, final Collection<?> remove); static List<E> synchronizedList(final List<E> list); static List<E> unmodifiableList(final List<? extends E> list); static List<E> predicatedList(final List<E> list, final Predicate<E> predicate); static List<E> transformedList(final List<E> list,
final Transformer<? super E, ? extends E> transformer); static List<E> lazyList(final List<E> list, final Factory<? extends E> factory); static List<E> fixedSizeList(final List<E> list); static int indexOf(final List<E> list, final Predicate<E> predicate); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b,
final Equator<? super E> equator); static String longestCommonSubsequence(final CharSequence a, final CharSequence b); static List<List<T>> partition(final List<T> list, final int size); }
|
@Test public void testHashCode() { final Collection<String> data = Arrays.asList("a", "b", "c"); final List<String> a = new ArrayList<String>(data); final List<String> b = new ArrayList<String>(data); assertEquals(true, a.hashCode() == b.hashCode()); assertEquals(true, a.hashCode() == ListUtils.hashCodeForList(a)); assertEquals(true, b.hashCode() == ListUtils.hashCodeForList(b)); assertEquals(true, ListUtils.hashCodeForList(a) == ListUtils.hashCodeForList(b)); a.clear(); assertEquals(false, ListUtils.hashCodeForList(a) == ListUtils.hashCodeForList(b)); assertEquals(0, ListUtils.hashCodeForList(null)); }
|
ListUtils { public static <E> List<E> retainAll(final Collection<E> collection, final Collection<?> retain) { final List<E> list = new ArrayList<E>(Math.min(collection.size(), retain.size())); for (final E obj : collection) { if (retain.contains(obj)) { list.add(obj); } } return list; } private ListUtils(); static List<T> emptyIfNull(final List<T> list); static List<T> defaultIfNull(final List<T> list, final List<T> defaultList); static List<E> intersection(final List<? extends E> list1, final List<? extends E> list2); static List<E> subtract(final List<E> list1, final List<? extends E> list2); static List<E> sum(final List<? extends E> list1, final List<? extends E> list2); static List<E> union(final List<? extends E> list1, final List<? extends E> list2); static List<E> select(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static List<E> selectRejected(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static boolean isEqualList(final Collection<?> list1, final Collection<?> list2); static int hashCodeForList(final Collection<?> list); static List<E> retainAll(final Collection<E> collection, final Collection<?> retain); static List<E> removeAll(final Collection<E> collection, final Collection<?> remove); static List<E> synchronizedList(final List<E> list); static List<E> unmodifiableList(final List<? extends E> list); static List<E> predicatedList(final List<E> list, final Predicate<E> predicate); static List<E> transformedList(final List<E> list,
final Transformer<? super E, ? extends E> transformer); static List<E> lazyList(final List<E> list, final Factory<? extends E> factory); static List<E> fixedSizeList(final List<E> list); static int indexOf(final List<E> list, final Predicate<E> predicate); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b,
final Equator<? super E> equator); static String longestCommonSubsequence(final CharSequence a, final CharSequence b); static List<List<T>> partition(final List<T> list, final int size); }
|
@Test public void testRetainAll() { final List<String> sub = new ArrayList<String>(); sub.add(a); sub.add(b); sub.add(x); final List<String> retained = ListUtils.retainAll(fullList, sub); assertTrue(retained.size() == 2); sub.remove(x); assertTrue(retained.equals(sub)); fullList.retainAll(sub); assertTrue(retained.equals(fullList)); try { ListUtils.retainAll(null, null); fail("expecting NullPointerException"); } catch(final NullPointerException npe){} }
|
ListUtils { public static <E> List<E> removeAll(final Collection<E> collection, final Collection<?> remove) { final List<E> list = new ArrayList<E>(); for (final E obj : collection) { if (!remove.contains(obj)) { list.add(obj); } } return list; } private ListUtils(); static List<T> emptyIfNull(final List<T> list); static List<T> defaultIfNull(final List<T> list, final List<T> defaultList); static List<E> intersection(final List<? extends E> list1, final List<? extends E> list2); static List<E> subtract(final List<E> list1, final List<? extends E> list2); static List<E> sum(final List<? extends E> list1, final List<? extends E> list2); static List<E> union(final List<? extends E> list1, final List<? extends E> list2); static List<E> select(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static List<E> selectRejected(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static boolean isEqualList(final Collection<?> list1, final Collection<?> list2); static int hashCodeForList(final Collection<?> list); static List<E> retainAll(final Collection<E> collection, final Collection<?> retain); static List<E> removeAll(final Collection<E> collection, final Collection<?> remove); static List<E> synchronizedList(final List<E> list); static List<E> unmodifiableList(final List<? extends E> list); static List<E> predicatedList(final List<E> list, final Predicate<E> predicate); static List<E> transformedList(final List<E> list,
final Transformer<? super E, ? extends E> transformer); static List<E> lazyList(final List<E> list, final Factory<? extends E> factory); static List<E> fixedSizeList(final List<E> list); static int indexOf(final List<E> list, final Predicate<E> predicate); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b,
final Equator<? super E> equator); static String longestCommonSubsequence(final CharSequence a, final CharSequence b); static List<List<T>> partition(final List<T> list, final int size); }
|
@Test public void testRemoveAll() { final List<String> sub = new ArrayList<String>(); sub.add(a); sub.add(b); sub.add(x); final List<String> remainder = ListUtils.removeAll(fullList, sub); assertTrue(remainder.size() == 3); fullList.removeAll(sub); assertTrue(remainder.equals(fullList)); try { ListUtils.removeAll(null, null); fail("expecting NullPointerException"); } catch(final NullPointerException npe) {} }
|
ListUtils { public static <E> List<E> subtract(final List<E> list1, final List<? extends E> list2) { final ArrayList<E> result = new ArrayList<E>(); final HashBag<E> bag = new HashBag<E>(list2); for (final E e : list1) { if (!bag.remove(e, 1)) { result.add(e); } } return result; } private ListUtils(); static List<T> emptyIfNull(final List<T> list); static List<T> defaultIfNull(final List<T> list, final List<T> defaultList); static List<E> intersection(final List<? extends E> list1, final List<? extends E> list2); static List<E> subtract(final List<E> list1, final List<? extends E> list2); static List<E> sum(final List<? extends E> list1, final List<? extends E> list2); static List<E> union(final List<? extends E> list1, final List<? extends E> list2); static List<E> select(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static List<E> selectRejected(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static boolean isEqualList(final Collection<?> list1, final Collection<?> list2); static int hashCodeForList(final Collection<?> list); static List<E> retainAll(final Collection<E> collection, final Collection<?> retain); static List<E> removeAll(final Collection<E> collection, final Collection<?> remove); static List<E> synchronizedList(final List<E> list); static List<E> unmodifiableList(final List<? extends E> list); static List<E> predicatedList(final List<E> list, final Predicate<E> predicate); static List<E> transformedList(final List<E> list,
final Transformer<? super E, ? extends E> transformer); static List<E> lazyList(final List<E> list, final Factory<? extends E> factory); static List<E> fixedSizeList(final List<E> list); static int indexOf(final List<E> list, final Predicate<E> predicate); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b,
final Equator<? super E> equator); static String longestCommonSubsequence(final CharSequence a, final CharSequence b); static List<List<T>> partition(final List<T> list, final int size); }
|
@Test public void testSubtract() { final List<String> list = new ArrayList<String>(); list.add(a); list.add(b); list.add(a); list.add(x); final List<String> sub = new ArrayList<String>(); sub.add(a); final List<String> result = ListUtils.subtract(list, sub); assertTrue(result.size() == 3); final List<String> expected = new ArrayList<String>(); expected.add(b); expected.add(a); expected.add(x); assertEquals(expected, result); try { ListUtils.subtract(list, null); fail("expecting NullPointerException"); } catch(final NullPointerException npe) {} }
@Test public void testSubtractNullElement() { final List<String> list = new ArrayList<String>(); list.add(a); list.add(null); list.add(null); list.add(x); final List<String> sub = new ArrayList<String>(); sub.add(null); final List<String> result = ListUtils.subtract(list, sub); assertTrue(result.size() == 3); final List<String> expected = new ArrayList<String>(); expected.add(a); expected.add(null); expected.add(x); assertEquals(expected, result); }
|
ListUtils { public static <E> int indexOf(final List<E> list, final Predicate<E> predicate) { if (list != null && predicate != null) { for (int i = 0; i < list.size(); i++) { final E item = list.get(i); if (predicate.evaluate(item)) { return i; } } } return -1; } private ListUtils(); static List<T> emptyIfNull(final List<T> list); static List<T> defaultIfNull(final List<T> list, final List<T> defaultList); static List<E> intersection(final List<? extends E> list1, final List<? extends E> list2); static List<E> subtract(final List<E> list1, final List<? extends E> list2); static List<E> sum(final List<? extends E> list1, final List<? extends E> list2); static List<E> union(final List<? extends E> list1, final List<? extends E> list2); static List<E> select(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static List<E> selectRejected(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static boolean isEqualList(final Collection<?> list1, final Collection<?> list2); static int hashCodeForList(final Collection<?> list); static List<E> retainAll(final Collection<E> collection, final Collection<?> retain); static List<E> removeAll(final Collection<E> collection, final Collection<?> remove); static List<E> synchronizedList(final List<E> list); static List<E> unmodifiableList(final List<? extends E> list); static List<E> predicatedList(final List<E> list, final Predicate<E> predicate); static List<E> transformedList(final List<E> list,
final Transformer<? super E, ? extends E> transformer); static List<E> lazyList(final List<E> list, final Factory<? extends E> factory); static List<E> fixedSizeList(final List<E> list); static int indexOf(final List<E> list, final Predicate<E> predicate); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b,
final Equator<? super E> equator); static String longestCommonSubsequence(final CharSequence a, final CharSequence b); static List<List<T>> partition(final List<T> list, final int size); }
|
@Test public void testIndexOf() { Predicate<String> testPredicate = EqualPredicate.equalPredicate("d"); int index = ListUtils.indexOf(fullList, testPredicate); assertEquals(d, fullList.get(index)); testPredicate = EqualPredicate.equalPredicate("de"); index = ListUtils.indexOf(fullList, testPredicate); assertEquals(index, -1); assertEquals(ListUtils.indexOf(null,testPredicate), -1); assertEquals(ListUtils.indexOf(fullList, null), -1); }
|
ListUtils { public static <E> List<E> longestCommonSubsequence(final List<E> a, final List<E> b) { return longestCommonSubsequence( a, b, DefaultEquator.defaultEquator() ); } private ListUtils(); static List<T> emptyIfNull(final List<T> list); static List<T> defaultIfNull(final List<T> list, final List<T> defaultList); static List<E> intersection(final List<? extends E> list1, final List<? extends E> list2); static List<E> subtract(final List<E> list1, final List<? extends E> list2); static List<E> sum(final List<? extends E> list1, final List<? extends E> list2); static List<E> union(final List<? extends E> list1, final List<? extends E> list2); static List<E> select(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static List<E> selectRejected(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static boolean isEqualList(final Collection<?> list1, final Collection<?> list2); static int hashCodeForList(final Collection<?> list); static List<E> retainAll(final Collection<E> collection, final Collection<?> retain); static List<E> removeAll(final Collection<E> collection, final Collection<?> remove); static List<E> synchronizedList(final List<E> list); static List<E> unmodifiableList(final List<? extends E> list); static List<E> predicatedList(final List<E> list, final Predicate<E> predicate); static List<E> transformedList(final List<E> list,
final Transformer<? super E, ? extends E> transformer); static List<E> lazyList(final List<E> list, final Factory<? extends E> factory); static List<E> fixedSizeList(final List<E> list); static int indexOf(final List<E> list, final Predicate<E> predicate); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b,
final Equator<? super E> equator); static String longestCommonSubsequence(final CharSequence a, final CharSequence b); static List<List<T>> partition(final List<T> list, final int size); }
|
@Test @SuppressWarnings("boxing") public void testLongestCommonSubsequence() { try { ListUtils.longestCommonSubsequence((List<?>) null, null); fail("failed to check for null argument"); } catch (final NullPointerException e) {} try { ListUtils.longestCommonSubsequence(Arrays.asList('A'), null); fail("failed to check for null argument"); } catch (final NullPointerException e) {} try { ListUtils.longestCommonSubsequence(null, Arrays.asList('A')); fail("failed to check for null argument"); } catch (final NullPointerException e) {} @SuppressWarnings("unchecked") List<Character> lcs = ListUtils.longestCommonSubsequence(Collections.EMPTY_LIST, Collections.EMPTY_LIST); assertEquals(0, lcs.size()); List<Character> list1 = Arrays.asList('B', 'A', 'N', 'A', 'N', 'A'); List<Character> list2 = Arrays.asList('A', 'N', 'A', 'N', 'A', 'S'); lcs = ListUtils.longestCommonSubsequence(list1, list2); List<Character> expected = Arrays.asList('A', 'N', 'A', 'N', 'A'); assertEquals(expected, lcs); List<Character> list3 = Arrays.asList('A', 'T', 'A', 'N', 'A'); lcs = ListUtils.longestCommonSubsequence(list1, list3); expected = Arrays.asList('A', 'A', 'N', 'A'); assertEquals(expected, lcs); List<Character> listZorro = Arrays.asList('Z', 'O', 'R', 'R', 'O'); lcs = ListUtils.longestCommonSubsequence(list1, listZorro); assertTrue(lcs.isEmpty()); }
@Test public void testLongestCommonSubsequenceWithString() { try { ListUtils.longestCommonSubsequence((String) null, null); fail("failed to check for null argument"); } catch (final NullPointerException e) {} try { ListUtils.longestCommonSubsequence("A", null); fail("failed to check for null argument"); } catch (final NullPointerException e) {} try { ListUtils.longestCommonSubsequence(null, "A"); fail("failed to check for null argument"); } catch (final NullPointerException e) {} String lcs = ListUtils.longestCommonSubsequence("", ""); assertEquals(0, lcs.length()); String banana = "BANANA"; String ananas = "ANANAS"; lcs = ListUtils.longestCommonSubsequence(banana, ananas); assertEquals("ANANA", lcs); String atana = "ATANA"; lcs = ListUtils.longestCommonSubsequence(banana, atana); assertEquals("AANA", lcs); String zorro = "ZORRO"; lcs = ListUtils.longestCommonSubsequence(banana, zorro); assertEquals(0, lcs.length()); }
|
ListUtils { public static <T> List<List<T>> partition(final List<T> list, final int size) { if (list == null) { throw new NullPointerException("List must not be null"); } if (size <= 0) { throw new IllegalArgumentException("Size must be greater than 0"); } return new Partition<T>(list, size); } private ListUtils(); static List<T> emptyIfNull(final List<T> list); static List<T> defaultIfNull(final List<T> list, final List<T> defaultList); static List<E> intersection(final List<? extends E> list1, final List<? extends E> list2); static List<E> subtract(final List<E> list1, final List<? extends E> list2); static List<E> sum(final List<? extends E> list1, final List<? extends E> list2); static List<E> union(final List<? extends E> list1, final List<? extends E> list2); static List<E> select(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static List<E> selectRejected(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static boolean isEqualList(final Collection<?> list1, final Collection<?> list2); static int hashCodeForList(final Collection<?> list); static List<E> retainAll(final Collection<E> collection, final Collection<?> retain); static List<E> removeAll(final Collection<E> collection, final Collection<?> remove); static List<E> synchronizedList(final List<E> list); static List<E> unmodifiableList(final List<? extends E> list); static List<E> predicatedList(final List<E> list, final Predicate<E> predicate); static List<E> transformedList(final List<E> list,
final Transformer<? super E, ? extends E> transformer); static List<E> lazyList(final List<E> list, final Factory<? extends E> factory); static List<E> fixedSizeList(final List<E> list); static int indexOf(final List<E> list, final Predicate<E> predicate); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b,
final Equator<? super E> equator); static String longestCommonSubsequence(final CharSequence a, final CharSequence b); static List<List<T>> partition(final List<T> list, final int size); }
|
@Test @SuppressWarnings("boxing") public void testPartition() { final List<Integer> strings = new ArrayList<Integer>(); for (int i = 0; i <= 6; i++) { strings.add(i); } final List<List<Integer>> partition = ListUtils.partition(strings, 3); assertNotNull(partition); assertEquals(3, partition.size()); assertEquals(1, partition.get(2).size()); try { ListUtils.partition(null, 3); fail("failed to check for null argument"); } catch (final NullPointerException e) {} try { ListUtils.partition(strings, 0); fail("failed to check for size argument"); } catch (final IllegalArgumentException e) {} try { ListUtils.partition(strings, -10); fail("failed to check for size argument"); } catch (final IllegalArgumentException e) {} }
|
ListUtils { public static <E> List<E> select(final Collection<? extends E> inputCollection, final Predicate<? super E> predicate) { return CollectionUtils.select(inputCollection, predicate, new ArrayList<E>(inputCollection.size())); } private ListUtils(); static List<T> emptyIfNull(final List<T> list); static List<T> defaultIfNull(final List<T> list, final List<T> defaultList); static List<E> intersection(final List<? extends E> list1, final List<? extends E> list2); static List<E> subtract(final List<E> list1, final List<? extends E> list2); static List<E> sum(final List<? extends E> list1, final List<? extends E> list2); static List<E> union(final List<? extends E> list1, final List<? extends E> list2); static List<E> select(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static List<E> selectRejected(final Collection<? extends E> inputCollection,
final Predicate<? super E> predicate); static boolean isEqualList(final Collection<?> list1, final Collection<?> list2); static int hashCodeForList(final Collection<?> list); static List<E> retainAll(final Collection<E> collection, final Collection<?> retain); static List<E> removeAll(final Collection<E> collection, final Collection<?> remove); static List<E> synchronizedList(final List<E> list); static List<E> unmodifiableList(final List<? extends E> list); static List<E> predicatedList(final List<E> list, final Predicate<E> predicate); static List<E> transformedList(final List<E> list,
final Transformer<? super E, ? extends E> transformer); static List<E> lazyList(final List<E> list, final Factory<? extends E> factory); static List<E> fixedSizeList(final List<E> list); static int indexOf(final List<E> list, final Predicate<E> predicate); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b); static List<E> longestCommonSubsequence(final List<E> a, final List<E> b,
final Equator<? super E> equator); static String longestCommonSubsequence(final CharSequence a, final CharSequence b); static List<List<T>> partition(final List<T> list, final int size); }
|
@Test @SuppressWarnings("boxing") public void testSelect() { final List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(4); final List<Integer> output1 = ListUtils.select(list, EQUALS_TWO); final List<Number> output2 = ListUtils.<Number>select(list, EQUALS_TWO); final HashSet<Number> output3 = CollectionUtils.select(list, EQUALS_TWO, new HashSet<Number>()); assertTrue(CollectionUtils.isEqualCollection(output1, output3)); assertEquals(4, list.size()); assertEquals(1, output1.size()); assertEquals(2, output2.iterator().next()); }
|
UpdateOperator extends AbstractOperator { @Override public Object execute(Object[] values, InvocationStat stat) { InvocationContext context = invocationContextFactory.newInvocationContext(values); return execute(context, stat); } UpdateOperator(ASTRootNode rootNode, MethodDescriptor md, Config config); @Override Object execute(Object[] values, InvocationStat stat); Object execute(InvocationContext context, InvocationStat stat); }
|
@Test public void testUpdate() throws Exception { TypeToken<User> pt = TypeToken.of(User.class); TypeToken<Integer> rt = TypeToken.of(int.class); String srcSql = "update user set name=:1.name where id=:1.id"; AbstractOperator operator = getOperator(pt, rt, srcSql); operator.setJdbcOperations(new JdbcOperationsAdapter() { @Override public int update(DataSource ds, BoundSql boundSql) { String sql = boundSql.getSql(); List<Object> args = boundSql.getArgs(); String descSql = "update user set name=? where id=?"; assertThat(sql, equalTo(descSql)); assertThat(args.size(), equalTo(2)); assertThat(args.get(0), equalTo((Object) "ash")); assertThat(args.get(1), equalTo((Object) 100)); return 1; } }); User user = new User(); user.setId(100); user.setName("ash"); Object r = operator.execute(new Object[]{user}, InvocationStat.create()); assertThat(r.getClass().equals(Integer.class), is(true)); }
@Test public void testUpdateReturnVoid() throws Exception { TypeToken<User> pt = TypeToken.of(User.class); TypeToken<Void> rt = TypeToken.of(void.class); String srcSql = "update user set name=:1.name where id=:1.id"; AbstractOperator operator = getOperator(pt, rt, srcSql); operator.setJdbcOperations(new JdbcOperationsAdapter() { @Override public int update(DataSource ds, BoundSql boundSql) { String sql = boundSql.getSql(); List<Object> args = boundSql.getArgs(); String descSql = "update user set name=? where id=?"; assertThat(sql, equalTo(descSql)); assertThat(args.size(), equalTo(2)); assertThat(args.get(0), equalTo((Object) "ash")); assertThat(args.get(1), equalTo((Object) 100)); return 1; } }); User user = new User(); user.setId(100); user.setName("ash"); Object r = operator.execute(new Object[]{user}, InvocationStat.create()); assertThat(r, nullValue()); }
@Test public void testUpdateReturnBoolean() throws Exception { TypeToken<User> pt = TypeToken.of(User.class); TypeToken<Boolean> rt = TypeToken.of(boolean.class); String srcSql = "update user set name=:1.name where id=:1.id"; AbstractOperator operator = getOperator(pt, rt, srcSql); operator.setJdbcOperations(new JdbcOperationsAdapter() { @Override public int update(DataSource ds, BoundSql boundSql) { String sql = boundSql.getSql(); List<Object> args = boundSql.getArgs(); String descSql = "update user set name=? where id=?"; assertThat(sql, equalTo(descSql)); assertThat(args.size(), equalTo(2)); assertThat(args.get(0), equalTo((Object) "ash")); assertThat(args.get(1), equalTo((Object) 100)); return 0; } }); User user = new User(); user.setId(100); user.setName("ash"); boolean r = (Boolean) operator.execute(new Object[]{user}, InvocationStat.create()); assertThat(r, is(false)); }
@Test public void testUpdateReturnGeneratedIdInt() throws Exception { TypeToken<User> pt = TypeToken.of(User.class); TypeToken<Integer> rt = TypeToken.of(int.class); String srcSql = "insert into user(id, name) values(:1.id, :1.name)"; AbstractOperator operator = getOperatorReturnGeneratedId(pt, rt, srcSql); operator.setJdbcOperations(new JdbcOperationsAdapter() { @Override public int update(DataSource ds, BoundSql boundSql, GeneratedKeyHolder holder) { String sql = boundSql.getSql(); List<Object> args = boundSql.getArgs(); String descSql = "insert into user(id, name) values(?, ?)"; assertThat(sql, equalTo(descSql)); assertThat(args.size(), equalTo(2)); assertThat(args.get(0), equalTo((Object) 100)); assertThat(args.get(1), equalTo((Object) "ash")); assertThat(holder.getTypeHandler().getClass().equals(IntegerTypeHandler.class), is(true)); holder.setKey(100); return 1; } }); User user = new User(); user.setId(100); user.setName("ash"); Object r = operator.execute(new Object[]{user}, InvocationStat.create()); assertThat(r.getClass().equals(Integer.class), is(true)); }
@Test public void testUpdateReturnGeneratedIdLong() throws Exception { TypeToken<User> pt = TypeToken.of(User.class); TypeToken<Long> rt = TypeToken.of(long.class); String srcSql = "insert into user(id, name) values(:1.id, :1.name)"; AbstractOperator operator = getOperatorReturnGeneratedId(pt, rt, srcSql); operator.setJdbcOperations(new JdbcOperationsAdapter() { @Override public int update(DataSource ds, BoundSql boundSql, GeneratedKeyHolder holder) { String sql = boundSql.getSql(); List<Object> args = boundSql.getArgs(); String descSql = "insert into user(id, name) values(?, ?)"; assertThat(sql, equalTo(descSql)); assertThat(args.size(), equalTo(2)); assertThat(args.get(0), equalTo((Object) 100)); assertThat(args.get(1), equalTo((Object) "ash")); System.out.println(holder.getTypeHandler()); assertThat(holder.getTypeHandler().getClass().equals(LongTypeHandler.class), is(true)); holder.setKey(100L); return 1; } }); User user = new User(); user.setId(100); user.setName("ash"); Object r = operator.execute(new Object[]{user}, InvocationStat.create()); assertThat(r.getClass().equals(Long.class), is(true)); }
@Test public void testStatsCounter() throws Exception { TypeToken<User> pt = TypeToken.of(User.class); TypeToken<Integer> rt = TypeToken.of(int.class); String srcSql = "update user set name=:1.name where id=:1.id"; AbstractOperator operator = getOperator(pt, rt, srcSql); operator.setJdbcOperations(new JdbcOperationsAdapter() { @Override public int update(DataSource ds, BoundSql boundSql) { String sql = boundSql.getSql(); List<Object> args = boundSql.getArgs(); String descSql = "update user set name=? where id=?"; assertThat(sql, equalTo(descSql)); assertThat(args.size(), equalTo(2)); assertThat(args.get(0), equalTo((Object) "ash")); assertThat(args.get(1), equalTo((Object) 100)); return 1; } }); User user = new User(); user.setId(100); user.setName("ash"); InvocationStat stat = InvocationStat.create(); operator.execute(new Object[]{user}, stat); assertThat(stat.getDatabaseExecuteSuccessCount(), equalTo(1L)); operator.execute(new Object[]{user}, stat); assertThat(stat.getDatabaseExecuteSuccessCount(), equalTo(2L)); operator.setJdbcOperations(new JdbcOperationsAdapter()); try { operator.execute(new Object[]{user}, stat); } catch (UnsupportedOperationException e) { } assertThat(stat.getDatabaseExecuteExceptionCount(), equalTo(1L)); try { operator.execute(new Object[]{user}, stat); } catch (UnsupportedOperationException e) { } assertThat(stat.getDatabaseExecuteExceptionCount(), equalTo(2L)); }
@Test public void testUpdateReturnTypeError() throws Exception { thrown.expect(DescriptionException.class); thrown.expectMessage("the return type of update expected one of [void, int, long, boolean, " + "Void, Integer, Long, Boolean] but class java.lang.String"); TypeToken<User> pt = TypeToken.of(User.class); TypeToken<String> rt = TypeToken.of(String.class); String srcSql = "update user set name=:1.name where id=:1.id"; AbstractOperator operator = getOperator(pt, rt, srcSql); operator.setJdbcOperations(new JdbcOperationsAdapter() { @Override public int update(DataSource ds, BoundSql boundSql) { String sql = boundSql.getSql(); List<Object> args = boundSql.getArgs(); String descSql = "update user set name=? where id=?"; assertThat(sql, equalTo(descSql)); assertThat(args.size(), equalTo(2)); assertThat(args.get(0), equalTo((Object) "ash")); assertThat(args.get(1), equalTo((Object) 100)); return 1; } }); User user = new User(); user.setId(100); user.setName("ash"); operator.execute(new Object[]{user}, InvocationStat.create()); }
@Test public void testUpdateReturnGeneratedIdReturnTypeError() throws Exception { thrown.expect(DescriptionException.class); thrown.expectMessage("the return type of update(returnGeneratedId) expected " + "one of [int, long, Integer, Long] but void"); TypeToken<User> pt = TypeToken.of(User.class); TypeToken<Void> rt = TypeToken.of(void.class); String srcSql = "insert into user(id, name) values(:1.id, :1.name)"; AbstractOperator operator = getOperatorReturnGeneratedId(pt, rt, srcSql); operator.setJdbcOperations(new JdbcOperationsAdapter() { @Override public int update(DataSource ds, BoundSql boundSql, GeneratedKeyHolder holder) { String sql = boundSql.getSql(); List<Object> args = boundSql.getArgs(); String descSql = "insert into user(id, name) values(?, ?)"; assertThat(sql, equalTo(descSql)); assertThat(args.size(), equalTo(2)); assertThat(args.get(0), equalTo((Object) 100)); assertThat(args.get(1), equalTo((Object) "ash")); assertThat(holder.getTypeHandler().getClass().equals(IntegerTypeHandler.class), is(true)); holder.setKey(100); return 1; } }); User user = new User(); user.setId(100); user.setName("ash"); operator.execute(new Object[]{user}, InvocationStat.create()); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.