diff --git a/LICENSE b/LICENSE index 73c1fb0..ce7e1dc 100644 --- a/LICENSE +++ b/LICENSE @@ -1,13 +1,189 @@ -Copyright 2010 Twitter, Inc. -Licensed under the Apache License, Version 2.0 (the "License"); you may not -use this file except in compliance with the License. You may obtain a copy of -the License at + Copyright 2011 Twitter, Inc. -http://www.apache.org/licenses/LICENSE-2.0 + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this work except in compliance with the License. + You may obtain a copy of the License below, or at: -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -License for the specific language governing permissions and limitations under -the License. + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. diff --git a/README b/README new file mode 100644 index 0000000..195105c --- /dev/null +++ b/README @@ -0,0 +1,18 @@ +Java port of the twitter-text jandling libraries. + +== Copyright and License == + +Copyright 2011 Twitter, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this work except in compliance with the License. + You may obtain a copy of the License in the LICENSE file, or at: + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/src/com/twitter/Autolink.java b/src/com/twitter/Autolink.java index 0a0d20c..2f52acb 100644 --- a/src/com/twitter/Autolink.java +++ b/src/com/twitter/Autolink.java @@ -177,9 +177,9 @@ public String autoLinkURLs(String text) { matcher.appendReplacement(sb, String.format("$%s%s", Regex.VALID_URL_GROUP_BEFORE, - url, + url.replaceAll("\\$", "\\\\\\$"), noFollow ? NO_FOLLOW_HTML_ATTRIBUTE : "", - url + url.replaceAll("\\$", "\\\\\\$") )); continue; } diff --git a/src/com/twitter/Extractor.java b/src/com/twitter/Extractor.java index 50d26c3..eb38965 100644 --- a/src/com/twitter/Extractor.java +++ b/src/com/twitter/Extractor.java @@ -15,12 +15,16 @@ public static class Entity { protected String type = null; public Entity(Matcher matcher, String valueType, Integer groupNumber) { - this.start = matcher.start(groupNumber)-1; // 0-indexed. + // Offset -1 on start index to include @, # symbols for mentions and hashtags + this(matcher, valueType, groupNumber, -1); + } + + public Entity(Matcher matcher, String valueType, Integer groupNumber, int startOffset) { + this.start = matcher.start(groupNumber) + startOffset; // 0-indexed. this.end = matcher.end(groupNumber); this.value = matcher.group(groupNumber); this.type = valueType; } - /** Constructor used from conformance data */ public Entity(Map config, String valueType) { this.type = valueType; @@ -84,6 +88,28 @@ public List extractMentionedScreennames(String text) { return extracted; } + /** + * Extract @username references from Tweet text. A mention is an occurance of @username anywhere in a Tweet. + * + * @param text of the tweet from which to extract usernames + * @return List of usernames referenced (without the leading @ sign) + */ + public List extractMentionedScreennamesWithIndices(String text) { + if (text == null) { + return null; + } + + List extracted = new ArrayList(); + Matcher matcher = Regex.EXTRACT_MENTIONS.matcher(text); + while (matcher.find()) { + if (! Regex.SCREEN_NAME_MATCH_END.matcher(matcher.group(Regex.EXTRACT_MENTIONS_GROUP_AFTER)).matches()) { + extracted.add(new Entity(matcher, "mention", Regex.EXTRACT_MENTIONS_GROUP_USERNAME)); + } + } + return extracted; + } + + /** * Extract a @username reference from the beginning of Tweet text. A reply is an occurance of @username at the * beginning of a Tweet, preceded by 0 or more spaces. @@ -128,6 +154,31 @@ public List extractURLs(String text) { return urls; } + /** + * Extract URL references from Tweet text. + * + * @param text of the tweet from which to extract URLs + * @return List of URLs referenced. + */ + public List extractURLsWithIndices(String text) { + if (text == null) { + return null; + } + + List urls = new ArrayList(); + + Matcher matcher = Regex.VALID_URL.matcher(text); + while (matcher.find()) { + String protocol = matcher.group(Regex.VALID_URL_GROUP_PROTOCOL); + if (!protocol.isEmpty()) { + urls.add(new Entity(matcher, "url", Regex.VALID_URL_GROUP_URL, 0)); + } + } + + return urls; + } + + /** * Extract #hashtag references from Tweet text. * diff --git a/src/com/twitter/Regex.java b/src/com/twitter/Regex.java index 7e3e4c3..0ed9412 100644 --- a/src/com/twitter/Regex.java +++ b/src/com/twitter/Regex.java @@ -17,6 +17,9 @@ public class Regex { private static final String URL_VALID_DOMAIN = "(?:[^\\p{Punct}\\s][\\.-](?=[^\\p{Punct}\\s])|[^\\p{Punct}\\s]){1,}\\.[a-z]{2,}(?::[0-9]+)?"; private static final String URL_VALID_GENERAL_PATH_CHARS = "[a-z0-9!\\*';:=\\+\\$/%#\\[\\]\\-_,~]"; + private static final String URL_VALID_PATH_CHARS_WITHOUT_SLASH = "[" + URL_VALID_GENERAL_PATH_CHARS + "&&[^/]]"; + private static final String URL_VALID_PATH_CHARS_WITHOUT_COMMA = "[" + URL_VALID_GENERAL_PATH_CHARS + "&&[^,]]"; + /** Allow URL paths to contain balanced parens * 1. Used in Wikipedia URLs like /Primer_(film) * 2. Used in IIS sessions like /S(dfd346)/ @@ -24,8 +27,8 @@ public class Regex { private static final String URL_BALANCE_PARENS = "(?:\\(" + URL_VALID_GENERAL_PATH_CHARS + "+\\))"; private static final String URL_VALID_URL_PATH_CHARS = "(?:" + URL_BALANCE_PARENS + - "|@" + URL_VALID_GENERAL_PATH_CHARS + "+/" + - "|[\\.,]?" + URL_VALID_GENERAL_PATH_CHARS + "+" + + "|@" + URL_VALID_PATH_CHARS_WITHOUT_SLASH + "++/" + + "|(?:[.,]*+" + URL_VALID_PATH_CHARS_WITHOUT_COMMA + ")++" + ")"; /** Valid end-of-path chracters (so /foo. does not gobble the period). @@ -42,10 +45,7 @@ public class Regex { "(" + URL_VALID_DOMAIN + ")" + // $5 Domain(s) and optional port number "(/" + "(?:" + - URL_VALID_URL_PATH_CHARS + "+" + - URL_VALID_URL_PATH_ENDING_CHARS + "|" + // 1+ path chars and a valid last char - URL_VALID_URL_PATH_CHARS + "+" + - URL_VALID_URL_PATH_ENDING_CHARS + "?|" + // Optional last char to handle /@foo/ case + URL_VALID_URL_PATH_CHARS + "+|" + // 1+ path chars and a valid last char URL_VALID_URL_PATH_ENDING_CHARS + // Just a # case ")?" + ")?" + // $6 URL Path and anchor diff --git a/tests/com/twitter/AutolinkTest.java b/tests/com/twitter/AutolinkTest.java index 0cc7717..b45b46c 100644 --- a/tests/com/twitter/AutolinkTest.java +++ b/tests/com/twitter/AutolinkTest.java @@ -33,6 +33,14 @@ public void testBlogspotWithDash() { assertAutolink(expected, linker.autoLinkURLs(tweet)); } + /** See also: https://github.com/mzsanford/twitter-text-java/issues/8 */ + public void testURLWithDollarThatLooksLikeARegex() { + linker.setNoFollow(false); + String tweet = "Url: http://example.com/$ABC"; + String expected = "Url: http://example.com/$ABC"; + assertAutolink(expected, linker.autoLinkURLs(tweet)); + } + protected void assertAutolink(String expected, String linked) { assertEquals("Autolinked text should not equal the input", expected, linked); } diff --git a/tests/com/twitter/ExtractorTest.java b/tests/com/twitter/ExtractorTest.java index c0ef043..866ff50 100644 --- a/tests/com/twitter/ExtractorTest.java +++ b/tests/com/twitter/ExtractorTest.java @@ -11,7 +11,7 @@ public class ExtractorTest extends TestCase { protected Extractor extractor; public static Test suite() { - Class[] testClasses = { ReplyTest.class, MentionTest.class, HashtagTest.class }; + Class[] testClasses = { ReplyTest.class, MentionTest.class, HashtagTest.class, URLTest.class }; return new TestSuite(testClasses); } @@ -35,7 +35,7 @@ public void testReplyWithLeadingSpace() { } /** - * Tests for the extractMentionedScreennames method + * Tests for the extractMentionedScreennames{WithIndices} methods */ public static class MentionTest extends ExtractorTest { public void testMentionAtTheBeginning() { @@ -57,6 +57,17 @@ public void testMultipleMentions() { List extracted = extractor.extractMentionedScreennames("mention @user1 here and @user2 here"); assertList("Failed to extract multiple mentioned users", new String[]{"user1", "user2"}, extracted); } + + public void testMentionWithIndices() { + List extracted = extractor.extractMentionedScreennamesWithIndices(" @user1 mention @user2 here @user3 "); + assertEquals(extracted.size(), 3); + assertEquals(extracted.get(0).start.intValue(), 1); + assertEquals(extracted.get(0).end.intValue(), 7); + assertEquals(extracted.get(1).start.intValue(), 16); + assertEquals(extracted.get(1).end.intValue(), 22); + assertEquals(extracted.get(2).start.intValue(), 28); + assertEquals(extracted.get(2).end.intValue(), 34); + } } /** @@ -82,8 +93,31 @@ public void testMultipleHashtags() { List extracted = extractor.extractHashtags("text #hashtag1 #hashtag2"); assertList("Failed to extract multiple hashtags", new String[]{"hashtag1", "hashtag2"}, extracted); } + + public void testHashtagWithIndices() { + List extracted = extractor.extractHashtagsWithIndices(" #user1 mention #user2 here #user3 "); + assertEquals(extracted.size(), 3); + assertEquals(extracted.get(0).start.intValue(), 1); + assertEquals(extracted.get(0).end.intValue(), 7); + assertEquals(extracted.get(1).start.intValue(), 16); + assertEquals(extracted.get(1).end.intValue(), 22); + assertEquals(extracted.get(2).start.intValue(), 28); + assertEquals(extracted.get(2).end.intValue(), 34); + } } + /** + * Tests for the extractURLsWithIndices method + */ + public static class URLTest extends ExtractorTest { + public void testUrlWithIndices() { + List extracted = extractor.extractURLsWithIndices("http://t.co url https://www.twitter.com "); + assertEquals(extracted.get(0).start.intValue(), 0); + assertEquals(extracted.get(0).end.intValue(), 11); + assertEquals(extracted.get(1).start.intValue(), 16); + assertEquals(extracted.get(1).end.intValue(), 39); + } + } /** * Helper method for asserting that the List of extracted Strings match the expected values. * @@ -103,4 +137,4 @@ protected void assertList(String message, String[] expected, List actual } } } -} \ No newline at end of file +} diff --git a/tests/com/twitter/RegexTest.java b/tests/com/twitter/RegexTest.java index cb096de..cf93dc3 100644 --- a/tests/com/twitter/RegexTest.java +++ b/tests/com/twitter/RegexTest.java @@ -25,6 +25,20 @@ public void testValidURLDoesNotCrashOnLongPaths() { assertTrue("Failed to correctly match a very long path", Regex.VALID_URL.matcher(longPathIsLong).find()); } + public void testValidUrlDoesNotTakeForeverOnRepeatedPuctuationAtEnd() { + String repeatedPath = "Try http://example.com/path**********************"; + + long start = System.currentTimeMillis(); + Matcher matcher = Regex.VALID_URL.matcher(repeatedPath); + boolean isValid = matcher.find(); + long end = System.currentTimeMillis(); + + assertTrue("Repeated puctuation should still produce a valid URL", isValid); + + long duration = (end - start); + assertTrue("Matching a repeated path end should take less than 10ms (took " + duration + "ms)", (duration < 10) ); + } + public void testExtractMentions() { assertCaptureCount(3, Regex.EXTRACT_MENTIONS, "sample @user mention"); }