diff --git a/android/client/.idea/dictionaries/Jason.xml b/android/client/.idea/dictionaries/Jason.xml deleted file mode 100644 index e4a5141b..00000000 --- a/android/client/.idea/dictionaries/Jason.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/android/client/AndroidManifest.xml b/android/client/AndroidManifest.xml index 2ff162e0..68a0f1ca 100644 --- a/android/client/AndroidManifest.xml +++ b/android/client/AndroidManifest.xml @@ -2,7 +2,7 @@ + android:versionName="1.2.1"> @@ -32,6 +32,24 @@ + + + + + + + + + + + + + + + + + + @@ -13,7 +19,7 @@ - + diff --git a/android/client/project.properties b/android/client/project.properties index 639acfbf..60173a6d 100644 --- a/android/client/project.properties +++ b/android/client/project.properties @@ -13,3 +13,4 @@ target=android-17 proguard.config=proguard.cfg android.library.reference.1=../libraries/TweetLanesCore + diff --git a/android/clientbeta/AndroidManifest.xml b/android/clientbeta/AndroidManifest.xml index 478335c0..71f1dbcf 100644 --- a/android/clientbeta/AndroidManifest.xml +++ b/android/clientbeta/AndroidManifest.xml @@ -1,8 +1,10 @@ + android:versionCode="51" + android:versionName="1.2.1_b8"> + + @@ -32,6 +34,24 @@ + + + + + + + + + + + + + + + + + + @@ -13,7 +19,7 @@ - + diff --git a/android/clientbeta/project.properties b/android/clientbeta/project.properties index 60173a6d..9d3820d3 100644 --- a/android/clientbeta/project.properties +++ b/android/clientbeta/project.properties @@ -14,3 +14,4 @@ proguard.config=proguard.cfg android.library.reference.1=../libraries/TweetLanesCore + diff --git a/android/libraries/SocialNetLib/SocialNetLib.iml b/android/libraries/SocialNetLib/SocialNetLib.iml new file mode 100644 index 00000000..79a550ad --- /dev/null +++ b/android/libraries/SocialNetLib/SocialNetLib.iml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android/libraries/SocialNetLib/TL-SocialNetLib.iml b/android/libraries/SocialNetLib/TL-SocialNetLib.iml index e04eae0e..d0407553 100644 --- a/android/libraries/SocialNetLib/TL-SocialNetLib.iml +++ b/android/libraries/SocialNetLib/TL-SocialNetLib.iml @@ -15,6 +15,12 @@ @@ -25,7 +31,7 @@ - + diff --git a/android/libraries/SocialNetLib/src/com/twitter/Autolink.java b/android/libraries/SocialNetLib/src/com/twitter/Autolink.java old mode 100755 new mode 100644 index feec2ee5..4a712a03 --- a/android/libraries/SocialNetLib/src/com/twitter/Autolink.java +++ b/android/libraries/SocialNetLib/src/com/twitter/Autolink.java @@ -6,114 +6,75 @@ import java.util.List; import java.util.Map; +import twitter4j.MediaEntity; +import twitter4j.URLEntity; + /** * A class for adding HTML links to hashtag, username and list references in * Tweet text. */ public class Autolink { - /** Default CSS class for auto-linked list URLs */ - public static final String DEFAULT_LIST_CLASS = "tweet-url list-slug"; - /** Default CSS class for auto-linked username URLs */ - public static final String DEFAULT_USERNAME_CLASS = "tweet-url username"; - /** Default CSS class for auto-linked hashtag URLs */ - public static final String DEFAULT_HASHTAG_CLASS = "tweet-url hashtag"; - /** Default CSS class for auto-linked cashtag URLs */ - public static final String DEFAULT_CASHTAG_CLASS = "tweet-url cashtag"; - /** - * Default href for username links (the username without the @ will be - * appended) - */ - public static final String DEFAULT_USERNAME_URL_BASE = "https://twitter.com/"; - /** - * Default href for list links (the username/list without the @ will be - * appended) - */ - public static final String DEFAULT_LIST_URL_BASE = "https://twitter.com/"; - /** - * Default href for hashtag links (the hashtag without the # will be - * appended) - */ - public static final String DEFAULT_HASHTAG_URL_BASE = "https://twitter.com/#!/search?q=%23"; - /** - * Default href for cashtag links (the cashtag without the $ will be - * appended) - */ - public static final String DEFAULT_CASHTAG_URL_BASE = "https://twitter.com/#!/search?q=%24"; - /** Default attribute for invisible span tag */ - public static final String DEFAULT_INVISIBLE_TAG_ATTRS = "style='position:absolute;left:-9999px;'"; public static interface LinkAttributeModifier { public void modify(Entity entity, Map attributes); - }; + } public static interface LinkTextModifier { public CharSequence modify(Entity entity, CharSequence text); } - protected String urlClass = null; - protected String listClass; - protected String usernameClass; - protected String hashtagClass; - protected String cashtagClass; - protected String usernameUrlBase; - protected String listUrlBase; - protected String hashtagUrlBase; - protected String cashtagUrlBase; - protected String invisibleTagAttrs; - protected boolean noFollow = true; - protected boolean usernameIncludeSymbol = false; - protected String symbolTag = null; - protected String textWithSymbolTag = null; - protected String urlTarget = null; - protected LinkAttributeModifier linkAttributeModifier = null; - protected LinkTextModifier linkTextModifier = null; - - private Extractor extractor = new Extractor(); + private final String usernameUrlBase; + private final String listUrlBase; + private final String hashtagUrlBase; + private final String cashtagUrlBase; + private final String symbolTag = null; + private final String textWithSymbolTag = null; + private final LinkAttributeModifier linkAttributeModifier = null; + private final LinkTextModifier linkTextModifier = null; + + private final Extractor extractor = new Extractor(); private static CharSequence escapeHTML(CharSequence text) { StringBuilder builder = new StringBuilder(text.length() * 2); for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); switch (c) { - case '&': - builder.append("&"); - break; - case '>': - builder.append(">"); - break; - case '<': - builder.append("<"); - break; - case '"': - builder.append("""); - break; - case '\'': - builder.append("'"); - break; - default: - builder.append(c); - break; + case '&': + builder.append("&"); + break; + case '>': + builder.append(">"); + break; + case '<': + builder.append("<"); + break; + case '"': + builder.append("""); + break; + case '\'': + builder.append("'"); + break; + default: + builder.append(c); + break; } } return builder; } public Autolink() { - urlClass = null; - listClass = DEFAULT_LIST_CLASS; - usernameClass = DEFAULT_USERNAME_CLASS; - hashtagClass = DEFAULT_HASHTAG_CLASS; - cashtagClass = DEFAULT_CASHTAG_CLASS; - usernameUrlBase = DEFAULT_USERNAME_URL_BASE; - listUrlBase = DEFAULT_LIST_URL_BASE; - hashtagUrlBase = DEFAULT_HASHTAG_URL_BASE; - cashtagUrlBase = DEFAULT_CASHTAG_URL_BASE; - invisibleTagAttrs = DEFAULT_INVISIBLE_TAG_ATTRS; - + usernameUrlBase = "com.tweetlanes.android.core.profile://"; + listUrlBase = "com.tweetlanes.android.core.profile://"; + hashtagUrlBase = "com.tweetlanes.android.core.search://"; + cashtagUrlBase = "com.tweetlanes.android.core.search://"; extractor.setExtractURLWithoutProtocol(false); } - public String escapeBrackets(String text) { + public void setExtractURLWithoutProtocol(boolean newValue){ + extractor.setExtractURLWithoutProtocol(newValue); + } + + String escapeBrackets(String text) { int len = text.length(); if (len == 0) return text; @@ -130,11 +91,9 @@ else if (c == '<') return sb.toString(); } - public void linkToText(Entity entity, CharSequence text, - Map attributes, StringBuilder builder) { - if (noFollow) { - attributes.put("rel", "nofollow"); - } + void linkToText(Entity entity, CharSequence text, + Map attributes, StringBuilder builder) { + if (linkAttributeModifier != null) { linkAttributeModifier.modify(entity, attributes); } @@ -151,9 +110,9 @@ public void linkToText(Entity entity, CharSequence text, builder.append(">").append(text).append(""); } - public void linkToTextWithSymbol(Entity entity, CharSequence symbol, - CharSequence text, Map attributes, - StringBuilder builder) { + void linkToTextWithSymbol(Entity entity, CharSequence symbol, + CharSequence text, Map attributes, + StringBuilder builder) { CharSequence taggedSymbol = symbolTag == null || symbolTag.isEmpty() ? symbol : String.format("<%s>%s", symbolTag, symbol, symbolTag); text = escapeHTML(text); @@ -161,19 +120,10 @@ public void linkToTextWithSymbol(Entity entity, CharSequence symbol, || textWithSymbolTag.isEmpty() ? text : String.format( "<%s>%s", textWithSymbolTag, text, textWithSymbolTag); - boolean includeSymbol = usernameIncludeSymbol - || !Regex.AT_SIGNS.matcher(symbol).matches(); - - if (includeSymbol) { - linkToText(entity, taggedSymbol.toString() + taggedText, - attributes, builder); - } else { - builder.append(taggedSymbol); - linkToText(entity, taggedText, attributes, builder); - } + linkToText(entity, taggedSymbol.toString() + taggedText, attributes, builder); } - public void linkToHashtag(Entity entity, String text, StringBuilder builder) { + void linkToHashtag(Entity entity, String text, StringBuilder builder) { // Get the original hash char from text as it could be a full-width // char. CharSequence hashChar = text.subSequence(entity.getStart(), @@ -181,26 +131,22 @@ public void linkToHashtag(Entity entity, String text, StringBuilder builder) { CharSequence hashtag = entity.getValue(); Map attrs = new LinkedHashMap(); - attrs.put("href", hashtagUrlBase + hashtag); - attrs.put("title", "#" + hashtag); - attrs.put("class", hashtagClass); + attrs.put("href", hashtagUrlBase + "#" + hashtag); linkToTextWithSymbol(entity, hashChar, hashtag, attrs, builder); } - public void linkToCashtag(Entity entity, String text, StringBuilder builder) { + void linkToCashtag(Entity entity, String text, StringBuilder builder) { CharSequence cashtag = entity.getValue(); Map attrs = new LinkedHashMap(); attrs.put("href", cashtagUrlBase + cashtag); - attrs.put("title", "$" + cashtag); - attrs.put("class", cashtagClass); linkToTextWithSymbol(entity, "$", cashtag, attrs, builder); } - public void linkToMentionAndList(Entity entity, String text, - StringBuilder builder) { + void linkToMentionAndList(Entity entity, String text, + StringBuilder builder) { String mention = entity.getValue(); // Get the original at char from text as it could be a full-width char. CharSequence atChar = text.subSequence(entity.getStart(), @@ -209,159 +155,89 @@ public void linkToMentionAndList(Entity entity, String text, Map attrs = new LinkedHashMap(); if (entity.listSlug != null) { mention += entity.listSlug; - attrs.put("class", listClass); + attrs.put("href", listUrlBase + mention); } else { - attrs.put("class", usernameClass); + attrs.put("href", usernameUrlBase + mention); } linkToTextWithSymbol(entity, atChar, mention, attrs, builder); } - public void linkToURL(Entity entity, String text, StringBuilder builder) { + void linkToURL(Entity entity, String text, StringBuilder builder, + URLEntity urlEntity) { CharSequence url = entity.getValue(); - CharSequence linkText = escapeHTML(url); - - if (entity.displayURL != null && entity.expandedURL != null) { - // Goal: If a user copies and pastes a tweet containing t.co'ed - // link, the resulting - // paste - // should contain the full original URL (expanded_url), not the - // display URL. - // - // Method: Whenever possible, we actually emit HTML that contains - // expanded_url, and use - // font-size:0 to hide those parts that should not be displayed - // (because they are not - // part of display_url). - // Elements with font-size:0 get copied even though they are not - // visible. - // Note that display:none doesn't work here. Elements with - // display:none don't get - // copied. - // - // Additionally, we want to *display* ellipses, but we don't want - // them copied. To make - // this happen we - // wrap the ellipses in a tco-ellipsis class and provide an onCopy - // handler that sets - // display:none on - // everything with the tco-ellipsis class. - // - // As an example: The user tweets "hi http://longdomainname.com/foo" - // This gets shortened to "hi http://t.co/xyzabc", with display_url - // = "…nname.com/foo" - // This will get rendered as: - // - // … - // - // http://longdomai - // - // - // nname.com/foo - // - // - //   - // … - // - // - // Exception: pic.twitter.com images, for which expandedUrl = - // "https://twitter.com/#!/username/status/1234/photo/1 - // For those URLs, display_url is not a substring of expanded_url, - // so we don't do - // anything special to render the elided parts. - // For a pic.twitter.com URL, the only elided part will be the - // "https://", so this is - // fine. - String displayURLSansEllipses = entity.displayURL - .replace("…", ""); - int diplayURLIndexInExpandedURL = entity.expandedURL - .indexOf(displayURLSansEllipses); - if (diplayURLIndexInExpandedURL != -1) { - String beforeDisplayURL = entity.expandedURL.substring(0, - diplayURLIndexInExpandedURL); - String afterDisplayURL = entity.expandedURL - .substring(diplayURLIndexInExpandedURL - + displayURLSansEllipses.length()); - String precedingEllipsis = entity.displayURL.startsWith("…") ? "…" - : ""; - String followingEllipsis = entity.displayURL.endsWith("…") ? "…" - : ""; - String invisibleSpan = ""; - - StringBuilder sb = new StringBuilder( - ""); - sb.append(precedingEllipsis); - sb.append(invisibleSpan).append(" "); - sb.append(invisibleSpan).append(escapeHTML(beforeDisplayURL)) - .append(""); - sb.append("") - .append(escapeHTML(displayURLSansEllipses)) - .append(""); - sb.append(invisibleSpan).append(escapeHTML(afterDisplayURL)) - .append(""); - sb.append("").append(invisibleSpan) - .append(" ").append(followingEllipsis) - .append(""); - - linkText = sb; - } else { - linkText = entity.displayURL; - } + String linkText = escapeHTML(url).toString(); + + if (urlEntity != null && urlEntity.getExpandedURL() != null) { + linkText = urlEntity.getExpandedURL(); + } else if (urlEntity != null && urlEntity.getDisplayURL() != null) { + linkText = urlEntity.getDisplayURL(); + } else if (entity.displayURL != null) { + linkText = entity.displayURL; } + //Remove "http://" or "https://" + //Then remove "www." + linkText = linkText.replaceAll("^https?://", "").replaceAll("^www.", ""); + Map attrs = new LinkedHashMap(); - attrs.put("href", url.toString()); - if (urlClass != null) { - attrs.put("class", urlClass); - } - if (urlClass != null && !urlClass.isEmpty()) { - attrs.put("class", urlClass); + + if(urlEntity != null && urlEntity.getExpandedURL() != null){ + attrs.put("href", urlEntity.getExpandedURL()); } - if (urlTarget != null && !urlTarget.isEmpty()) { - attrs.put("target", urlTarget); + else + { + attrs.put("href", url.toString()); } + linkToText(entity, linkText, attrs, builder); } - public String autoLinkEntities(String text, List entities) { + String autoLinkEntities(String text, List entities, + MediaEntity[] mediaEntities, URLEntity[] urlEntities) { StringBuilder builder = new StringBuilder(text.length() * 2); int beginIndex = 0; + int urlCount = 0; + for (Entity entity : entities) { builder.append(text.subSequence(beginIndex, entity.start)); switch (entity.type) { - case URL: - linkToURL(entity, text, builder); - break; - case HASHTAG: - linkToHashtag(entity, text, builder); - break; - case MENTION: - linkToMentionAndList(entity, text, builder); - break; - case CASHTAG: - linkToCashtag(entity, text, builder); - break; + case URL: + URLEntity urlEntity = null; + + if (urlEntities != null && urlCount < urlEntities.length) { + urlEntity = urlEntities[urlCount]; + urlCount += 1; + } + + if (urlEntity == null) { + if (entity != null && entity.value != null + && mediaEntities != null + && mediaEntities.length > 0) { + MediaEntity mediaEntity = mediaEntities[0]; + if (entity.value + .equals(mediaEntity.getURL())) { + entity.displayURL = mediaEntity.getDisplayURL(); + entity.expandedURL = mediaEntity.getExpandedURL(); + } + } + } + + linkToURL(entity, text, builder, urlEntity); + break; + case HASHTAG: + linkToHashtag(entity, text, builder); + break; + case MENTION: + linkToMentionAndList(entity, text, builder); + break; + case CASHTAG: + linkToCashtag(entity, text, builder); + break; } beginIndex = entity.end; } @@ -370,310 +246,13 @@ public String autoLinkEntities(String text, List entities) { return builder.toString(); } - /** - * Auto-link hashtags, URLs, usernames and lists. - * - * @param text - * of the Tweet to auto-link - * @return text with auto-link HTML added - */ - public String autoLink(String text) { + public String autoLinkAll(String text, MediaEntity[] mediaEntities, + URLEntity[] urlEntities) { text = escapeBrackets(text); // extract entities List entities = extractor.extractEntitiesWithIndices(text); - return autoLinkEntities(text, entities); - } - - /** - * Auto-link the @username and @username/list references in the provided - * text. Links to @username references will have the usernameClass CSS - * classes added. Links to @username/list references will have the listClass - * CSS class added. - * - * @param text - * of the Tweet to auto-link - * @return text with auto-link HTML added - */ - public String autoLinkUsernamesAndLists(String text) { - return autoLinkEntities(text, - extractor.extractMentionsOrListsWithIndices(text)); - } - - /** - * Auto-link #hashtag references in the provided Tweet text. The #hashtag - * links will have the hashtagClass CSS class added. - * - * @param text - * of the Tweet to auto-link - * @return text with auto-link HTML added - */ - public String autoLinkHashtags(String text) { - return autoLinkEntities(text, - extractor.extractHashtagsWithIndices(text)); - } - - /** - * Auto-link URLs in the Tweet text provided. - *

- * This only auto-links URLs with protocol. - * - * @param text - * of the Tweet to auto-link - * @return text with auto-link HTML added - */ - public String autoLinkURLs(String text) { - return autoLinkEntities(text, extractor.extractURLsWithIndices(text)); - } - - /** - * Auto-link $cashtag references in the provided Tweet text. The $cashtag - * links will have the cashtagClass CSS class added. - * - * @param text - * of the Tweet to auto-link - * @return text with auto-link HTML added - */ - public String autoLinkCashtags(String text) { - return autoLinkEntities(text, - extractor.extractCashtagsWithIndices(text)); - } - - /** - * @return CSS class for auto-linked URLs - */ - public String getUrlClass() { - return urlClass; - } - - /** - * Set the CSS class for auto-linked URLs - * - * @param urlClass - * new CSS value. - */ - public void setUrlClass(String urlClass) { - this.urlClass = urlClass; - } - - /** - * @return CSS class for auto-linked list URLs - */ - public String getListClass() { - return listClass; - } - - /** - * Set the CSS class for auto-linked list URLs - * - * @param listClass - * new CSS value. - */ - public void setListClass(String listClass) { - this.listClass = listClass; - } - - /** - * @return CSS class for auto-linked username URLs - */ - public String getUsernameClass() { - return usernameClass; - } - - /** - * Set the CSS class for auto-linked username URLs - * - * @param usernameClass - * new CSS value. - */ - public void setUsernameClass(String usernameClass) { - this.usernameClass = usernameClass; - } - - /** - * @return CSS class for auto-linked hashtag URLs - */ - public String getHashtagClass() { - return hashtagClass; - } - - /** - * Set the CSS class for auto-linked hashtag URLs - * - * @param hashtagClass - * new CSS value. - */ - public void setHashtagClass(String hashtagClass) { - this.hashtagClass = hashtagClass; - } - - /** - * @return CSS class for auto-linked cashtag URLs - */ - public String getCashtagClass() { - return cashtagClass; - } - - /** - * Set the CSS class for auto-linked cashtag URLs - * - * @param cashtagClass - * new CSS value. - */ - public void setCashtagClass(String cashtagClass) { - this.cashtagClass = cashtagClass; - } - - /** - * @return the href value for username links (to which the username will be - * appended) - */ - public String getUsernameUrlBase() { - return usernameUrlBase; - } - - /** - * Set the href base for username links. - * - * @param usernameUrlBase - * new href base value - */ - public void setUsernameUrlBase(String usernameUrlBase) { - this.usernameUrlBase = usernameUrlBase; - } - - /** - * @return the href value for list links (to which the username/list will be - * appended) - */ - public String getListUrlBase() { - return listUrlBase; - } - - /** - * Set the href base for list links. - * - * @param listUrlBase - * new href base value - */ - public void setListUrlBase(String listUrlBase) { - this.listUrlBase = listUrlBase; - } - - /** - * @return the href value for hashtag links (to which the hashtag will be - * appended) - */ - public String getHashtagUrlBase() { - return hashtagUrlBase; - } - - /** - * Set the href base for hashtag links. - * - * @param hashtagUrlBase - * new href base value - */ - public void setHashtagUrlBase(String hashtagUrlBase) { - this.hashtagUrlBase = hashtagUrlBase; - } - - /** - * @return the href value for cashtag links (to which the cashtag will be - * appended) - */ - public String getCashtagUrlBase() { - return cashtagUrlBase; - } - - /** - * Set the href base for cashtag links. - * - * @param cashtagUrlBase - * new href base value - */ - public void setCashtagUrlBase(String cashtagUrlBase) { - this.cashtagUrlBase = cashtagUrlBase; - } - - /** - * @return if the current URL links will include rel="nofollow" (true by - * default) - */ - public boolean isNoFollow() { - return noFollow; - } - - /** - * Set if the current URL links will include rel="nofollow" (true by - * default) - * - * @param noFollow - * new noFollow value - */ - public void setNoFollow(boolean noFollow) { - this.noFollow = noFollow; - } - - /** - * Set if the at mark '@' should be included in the link (false by default) - * - * @param noFollow - * new noFollow value - */ - public void setUsernameIncludeSymbol(boolean usernameIncludeSymbol) { - this.usernameIncludeSymbol = usernameIncludeSymbol; - } - - /** - * Set HTML tag to be applied around #/@/# symbols in - * hashtags/usernames/lists/cashtag - * - * @param tag - * HTML tag without bracket. e.g., "b" or "s" - */ - public void setSymbolTag(String tag) { - this.symbolTag = tag; - } - - /** - * Set HTML tag to be applied around text part of - * hashtags/usernames/lists/cashtag - * - * @param tag - * HTML tag without bracket. e.g., "b" or "s" - */ - public void setTextWithSymbolTag(String tag) { - this.textWithSymbolTag = tag; - } - - /** - * Set the value of the target attribute in auto-linked URLs - * - * @param target - * target value e.g., "_blank" - */ - public void setUrlTarget(String target) { - this.urlTarget = target; - } - - /** - * Set a modifier to modify attributes of a link based on an entity - * - * @param modifier - * LinkAttributeModifier instance - */ - public void setLinkAttributeModifier(LinkAttributeModifier modifier) { - this.linkAttributeModifier = modifier; - } - - /** - * Set a modifier to modify text of a link based on an entity - * - * @param modifier - * LinkTextModifier instance - */ - public void setLinkTextModifier(LinkTextModifier modifier) { - this.linkTextModifier = modifier; + return autoLinkEntities(text, entities, + mediaEntities, urlEntities); } } diff --git a/android/libraries/SocialNetLib/src/com/twitter/AutolinkEx.java b/android/libraries/SocialNetLib/src/com/twitter/AutolinkEx.java deleted file mode 100755 index 96a8dc14..00000000 --- a/android/libraries/SocialNetLib/src/com/twitter/AutolinkEx.java +++ /dev/null @@ -1,641 +0,0 @@ -package com.twitter; - -import com.twitter.Extractor.Entity; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.tweetalib.android.model.TwitterMediaEntity; -import twitter4j.MediaEntity; -import twitter4j.URLEntity; - -/** - * A class for adding HTML links to hashtag, username and list references in - * Tweet text. - */ -public class AutolinkEx { - /** Default CSS class for auto-linked list URLs */ - public static final String DEFAULT_LIST_CLASS = null;// "tweet-url list-slug"; - /** Default CSS class for auto-linked username URLs */ - public static final String DEFAULT_USERNAME_CLASS = null;// "tweet-url username"; - /** Default CSS class for auto-linked hashtag URLs */ - public static final String DEFAULT_HASHTAG_CLASS = null;// "tweet-url hashtag"; - /** Default CSS class for auto-linked cashtag URLs */ - public static final String DEFAULT_CASHTAG_CLASS = null;// "tweet-url cashtag"; - /** - * Default href for username links (the username without the @ will be - * appended) - */ - public static final String DEFAULT_USERNAME_URL_BASE = "com.tweetlanes.android.core.profile://"; - /** - * Default href for list links (the username/list without the @ will be - * appended) - */ - public static final String DEFAULT_LIST_URL_BASE = "com.tweetlanes.android.core.profile://"; - /** - * Default href for hashtag links (the hashtag without the # will be - * appended) - */ - public static final String DEFAULT_HASHTAG_URL_BASE = "com.tweetlanes.android.core.search://"; - /** - * Default href for cashtag links (the cashtag without the $ will be - * appended) - */ - public static final String DEFAULT_CASHTAG_URL_BASE = "com.tweetlanes.android.core.search://"; - - /** Default attribute for invisible span tag */ - public static final String DEFAULT_INVISIBLE_TAG_ATTRS = null;// "style='position:absolute;left:-9999px;'"; - - public static interface LinkAttributeModifier { - public void modify(Entity entity, Map attributes); - }; - - public static interface LinkTextModifier { - public CharSequence modify(Entity entity, CharSequence text); - } - - protected String urlClass = null; - protected String listClass; - protected String usernameClass; - protected String hashtagClass; - protected String cashtagClass; - protected String usernameUrlBase; - protected String listUrlBase; - protected String hashtagUrlBase; - protected String cashtagUrlBase; - protected String invisibleTagAttrs; - protected boolean noFollow = true; - protected boolean usernameIncludeSymbol = false; - protected String symbolTag = null; - protected String textWithSymbolTag = null; - protected String urlTarget = null; - protected LinkAttributeModifier linkAttributeModifier = null; - protected LinkTextModifier linkTextModifier = null; - - private Extractor extractor = new Extractor(); - - private static CharSequence escapeHTML(CharSequence text) { - StringBuilder builder = new StringBuilder(text.length() * 2); - for (int i = 0; i < text.length(); i++) { - char c = text.charAt(i); - switch (c) { - case '&': - builder.append("&"); - break; - case '>': - builder.append(">"); - break; - case '<': - builder.append("<"); - break; - case '"': - builder.append("""); - break; - case '\'': - builder.append("'"); - break; - default: - builder.append(c); - break; - } - } - return builder; - } - - public AutolinkEx() { - urlClass = null; - listClass = DEFAULT_LIST_CLASS; - usernameClass = DEFAULT_USERNAME_CLASS; - hashtagClass = DEFAULT_HASHTAG_CLASS; - cashtagClass = DEFAULT_CASHTAG_CLASS; - usernameUrlBase = DEFAULT_USERNAME_URL_BASE; - listUrlBase = DEFAULT_LIST_URL_BASE; - hashtagUrlBase = DEFAULT_HASHTAG_URL_BASE; - cashtagUrlBase = DEFAULT_CASHTAG_URL_BASE; - invisibleTagAttrs = DEFAULT_INVISIBLE_TAG_ATTRS; - - extractor.setExtractURLWithoutProtocol(false); - } - - public String escapeBrackets(String text) { - int len = text.length(); - if (len == 0) return text; - - StringBuilder sb = new StringBuilder(len + 16); - for (int i = 0; i < len; ++i) { - char c = text.charAt(i); - if (c == '>') - sb.append(">"); - else if (c == '<') - sb.append("<"); - else - sb.append(c); - } - return sb.toString(); - } - - public void linkToText(Entity entity, CharSequence text, - Map attributes, StringBuilder builder) { - if (noFollow) { - attributes.put("rel", "nofollow"); - } - if (linkAttributeModifier != null) { - linkAttributeModifier.modify(entity, attributes); - } - if (linkTextModifier != null) { - text = linkTextModifier.modify(entity, text); - } - // append tag - builder.append(" entry : attributes.entrySet()) { - builder.append(" ").append(escapeHTML(entry.getKey())) - .append("=\"").append(escapeHTML(entry.getValue())) - .append("\""); - } - builder.append(">").append(text).append(""); - } - - public void linkToTextWithSymbol(Entity entity, CharSequence symbol, - CharSequence text, Map attributes, - StringBuilder builder) { - CharSequence taggedSymbol = symbolTag == null || symbolTag.isEmpty() ? symbol - : String.format("<%s>%s", symbolTag, symbol, symbolTag); - text = escapeHTML(text); - CharSequence taggedText = textWithSymbolTag == null - || textWithSymbolTag.isEmpty() ? text : String.format( - "<%s>%s", textWithSymbolTag, text, textWithSymbolTag); - - boolean includeSymbol = usernameIncludeSymbol - || !Regex.AT_SIGNS.matcher(symbol).matches(); - - if (includeSymbol) { - linkToText(entity, taggedSymbol.toString() + taggedText, - attributes, builder); - } else { - builder.append(taggedSymbol); - linkToText(entity, taggedText, attributes, builder); - } - } - - public void linkToHashtag(Entity entity, String text, StringBuilder builder) { - // Get the original hash char from text as it could be a full-width - // char. - CharSequence hashChar = text.subSequence(entity.getStart(), - entity.getStart() + 1); - CharSequence hashtag = entity.getValue(); - - Map attrs = new LinkedHashMap(); - attrs.put("href", hashtagUrlBase + "#" + hashtag); - // attrs.put("title", "#" + hashtag); - if (hashtagClass != null) { - attrs.put("class", hashtagClass); - } - - linkToTextWithSymbol(entity, hashChar, hashtag, attrs, builder); - } - - public void linkToCashtag(Entity entity, String text, StringBuilder builder) { - CharSequence cashtag = entity.getValue(); - - Map attrs = new LinkedHashMap(); - attrs.put("href", cashtagUrlBase + cashtag); - // attrs.put("title", "$" + cashtag); - if (cashtagClass != null) { - attrs.put("class", cashtagClass); - } - - linkToTextWithSymbol(entity, "$", cashtag, attrs, builder); - } - - public void linkToMentionAndList(Entity entity, String text, - StringBuilder builder) { - String mention = entity.getValue(); - // Get the original at char from text as it could be a full-width char. - CharSequence atChar = text.subSequence(entity.getStart(), - entity.getStart() + 1); - - Map attrs = new LinkedHashMap(); - if (entity.listSlug != null) { - mention += entity.listSlug; - if (listClass != null) { - attrs.put("class", listClass); - } - attrs.put("href", listUrlBase + mention); - } else { - if (usernameClass != null) { - attrs.put("class", usernameClass); - } - attrs.put("href", usernameUrlBase + mention); - } - - linkToTextWithSymbol(entity, atChar, mention, attrs, builder); - } - - public void linkToURL(Entity entity, String text, StringBuilder builder, - URLEntity urlEntity) { - CharSequence url = entity.getValue(); - CharSequence linkText = escapeHTML(url); - - if (urlEntity != null && urlEntity.getDisplayURL() != null) { - linkText = urlEntity.getDisplayURL(); - } else if (entity.displayURL != null) { - linkText = entity.displayURL; - } - - Map attrs = new LinkedHashMap(); - attrs.put("href", url.toString()); - - linkToText(entity, linkText, attrs, builder); - } - - public String autoLinkEntities(String text, List entities) { - return autoLinkEntities(text, null, entities, null, null); - } - - public String autoLinkEntities(String text, - TwitterMediaEntity twitterMediaEntity, List entities, - MediaEntity[] mediaEntities, URLEntity[] urlEntities) { - StringBuilder builder = new StringBuilder(text.length() * 2); - int beginIndex = 0; - - int urlCount = 0; - - for (Entity entity : entities) { - builder.append(text.subSequence(beginIndex, entity.start)); - - switch (entity.type) { - case URL: - URLEntity urlEntity = null; - - if (urlEntities != null && urlCount < urlEntities.length) { - urlEntity = urlEntities[urlCount]; - urlCount += 1; - // if (twitterMediaEntity != null && - // twitterMediaEntity.getUrl().equals(urlEntity.getURL().toString())) - // { - // break; - // } - } - - if (urlEntity == null) { - if (entity != null && entity.value != null - && mediaEntities != null - && mediaEntities.length > 0) { - MediaEntity mediaEntity = mediaEntities[0]; - if (entity.value - .equals(mediaEntity.getURL().toString())) { - entity.displayURL = mediaEntity.getDisplayURL(); - entity.expandedURL = mediaEntity.getExpandedURL() - .toString(); - } - } - } - - /* - * if (twitterMediaEntity != null && urlEntity != null) { if - * (urlEntity.getExpandedURL - * ().toString().equals(twitterMediaEntity.getExpandedUrl())) { - * entity.expandedURL = DEFAULT_MEDIA_URL_BASE + - * twitterMediaEntity.getExpandedUrl().toString(); entity.value - * = DEFAULT_MEDIA_URL_BASE + - * twitterMediaEntity.getExpandedUrl().toString(); } } - */ - - linkToURL(entity, text, builder, urlEntity); - break; - case HASHTAG: - linkToHashtag(entity, text, builder); - break; - case MENTION: - linkToMentionAndList(entity, text, builder); - break; - case CASHTAG: - linkToCashtag(entity, text, builder); - break; - } - beginIndex = entity.end; - } - builder.append(text.subSequence(beginIndex, text.length())); - - return builder.toString(); - } - - /** - * Auto-link hashtags, URLs, usernames and lists. - * - * @param text - * of the Tweet to auto-link - * @return text with auto-link HTML added - */ - public String autoLink(String text) { - text = escapeBrackets(text); - - // extract entities - List entities = extractor.extractEntitiesWithIndices(text); - return autoLinkEntities(text, entities); - } - - public String autoLinkAll(String text, - TwitterMediaEntity twitterMediaEntity, MediaEntity[] mediaEntities, - URLEntity[] urlEntities) { - text = escapeBrackets(text); - - // extract entities - List entities = extractor.extractEntitiesWithIndices(text); - return autoLinkEntities(text, twitterMediaEntity, entities, - mediaEntities, urlEntities); - } - - /** - * Auto-link the @username and @username/list references in the provided - * text. Links to @username references will have the usernameClass CSS - * classes added. Links to @username/list references will have the listClass - * CSS class added. - * - * @param text - * of the Tweet to auto-link - * @return text with auto-link HTML added - */ - public String autoLinkUsernamesAndLists(String text) { - return autoLinkEntities(text, - extractor.extractMentionsOrListsWithIndices(text)); - } - - /** - * Auto-link #hashtag references in the provided Tweet text. The #hashtag - * links will have the hashtagClass CSS class added. - * - * @param text - * of the Tweet to auto-link - * @return text with auto-link HTML added - */ - public String autoLinkHashtags(String text) { - return autoLinkEntities(text, - extractor.extractHashtagsWithIndices(text)); - } - - /** - * Auto-link URLs in the Tweet text provided. - *

- * This only auto-links URLs with protocol. - * - * @param text - * of the Tweet to auto-link - * @return text with auto-link HTML added - */ - public String autoLinkURLs(String text) { - return autoLinkEntities(text, extractor.extractURLsWithIndices(text)); - } - - /** - * Auto-link $cashtag references in the provided Tweet text. The $cashtag - * links will have the cashtagClass CSS class added. - * - * @param text - * of the Tweet to auto-link - * @return text with auto-link HTML added - */ - public String autoLinkCashtags(String text) { - return autoLinkEntities(text, - extractor.extractCashtagsWithIndices(text)); - } - - /** - * @return CSS class for auto-linked URLs - */ - public String getUrlClass() { - return urlClass; - } - - /** - * Set the CSS class for auto-linked URLs - * - * @param urlClass - * new CSS value. - */ - public void setUrlClass(String urlClass) { - this.urlClass = urlClass; - } - - /** - * @return CSS class for auto-linked list URLs - */ - public String getListClass() { - return listClass; - } - - /** - * Set the CSS class for auto-linked list URLs - * - * @param listClass - * new CSS value. - */ - public void setListClass(String listClass) { - this.listClass = listClass; - } - - /** - * @return CSS class for auto-linked username URLs - */ - public String getUsernameClass() { - return usernameClass; - } - - /** - * Set the CSS class for auto-linked username URLs - * - * @param usernameClass - * new CSS value. - */ - public void setUsernameClass(String usernameClass) { - this.usernameClass = usernameClass; - } - - /** - * @return CSS class for auto-linked hashtag URLs - */ - public String getHashtagClass() { - return hashtagClass; - } - - /** - * Set the CSS class for auto-linked hashtag URLs - * - * @param hashtagClass - * new CSS value. - */ - public void setHashtagClass(String hashtagClass) { - this.hashtagClass = hashtagClass; - } - - /** - * @return CSS class for auto-linked cashtag URLs - */ - public String getCashtagClass() { - return cashtagClass; - } - - /** - * Set the CSS class for auto-linked cashtag URLs - * - * @param cashtagClass - * new CSS value. - */ - public void setCashtagClass(String cashtagClass) { - this.cashtagClass = cashtagClass; - } - - /** - * @return the href value for username links (to which the username will be - * appended) - */ - public String getUsernameUrlBase() { - return usernameUrlBase; - } - - /** - * Set the href base for username links. - * - * @param usernameUrlBase - * new href base value - */ - public void setUsernameUrlBase(String usernameUrlBase) { - this.usernameUrlBase = usernameUrlBase; - } - - /** - * @return the href value for list links (to which the username/list will be - * appended) - */ - public String getListUrlBase() { - return listUrlBase; - } - - /** - * Set the href base for list links. - * - * @param listUrlBase - * new href base value - */ - public void setListUrlBase(String listUrlBase) { - this.listUrlBase = listUrlBase; - } - - /** - * @return the href value for hashtag links (to which the hashtag will be - * appended) - */ - public String getHashtagUrlBase() { - return hashtagUrlBase; - } - - /** - * Set the href base for hashtag links. - * - * @param hashtagUrlBase - * new href base value - */ - public void setHashtagUrlBase(String hashtagUrlBase) { - this.hashtagUrlBase = hashtagUrlBase; - } - - /** - * @return the href value for cashtag links (to which the cashtag will be - * appended) - */ - public String getCashtagUrlBase() { - return cashtagUrlBase; - } - - /** - * Set the href base for cashtag links. - * - * @param cashtagUrlBase - * new href base value - */ - public void setCashtagUrlBase(String cashtagUrlBase) { - this.cashtagUrlBase = cashtagUrlBase; - } - - /** - * @return if the current URL links will include rel="nofollow" (true by - * default) - */ - public boolean isNoFollow() { - return noFollow; - } - - /** - * Set if the current URL links will include rel="nofollow" (true by - * default) - * - * @param noFollow - * new noFollow value - */ - public void setNoFollow(boolean noFollow) { - this.noFollow = noFollow; - } - - /** - * Set if the at mark '@' should be included in the link (false by default) - * - * @param noFollow - * new noFollow value - */ - public void setUsernameIncludeSymbol(boolean usernameIncludeSymbol) { - this.usernameIncludeSymbol = usernameIncludeSymbol; - } - - /** - * Set HTML tag to be applied around #/@/# symbols in - * hashtags/usernames/lists/cashtag - * - * @param tag - * HTML tag without bracket. e.g., "b" or "s" - */ - public void setSymbolTag(String tag) { - this.symbolTag = tag; - } - - /** - * Set HTML tag to be applied around text part of - * hashtags/usernames/lists/cashtag - * - * @param tag - * HTML tag without bracket. e.g., "b" or "s" - */ - public void setTextWithSymbolTag(String tag) { - this.textWithSymbolTag = tag; - } - - /** - * Set the value of the target attribute in auto-linked URLs - * - * @param target - * target value e.g., "_blank" - */ - public void setUrlTarget(String target) { - this.urlTarget = target; - } - - /** - * Set a modifier to modify attributes of a link based on an entity - * - * @param modifier - * LinkAttributeModifier instance - */ - public void setLinkAttributeModifier(LinkAttributeModifier modifier) { - this.linkAttributeModifier = modifier; - } - - /** - * Set a modifier to modify text of a link based on an entity - * - * @param modifier - * LinkTextModifier instance - */ - public void setLinkTextModifier(LinkTextModifier modifier) { - this.linkTextModifier = modifier; - } -} diff --git a/android/libraries/SocialNetLib/src/com/twitter/Extractor.java b/android/libraries/SocialNetLib/src/com/twitter/Extractor.java index 6cf3bf30..2f0c4f5a 100755 --- a/android/libraries/SocialNetLib/src/com/twitter/Extractor.java +++ b/android/libraries/SocialNetLib/src/com/twitter/Extractor.java @@ -1,7 +1,11 @@ package com.twitter; -import java.util.*; -import java.util.regex.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.regex.Matcher; /** * A class to extract usernames, lists, hashtags and URLs from Tweet text. @@ -12,18 +16,18 @@ public enum Type { URL, HASHTAG, MENTION, CASHTAG } - protected int start; - protected int end; - protected final String value; + int start; + int end; + final String value; // listSlug is used to store the list portion of @mention/list. - protected final String listSlug; - protected final Type type; + final String listSlug; + final Type type; - protected String displayURL = null; - protected String expandedURL = null; + String displayURL = null; + String expandedURL = null; public Entity(int start, int end, String value, String listSlug, - Type type) { + Type type) { this.start = start; this.end = end; this.value = value; @@ -42,7 +46,7 @@ public Entity(Matcher matcher, Type type, int groupNumber) { } public Entity(Matcher matcher, Type type, int groupNumber, - int startOffset) { + int startOffset) { this(matcher.start(groupNumber) + startOffset, matcher .end(groupNumber), matcher.group(groupNumber), type); } @@ -59,12 +63,8 @@ public boolean equals(Object obj) { Entity other = (Entity) obj; - if (this.type.equals(other.type) && this.start == other.start - && this.end == other.end && this.value.equals(other.value)) { - return true; - } else { - return false; - } + return this.type.equals(other.type) && this.start == other.start + && this.end == other.end && this.value.equals(other.value); } @Override @@ -115,7 +115,7 @@ public void setExpandedURL(String expandedURL) { } } - protected boolean extractURLWithoutProtocol = true; + private boolean extractURLWithoutProtocol = true; /** * Create a new extractor. @@ -123,9 +123,10 @@ public void setExpandedURL(String expandedURL) { public Extractor() { } - private void removeOverlappingEntities(List entities) { + private static void removeOverlappingEntities(List entities) { // sort by index - Collections. sort(entities, new Comparator() { + Collections.sort(entities, new Comparator() { + @Override public int compare(Entity e1, Entity e2) { return e1.start - e2.start; } @@ -153,9 +154,8 @@ public int compare(Entity e1, Entity e2) { /** * Extract URLs, @mentions, lists and #hashtag from a given text/tweet. - * - * @param text - * text of tweet + * + * @param text text of tweet * @return list of extracted entities */ public List extractEntitiesWithIndices(String text) { @@ -172,9 +172,8 @@ public List extractEntitiesWithIndices(String text) { /** * 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 + * + * @param text of the tweet from which to extract usernames * @return List of usernames referenced (without the leading @ sign) */ public List extractMentionedScreennames(String text) { @@ -192,12 +191,11 @@ public List extractMentionedScreennames(String text) { /** * 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 + * + * @param text of the tweet from which to extract usernames * @return List of usernames referenced (without the leading @ sign) */ - public List extractMentionedScreennamesWithIndices(String text) { + List extractMentionedScreennamesWithIndices(String text) { List extracted = new ArrayList(); for (Entity entity : extractMentionsOrListsWithIndices(text)) { if (entity.listSlug == null) { @@ -252,9 +250,8 @@ public List extractMentionsOrListsWithIndices(String text) { * 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. - * - * @param text - * of the tweet from which to extract the replied to username + * + * @param text of the tweet from which to extract the replied to username * @return username referenced, if any (without the leading @ sign). Returns * null if this is not a reply. */ @@ -278,9 +275,8 @@ public String extractReplyScreenname(String text) { /** * Extract URL references from Tweet text. - * - * @param text - * of the tweet from which to extract URLs + * + * @param text of the tweet from which to extract URLs * @return List of URLs referenced. */ public List extractURLs(String text) { @@ -297,16 +293,15 @@ public List extractURLs(String text) { /** * Extract URL references from Tweet text. - * - * @param text - * of the tweet from which to extract URLs + * + * @param text of the tweet from which to extract URLs * @return List of URLs referenced. */ public List extractURLsWithIndices(String text) { if (text == null || text.isEmpty() || (extractURLWithoutProtocol ? text.indexOf('.') : text - .indexOf(':')) == -1) { + .indexOf(':')) == -1) { // Performance optimization. // If text doesn't contain '.' or ':' at all, text doesn't contain // URL, @@ -324,9 +319,9 @@ public List extractURLsWithIndices(String text) { // or URL is preceded by invalid character. if (!extractURLWithoutProtocol || Regex.INVALID_URL_WITHOUT_PROTOCOL_MATCH_BEGIN - .matcher( - matcher.group(Regex.VALID_URL_GROUP_BEFORE)) - .matches()) { + .matcher( + matcher.group(Regex.VALID_URL_GROUP_BEFORE)) + .matches()) { continue; } } @@ -349,9 +344,8 @@ public List extractURLsWithIndices(String text) { /** * Extract #hashtag references from Tweet text. - * - * @param text - * of the tweet from which to extract hashtags + * + * @param text of the tweet from which to extract hashtags * @return List of hashtags referenced (without the leading # sign) */ public List extractHashtags(String text) { @@ -369,9 +363,8 @@ public List extractHashtags(String text) { /** * Extract #hashtag references from Tweet text. - * - * @param text - * of the tweet from which to extract hashtags + * + * @param text of the tweet from which to extract hashtags * @return List of hashtags referenced (without the leading # sign) */ public List extractHashtagsWithIndices(String text) { @@ -380,16 +373,14 @@ public List extractHashtagsWithIndices(String text) { /** * Extract #hashtag references from Tweet text. - * - * @param text - * of the tweet from which to extract hashtags - * @param checkUrlOverlap - * if true, check if extracted hashtags overlap URLs and remove - * overlapping ones + * + * @param text of the tweet from which to extract hashtags + * @param checkUrlOverlap if true, check if extracted hashtags overlap URLs and remove + * overlapping ones * @return List of hashtags referenced (without the leading # sign) */ private List extractHashtagsWithIndices(String text, - boolean checkUrlOverlap) { + boolean checkUrlOverlap) { if (text == null || text.isEmpty()) { return Collections.emptyList(); } @@ -442,9 +433,8 @@ private List extractHashtagsWithIndices(String text, /** * Extract $cashtag references from Tweet text. - * - * @param text - * of the tweet from which to extract cashtags + * + * @param text of the tweet from which to extract cashtags * @return List of cashtags referenced (without the leading $ sign) */ public List extractCashtags(String text) { @@ -462,9 +452,8 @@ public List extractCashtags(String text) { /** * Extract $cashtag references from Tweet text. - * - * @param text - * of the tweet from which to extract cashtags + * + * @param text of the tweet from which to extract cashtags * @return List of cashtags referenced (without the leading $ sign) */ public List extractCashtagsWithIndices(String text) { @@ -513,7 +502,7 @@ public boolean isExtractURLWithoutProtocol() { * @param entities entities with Unicode based indices */ public void modifyIndicesFromUnicodeToUTF16(String text, - List entities) { + List entities) { IndexConverter convert = new IndexConverter(text); for (Entity entity : entities) { @@ -536,7 +525,7 @@ public void modifyIndicesFromUnicodeToUTF16(String text, * @param entities entities with UTF-16 based indices */ public void modifyIndicesFromUTF16ToToUnicode(String text, - List entities) { + List entities) { IndexConverter convert = new IndexConverter(text); for (Entity entity : entities) { @@ -549,21 +538,20 @@ public void modifyIndicesFromUTF16ToToUnicode(String text, * An efficient converter of indices between code points and code units. */ private static final class IndexConverter { - protected final String text; + final String text; // Keep track of a single corresponding pair of code unit and code point // offsets so that we can re-use counting work if the next requested // entity is near the most recent entity. - protected int codePointIndex = 0; - protected int charIndex = 0; + int codePointIndex = 0; + int charIndex = 0; IndexConverter(String text) { this.text = text; } /** - * @param charIndex - * Index into the string measured in code units. + * @param charIndex Index into the string measured in code units. * @return The code point index that corresponds to the specified * character index. */ @@ -582,15 +570,14 @@ int codeUnitsToCodePoints(int charIndex) { // surrogate pair. if (charIndex > 0 && Character.isSupplementaryCodePoint(text - .codePointAt(charIndex - 1))) { + .codePointAt(charIndex - 1))) { this.charIndex -= 1; } return this.codePointIndex; } /** - * @param codePointIndex - * Index into the string measured in code points. + * @param codePointIndex Index into the string measured in code points. * @return the code unit index that corresponds to the specified code * point index. */ diff --git a/android/libraries/SocialNetLib/src/com/twitter/HitHighlighter.java b/android/libraries/SocialNetLib/src/com/twitter/HitHighlighter.java index 3e2efc23..d62ec3a7 100755 --- a/android/libraries/SocialNetLib/src/com/twitter/HitHighlighter.java +++ b/android/libraries/SocialNetLib/src/com/twitter/HitHighlighter.java @@ -1,21 +1,27 @@ package com.twitter; -import java.util.*; -import java.util.regex.*; -import java.text.*; +import java.text.CharacterIterator; +import java.text.StringCharacterIterator; +import java.util.List; /** * A class for adding HTML highlighting in Tweet text (such as would be returned * from a Search) */ -public class HitHighlighter { - /** Default HTML tag for highlight hits */ - public static final String DEFAULT_HIGHLIGHT_TAG = "em"; +class HitHighlighter { + /** + * Default HTML tag for highlight hits + */ + private static final String DEFAULT_HIGHLIGHT_TAG = "em"; - /** the current HTML tag used for hit highlighting */ - protected String highlightTag; + /** + * the current HTML tag used for hit highlighting + */ + private String highlightTag; - /** Create a new HitHighlighter object. */ + /** + * Create a new HitHighlighter object. + */ public HitHighlighter() { highlightTag = DEFAULT_HIGHLIGHT_TAG; } @@ -24,12 +30,10 @@ public HitHighlighter() { * Surround the hits in the provided text with an * HTML tag. This is used with offsets from the search API to support the * highlighting of query terms. - * - * @param text - * of the Tweet to highlight - * @param hits - * A List of highlighting offsets (themselves lists of two - * elements) + * + * @param text of the Tweet to highlight + * @param hits A List of highlighting offsets (themselves lists of two + * elements) * @return text with highlight HTML added */ public String highlight(String text, List> hits) { @@ -80,10 +84,10 @@ public String highlight(String text, List> hits) { * Format the current highlightTag by adding < and >. If * closeTag is true then the tag returned will * include a / to signify a closing tag. - * + * * @param true if this is a closing tag, false otherwise */ - protected String tag(boolean closeTag) { + String tag(boolean closeTag) { StringBuilder sb = new StringBuilder(highlightTag.length() + 3); sb.append("<"); if (closeTag) { @@ -95,7 +99,7 @@ protected String tag(boolean closeTag) { /** * Get the current HTML tag used for phrase highlighting. - * + * * @return current HTML tag (without < or >) */ public String getHighlightTag() { @@ -104,7 +108,7 @@ public String getHighlightTag() { /** * Set the current HTML tag used for phrase highlighting. - * + * * @param new HTML tag (without < or >) */ public void setHighlightTag(String highlightTag) { diff --git a/android/libraries/SocialNetLib/src/com/twitter/Regex.java b/android/libraries/SocialNetLib/src/com/twitter/Regex.java index e6961292..1fbcc53b 100755 --- a/android/libraries/SocialNetLib/src/com/twitter/Regex.java +++ b/android/libraries/SocialNetLib/src/com/twitter/Regex.java @@ -1,14 +1,14 @@ package com.twitter; -import java.util.regex.*; +import java.util.regex.Pattern; -public class Regex { +class Regex { private static final String UNICODE_SPACES = "[" + "\\u0009-\\u000d" + // # - // White_Space - // # - // Cc - // [5] - // .. + // White_Space + // # + // Cc + // [5] + // .. "\\u0020" + // White_Space # Zs SPACE "\\u0085" + // White_Space # Cc "\\u00a0" + // White_Space # Zs NO-BREAK SPACE @@ -22,17 +22,17 @@ public class Regex { "\\u3000" + // White_Space # Zs IDEOGRAPHIC SPACE "]"; - private static String LATIN_ACCENTS_CHARS = "\\u00c0-\\u00d6\\u00d8-\\u00f6\\u00f8-\\u00ff" + private static final String LATIN_ACCENTS_CHARS = "\\u00c0-\\u00d6\\u00d8-\\u00f6\\u00f8-\\u00ff" + // Latin-1 "\\u0100-\\u024f" + // Latin Extended A and B "\\u0253\\u0254\\u0256\\u0257\\u0259\\u025b\\u0263\\u0268\\u026f\\u0272\\u0289\\u028b" + // IPA - // Extensions + // Extensions "\\u02bb" + // Hawaiian "\\u0300-\\u036f" + // Combining diacritics "\\u1e00-\\u1eff"; // Latin Extended Additional (mostly for - // Vietnamese) + // Vietnamese) private static final String HASHTAG_ALPHA_CHARS = "a-z" + LATIN_ACCENTS_CHARS + "\\u0400-\\u04ff\\u0500-\\u0527" @@ -50,14 +50,14 @@ public class Regex { + // Arabic "\\u0750-\\u077f\\u08a0\\u08a2-\\u08ac\\u08e4-\\u08fe" + // Arabic - // Supplement - // and - // Extended - // A + // Supplement + // and + // Extended + // A "\\ufb50-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb" + // Pres. - // Forms - // A + // Forms + // A "\\ufe70-\\ufe74\\ufe76-\\ufefc" + // Pres. Forms B "\\u200c" @@ -66,7 +66,7 @@ public class Regex { + // Thai "\\u1100-\\u11ff\\u3130-\\u3185\\uA960-\\uA97F\\uAC00-\\uD7AF\\uD7B0-\\uD7FF" + // Hangul - // (Korean) + // (Korean) "\\p{InHiragana}\\p{InKatakana}" + // Japanese Hiragana and Katakana "\\p{InCJKUnifiedIdeographs}" + // Japanese Kanji / Chinese Han "\\u3003\\u3005\\u303b" + // Kanji/Han iteration marks @@ -130,20 +130,20 @@ public class Regex { + URL_VALID_CCTLD + ")" + // protocol - // + - // domain - // + - // ccTLD + // + + // domain + // + + // ccTLD "|(?:" + URL_VALID_UNICODE_CHARS + "+\\." + // protocol + unicode - // domain + TLD + // domain + TLD "(?:" + URL_VALID_GTLD + "|" + URL_VALID_CCTLD + ")" + ")" + ")" + ")" + "|(?:" + // domain - // + - // ccTLD - // + - // '/' + // + + // ccTLD + // + + // '/' URL_VALID_DOMAIN_NAME + URL_VALID_CCTLD + "(?=/)" + // e.g. t.co/ ")"; @@ -154,13 +154,13 @@ public class Regex { /** * Allow URL paths to contain balanced parens 1. Used in Wikipedia URLs like * /Primer_(film) 2. Used in IIS sessions like /S(dfd346)/ - **/ + */ private static final String URL_BALANCED_PARENS = "\\(" + URL_VALID_GENERAL_PATH_CHARS + "+\\)"; /** * Valid end-of-path chracters (so /foo. does not gobble the period). 2. * Allow =&# for empty URL parameters and other URL-join artifacts - **/ + */ private static final String URL_VALID_PATH_ENDING_CHARS = "[a-z0-9=_#/\\-\\+" + LATIN_ACCENTS_CHARS + "]|(?:" + URL_BALANCED_PARENS + ")"; @@ -173,18 +173,18 @@ public class Regex { private static final String URL_VALID_URL_QUERY_CHARS = "[a-z0-9!?\\*'\\(\\);:&=\\+\\$/%#\\[\\]\\-_\\.,~\\|]"; private static final String URL_VALID_URL_QUERY_ENDING_CHARS = "[a-z0-9_&=#/]"; private static final String VALID_URL_PATTERN_STRING = "(" + // $1 total - // match + // match "(" + URL_VALID_PRECEEDING_CHARS + ")" + // $2 Preceeding chracter "(" + // $3 URL "(https?://)?" + // $4 Protocol (optional) "(" + URL_VALID_DOMAIN + ")" + // $5 Domain(s) "(?::(" + URL_VALID_PORT_NUMBER + "))?" + // $6 Port number - // (optional) + // (optional) "(/" + URL_VALID_PATH + "*+" + ")?" + // $7 URL Path and anchor "(\\?" + URL_VALID_URL_QUERY_CHARS + "*" + // $8 Query String URL_VALID_URL_QUERY_ENDING_CHARS + ")?" + ")" + ")"; - private static String AT_SIGNS_CHARS = "@\uFF20"; + private static final String AT_SIGNS_CHARS = "@\uFF20"; private static final String DOLLAR_SIGN_CHAR = "\\$"; private static final String CASHTAG = "[a-z]{1,6}(?:[._][a-z]{1,2})?"; diff --git a/android/libraries/SocialNetLib/src/com/twitter/Validator.java b/android/libraries/SocialNetLib/src/com/twitter/Validator.java index c34a7131..88970ba6 100755 --- a/android/libraries/SocialNetLib/src/com/twitter/Validator.java +++ b/android/libraries/SocialNetLib/src/com/twitter/Validator.java @@ -6,60 +6,44 @@ * A class for validating Tweet texts. */ public class Validator { - public static final int MAX_TWEET_LENGTH = 140; + private static final int MAX_TWEET_LENGTH = 140; - protected int shortUrlLength = 22; - protected int shortUrlLengthHttps = 23; + private int shortUrlLength = 22; + private int shortUrlLengthHttps = 23; - private Extractor extractor = new Extractor(); + private final Extractor extractor = new Extractor(); - public int getTweetLength(String text) { - text = Normalizer.normalize(text, Normalizer.Form.NFC); - int length = text.codePointCount(0, text.length()); + public int getTweetLength(String text) { + text = Normalizer.normalize(text, Normalizer.Form.NFC); + int length = text.codePointCount(0, text.length()); for (Extractor.Entity urlEntity : extractor .extractURLsWithIndices(text)) { - length += urlEntity.start - urlEntity.end; + length += urlEntity.start - urlEntity.end; length += urlEntity.value.toLowerCase().startsWith("https://") ? shortUrlLengthHttps : shortUrlLength; - } + } - return length; - } + return length; + } - public boolean isValidTweet(String text) { + public boolean isValidTweet(String text) { return isValidTweet(text, MAX_TWEET_LENGTH); } public boolean isValidTweet(String text, int maxLength) { - if (text == null || text.isEmpty()) { - return false; - } - - for (char c : text.toCharArray()) { - if (c == '\uFFFE' || c == '\uuFEFF' || // BOM - c == '\uFFFF' || // Special - (c >= '\u202A' && c <= '\u202E')) { // Direction change - return false; - } - } + if (text == null || text.isEmpty()) { + return false; + } + + for (char c : text.toCharArray()) { + if (c == '\uFFFE' || c == '\uuFEFF' || // BOM + c == '\uFFFF' || // Special + (c >= '\u202A' && c <= '\u202E')) { // Direction change + return false; + } + } return getTweetLength(text) <= maxLength; - } - - public int getShortUrlLength() { - return shortUrlLength; - } - - public void setShortUrlLength(int shortUrlLength) { - this.shortUrlLength = shortUrlLength; - } - - public int getShortUrlLengthHttps() { - return shortUrlLengthHttps; - } - - public void setShortUrlLengthHttps(int shortUrlLengthHttps) { - this.shortUrlLengthHttps = shortUrlLengthHttps; - } + } } diff --git a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnFile.java b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnFile.java index aa776c2a..b6fe5c90 100644 --- a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnFile.java +++ b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnFile.java @@ -8,8 +8,8 @@ * To change this template use File | Settings | File Templates. */ public class AdnFile { - public String mId; - public String mFileToken; + public final String mId; + public final String mFileToken; public AdnFile(String id, String fileToken) { mId = id; diff --git a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnInteraction.java b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnInteraction.java index d42e015b..fde70115 100644 --- a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnInteraction.java +++ b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnInteraction.java @@ -18,11 +18,9 @@ import java.text.ParseException; import java.util.Date; -public class AdnInteraction { +class AdnInteraction { public String mAction; - public Date mCreatedAt; - public AdnUsers mUsers; public AdnPosts mPosts; public AdnInteraction(String jsonAsString) { @@ -35,12 +33,12 @@ public AdnInteraction(String jsonAsString) { mAction = object.getString("action"); String eventDateString = object.getString("event_date"); - mCreatedAt = TwitterUtil.iso6801StringToDate(eventDateString); + Date createdAt = TwitterUtil.iso6801StringToDate(eventDateString); // more like "unique" Id. long unqiueId = Long.valueOf(eventDateString.replaceAll("-|:|Z|T", "")); - mUsers = new AdnUsers(object.getJSONArray("users")); + AdnUsers users = new AdnUsers(object.getJSONArray("users")); if (mAction.equals("repost") || mAction.equals("star") || mAction.equals("reply")) { mPosts = new AdnPosts(object.getJSONArray("objects")); @@ -49,37 +47,34 @@ public AdnInteraction(String jsonAsString) { if (mAction.equals("repost")) { verb = "reposted"; } else if (mAction.equals("star")) { - verb = "starred"; + verb = "starred"; } else if (mAction.equals("reply")) { - verb = "replied to"; + verb = "replied to"; } for (AdnPost post : mPosts.mPosts) { String userString = ""; - for (AdnUser user : mUsers.mUsers) { + for (AdnUser user : users.mUsers) { if (userString.equals("")) { userString = "@" + user.mUserName; - } - else { + } else { userString += ", " + "@" + user.mUserName; } } post.mId = unqiueId; post.mText = userString + " " + verb + " the following post:\n\n" + post.mText; - post.mUser = mUsers.mUsers.get(0); + post.mUser = users.mUsers.get(0); post.mInReplyTo = null; - post.mCreatedAt = mCreatedAt; + post.mCreatedAt = createdAt; } } - } - else if (mAction.equals("follow") && mUsers != null && mUsers.mUsers != null) { + } else if (mAction.equals("follow") && users != null && users.mUsers != null) { mPosts = new AdnPosts(); String userString = ""; long id = 0; - for (AdnUser user : mUsers.mUsers) { + for (AdnUser user : users.mUsers) { if (userString.equals("")) { userString = "@" + user.mUserName; - } - else { + } else { userString += ", " + "@" + user.mUserName; } id += user.mId; @@ -87,8 +82,8 @@ else if (mAction.equals("follow") && mUsers != null && mUsers.mUsers != null) { AdnPost meta = new AdnPost(); meta.mId = unqiueId; meta.mText = userString + " started following you."; - meta.mCreatedAt = mCreatedAt; - meta.mUser = mUsers.mUsers.get(0); + meta.mCreatedAt = createdAt; + meta.mUser = users.mUsers.get(0); meta.mSource = "App.net"; mPosts.mPosts.add(meta); } diff --git a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnInteractions.java b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnInteractions.java index b1c02fd8..9a5eb558 100644 --- a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnInteractions.java +++ b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnInteractions.java @@ -19,7 +19,7 @@ public class AdnInteractions { - public ArrayList mInteractions; + private ArrayList mInteractions; public AdnInteractions(String jsonAsString) { diff --git a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnPaging.java b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnPaging.java index b90bfd3b..869a2fa7 100644 --- a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnPaging.java +++ b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnPaging.java @@ -19,7 +19,6 @@ public class AdnPaging { public int mPage; private long mSinceId; - private Integer mCount; private long mMaxId; public AdnPaging(int mPage) { @@ -41,9 +40,4 @@ public long getSinceId() { public void setSinceId(long mSinceId) { this.mSinceId = mSinceId; } - - - public void setCount(Integer mCount) { - this.mCount = mCount; - } } diff --git a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnPost.java b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnPost.java index 7f9b59ac..63150e3e 100644 --- a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnPost.java +++ b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnPost.java @@ -11,15 +11,17 @@ package org.appdotnet4j.model; -import java.text.ParseException; -import java.util.Date; - import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.tweetalib.android.TwitterManager; import org.tweetalib.android.TwitterUtil; +import java.text.ParseException; +import java.util.Date; + +import twitter4j.URLEntity; + public class AdnPost { public long mId; @@ -33,9 +35,12 @@ public class AdnPost { public boolean mIsRetweetedByMe; public boolean mIsFavorited; public AdnUser mOriginalAuthor; + public long mOriginalId; public AdnMedia mEmbeddedMedia; + public URLEntity[] mUrls; - public AdnPost() {} + public AdnPost() { + } public AdnPost(String jsonAsString) { try { @@ -56,6 +61,7 @@ public AdnPost(String jsonAsString) { AdnPost repost = new AdnPost(object.getJSONObject("repost_of") .toString()); mOriginalAuthor = repost.mUser; + mOriginalId = repost.mId; mText = repost.mText; mEmbeddedMedia = repost.mEmbeddedMedia; } @@ -112,6 +118,17 @@ public AdnPost(String jsonAsString) { } } } + if (entities.has("links")) { + JSONArray jsonArray = entities.getJSONArray("links"); + mUrls = new URLEntity[jsonArray.length()]; + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject link = jsonArray.getJSONObject(i); + if (link.has("text") && link.has("url")) { + URLEntity url = new AdnUrl(link.getString("text"),link.getString("url")); + mUrls[i] = url; + } + } + } } if (object.has("annotations")) { diff --git a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnPostCompose.java b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnPostCompose.java index d7329f00..a5371ba1 100644 --- a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnPostCompose.java +++ b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnPostCompose.java @@ -20,9 +20,9 @@ public class AdnPostCompose { - public String mText; + public final String mText; public String mInReplyTo; - public File mMediaFile; + public final File mMediaFile; public AdnPostCompose(String text, Long inReplyTo, File mediaFile) { mText = text; diff --git a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnPosts.java b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnPosts.java index 5963833e..1f536113 100644 --- a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnPosts.java +++ b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnPosts.java @@ -11,12 +11,12 @@ package org.appdotnet4j.model; -import java.util.ArrayList; - import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import java.util.ArrayList; + public class AdnPosts { public ArrayList mPosts; diff --git a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnUrl.java b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnUrl.java new file mode 100644 index 00000000..20dd124a --- /dev/null +++ b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnUrl.java @@ -0,0 +1,44 @@ +package org.appdotnet4j.model; + +import twitter4j.URLEntity; + +public class AdnUrl implements URLEntity { + + private String text; + private String url; + + public AdnUrl(String text, String url){ + this.text = text; + this.url = url; + } + + @Override + public String getText() { + return text; + } + + @Override + public String getURL() { + return url; + } + + @Override + public String getExpandedURL() { + return url; + } + + @Override + public String getDisplayURL() { + return text; + } + + @Override + public int getStart() { + return 0; + } + + @Override + public int getEnd() { + return 0; + } +} diff --git a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnUser.java b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnUser.java index cb8a2bc7..fe61b888 100644 --- a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnUser.java +++ b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnUser.java @@ -23,7 +23,6 @@ public class AdnUser { public int mFollowersCount; public int mFollowingCount; public int mPostCount; - public String mAvatarUrl; public String mCoverUrl; public boolean mFollowsCurrentUser; public boolean mCurrentUserFollows; @@ -58,7 +57,6 @@ public AdnUser(String jsonAsString) { if (object.has("avatar_image")) { JSONObject avatar = object.getJSONObject("avatar_image"); - mAvatarUrl = avatar.getString("url"); } if (object.has("cover_image")) { diff --git a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnUsers.java b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnUsers.java index 91aa140e..c17b3b4a 100644 --- a/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnUsers.java +++ b/android/libraries/SocialNetLib/src/org/appdotnet4j/model/AdnUsers.java @@ -11,12 +11,12 @@ package org.appdotnet4j.model; -import java.util.ArrayList; - import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import java.util.ArrayList; + public class AdnUsers { public ArrayList mUsers; diff --git a/android/libraries/SocialNetLib/src/org/asynctasktex/AsyncTaskEx.java b/android/libraries/SocialNetLib/src/org/asynctasktex/AsyncTaskEx.java index 0d0f7f32..014440f9 100644 --- a/android/libraries/SocialNetLib/src/org/asynctasktex/AsyncTaskEx.java +++ b/android/libraries/SocialNetLib/src/org/asynctasktex/AsyncTaskEx.java @@ -32,11 +32,15 @@ * the License. */ +import android.os.Handler; +import android.os.Message; +import android.os.Process; + import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; -import java.util.concurrent.Executor; import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; @@ -46,17 +50,13 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import android.os.Handler; -import android.os.Message; -import android.os.Process; - /** *

* AsyncTask enables proper and easy use of the UI thread. This class allows to * perform background operations and publish results on the UI thread without * having to manipulate threads and/or handlers. *

- * + *

*

* AsyncTask is designed to be a helper class around {@link Thread} and * {@link Handler} and does not constitute a generic threading framework. @@ -66,7 +66,7 @@ * java.util.concurrent pacakge such as {@link Executor}, * {@link ThreadPoolExecutor} and {@link FutureTask}. *

- * + *

*

* An asynchronous task is defined by a computation that runs on a background * thread and whose result is published on the UI thread. An asynchronous task @@ -75,7 +75,7 @@ * onPreExecute, doInBackground, * onProgressUpdate and onPostExecute. *

- * + *

*

Developer Guides

*

* For more information about using tasks and threads, read the developer guide. *

*
- * + *

*

Usage

*

* AsyncTask must be subclassed to be used. The subclass will override at least * one method ( {@link #doInBackground}), and most often will override a second * one ({@link #onPostExecute}.) *

- * + *

*

* Here is an example of subclassing: *

- * + *

*

  * private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
- *     protected Long doInBackground(URL... urls) {
- *         int count = urls.length;
- *         long totalSize = 0;
- *         for (int i = 0; i < count; i++) {
- *             totalSize += Downloader.downloadFile(urls[i]);
- *             publishProgress((int) ((i / (float) count) * 100));
- *             // Escape early if cancel() is called
- *             if (isCancelled()) break;
- *         }
- *         return totalSize;
- *     }
- * 
- *     protected void onProgressUpdate(Integer... progress) {
- *         setProgressPercent(progress[0]);
- *     }
- * 
- *     protected void onPostExecute(Long result) {
- *         showDialog("Downloaded " + result + " bytes");
- *     }
+ * protected Long doInBackground(URL... urls) {
+ * int count = urls.length;
+ * long totalSize = 0;
+ * for (int i = 0; i < count; i++) {
+ * totalSize += Downloader.downloadFile(urls[i]);
+ * publishProgress((int) ((i / (float) count) * 100));
+ * // Escape early if cancel() is called
+ * if (isCancelled()) break;
+ * }
+ * return totalSize;
+ * }
+ * 

+ * protected void onProgressUpdate(Integer... progress) { + * setProgressPercent(progress[0]); + * } + *

+ * protected void onPostExecute(Long result) { + * showDialog("Downloaded " + result + " bytes"); + * } * } *

- * + *

*

* Once created, a task is executed very simply: *

- * + *

*

  * new DownloadFilesTask().execute(url1, url2, url3);
  * 
- * + *

*

AsyncTask's generic types

*

* The three types used by an asynchronous task are the following: @@ -144,11 +144,11 @@ * Not all types are always used by an asynchronous task. To mark a type as * unused, simply use the type {@link Void}: *

- * + *

*

  * private class MyTask extends AsyncTask<Void, Void, Void> { ... }
  * 
- * + *

*

The 4 steps

*

* When an asynchronous task is executed, the task goes through 4 steps: @@ -174,7 +174,7 @@ * computation finishes. The result of the background computation is passed to * this step as a parameter. * - * + *

*

Cancelling a task

*

* A task can be cancelled at any time by invoking {@link #cancel(boolean)}. @@ -186,7 +186,7 @@ * {@link #isCancelled()} periodically from {@link #doInBackground(Object[])}, * if possible (inside a loop for instance.) *

- * + *

*

Threading rules

*

* There are a few threading rules that must be followed for this class to work @@ -202,7 +202,7 @@ *

  • The task can be executed only once (an exception will be thrown if a * second execution is attempted.)
  • * - * + *

    *

    Memory observability

    *

    * AsyncTask guarantees that all callback calls are synchronized in such a way @@ -214,7 +214,7 @@ *

  • Set member fields in {@link #doInBackground}, and refer to them in * {@link #onProgressUpdate} and {@link #onPostExecute}. * - * + *

    *

    Order of execution

    *

    * When first introduced, AsyncTasks were executed serially on a single @@ -245,7 +245,8 @@ public abstract class AsyncTaskEx { public static final int PRIORITY_LOW = 1; public static final int PRIORITY_MEDIUM = 2; public static final int PRIORITY_HIGH = 3; - public static final int PRIORITY_HIGHEST = 7; + public static final int PRIORITY_NOT_QUITE_HIGHEST = 4; + public static final int PRIORITY_HIGHEST = 5; private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); @@ -269,7 +270,7 @@ public Thread newThread(Runnable r) { * An {@link Executor} that executes tasks one at a time in serial order. * This serialization is global to a particular process. */ - public static final PriorityExecutor DEFAULT_EXECUTOR = new PriorityExecutor(); + private static final PriorityExecutor DEFAULT_EXECUTOR = new PriorityExecutor(); // public static final SerialExecutor DEFAULT_EXECUTOR = new // SerialExecutor(); @@ -281,8 +282,6 @@ public Thread newThread(Runnable r) { private static volatile BaseExecutor sDefaultExecutor = DEFAULT_EXECUTOR; private final WorkerRunnable mWorker; private final FutureTask mFuture; - private int mPriority; - private String mDescription; private volatile Status mStatus = Status.PENDING; private final AtomicBoolean mCancelled = new AtomicBoolean(); @@ -307,16 +306,13 @@ public enum Status { FINISHED, } - /** @hide Used to force static handler to be created. */ + /** + * @hide Used to force static handler to be created. + */ public static void init() { sHandler.getLooper(); } - /** @hide */ - public static void setDefaultExecutor(PriorityExecutor exec) { - sDefaultExecutor = exec; - } - /** * Creates a new asynchronous task. This constructor must be invoked on the * UI thread. @@ -370,7 +366,7 @@ private Result postResult(Result result) { /** * Returns the current status of this task. - * + * * @return The current status. */ public final Status getStatus() { @@ -381,15 +377,12 @@ public final Status getStatus() { * Override this method to perform a computation on a background thread. The * specified parameters are the parameters passed to {@link #execute} by the * caller of this task. - * + *

    * This method can call {@link #publishProgress} to publish updates on the * UI thread. - * - * @param params - * The parameters of the task. - * + * + * @param params The parameters of the task. * @return A result, defined by the subclass of this task. - * * @see #onPreExecute() * @see #onPostExecute * @see #publishProgress @@ -398,11 +391,11 @@ public final Status getStatus() { /** * Runs on the UI thread before {@link #doInBackground}. - * + * * @see #onPostExecute * @see #doInBackground */ - protected void onPreExecute() { + void onPreExecute() { } /** @@ -410,34 +403,30 @@ protected void onPreExecute() { * Runs on the UI thread after {@link #doInBackground}. The specified result * is the value returned by {@link #doInBackground}. *

    - * + *

    *

    * This method won't be invoked if the task was cancelled. *

    - * - * @param result - * The result of the operation computed by - * {@link #doInBackground}. - * + * + * @param result The result of the operation computed by + * {@link #doInBackground}. * @see #onPreExecute * @see #doInBackground * @see #onCancelled(Object) */ - @SuppressWarnings({ "UnusedDeclaration" }) + @SuppressWarnings({"UnusedDeclaration"}) protected void onPostExecute(Result result) { } /** * Runs on the UI thread after {@link #publishProgress} is invoked. The * specified values are the values passed to {@link #publishProgress}. - * - * @param values - * The values indicating progress. - * + * + * @param values The values indicating progress. * @see #publishProgress * @see #doInBackground */ - @SuppressWarnings({ "UnusedDeclaration" }) + @SuppressWarnings({"UnusedDeclaration"}) protected void onProgressUpdate(Progress... values) { } @@ -446,22 +435,20 @@ protected void onProgressUpdate(Progress... values) { * Runs on the UI thread after {@link #cancel(boolean)} is invoked and * {@link #doInBackground(Object[])} has finished. *

    - * + *

    *

    * The default implementation simply invokes {@link #onCancelled()} and * ignores the result. If you write your own implementation, do not call * super.onCancelled(result). *

    - * - * @param result - * The result, if any, computed in - * {@link #doInBackground(Object[])}, can be null - * + * + * @param result The result, if any, computed in + * {@link #doInBackground(Object[])}, can be null * @see #cancel(boolean) * @see #isCancelled() */ - @SuppressWarnings({ "UnusedParameters" }) - protected void onCancelled(Result result) { + @SuppressWarnings({"UnusedParameters"}) + void onCancelled(Result result) { onCancelled(); } @@ -471,17 +458,17 @@ protected void onCancelled(Result result) { * This method is invoked by the default implementation of * {@link #onCancelled(Object)}. *

    - * + *

    *

    * Runs on the UI thread after {@link #cancel(boolean)} is invoked and * {@link #doInBackground(Object[])} has finished. *

    - * + * * @see #onCancelled(Object) * @see #cancel(boolean) * @see #isCancelled() */ - protected void onCancelled() { + void onCancelled() { } /** @@ -489,12 +476,11 @@ protected void onCancelled() { * normally. If you are calling {@link #cancel(boolean)} on the task, the * value returned by this method should be checked periodically from * {@link #doInBackground(Object[])} to end the task as soon as possible. - * + * * @return true if task was cancelled before it completed - * * @see #cancel(boolean) */ - public final boolean isCancelled() { + final boolean isCancelled() { return mCancelled.get(); } @@ -508,7 +494,7 @@ public final boolean isCancelled() { * parameter determines whether the thread executing this task should be * interrupted in an attempt to stop the task. *

    - * + *

    *

    * Calling this method will result in {@link #onCancelled(Object)} being * invoked on the UI thread after {@link #doInBackground(Object[])} returns. @@ -518,16 +504,13 @@ public final boolean isCancelled() { * {@link #doInBackground(Object[])} to finish the task as early as * possible. *

    - * - * @param mayInterruptIfRunning - * true if the thread executing this task should be - * interrupted; otherwise, in-progress tasks are allowed to - * complete. - * + * + * @param mayInterruptIfRunning true if the thread executing this task should be + * interrupted; otherwise, in-progress tasks are allowed to + * complete. * @return false if the task could not be cancelled, typically * because it has already completed normally; true * otherwise - * * @see #isCancelled() * @see #onCancelled(Object) */ @@ -539,15 +522,11 @@ public final boolean cancel(boolean mayInterruptIfRunning) { /** * Waits if necessary for the computation to complete, and then retrieves * its result. - * + * * @return The computed result. - * - * @throws CancellationException - * If the computation was cancelled. - * @throws ExecutionException - * If the computation threw an exception. - * @throws InterruptedException - * If the current thread was interrupted while waiting. + * @throws CancellationException If the computation was cancelled. + * @throws ExecutionException If the computation threw an exception. + * @throws InterruptedException If the current thread was interrupted while waiting. */ public final Result get() throws InterruptedException, ExecutionException { return mFuture.get(); @@ -556,22 +535,14 @@ public final Result get() throws InterruptedException, ExecutionException { /** * Waits if necessary for at most the given time for the computation to * complete, and then retrieves its result. - * - * @param timeout - * Time to wait before cancelling the operation. - * @param unit - * The time unit for the timeout. - * + * + * @param timeout Time to wait before cancelling the operation. + * @param unit The time unit for the timeout. * @return The computed result. - * - * @throws CancellationException - * If the computation was cancelled. - * @throws ExecutionException - * If the computation threw an exception. - * @throws InterruptedException - * If the current thread was interrupted while waiting. - * @throws TimeoutException - * If the wait timed out. + * @throws CancellationException If the computation was cancelled. + * @throws ExecutionException If the computation threw an exception. + * @throws InterruptedException If the current thread was interrupted while waiting. + * @throws TimeoutException If the wait timed out. */ public final Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { @@ -581,8 +552,8 @@ public final Result get(long timeout, TimeUnit unit) /** * Executes the task with the specified parameters. The task returns itself * (this) so that the caller can keep a reference to it. - * - *

    + *

    + *

    * Note: this function schedules the task on a queue for a single background * thread or pool of threads depending on the platform version. When first * introduced, AsyncTasks were executed serially on a single background @@ -594,30 +565,25 @@ public final Result get(long timeout, TimeUnit unit) * parallel execution, you can use the {@link #executeOnExecutor} version of * this method with {@link #THREAD_POOL_EXECUTOR}; however, see commentary * there for warnings on its use. - * - *

    + *

    + *

    * This method must be invoked on the UI thread. - * - * @param params - * The parameters of the task. - * + * + * @param params The parameters of the task. * @return This instance of AsyncTask. - * - * @throws IllegalStateException - * If {@link #getStatus()} returns either - * {@link AsyncTask.Status#RUNNING} or - * {@link AsyncTask.Status#FINISHED}. - * + * @throws IllegalStateException If {@link #getStatus()} returns either + * {@link AsyncTask.Status#RUNNING} or + * {@link AsyncTask.Status#FINISHED}. * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) * @see #execute(Runnable) */ public final AsyncTaskEx execute(int priority, - Params... params) { + Params... params) { return execute(priority, null, params); } public final AsyncTaskEx execute(int priority, - String description, Params... params) { + String description, Params... params) { return executeOnExecutor(sDefaultExecutor, priority, description, params); } @@ -625,14 +591,14 @@ public final AsyncTaskEx execute(int priority, /** * Executes the task with the specified parameters. The task returns itself * (this) so that the caller can keep a reference to it. - * - *

    + *

    + *

    * This method is typically used with {@link #THREAD_POOL_EXECUTOR} to allow * multiple tasks to run in parallel on a pool of threads managed by * AsyncTask, however you can also use your own {@link Executor} for custom * behavior. - * - *

    + *

    + *

    * Warning: Allowing multiple tasks to run in parallel from a * thread pool is generally not what one wants, because the order * of their operation is not defined. For example, if these tasks are used @@ -643,45 +609,37 @@ public final AsyncTaskEx execute(int priority, * loss and stability issues. Such changes are best executed in serial; to * guarantee such work is serialized regardless of platform version you can * use this function with {@link #DEFAULT_EXECUTOR}. - * - *

    + *

    + *

    * This method must be invoked on the UI thread. - * - * @param exec - * The executor to use. {@link #THREAD_POOL_EXECUTOR} is - * available as a convenient process-wide thread pool for tasks - * that are loosely coupled. - * @param params - * The parameters of the task. - * + * + * @param exec The executor to use. {@link #THREAD_POOL_EXECUTOR} is + * available as a convenient process-wide thread pool for tasks + * that are loosely coupled. + * @param params The parameters of the task. * @return This instance of AsyncTask. - * - * @throws IllegalStateException - * If {@link #getStatus()} returns either - * {@link AsyncTask.Status#RUNNING} or - * {@link AsyncTask.Status#FINISHED}. - * + * @throws IllegalStateException If {@link #getStatus()} returns either + * {@link AsyncTask.Status#RUNNING} or + * {@link AsyncTask.Status#FINISHED}. * @see #execute(Object[]) */ - public final AsyncTaskEx executeOnExecutor( + final AsyncTaskEx executeOnExecutor( BaseExecutor exec, int priority, String description, Params... params) { if (mStatus != Status.PENDING) { switch (mStatus) { - case RUNNING: - throw new IllegalStateException("Cannot execute task:" - + " the task is already running."); - case FINISHED: - throw new IllegalStateException("Cannot execute task:" - + " the task has already been executed " - + "(a task can be executed only once)"); - default: - break; + case RUNNING: + throw new IllegalStateException("Cannot execute task:" + + " the task is already running."); + case FINISHED: + throw new IllegalStateException("Cannot execute task:" + + " the task has already been executed " + + "(a task can be executed only once)"); + default: + break; } } - mDescription = description; - mPriority = priority; mStatus = Status.RUNNING; onPreExecute(); @@ -695,7 +653,7 @@ public final AsyncTaskEx executeOnExecutor( * Convenience version of {@link #execute(Object...)} for use with a simple * Runnable object. See {@link #execute(Object[])} for more information on * the order of execution. - * + * * @see #execute(Object[]) * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) */ @@ -708,13 +666,11 @@ public static void execute(Runnable runnable) { * updates on the UI thread while the background computation is still * running. Each call to this method will trigger the execution of * {@link #onProgressUpdate} on the UI thread. - * + *

    * {@link #onProgressUpdate} will note be called if the task has been * canceled. - * - * @param values - * The progress values to update the UI with. - * + * + * @param values The progress values to update the UI with. * @see #onProgressUpdate * @see #doInBackground */ @@ -736,18 +692,18 @@ private void finish(Result result) { } private static class InternalHandler extends Handler { - @SuppressWarnings({ "unchecked", "RawUseOfParameterizedType" }) + @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override public void handleMessage(Message msg) { PrioritizedAsyncTaskResult result = (PrioritizedAsyncTaskResult) msg.obj; switch (msg.what) { - case MESSAGE_POST_RESULT: - // There is only one result - result.mTask.finish(result.mData[0]); - break; - case MESSAGE_POST_PROGRESS: - result.mTask.onProgressUpdate(result.mData); - break; + case MESSAGE_POST_RESULT: + // There is only one result + result.mTask.finish(result.mData[0]); + break; + case MESSAGE_POST_PROGRESS: + result.mTask.onProgressUpdate(result.mData); + break; } } } @@ -757,7 +713,7 @@ private static abstract class WorkerRunnable implements Params[] mParams; } - @SuppressWarnings({ "RawUseOfParameterizedType" }) + @SuppressWarnings({"RawUseOfParameterizedType"}) private static class PrioritizedAsyncTaskResult { final AsyncTaskEx mTask; final Data[] mData; diff --git a/android/libraries/SocialNetLib/src/org/asynctasktex/BaseExecutor.java b/android/libraries/SocialNetLib/src/org/asynctasktex/BaseExecutor.java index 12d9a6f9..e056f9e7 100644 --- a/android/libraries/SocialNetLib/src/org/asynctasktex/BaseExecutor.java +++ b/android/libraries/SocialNetLib/src/org/asynctasktex/BaseExecutor.java @@ -20,4 +20,4 @@ interface BaseExecutor extends Executor { public void execute(int priority, final Runnable r); -}; \ No newline at end of file +} \ No newline at end of file diff --git a/android/libraries/SocialNetLib/src/org/asynctasktex/PriorityExecutor.java b/android/libraries/SocialNetLib/src/org/asynctasktex/PriorityExecutor.java index 21195aad..d311decd 100644 --- a/android/libraries/SocialNetLib/src/org/asynctasktex/PriorityExecutor.java +++ b/android/libraries/SocialNetLib/src/org/asynctasktex/PriorityExecutor.java @@ -26,8 +26,8 @@ class PriorityExecutor implements BaseExecutor { * */ private static class PrioritizedRunnable { - public Runnable mRunnable; - public int mPriority; + public final Runnable mRunnable; + public final int mPriority; public PrioritizedRunnable(int priority, Runnable runnable) { mPriority = priority; @@ -38,7 +38,7 @@ public PrioritizedRunnable(int priority, Runnable runnable) { /* * */ - public static class PrioritizedRunnableComparator implements + private static class PrioritizedRunnableComparator implements Comparator { @Override public int compare(PrioritizedRunnable left, PrioritizedRunnable right) { @@ -46,8 +46,8 @@ public int compare(PrioritizedRunnable left, PrioritizedRunnable right) { } } - final ArrayList mTasks = new ArrayList(); - PrioritizedRunnable mActive; + private final ArrayList mTasks = new ArrayList(); + private PrioritizedRunnable mActive; /* * (non-Javadoc) @@ -85,7 +85,7 @@ public synchronized void execute(final Runnable r) { /* * */ - protected synchronized void scheduleNext() { + synchronized void scheduleNext() { if (mTasks.size() > 0) { mActive = mTasks.get(0); diff --git a/android/libraries/SocialNetLib/src/org/asynctasktex/SerialExecutor.java b/android/libraries/SocialNetLib/src/org/asynctasktex/SerialExecutor.java index 5f7d5ab1..3a40bd84 100644 --- a/android/libraries/SocialNetLib/src/org/asynctasktex/SerialExecutor.java +++ b/android/libraries/SocialNetLib/src/org/asynctasktex/SerialExecutor.java @@ -19,8 +19,8 @@ import java.util.ArrayDeque; class SerialExecutor implements BaseExecutor { - final ArrayDeque mTasks = new ArrayDeque(); - Runnable mActive; + private final ArrayDeque mTasks = new ArrayDeque(); + private Runnable mActive; @Override public synchronized void execute(int priority, Runnable r) { @@ -42,7 +42,7 @@ public void run() { } } - protected synchronized void scheduleNext() { + synchronized void scheduleNext() { if ((mActive = mTasks.poll()) != null) { AsyncTaskEx.THREAD_POOL_EXECUTOR.execute(mActive); } diff --git a/android/libraries/SocialNetLib/src/org/socialnetlib/android/AppdotnetApi.java b/android/libraries/SocialNetLib/src/org/socialnetlib/android/AppdotnetApi.java index aeeb323d..9f1f777a 100644 --- a/android/libraries/SocialNetLib/src/org/socialnetlib/android/AppdotnetApi.java +++ b/android/libraries/SocialNetLib/src/org/socialnetlib/android/AppdotnetApi.java @@ -14,17 +14,26 @@ import com.turbomanage.httpclient.BasicHttpClient; import com.turbomanage.httpclient.HttpResponse; import com.turbomanage.httpclient.ParameterMap; -import org.appdotnet4j.model.*; + +import org.appdotnet4j.model.AdnFile; +import org.appdotnet4j.model.AdnInteractions; +import org.appdotnet4j.model.AdnPaging; +import org.appdotnet4j.model.AdnPost; +import org.appdotnet4j.model.AdnPostCompose; +import org.appdotnet4j.model.AdnPosts; +import org.appdotnet4j.model.AdnUser; +import org.appdotnet4j.model.AdnUsers; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.tweetalib.android.model.TwitterUser; -import twitter4j.Twitter; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; +import twitter4j.Twitter; + public class AppdotnetApi extends SocialNetApi { /* @@ -46,10 +55,7 @@ boolean isResponseValid(HttpResponse httpResponse) { return false; } int status = httpResponse.getStatus(); - if (status >= 200 && status < 300) { - return true; - } - return false; + return status >= 200 && status < 300; } BasicHttpClient getHttpClient() { @@ -78,8 +84,7 @@ String doGet(String path, ParameterMap params, String accessToken) { HttpResponse httpResponse = getHttpClient(accessToken) .get(path, params); if (isResponseValid(httpResponse)) { - String body = httpResponse.getBodyAsString(); - return body; + return httpResponse.getBodyAsString(); } return null; } @@ -89,8 +94,7 @@ String doPost(String path, JSONObject json) { HttpResponse httpResponse = getHttpClient().post(path, "application/json", data); if (isResponseValid(httpResponse)) { - String body = httpResponse.getBodyAsString(); - return body; + return httpResponse.getBodyAsString(); } return null; } @@ -121,7 +125,7 @@ public TwitterUser verifyCredentialsSync(String oAuthToken, } /* - * + * */ public TwitterUser getAdnUser(long userId) { @@ -266,8 +270,7 @@ private AdnPosts getPosts(String path, ParameterMap params, AdnPaging paging) { } String streamString = doGet(path, params); if (streamString != null) { - AdnPosts posts = new AdnPosts(streamString); - return posts; + return new AdnPosts(streamString); } return null; @@ -278,9 +281,8 @@ private AdnInteractions getInteractions(String path, ParameterMap params) { params = new ParameterMap(); } String interactionString = doGet(path, params); - if (interactionString!= null) { - AdnInteractions interactions = new AdnInteractions(interactionString); - return interactions; + if (interactionString != null) { + return new AdnInteractions(interactionString); } return null; @@ -292,8 +294,7 @@ private AdnUsers getUsers(String path, ParameterMap params) { } String userString = doGet(path, params); if (userString != null) { - AdnUsers users = new AdnUsers(userString); - return users; + return new AdnUsers(userString); } return null; @@ -303,7 +304,9 @@ private AdnUsers getUsers(String path, ParameterMap params) { * */ public AdnPost getAdnPost(long id) { - String postString = doGet("/stream/0/posts/" + id, null); + ParameterMap params = new ParameterMap(); + params.add("include_post_annotations", "1"); + String postString = doGet("/stream/0/posts/" + id, params); if (postString != null) { return new AdnPost(postString); } @@ -316,8 +319,8 @@ public AdnPost setAdnStatus(AdnPostCompose compose) { try { post = new JSONObject() - .put("text", compose.mText) - .put("reply_to", compose.mInReplyTo); + .put("text", compose.mText) + .put("reply_to", compose.mInReplyTo); if (compose.mMediaFile != null) { @@ -335,8 +338,7 @@ public AdnPost setAdnStatus(AdnPostCompose compose) { post.put("annotations", new JSONArray().put(ann)); } - } - catch (JSONException e) { + } catch (JSONException e) { e.printStackTrace(); return null; } @@ -354,10 +356,10 @@ private AdnFile setAdnFile(File file) { JSONObject json; try { json = new JSONObject() - .put("kind", "image") - .put("type", "com.tweetlanes.image") - .put("public", "0") - .put("name", file.getName()); + .put("kind", "image") + .put("type", "com.tweetlanes.image") + .put("public", "0") + .put("name", file.getName()); JSONObject response = new JSONObject(doPost("/stream/0/files", json)); if (response.has("data")) { @@ -375,19 +377,15 @@ private AdnFile setAdnFile(File file) { if (isResponseValid(httpResponse)) { return new AdnFile(id, fileToken); } - } - catch (JSONException e) { + } catch (JSONException e) { e.printStackTrace(); return null; - } - catch (IOException e) { + } catch (IOException e) { e.printStackTrace(); return null; } - - return null; } @@ -427,8 +425,7 @@ public AdnPost setAdnFavorite(long existingPostId, boolean favorite) { HttpResponse httpResponse; if (favorite) { httpResponse = httpClient.post("/stream/0/posts/" + existingPostId + "/star", null); - } - else { + } else { httpResponse = httpClient.delete("/stream/0/posts/" + existingPostId + "/star", null); } @@ -447,7 +444,8 @@ public AdnUser setAdnFollow(String username, boolean follow) { if (follow) { return followUser(username); } else { - return unfollowUser(username); + unfollowUser(username); + return null; } } @@ -455,7 +453,8 @@ public AdnUser setAdnFollow(long userId, boolean follow) { if (follow) { return followUser(userId); } else { - return unfollowUser(userId); + unfollowUser(userId); + return null; } } @@ -485,16 +484,14 @@ private AdnUser followUser(String username) { return null; } - private AdnUser unfollowUser(long userId) { + private void unfollowUser(long userId) { BasicHttpClient httpClient = getHttpClient(); httpClient.delete("/stream/0/users/" + userId + "/follow", null); - return null; } - private AdnUser unfollowUser(String username) { + private void unfollowUser(String username) { BasicHttpClient httpClient = getHttpClient(); httpClient.delete("/stream/0/users/@" + username + "/follow", null); - return null; } @Override @@ -512,7 +509,7 @@ public SocialNetConstant.Type getSocialNetType() { return SocialNetConstant.Type.Appdotnet; } - private static byte[] readFile (File file) throws IOException { + private static byte[] readFile(File file) throws IOException { // Open file RandomAccessFile f = new RandomAccessFile(file, "r"); @@ -526,8 +523,7 @@ private static byte[] readFile (File file) throws IOException { byte[] data = new byte[length]; f.readFully(data); return data; - } - finally { + } finally { f.close(); } } diff --git a/android/libraries/SocialNetLib/src/org/socialnetlib/android/SocialNetApi.java b/android/libraries/SocialNetLib/src/org/socialnetlib/android/SocialNetApi.java index 6080e7d5..72784b45 100644 --- a/android/libraries/SocialNetLib/src/org/socialnetlib/android/SocialNetApi.java +++ b/android/libraries/SocialNetLib/src/org/socialnetlib/android/SocialNetApi.java @@ -53,28 +53,28 @@ public abstract class SocialNetApi { - public abstract void init(); + protected abstract void init(); - public abstract TwitterUser verifyCredentialsSync(String oAuthToken, - String oAuthSecret); + protected abstract TwitterUser verifyCredentialsSync(String oAuthToken, + String oAuthSecret); abstract Twitter getAndConfigureApiInstance(); abstract void clearApiInstance(); - SocialNetConstant.Type mType; + private final SocialNetConstant.Type mType; String mCurrentOAuthToken; String mCurrentOAuthSecret; - String mAppConsumerKey; - String mAppConsumerSecret; - String mCurrentAccountKey; + final String mAppConsumerKey; + final String mAppConsumerSecret; + private final String mCurrentAccountKey; private TwitterFetchBooleans mFetchBooleans; private TwitterFetchDirectMessages mFetchDirectMessages; private TwitterFetchStatus mFetchStatus; private TwitterFetchStatuses mFetchStatuses; private TwitterFetchUser mFetchUser; - protected TwitterFetchUsers mFetchUsers; + private TwitterFetchUsers mFetchUsers; private TwitterFetchLists mFetchLists; private TwitterModifyStatuses mModifyStatuses; private TwitterSignIn mSignIn; @@ -263,7 +263,7 @@ public AppdotnetApi getAppdotnetApi() { mFetchUser.setWorkerCallbacks(callbacks); } - protected AppdotnetApi getAppdotnetApi() { + AppdotnetApi getAppdotnetApi() { if (mType == SocialNetConstant.Type.Appdotnet) { return (AppdotnetApi) this; @@ -413,15 +413,15 @@ public void setOAuthTokenWithSecret(String oAuthToken, String oAuthSecret, if (oAuthToken == null && mCurrentOAuthToken == null) { return; } else if (oAuthToken != null && mCurrentOAuthToken != null - && oAuthToken.equals(mCurrentOAuthToken) == true) { + && oAuthToken.equals(mCurrentOAuthToken)) { return; } else if (oAuthSecret != null && mCurrentOAuthSecret != null - && oAuthSecret.equals(mCurrentOAuthSecret) == true) { + && oAuthSecret.equals(mCurrentOAuthSecret)) { return; } - if (cancelPending == true) { + if (cancelPending) { mFetchBooleans.clearCallbacks(); mFetchLists.clearCallbacks(); mFetchDirectMessages.clearCallbacks(); @@ -480,16 +480,14 @@ public TwitterUser getUser(Long userId) { public TwitterUser getUser(Long userId, TwitterFetchUser.FinishedCallback callback) { - TwitterUser cachedUser = mFetchUser.getUser(userId, callback, + return mFetchUser.getUser(userId, callback, mConnectionStatus); - return cachedUser; } public TwitterUser getUser(String screenName, TwitterFetchUser.FinishedCallback callback) { - TwitterUser cachedUser = mFetchUser.getUser(screenName, callback, + return mFetchUser.getUser(screenName, callback, mConnectionStatus); - return cachedUser; } public void verifyUser(TwitterFetchUser.FinishedCallback callback) { @@ -501,15 +499,13 @@ public void verifyUser(TwitterFetchUser.FinishedCallback callback) { */ public TwitterUsers getUsers(TwitterContentHandle contentHandle, TwitterPaging paging) { - TwitterUsers cachedUsers = mFetchUsers.getUsers(contentHandle, paging); - return cachedUsers; + return mFetchUsers.getUsers(contentHandle, paging); } public TwitterUsers getUsers(TwitterContentHandle contentHandle, TwitterPaging paging, TwitterFetchUsers.FinishedCallback callback) { - TwitterUsers cachedUsers = mFetchUsers.getUsers(contentHandle, paging, + return mFetchUsers.getUsers(contentHandle, paging, callback, mConnectionStatus); - return cachedUsers; } /* @@ -517,18 +513,16 @@ public TwitterUsers getUsers(TwitterContentHandle contentHandle, */ public TwitterDirectMessages getDirectMessages( TwitterContentHandle contentHandle) { - TwitterDirectMessages cachedMessages = mFetchDirectMessages + return mFetchDirectMessages .getDirectMessages(contentHandle); - return cachedMessages; } public TwitterDirectMessages getDirectMessages( TwitterContentHandle contentHandle, TwitterPaging paging, TwitterFetchDirectMessagesFinishedCallback callback) { - TwitterDirectMessages cachedMessages = mFetchDirectMessages + return mFetchDirectMessages .getDirectMessages(contentHandle, paging, callback, mConnectionStatus); - return cachedMessages; } public void sendDirectMessage(long userId, String recipientScreenName, @@ -613,29 +607,14 @@ public void reportSpam(long currentUserId, ArrayList userIds, mConnectionStatus); } - /* - * - */ - public TwitterLists getLists(int userId) { - TwitterLists cachedLists = mFetchLists.getLists(userId, null); - return cachedLists; - } - public TwitterLists getLists(int userId, TwitterFetchLists.FinishedCallback callback) { - TwitterLists cachedLists = mFetchLists.getLists(userId, callback); - return cachedLists; - } - - public TwitterLists getLists(String screenName) { - TwitterLists cachedLists = mFetchLists.getLists(screenName, null); - return cachedLists; + return mFetchLists.getLists(userId, callback); } public TwitterLists getLists(String screenName, TwitterFetchLists.FinishedCallback callback) { - TwitterLists cachedLists = mFetchLists.getLists(screenName, callback); - return cachedLists; + return mFetchLists.getLists(screenName, callback); } /* diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/ConnectionStatus.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/ConnectionStatus.java index ff408bf5..5e860e2d 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/ConnectionStatus.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/ConnectionStatus.java @@ -18,10 +18,10 @@ public class ConnectionStatus { - Callbacks mCallbacks; + private final Callbacks mCallbacks; /* - * + * */ public ConnectionStatus(Callbacks callbacks) { mCallbacks = callbacks; diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterConstant.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterConstant.java index 0d519779..c4564ae4 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterConstant.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterConstant.java @@ -29,7 +29,7 @@ public enum ContentType { public enum DirectMessagesType { ALL_MESSAGES, SENT_MESSAGE - }; + } public enum BooleanType { FRIENDSHIP_EXISTS, BLOCK_EXISTS, diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterContentHandle.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterContentHandle.java index 2798463b..543575ec 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterContentHandle.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterContentHandle.java @@ -19,12 +19,12 @@ public class TwitterContentHandle extends TwitterContentHandleBase { /** - * - */ + * + */ private static final long serialVersionUID = 231396385372202288L; - public TwitterContentHandle(TwitterContentHandleBase contentHandleBase, - String screenName, String identifier, String currentAccountKey) { + public TwitterContentHandle(TwitterContentHandleBase contentHandleBase, + String screenName, String identifier, String currentAccountKey) { super(contentHandleBase); mScreenName = screenName; @@ -34,9 +34,8 @@ public TwitterContentHandle(TwitterContentHandleBase contentHandleBase, } public String getKey() { - String key = mScreenNameLower + "_" + getEnumsAsString() + "_" + return mScreenNameLower + "_" + getEnumsAsString() + "_" + mIdentifier; - return key; } // TODO: Look at this and ensure there aren't savings to be had @@ -75,8 +74,8 @@ public String getCurrentAccountKey() { return mCurrentAccountKey; } - private String mScreenNameLower; - private String mScreenName; - private String mIdentifier; - private String mCurrentAccountKey; + private final String mScreenNameLower; + private final String mScreenName; + private final String mIdentifier; + private final String mCurrentAccountKey; } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterContentHandleBase.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterContentHandleBase.java index cf3de5b2..137664f3 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterContentHandleBase.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterContentHandleBase.java @@ -16,22 +16,22 @@ package org.tweetalib.android; -import java.io.Serializable; - import org.tweetalib.android.TwitterConstant.ContentType; import org.tweetalib.android.TwitterConstant.DirectMessagesType; import org.tweetalib.android.TwitterConstant.StatusType; import org.tweetalib.android.TwitterConstant.StatusesType; import org.tweetalib.android.TwitterConstant.UsersType; +import java.io.Serializable; + public class TwitterContentHandleBase implements Serializable { /** - * - */ + * + */ private static final long serialVersionUID = 4132026070249216175L; - public TwitterContentHandleBase(TwitterContentHandleBase other) { + TwitterContentHandleBase(TwitterContentHandleBase other) { mContentType = other.mContentType; mDirectMessagesType = other.mDirectMessagesType; mStatusType = other.mStatusType; @@ -40,7 +40,7 @@ public TwitterContentHandleBase(TwitterContentHandleBase other) { } public TwitterContentHandleBase(ContentType contentType, - DirectMessagesType directMessagesType) { + DirectMessagesType directMessagesType) { this(contentType, directMessagesType, null, null, null); } @@ -49,12 +49,12 @@ public TwitterContentHandleBase(ContentType contentType) { } public TwitterContentHandleBase(ContentType contentType, - StatusType statusType) { + StatusType statusType) { this(contentType, null, statusType, null, null); } public TwitterContentHandleBase(ContentType contentType, - StatusesType statusesType) { + StatusesType statusesType) { this(contentType, null, null, statusesType, null); } @@ -62,9 +62,9 @@ public TwitterContentHandleBase(ContentType contentType, UsersType usersType) { this(contentType, null, null, null, usersType); } - public TwitterContentHandleBase(ContentType contentType, - DirectMessagesType directMessagesType, StatusType statusType, - StatusesType statusesType, UsersType usersType) { + private TwitterContentHandleBase(ContentType contentType, + DirectMessagesType directMessagesType, StatusType statusType, + StatusesType statusesType, UsersType usersType) { mContentType = contentType; mDirectMessagesType = directMessagesType; mStatusType = statusType; @@ -72,7 +72,7 @@ public TwitterContentHandleBase(ContentType contentType, mUsersType = usersType; } - public String getTypeAsString() { + String getTypeAsString() { String result = mContentType.toString(); if (mDirectMessagesType != null) { result += "_" + mDirectMessagesType.toString(); @@ -89,18 +89,10 @@ public String getTypeAsString() { return result; } - public ContentType getContentType() { - return mContentType; - } - public DirectMessagesType getDirectMessagesType() { return mDirectMessagesType; } - public StatusType getStatusType() { - return mStatusType; - } - public StatusesType getStatusesType() { return mStatusesType; } @@ -109,9 +101,9 @@ public UsersType getUsersType() { return mUsersType; } - protected ContentType mContentType; - protected DirectMessagesType mDirectMessagesType; - protected StatusType mStatusType; - protected StatusesType mStatusesType; - protected UsersType mUsersType; + final ContentType mContentType; + private final DirectMessagesType mDirectMessagesType; + final StatusType mStatusType; + final StatusesType mStatusesType; + final UsersType mUsersType; } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchBooleans.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchBooleans.java index f005d8aa..7435173e 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchBooleans.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchBooleans.java @@ -11,14 +11,14 @@ package org.tweetalib.android; -import java.util.ArrayList; -import java.util.HashMap; - import org.asynctasktex.AsyncTaskEx; import org.socialnetlib.android.AppdotnetApi; import org.tweetalib.android.TwitterConstant.BooleanType; import org.tweetalib.android.model.TwitterUser; +import java.util.ArrayList; +import java.util.HashMap; + import twitter4j.Friendship; import twitter4j.ResponseList; import twitter4j.Twitter; @@ -28,10 +28,10 @@ public class TwitterFetchBooleans { private FetchBooleansWorkerCallbacks mCallbacks; private Integer mFetchBooleanCallbackHandle; - private HashMap mFinishedCallbackMap; + private final HashMap mFinishedCallbackMap; /* - * + * */ public void clearCallbacks() { if (mFinishedCallbackMap != null) { @@ -55,7 +55,7 @@ public interface FetchBooleansWorkerCallbacks { public interface FinishedCallbackInterface { public void finished(TwitterFetchResult result, - ArrayList returnValues); + ArrayList returnValues); } @@ -70,10 +70,6 @@ public FinishedCallback() { mHandle = kInvalidHandle; } - void setHandle(int handle) { - mHandle = handle; - } - private int mHandle; } @@ -100,8 +96,7 @@ public void setWorkerCallbacks(FetchBooleansWorkerCallbacks callbacks) { * */ FinishedCallback getFetchBooleanCallback(Integer callbackHandle) { - FinishedCallback callback = mFinishedCallbackMap.get(callbackHandle); - return callback; + return mFinishedCallbackMap.get(callbackHandle); } /* @@ -128,8 +123,8 @@ AppdotnetApi getAppdotnetInstance() { * */ public void getFriendshipExists(String userScreenName, - String userScreenNameToCheck, FinishedCallback callback, - ConnectionStatus connectionStatus) { + String userScreenNameToCheck, FinishedCallback callback, + ConnectionStatus connectionStatus) { triggerFetchBooleanTask(new FetchBooleanTaskInput( mFetchBooleanCallbackHandle, connectionStatus, @@ -141,9 +136,9 @@ public void getFriendshipExists(String userScreenName, * */ void triggerFetchBooleanTask(FetchBooleanTaskInput taskInput, - FinishedCallback callback, ConnectionStatus connectionStatus) { + FinishedCallback callback, ConnectionStatus connectionStatus) { - if (connectionStatus != null && connectionStatus.isOnline() == false) { + if (connectionStatus != null && !connectionStatus.isOnline()) { if (callback != null) { callback.finished(new TwitterFetchResult(false, connectionStatus.getErrorMessageNoConnection()), null); @@ -171,8 +166,8 @@ public void cancel(FinishedCallback callback) { class FetchBooleanTaskInput { FetchBooleanTaskInput(Integer callbackHandle, - ConnectionStatus connectionStatus, BooleanType booleanType, - String userScreenName, String userScreenNameToCheck) { + ConnectionStatus connectionStatus, BooleanType booleanType, + String userScreenName, String userScreenNameToCheck) { mCallbackHandle = callbackHandle; mConnectionStatus = connectionStatus; mBooleanType = booleanType; @@ -180,11 +175,11 @@ class FetchBooleanTaskInput { mUserScreenNameToCheck = userScreenNameToCheck; } - Integer mCallbackHandle; - ConnectionStatus mConnectionStatus; - BooleanType mBooleanType; - String mUserScreenName; - String mUserScreenNameToCheck; + final Integer mCallbackHandle; + final ConnectionStatus mConnectionStatus; + final BooleanType mBooleanType; + final String mUserScreenName; + final String mUserScreenNameToCheck; } /* @@ -193,7 +188,7 @@ class FetchBooleanTaskInput { class FetchBooleanTaskOutput { FetchBooleanTaskOutput(TwitterFetchResult result, - Integer callbackHandle, ArrayList returnValues) { + Integer callbackHandle, ArrayList returnValues) { mResult = result; mCallbackHandle = callbackHandle; if (returnValues != null) { @@ -201,8 +196,8 @@ class FetchBooleanTaskOutput { } } - TwitterFetchResult mResult; - Integer mCallbackHandle; + final TwitterFetchResult mResult; + final Integer mCallbackHandle; ArrayList mReturnValues; } @@ -222,7 +217,7 @@ protected FetchBooleanTaskOutput doInBackground( AppdotnetApi appdotnet = getAppdotnetInstance(); String errorDescription = null; - if (input.mConnectionStatus != null && input.mConnectionStatus.isOnline() == false) { + if (input.mConnectionStatus != null && !input.mConnectionStatus.isOnline()) { return new FetchBooleanTaskOutput(new TwitterFetchResult(false, input.mConnectionStatus.getErrorMessageNoConnection()), input.mCallbackHandle, null); @@ -231,20 +226,20 @@ protected FetchBooleanTaskOutput doInBackground( if (twitter != null) { try { switch (input.mBooleanType) { - case FRIENDSHIP_EXISTS: { - if (input.mUserScreenName.toLowerCase().equals( - input.mUserScreenNameToCheck.toLowerCase()) == false) { - ResponseList response = twitter - .lookupFriendships(new String[] { input.mUserScreenName }); - if (response != null && response.size() == 1) { - result.add(response.get(0).isFollowedBy()); - result.add(response.get(0).isFollowing()); + case FRIENDSHIP_EXISTS: { + if (!input.mUserScreenName.toLowerCase().equals( + input.mUserScreenNameToCheck.toLowerCase())) { + ResponseList response = twitter + .lookupFriendships(new String[]{input.mUserScreenName}); + if (response != null && response.size() == 1) { + result.add(response.get(0).isFollowedBy()); + result.add(response.get(0).isFollowing()); + } } + break; } - break; - } - default: - break; + default: + break; } } catch (TwitterException e) { @@ -253,20 +248,20 @@ protected FetchBooleanTaskOutput doInBackground( } } else if (appdotnet != null) { switch (input.mBooleanType) { - case FRIENDSHIP_EXISTS: { - if (input.mUserScreenName.toLowerCase().equals( - input.mUserScreenNameToCheck.toLowerCase()) == false) { - TwitterUser user = appdotnet - .getAdnUser(input.mUserScreenName); - if (user != null) { - result.add(user.getFollowsCurrentUser()); - result.add(user.getCurrentUserFollows()); + case FRIENDSHIP_EXISTS: { + if (!input.mUserScreenName.toLowerCase().equals( + input.mUserScreenNameToCheck.toLowerCase())) { + TwitterUser user = appdotnet + .getAdnUser(input.mUserScreenName); + if (user != null) { + result.add(user.getFollowsCurrentUser()); + result.add(user.getCurrentUserFollows()); + } } + break; } - break; - } - default: - break; + default: + break; } } @@ -275,7 +270,7 @@ protected FetchBooleanTaskOutput doInBackground( } return new FetchBooleanTaskOutput(new TwitterFetchResult( - errorDescription == null ? true : false, errorDescription), + errorDescription == null, errorDescription), input.mCallbackHandle, result); } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchLists.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchLists.java index d6b2d206..88051cd0 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchLists.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchLists.java @@ -16,13 +16,13 @@ package org.tweetalib.android; -import java.util.HashMap; - import android.util.Log; -import org.asynctasktex.AsyncTaskEx; +import org.asynctasktex.AsyncTaskEx; import org.tweetalib.android.model.TwitterLists; +import java.util.HashMap; + import twitter4j.ResponseList; import twitter4j.Twitter; import twitter4j.TwitterException; @@ -31,15 +31,15 @@ public class TwitterFetchLists { private FetchListsWorkerCallbacks mCallbacks; - private HashMap mListsHashMap; + private final HashMap mListsHashMap; private Integer mFetchListsCallbackHandle; - private HashMap mFinishedCallbackMap; + private final HashMap mFinishedCallbackMap; /* - * + * */ public void clearCallbacks() { - if (mFinishedCallbackMap != null ) { + if (mFinishedCallbackMap != null) { mFinishedCallbackMap.clear(); } } @@ -72,10 +72,6 @@ public FinishedCallback() { mHandle = kInvalidHandle; } - void setHandle(int handle) { - mHandle = handle; - } - private int mHandle; } @@ -100,8 +96,7 @@ public void setWorkerCallbacks(FetchListsWorkerCallbacks callbacks) { * */ FinishedCallback getFetchStatusesCallback(Integer callbackHandle) { - FinishedCallback callback = mFinishedCallbackMap.get(callbackHandle); - return callback; + return mFinishedCallbackMap.get(callbackHandle); } /* @@ -148,24 +143,24 @@ public TwitterLists getLists(String screenName, FinishedCallback callback) { */ private void trigger(Integer userId, FinishedCallback callback) { - assert (mFinishedCallbackMap.containsValue(callback) == false); + assert (!mFinishedCallbackMap.containsValue(callback)); mFinishedCallbackMap.put(mFetchListsCallbackHandle, callback); new FetchListsTask().execute(AsyncTaskEx.PRIORITY_MEDIUM, "Fetch Lists", new FetchListsTaskInput(userId, - mFetchListsCallbackHandle)); + mFetchListsCallbackHandle)); mFetchListsCallbackHandle += 1; } private void trigger(String screenName, FinishedCallback callback) { - assert (mFinishedCallbackMap.containsValue(callback) == false); + assert (!mFinishedCallbackMap.containsValue(callback)); mFinishedCallbackMap.put(mFetchListsCallbackHandle, callback); new FetchListsTask().execute(AsyncTaskEx.PRIORITY_MEDIUM, "Fetch Lists", new FetchListsTaskInput(screenName, - mFetchListsCallbackHandle)); + mFetchListsCallbackHandle)); mFetchListsCallbackHandle += 1; } @@ -193,7 +188,7 @@ class FetchListsTaskInput { mScreenName = screenName; } - Integer mCallbackHandle; + final Integer mCallbackHandle; Integer mUserId; String mScreenName; } @@ -208,8 +203,8 @@ class FetchListsTaskOutput { mLists = lists; } - Integer mCallbackHandle; - TwitterLists mLists; + final Integer mCallbackHandle; + final TwitterLists mLists; } /* diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchResult.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchResult.java index 363946e5..16447a9b 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchResult.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchResult.java @@ -18,19 +18,19 @@ public class TwitterFetchResult { - boolean mSuccessful; - String mErrorMessage; + private final boolean mSuccessful; + final String mErrorMessage; /* - * + * */ public TwitterFetchResult(boolean successful, String errorMessage) { mSuccessful = successful; mErrorMessage = errorMessage; - if (mSuccessful == false && TwitterManager.get() != null && TwitterManager.get().getConnectionStatus() != + if (!mSuccessful && TwitterManager.get() != null && TwitterManager.get().getConnectionStatus() != null) { - TwitterManager.get().getConnectionStatus().handleError(this); + TwitterManager.get().getConnectionStatus().handleError(this); } } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchStatus.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchStatus.java index 6ad3045a..2be1bba3 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchStatus.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchStatus.java @@ -11,9 +11,8 @@ package org.tweetalib.android; -import java.util.HashMap; - import android.util.Log; + import org.appdotnet4j.model.AdnPost; import org.appdotnet4j.model.AdnPostCompose; import org.asynctasktex.AsyncTaskEx; @@ -22,6 +21,8 @@ import org.tweetalib.android.model.TwitterStatus; import org.tweetalib.android.model.TwitterStatusUpdate; +import java.util.HashMap; + import twitter4j.StatusUpdate; import twitter4j.Twitter; import twitter4j.TwitterException; @@ -31,13 +32,13 @@ public class TwitterFetchStatus { private FetchStatusWorkerCallbacks mCallbacks; private Integer mFetchStatusCallbackHandle; - private HashMap mFinishedCallbackMap; + private final HashMap mFinishedCallbackMap; /* - * + * */ public void clearCallbacks() { - if (mFinishedCallbackMap != null ) { + if (mFinishedCallbackMap != null) { mFinishedCallbackMap.clear(); } } @@ -74,10 +75,6 @@ public FinishedCallback() { mHandle = kInvalidHandle; } - void setHandle(int handle) { - mHandle = handle; - } - private int mHandle; } @@ -104,8 +101,7 @@ public void setWorkerCallbacks(FetchStatusWorkerCallbacks callbacks) { * */ FinishedCallback getFetchStatusCallback(Integer callbackHandle) { - FinishedCallback callback = mFinishedCallbackMap.get(callbackHandle); - return callback; + return mFinishedCallbackMap.get(callbackHandle); } /* @@ -132,7 +128,7 @@ AppdotnetApi getAppdotnetApi() { * */ public TwitterStatus getStatus(long statusId, FinishedCallback callback, - ConnectionStatus connectionStatus) { + ConnectionStatus connectionStatus) { triggerFetchStatusTask(new FetchStatusTaskInput( mFetchStatusCallbackHandle, StatusType.GET_STATUS, statusId, @@ -144,7 +140,7 @@ public TwitterStatus getStatus(long statusId, FinishedCallback callback, * */ public void setStatus(TwitterStatusUpdate statusUpdate, - FinishedCallback callback, ConnectionStatus connectionStatus) { + FinishedCallback callback, ConnectionStatus connectionStatus) { triggerFetchStatusTask(new FetchStatusTaskInput( mFetchStatusCallbackHandle, statusUpdate, connectionStatus), @@ -155,7 +151,7 @@ public void setStatus(TwitterStatusUpdate statusUpdate, * */ public void setRetweet(long statusId, FinishedCallback callback, - ConnectionStatus connectionStatus) { + ConnectionStatus connectionStatus) { triggerFetchStatusTask(new FetchStatusTaskInput( mFetchStatusCallbackHandle, StatusType.SET_RETWEET, statusId, connectionStatus), callback, connectionStatus); @@ -165,9 +161,9 @@ public void setRetweet(long statusId, FinishedCallback callback, * */ void triggerFetchStatusTask(FetchStatusTaskInput taskInput, - FinishedCallback callback, ConnectionStatus connectionStatus) { + FinishedCallback callback, ConnectionStatus connectionStatus) { - if (connectionStatus != null && connectionStatus.isOnline() == false) { + if (connectionStatus != null && !connectionStatus.isOnline()) { if (callback != null) { callback.finished(new TwitterFetchResult(false, connectionStatus.getErrorMessageNoConnection()), null); @@ -195,8 +191,8 @@ public void cancel(FinishedCallback callback) { class FetchStatusTaskInput { FetchStatusTaskInput(Integer callbackHandle, - TwitterStatusUpdate statusUpdate, - ConnectionStatus connectionStatus) { + TwitterStatusUpdate statusUpdate, + ConnectionStatus connectionStatus) { mCallbackHandle = callbackHandle; mStatusUpdate = statusUpdate; mStatusType = StatusType.SET_STATUS; @@ -204,18 +200,18 @@ class FetchStatusTaskInput { } FetchStatusTaskInput(Integer callbackHandle, StatusType statusType, - long existingStatus, ConnectionStatus connectionStatus) { + long existingStatus, ConnectionStatus connectionStatus) { mCallbackHandle = callbackHandle; mExistingStatusId = existingStatus; mStatusType = statusType; mConnectionStatus = connectionStatus; } - Integer mCallbackHandle; - StatusType mStatusType; + final Integer mCallbackHandle; + final StatusType mStatusType; TwitterStatusUpdate mStatusUpdate; Long mExistingStatusId; - ConnectionStatus mConnectionStatus; + final ConnectionStatus mConnectionStatus; } /* @@ -224,15 +220,15 @@ class FetchStatusTaskInput { class FetchStatusTaskOutput { FetchStatusTaskOutput(TwitterFetchResult result, - Integer callbackHandle, TwitterStatus status) { + Integer callbackHandle, TwitterStatus status) { mResult = result; mCallbackHandle = callbackHandle; mStatus = status; } - TwitterFetchResult mResult; - Integer mCallbackHandle; - TwitterStatus mStatus; + final TwitterFetchResult mResult; + final Integer mCallbackHandle; + final TwitterStatus mStatus; } /* @@ -250,7 +246,7 @@ protected FetchStatusTaskOutput doInBackground( TwitterStatus twitterStatus = null; String errorDescription = null; - if (input.mConnectionStatus != null && input.mConnectionStatus.isOnline() == false) { + if (input.mConnectionStatus != null && !input.mConnectionStatus.isOnline()) { return new FetchStatusTaskOutput(new TwitterFetchResult(false, input.mConnectionStatus.getErrorMessageNoConnection()), input.mCallbackHandle, null); @@ -260,23 +256,23 @@ protected FetchStatusTaskOutput doInBackground( if (appdotnetApi != null) { AdnPost status = null; switch (input.mStatusType) { - case SET_STATUS: - AdnPostCompose post = input.mStatusUpdate.getAdnComposePost(); - appdotnetApi.setAdnStatus(post); - break; - - case GET_STATUS: { - status = appdotnetApi.getAdnPost(input.mExistingStatusId); - break; - } + case SET_STATUS: + AdnPostCompose post = input.mStatusUpdate.getAdnComposePost(); + appdotnetApi.setAdnStatus(post); + break; - case SET_RETWEET: { - status = appdotnetApi.setAdnRepost(input.mExistingStatusId); - break; - } + case GET_STATUS: { + status = appdotnetApi.getAdnPost(input.mExistingStatusId); + break; + } - default: - break; + case SET_RETWEET: { + status = appdotnetApi.setAdnRepost(input.mExistingStatusId); + break; + } + + default: + break; } if (status != null) { @@ -287,17 +283,17 @@ protected FetchStatusTaskOutput doInBackground( try { switch (input.mStatusType) { - case GET_STATUS: { - Log.d("api-call", "showStatus"); - status = twitter.showStatus(input.mExistingStatusId); - break; - } - - case SET_STATUS: { - Log.d("api-call", "updateStatus"); - StatusUpdate statusUpdate = input.mStatusUpdate - .getT4JStatusUpdate(); - status = twitter.updateStatus(statusUpdate); + case GET_STATUS: { + Log.d("api-call", "showStatus"); + status = twitter.showStatus(input.mExistingStatusId); + break; + } + + case SET_STATUS: { + Log.d("api-call", "updateStatus"); + StatusUpdate statusUpdate = input.mStatusUpdate + .getT4JStatusUpdate(); + status = twitter.updateStatus(statusUpdate); /* * Configuration conf = getConfiguration(); @@ -336,15 +332,15 @@ protected FetchStatusTaskOutput doInBackground( * e.printStackTrace(); } } */ - // status = twitter.showStatus(181681943774117888L); - break; - } + // status = twitter.showStatus(181681943774117888L); + break; + } - case SET_RETWEET: { - Log.d("api-call", "retweetStatus"); - status = twitter.retweetStatus(input.mExistingStatusId); - break; - } + case SET_RETWEET: { + Log.d("api-call", "retweetStatus"); + status = twitter.retweetStatus(input.mExistingStatusId); + break; + } } @@ -356,7 +352,7 @@ protected FetchStatusTaskOutput doInBackground( errorDescription += "\nTry again in " + e.getRateLimitStatus().getSecondsUntilReset() + " " + "seconds"; } - }catch (OutOfMemoryError e) { + } catch (OutOfMemoryError e) { e.printStackTrace(); errorDescription = e.getMessage(); Log.e("api-call", errorDescription, e); @@ -368,7 +364,7 @@ protected FetchStatusTaskOutput doInBackground( } return new FetchStatusTaskOutput(new TwitterFetchResult( - errorDescription == null ? true : false, errorDescription), + errorDescription == null, errorDescription), input.mCallbackHandle, twitterStatus); } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchUser.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchUser.java index 5d8f31ef..cae4ede6 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchUser.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchUser.java @@ -34,16 +34,16 @@ public class TwitterFetchUser { private FetchUserWorkerCallbacks mCallbacks; - private HashMap mUserIdHashMap; - private HashMap mUserScreenNameHashMap; + private final HashMap mUserIdHashMap; + private final HashMap mUserScreenNameHashMap; private Integer mFetchUserCallbackHandle; - private HashMap mFinishedCallbackMap; + private final HashMap mFinishedCallbackMap; /* - * + * */ public void clearCallbacks() { - if (mFinishedCallbackMap != null ) { + if (mFinishedCallbackMap != null) { mFinishedCallbackMap.clear(); } } @@ -78,10 +78,6 @@ public FinishedCallback() { mHandle = kInvalidHandle; } - void setHandle(int handle) { - mHandle = handle; - } - private int mHandle; } @@ -106,8 +102,7 @@ public void setWorkerCallbacks(FetchUserWorkerCallbacks callbacks) { * */ FinishedCallback getFetchStatusesCallback(Integer callbackHandle) { - FinishedCallback callback = mFinishedCallbackMap.get(callbackHandle); - return callback; + return mFinishedCallbackMap.get(callbackHandle); } /* @@ -138,10 +133,10 @@ public void setUser(TwitterUser twitterUser) { return; } - if (mUserIdHashMap.containsKey(twitterUser.getId()) == false) { + if (!mUserIdHashMap.containsKey(twitterUser.getId())) { mUserIdHashMap.put(twitterUser.getId(), twitterUser); } - if (mUserScreenNameHashMap.containsKey(twitterUser.getScreenName()) == false) { + if (!mUserScreenNameHashMap.containsKey(twitterUser.getScreenName())) { mUserScreenNameHashMap .put(twitterUser.getScreenName(), twitterUser); } @@ -150,11 +145,11 @@ public void setUser(TwitterUser twitterUser) { public void setUser(User user, boolean forceUpdate) { Long userId = Long.valueOf(user.getId()); TwitterUser twitterUser = new TwitterUser(user); - if (forceUpdate == true || mUserIdHashMap.containsKey(userId) == false) { + if (forceUpdate || !mUserIdHashMap.containsKey(userId)) { mUserIdHashMap.put(userId, twitterUser); } - if (forceUpdate == true - || mUserIdHashMap.containsKey(twitterUser.getScreenName()) == false) { + if (forceUpdate + || !mUserIdHashMap.containsKey(twitterUser.getScreenName())) { mUserScreenNameHashMap .put(twitterUser.getScreenName(), twitterUser); } @@ -163,11 +158,11 @@ public void setUser(User user, boolean forceUpdate) { public void setUser(AdnUser user, boolean forceUpdate) { Long userId = Long.valueOf(user.mId); TwitterUser twitterUser = new TwitterUser(user); - if (forceUpdate == true || mUserIdHashMap.containsKey(userId) == false) { + if (forceUpdate || !mUserIdHashMap.containsKey(userId)) { mUserIdHashMap.put(userId, twitterUser); } - if (forceUpdate == true - || mUserIdHashMap.containsKey(twitterUser.getScreenName()) == false) { + if (forceUpdate + || !mUserIdHashMap.containsKey(twitterUser.getScreenName())) { mUserScreenNameHashMap .put(twitterUser.getScreenName(), twitterUser); } @@ -177,7 +172,7 @@ public void setUser(AdnUser user, boolean forceUpdate) { * */ public TwitterUser getUser(Long userId, FinishedCallback callback, - ConnectionStatus connectionStatus) { + ConnectionStatus connectionStatus) { TwitterUser user = mUserIdHashMap.get(userId); @@ -189,7 +184,7 @@ public TwitterUser getUser(Long userId, FinishedCallback callback, } public TwitterUser getUser(String screenName, FinishedCallback callback, - ConnectionStatus connectionStatus) { + ConnectionStatus connectionStatus) { TwitterUser user = mUserScreenNameHashMap.get(screenName); @@ -201,13 +196,11 @@ public TwitterUser getUser(String screenName, FinishedCallback callback, } public List getCachedUsers() { - List users = new ArrayList(mUserIdHashMap.values()); - return users; + return new ArrayList(mUserIdHashMap.values()); } public TwitterUser getCachedUser(Long userId) { - if (!mUserIdHashMap.containsKey(userId)) - { + if (!mUserIdHashMap.containsKey(userId)) { return null; } return mUserIdHashMap.get(userId); @@ -218,9 +211,9 @@ public TwitterUser getCachedUser(Long userId) { * */ public void verifyUser(FinishedCallback callback, - ConnectionStatus connectionStatus) { + ConnectionStatus connectionStatus) { - if (connectionStatus != null && connectionStatus.isOnline() == false) { + if (connectionStatus != null && !connectionStatus.isOnline()) { if (callback != null) { callback.finished(new TwitterFetchResult(false, connectionStatus.getErrorMessageNoConnection()), null); @@ -239,9 +232,9 @@ public void verifyUser(FinishedCallback callback, * */ private void trigger(Long userId, FinishedCallback callback, - ConnectionStatus connectionStatus) { + ConnectionStatus connectionStatus) { - if (connectionStatus != null && connectionStatus.isOnline() == false) { + if (connectionStatus != null && !connectionStatus.isOnline()) { if (callback != null) { callback.finished(new TwitterFetchResult(false, connectionStatus.getErrorMessageNoConnection()), null); @@ -249,7 +242,7 @@ private void trigger(Long userId, FinishedCallback callback, return; } - assert (mFinishedCallbackMap.containsValue(callback) == false); + assert (!mFinishedCallbackMap.containsValue(callback)); mFinishedCallbackMap.put(mFetchUserCallbackHandle, callback); new FetchUserTask().execute(AsyncTaskEx.PRIORITY_HIGH, "Fetch User", @@ -260,9 +253,9 @@ private void trigger(Long userId, FinishedCallback callback, } private void trigger(String screenName, FinishedCallback callback, - ConnectionStatus connectionStatus) { + ConnectionStatus connectionStatus) { - if (connectionStatus != null && connectionStatus.isOnline() == false) { + if (connectionStatus != null && !connectionStatus.isOnline()) { if (callback != null) { callback.finished(new TwitterFetchResult(false, connectionStatus.getErrorMessageNoConnection()), null); @@ -270,7 +263,7 @@ private void trigger(String screenName, FinishedCallback callback, return; } - assert (mFinishedCallbackMap.containsValue(callback) == false); + assert (!mFinishedCallbackMap.containsValue(callback)); mFinishedCallbackMap.put(mFetchUserCallbackHandle, callback); new FetchUserTask().execute(AsyncTaskEx.PRIORITY_HIGH, "Fetch User", @@ -294,31 +287,31 @@ public void cancel(FinishedCallback callback) { class FetchUserTaskInput { FetchUserTaskInput(Long userId, Integer callbackHandle, - ConnectionStatus connectionStatus) { + ConnectionStatus connectionStatus) { mCallbackHandle = callbackHandle; mUserId = userId; mConnectionStatus = connectionStatus; } FetchUserTaskInput(String screenName, Integer callbackHandle, - ConnectionStatus connectionStatus) { + ConnectionStatus connectionStatus) { mCallbackHandle = callbackHandle; mScreenName = screenName; mConnectionStatus = connectionStatus; } FetchUserTaskInput(Integer callbackHandle, - ConnectionStatus connectionStatus) { + ConnectionStatus connectionStatus) { mCallbackHandle = callbackHandle; mVerifyCredentials = true; mConnectionStatus = connectionStatus; } - Integer mCallbackHandle; + final Integer mCallbackHandle; Boolean mVerifyCredentials; Long mUserId; String mScreenName; - ConnectionStatus mConnectionStatus; + final ConnectionStatus mConnectionStatus; } @@ -328,15 +321,15 @@ class FetchUserTaskInput { class FetchUserTaskOutput { FetchUserTaskOutput(TwitterFetchResult fetchResult, - Integer callbackHandle, TwitterUser user) { + Integer callbackHandle, TwitterUser user) { mFetchResult = fetchResult; mCallbackHandle = callbackHandle; mUser = user; } - TwitterFetchResult mFetchResult; - Integer mCallbackHandle; - TwitterUser mUser; + final TwitterFetchResult mFetchResult; + final Integer mCallbackHandle; + final TwitterUser mUser; } /* @@ -352,7 +345,7 @@ protected FetchUserTaskOutput doInBackground( TwitterUser result = null; FetchUserTaskInput input = inputArray[0]; - if (input.mConnectionStatus != null && input.mConnectionStatus.isOnline() == false) { + if (input.mConnectionStatus != null && !input.mConnectionStatus.isOnline()) { return new FetchUserTaskOutput(new TwitterFetchResult(false, input.mConnectionStatus.getErrorMessageNoConnection()), input.mCallbackHandle, null); @@ -364,7 +357,7 @@ protected FetchUserTaskOutput doInBackground( try { User user = null; if (input.mVerifyCredentials != null - && input.mVerifyCredentials.booleanValue() == true) { + && input.mVerifyCredentials.booleanValue()) { Log.d("api-call", "verifyCredentials"); user = twitter.verifyCredentials(); } else { @@ -395,7 +388,7 @@ protected FetchUserTaskOutput doInBackground( } return new FetchUserTaskOutput(new TwitterFetchResult( - errorDescription == null ? true : false, errorDescription), + errorDescription == null, errorDescription), input.mCallbackHandle, result); } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchUsers.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchUsers.java index e1edc5c9..7370da29 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchUsers.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterFetchUsers.java @@ -23,15 +23,10 @@ import org.tweetalib.android.model.TwitterUsers; import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; import twitter4j.IDs; import twitter4j.Paging; -import twitter4j.RateLimitStatus; import twitter4j.ResponseList; import twitter4j.Twitter; import twitter4j.TwitterException; @@ -40,21 +35,21 @@ public class TwitterFetchUsers { private FetchUsersWorkerCallbacks mWorkerCallbacks; - private HashMap mIdsHashMap; + private final HashMap mIdsHashMap; private Integer mFetchUsersCallbackHandle; - private HashMap mFinishedCallbackMap; + private final HashMap mFinishedCallbackMap; /* - * + * */ public void clearCallbacks() { - if (mFinishedCallbackMap != null ) { + if (mFinishedCallbackMap != null) { mFinishedCallbackMap.clear(); } } /* - * + * */ public interface FetchUsersWorkerCallbacks { @@ -91,10 +86,6 @@ public FinishedCallback() { mHandle = kInvalidHandle; } - void setHandle(int handle) { - mHandle = handle; - } - private int mHandle; } @@ -119,8 +110,7 @@ public void setWorkerCallbacks(FetchUsersWorkerCallbacks callbacks) { * */ FinishedCallback getFetchUsersCallback(Integer callbackHandle) { - FinishedCallback callback = mFinishedCallbackMap.get(callbackHandle); - return callback; + return mFinishedCallbackMap.get(callbackHandle); } /* @@ -179,7 +169,7 @@ TwitterIds getUserIds(TwitterContentHandle handle) { * */ public TwitterUsers getUsers(TwitterContentHandle contentHandle, - TwitterPaging paging) { + TwitterPaging paging) { TwitterIds ids = getUserIds(contentHandle); @@ -202,8 +192,8 @@ public TwitterUsers getUsers(TwitterContentHandle contentHandle, * */ public TwitterUsers getUsers(TwitterContentHandle contentHandle, - TwitterPaging paging, FinishedCallback callback, - ConnectionStatus connectionStatus) { + TwitterPaging paging, FinishedCallback callback, + ConnectionStatus connectionStatus) { TwitterUsers result = getUsers(contentHandle, paging); if (result == null) { @@ -218,11 +208,11 @@ public TwitterUsers getUsers(TwitterContentHandle contentHandle, /* * */ - public void trigger(TwitterContentHandle contentHandle, - TwitterPaging paging, FinishedCallback callback, - ConnectionStatus connectionStatus) { + void trigger(TwitterContentHandle contentHandle, + TwitterPaging paging, FinishedCallback callback, + ConnectionStatus connectionStatus) { - if (connectionStatus != null && connectionStatus.isOnline() == false) { + if (connectionStatus != null && !connectionStatus.isOnline()) { if (callback != null) { callback.finished(new TwitterFetchResult(false, connectionStatus.getErrorMessageNoConnection()), null); @@ -230,13 +220,13 @@ public void trigger(TwitterContentHandle contentHandle, return; } - assert (mFinishedCallbackMap.containsValue(callback) == false); + assert (!mFinishedCallbackMap.containsValue(callback)); mFinishedCallbackMap.put(mFetchUsersCallbackHandle, callback); new FetchUsersTask().execute(AsyncTaskEx.PRIORITY_MEDIUM, "Fetch Users", new FetchUsersTaskInput( - mFetchUsersCallbackHandle, contentHandle, - connectionStatus, paging)); + mFetchUsersCallbackHandle, contentHandle, + connectionStatus, paging)); mFetchUsersCallbackHandle += 1; } @@ -253,15 +243,15 @@ public void cancel(FinishedCallback callback) { * */ public void updateFriendshipUser(String currentUserScreenName, - TwitterUser userToUpdate, boolean create, - FinishedCallback callback, ConnectionStatus connectionStatus) { + TwitterUser userToUpdate, boolean create, + FinishedCallback callback, ConnectionStatus connectionStatus) { updateFriendshipUsers(currentUserScreenName, new TwitterUsers( userToUpdate), create, callback, connectionStatus); } public void updateFriendshipUsers(String currentUserScreenName, - TwitterUsers usersToUpdate, boolean create, - FinishedCallback callback, ConnectionStatus connectionStatus) { + TwitterUsers usersToUpdate, boolean create, + FinishedCallback callback, ConnectionStatus connectionStatus) { ArrayList userScreenNames = new ArrayList(); for (int i = 0; i < usersToUpdate.getUserCount(); i++) { userScreenNames.add(usersToUpdate.getUser(i).getScreenName()); @@ -274,8 +264,8 @@ public void updateFriendshipUsers(String currentUserScreenName, * */ public void updateFriendshipScreenName(String currentUserScreenName, - String screenNameToUpdate, boolean create, - FinishedCallback callback, ConnectionStatus connectionStatus) { + String screenNameToUpdate, boolean create, + FinishedCallback callback, ConnectionStatus connectionStatus) { ArrayList userScreenNames = new ArrayList(); userScreenNames.add(screenNameToUpdate); updateFriendshipScreenNames(currentUserScreenName, userScreenNames, @@ -285,10 +275,10 @@ public void updateFriendshipScreenName(String currentUserScreenName, private static int _mFriendshipCounter = 0; public void updateFriendshipScreenNames(String currentUserScreenName, - ArrayList userScreenNamesToUpdate, boolean create, - FinishedCallback callback, ConnectionStatus connectionStatus) { + ArrayList userScreenNamesToUpdate, boolean create, + FinishedCallback callback, ConnectionStatus connectionStatus) { - if (connectionStatus != null && connectionStatus.isOnline() == false) { + if (connectionStatus != null && !connectionStatus.isOnline()) { if (callback != null) { callback.finished(new TwitterFetchResult(false, connectionStatus.getErrorMessageNoConnection()), null); @@ -314,8 +304,8 @@ public void updateFriendshipScreenNames(String currentUserScreenName, * */ public void updateFriendshipUserId(long currentUserId, Long userIdToUpdate, - boolean create, FinishedCallback callback, - ConnectionStatus connectionStatus) { + boolean create, FinishedCallback callback, + ConnectionStatus connectionStatus) { ArrayList userIds = new ArrayList(); userIds.add(userIdToUpdate); updateFriendshipUserIds(currentUserId, userIds, create, callback, @@ -323,9 +313,9 @@ public void updateFriendshipUserId(long currentUserId, Long userIdToUpdate, } public void updateFriendshipUserIds(long currentUserId, - ArrayList userIdsToUpdate, boolean create, - FinishedCallback callback, ConnectionStatus connectionStatus) { - if (connectionStatus != null && connectionStatus.isOnline() == false) { + ArrayList userIdsToUpdate, boolean create, + FinishedCallback callback, ConnectionStatus connectionStatus) { + if (connectionStatus != null && !connectionStatus.isOnline()) { if (callback != null) { callback.finished(new TwitterFetchResult(false, connectionStatus.getErrorMessageNoConnection()), null); @@ -343,16 +333,16 @@ public void updateFriendshipUserIds(long currentUserId, mFinishedCallbackMap.put(mFetchUsersCallbackHandle, callback); new FetchUsersTask().execute(AsyncTaskEx.PRIORITY_MEDIUM, "Update Friendships", new FetchUsersTaskInput( - mFetchUsersCallbackHandle, contentHandle, - connectionStatus, null, userIdsToUpdate, create)); + mFetchUsersCallbackHandle, contentHandle, + connectionStatus, null, userIdsToUpdate, create)); } /* * */ private void createBlockOrReportSpam(UsersType usersType, - long currentUserId, Long userId, FinishedCallback callback, - ConnectionStatus connectionStatus) { + long currentUserId, Long userId, FinishedCallback callback, + ConnectionStatus connectionStatus) { ArrayList userIds = new ArrayList(); userIds.add(userId); createBlockOrReportSpam(usersType, currentUserId, userIds, callback, @@ -360,9 +350,9 @@ private void createBlockOrReportSpam(UsersType usersType, } private void createBlockOrReportSpam(UsersType usersType, - long currentUserId, ArrayList userIds, - FinishedCallback callback, ConnectionStatus connectionStatus) { - if (connectionStatus != null && connectionStatus.isOnline() == false) { + long currentUserId, ArrayList userIds, + FinishedCallback callback, ConnectionStatus connectionStatus) { + if (connectionStatus != null && !connectionStatus.isOnline()) { if (callback != null) { callback.finished(new TwitterFetchResult(false, connectionStatus.getErrorMessageNoConnection()), null); @@ -379,21 +369,21 @@ private void createBlockOrReportSpam(UsersType usersType, mFinishedCallbackMap.put(mFetchUsersCallbackHandle, callback); new FetchUsersTask().execute(AsyncTaskEx.PRIORITY_MEDIUM, "Block or Report", new FetchUsersTaskInput( - mFetchUsersCallbackHandle, contentHandle, - connectionStatus, userIds)); + mFetchUsersCallbackHandle, contentHandle, + connectionStatus, userIds)); } /* * */ public void reportSpam(long currentUserId, Long userId, - FinishedCallback callback, ConnectionStatus connectionStatus) { + FinishedCallback callback, ConnectionStatus connectionStatus) { createBlockOrReportSpam(UsersType.REPORT_SPAM, currentUserId, userId, callback, connectionStatus); } public void reportSpam(long currentUserId, ArrayList userIds, - FinishedCallback callback, ConnectionStatus connectionStatus) { + FinishedCallback callback, ConnectionStatus connectionStatus) { createBlockOrReportSpam(UsersType.REPORT_SPAM, currentUserId, userIds, callback, connectionStatus); } @@ -402,13 +392,13 @@ public void reportSpam(long currentUserId, ArrayList userIds, * */ public void createBlock(long currentUserId, Long userId, - FinishedCallback callback, ConnectionStatus connectionStatus) { + FinishedCallback callback, ConnectionStatus connectionStatus) { createBlockOrReportSpam(UsersType.CREATE_BLOCK, currentUserId, userId, callback, connectionStatus); } public void createBlock(long currentUserId, ArrayList userIds, - FinishedCallback callback, ConnectionStatus connectionStatus) { + FinishedCallback callback, ConnectionStatus connectionStatus) { createBlockOrReportSpam(UsersType.CREATE_BLOCK, currentUserId, userIds, callback, connectionStatus); } @@ -419,8 +409,8 @@ public void createBlock(long currentUserId, ArrayList userIds, class FetchUsersTaskInput { FetchUsersTaskInput(Integer callbackHandle, - TwitterContentHandle contentHandle, - ConnectionStatus connectionStatus, TwitterPaging paging) { + TwitterContentHandle contentHandle, + ConnectionStatus connectionStatus, TwitterPaging paging) { mCallbackHandle = callbackHandle; mContentHandle = contentHandle; mConnectionStatus = connectionStatus; @@ -428,8 +418,8 @@ class FetchUsersTaskInput { } FetchUsersTaskInput(Integer callbackHandle, - TwitterContentHandle contentHandle, - ConnectionStatus connectionStatus, ArrayList userIds) { + TwitterContentHandle contentHandle, + ConnectionStatus connectionStatus, ArrayList userIds) { mCallbackHandle = callbackHandle; mContentHandle = contentHandle; mConnectionStatus = connectionStatus; @@ -437,10 +427,10 @@ class FetchUsersTaskInput { } FetchUsersTaskInput(Integer callbackHandle, - TwitterContentHandle contentHandle, - ConnectionStatus connectionStatus, - ArrayList userScreenNames, ArrayList userIds, - boolean createFriendship) { + TwitterContentHandle contentHandle, + ConnectionStatus connectionStatus, + ArrayList userScreenNames, ArrayList userIds, + boolean createFriendship) { mCallbackHandle = callbackHandle; mContentHandle = contentHandle; mConnectionStatus = connectionStatus; @@ -450,10 +440,10 @@ class FetchUsersTaskInput { mCreateFriendship = createFriendship; } - Integer mCallbackHandle; - TwitterContentHandle mContentHandle; + final Integer mCallbackHandle; + final TwitterContentHandle mContentHandle; TwitterPaging mPaging; - ConnectionStatus mConnectionStatus; + final ConnectionStatus mConnectionStatus; ArrayList mScreenNames; ArrayList mUserIds; boolean mCreateFriendship; @@ -465,15 +455,15 @@ class FetchUsersTaskInput { class FetchUsersTaskOutput { FetchUsersTaskOutput(TwitterFetchResult result, Integer callbackHandle, - TwitterUsers users) { + TwitterUsers users) { mResult = result; mCallbackHandle = callbackHandle; mUsers = users; } - TwitterFetchResult mResult; - Integer mCallbackHandle; - TwitterUsers mUsers; + final TwitterFetchResult mResult; + final Integer mCallbackHandle; + final TwitterUsers mUsers; } /* @@ -492,7 +482,7 @@ protected FetchUsersTaskOutput doInBackground( AppdotnetApi appdotnet = getAppdotnetInstance(); String errorDescription = null; - if (input.mConnectionStatus != null && input.mConnectionStatus.isOnline() == false) { + if (input.mConnectionStatus != null && !input.mConnectionStatus.isOnline()) { return new FetchUsersTaskOutput(new TwitterFetchResult(false, input.mConnectionStatus.getErrorMessageNoConnection()), input.mCallbackHandle, null); @@ -505,73 +495,73 @@ protected FetchUsersTaskOutput doInBackground( AdnUsers users = null; switch (usersType) { - case FRIENDS: { - ids = appdotnet.getAdnFollowing(); - setUsers(input.mContentHandle, ids); - break; - } - - case FOLLOWERS: { - ids = appdotnet.getAdnFollowedBy(); - setUsers(input.mContentHandle, ids); - break; - } + case FRIENDS: { + ids = appdotnet.getAdnFollowing(); + setUsers(input.mContentHandle, ids); + break; + } - case RETWEETED_BY: { - try { - long postId = Long.valueOf(input.mContentHandle - .getIdentifier()); - users = appdotnet.getUsersWhoReposted(postId); + case FOLLOWERS: { + ids = appdotnet.getAdnFollowedBy(); setUsers(input.mContentHandle, ids); - } catch (NumberFormatException e) { + break; } - break; - } - case UPDATE_FRIENDSHIP: { - twitterUsers = new TwitterUsers(); + case RETWEETED_BY: { + try { + long postId = Long.valueOf(input.mContentHandle + .getIdentifier()); + users = appdotnet.getUsersWhoReposted(postId); + setUsers(input.mContentHandle, ids); + } catch (NumberFormatException e) { + } + break; + } + + case UPDATE_FRIENDSHIP: { + twitterUsers = new TwitterUsers(); - if (input.mScreenNames != null) { - for (String screenName : input.mScreenNames) { - AdnUser user = null; - // We can't follow ourself... - if (screenName.toLowerCase().equals( - input.mContentHandle.getScreenName() - .toLowerCase()) == false) { - if (input.mCreateFriendship) { - user = appdotnet.setAdnFollow(screenName, - true); - } else { - user = appdotnet.setAdnFollow(screenName, - false); + if (input.mScreenNames != null) { + for (String screenName : input.mScreenNames) { + AdnUser user = null; + // We can't follow ourself... + if (!screenName.toLowerCase().equals( + input.mContentHandle.getScreenName() + .toLowerCase())) { + if (input.mCreateFriendship) { + user = appdotnet.setAdnFollow(screenName, + true); + } else { + user = appdotnet.setAdnFollow(screenName, + false); + } } - } - if (user != null) { - twitterUsers.add(new TwitterUser(user)); - } - } - } else if (input.mUserIds != null) { - - long currentUserId = Long - .parseLong(input.mContentHandle.getScreenName()); - - for (Long userId : input.mUserIds) { - AdnUser user = null; - // We can't follow ourself... - if (currentUserId != userId) { - if (input.mCreateFriendship) { - user = appdotnet.setAdnFollow(userId, true); - } else { - user = appdotnet - .setAdnFollow(userId, false); + if (user != null) { + twitterUsers.add(new TwitterUser(user)); } } - if (user != null) { - twitterUsers.add(new TwitterUser(user)); + } else if (input.mUserIds != null) { + + long currentUserId = Long + .parseLong(input.mContentHandle.getScreenName()); + + for (Long userId : input.mUserIds) { + AdnUser user = null; + // We can't follow ourself... + if (currentUserId != userId) { + if (input.mCreateFriendship) { + user = appdotnet.setAdnFollow(userId, true); + } else { + user = appdotnet + .setAdnFollow(userId, false); + } + } + if (user != null) { + twitterUsers.add(new TwitterUser(user)); + } } } } - } } @@ -579,9 +569,7 @@ protected FetchUsersTaskOutput doInBackground( int max = input.mPaging == null ? 40 : input.mPaging.getCount(); int numberToFetch = Math.min(max, ids.length); long[] longArray = new long[numberToFetch]; - for (int i = 0; i < numberToFetch; i++) { - longArray[i] = ids[i]; - } + System.arraycopy(ids, 0, longArray, 0, numberToFetch); users = appdotnet.getAdnMultipleUsers(longArray); } @@ -595,7 +583,7 @@ protected FetchUsersTaskOutput doInBackground( } return new FetchUsersTaskOutput(new TwitterFetchResult( - errorDescription == null ? true : false, + errorDescription == null, errorDescription), input.mCallbackHandle, twitterUsers); } else if (twitter != null) { @@ -609,131 +597,131 @@ protected FetchUsersTaskOutput doInBackground( try { switch (usersType) { - case FRIENDS: { - Log.d("api-call", "getFriendsIDs"); - userIds = twitter.getFriendsIDs(-1); - setUsers(input.mContentHandle, userIds); - break; - } - - case FOLLOWERS: { - Log.d("api-call", "getFollowersIDs"); - userIds = twitter.getFollowersIDs(-1); - setUsers(input.mContentHandle, userIds); - break; - } + case FRIENDS: { + Log.d("api-call", "getFriendsIDs"); + userIds = twitter.getFriendsIDs(-1); + setUsers(input.mContentHandle, userIds); + break; + } - case RETWEETED_BY: { - Log.d("api-call", "getRetweets"); - long statusId = Long.parseLong(input.mContentHandle - .getIdentifier()); - ResponseList statuses = twitter - .getRetweets(statusId); + case FOLLOWERS: { + Log.d("api-call", "getFollowersIDs"); + userIds = twitter.getFollowersIDs(-1); + setUsers(input.mContentHandle, userIds); + break; + } - if (statuses != null) { - twitterUsers = new TwitterUsers(); - for (twitter4j.Status status : statuses) { - mWorkerCallbacks.addUser(status.getUser()); - twitterUsers.add(new TwitterUser(status - .getUser())); + case RETWEETED_BY: { + Log.d("api-call", "getRetweets"); + long statusId = Long.parseLong(input.mContentHandle + .getIdentifier()); + ResponseList statuses = twitter + .getRetweets(statusId); + + if (statuses != null) { + twitterUsers = new TwitterUsers(); + for (twitter4j.Status status : statuses) { + mWorkerCallbacks.addUser(status.getUser()); + twitterUsers.add(new TwitterUser(status + .getUser())); + } } + break; } - break; - } - case PEOPLE_SEARCH: { - Log.d("api-call", "searchUsers"); - String searchTerm = input.mContentHandle - .getScreenName(); - users = twitter.searchUsers(searchTerm, 0); - break; - } + case PEOPLE_SEARCH: { + Log.d("api-call", "searchUsers"); + String searchTerm = input.mContentHandle + .getScreenName(); + users = twitter.searchUsers(searchTerm, 0); + break; + } - case UPDATE_FRIENDSHIP: { - twitterUsers = new TwitterUsers(); + case UPDATE_FRIENDSHIP: { + twitterUsers = new TwitterUsers(); - if (input.mScreenNames != null) { - for (String screenName : input.mScreenNames) { - User user = null; - // We can't follow ourself... - if (screenName.toLowerCase().equals( - input.mContentHandle.getScreenName() - .toLowerCase()) == false) { - if (input.mCreateFriendship) { - Log.d("api-call", "createFriendship"); - user = twitter - .createFriendship(screenName); - } else { - Log.d("api-call", "destroyFriendship"); - user = twitter - .destroyFriendship(screenName); + if (input.mScreenNames != null) { + for (String screenName : input.mScreenNames) { + User user = null; + // We can't follow ourself... + if (!screenName.toLowerCase().equals( + input.mContentHandle.getScreenName() + .toLowerCase())) { + if (input.mCreateFriendship) { + Log.d("api-call", "createFriendship"); + user = twitter + .createFriendship(screenName); + } else { + Log.d("api-call", "destroyFriendship"); + user = twitter + .destroyFriendship(screenName); + } + } + if (user != null) { + twitterUsers.add(new TwitterUser(user)); } } - if (user != null) { - twitterUsers.add(new TwitterUser(user)); + } else if (input.mUserIds != null) { + + long currentUserId = Long + .parseLong(input.mContentHandle + .getScreenName()); + + for (Long userId : input.mUserIds) { + User user = null; + // We can't follow ourself... + if (currentUserId != userId) { + if (input.mCreateFriendship) { + Log.d("api-call", "createFriendship"); + user = twitter.createFriendship(userId); + } else { + Log.d("api-call", "destroyFriendship"); + user = twitter + .destroyFriendship(userId); + } + } + if (user != null) { + twitterUsers.add(new TwitterUser(user)); + } } } - } else if (input.mUserIds != null) { - long currentUserId = Long - .parseLong(input.mContentHandle - .getScreenName()); + if (twitterUsers.getUserCount() == 0) { + twitterUsers = null; + } + + break; + } + case CREATE_BLOCK: + case REPORT_SPAM: { + twitterUsers = new TwitterUsers(); + long currentUserId = Long + .parseLong(input.mContentHandle.getScreenName()); for (Long userId : input.mUserIds) { User user = null; - // We can't follow ourself... + // We can't act on ourself... if (currentUserId != userId) { - if (input.mCreateFriendship) { - Log.d("api-call", "createFriendship"); - user = twitter.createFriendship(userId); - } else { - Log.d("api-call", "destroyFriendship"); - user = twitter - .destroyFriendship(userId); + if (usersType == UsersType.CREATE_BLOCK) { + Log.d("api-call", "createBlock"); + user = twitter.createBlock(userId); + } else if (usersType == UsersType.REPORT_SPAM) { + Log.d("api-call", "reportSpam"); + user = twitter.reportSpam(userId); + } + if (user != null) { + twitterUsers.add(new TwitterUser(user)); } - } - if (user != null) { - twitterUsers.add(new TwitterUser(user)); } } - } - - if (twitterUsers.getUserCount() == 0) { - twitterUsers = null; - } - - break; - } - case CREATE_BLOCK: - case REPORT_SPAM: { - twitterUsers = new TwitterUsers(); - long currentUserId = Long - .parseLong(input.mContentHandle.getScreenName()); - for (Long userId : input.mUserIds) { - User user = null; - // We can't act on ourself... - if (currentUserId != userId) { - if (usersType == UsersType.CREATE_BLOCK) { - Log.d("api-call", "createBlock"); - user = twitter.createBlock(userId); - } else if (usersType == UsersType.REPORT_SPAM) { - Log.d("api-call", "reportSpam"); - user = twitter.reportSpam(userId); - } - if (user != null) { - twitterUsers.add(new TwitterUser(user)); - } + if (twitterUsers.getUserCount() == 0) { + twitterUsers = null; } - } - if (twitterUsers.getUserCount() == 0) { - twitterUsers = null; + break; } - break; - } - } if (userIds != null) { @@ -743,17 +731,16 @@ protected FetchUsersTaskOutput doInBackground( int finish = numberToFetch; ArrayList fetchIds = new ArrayList(); boolean check = true; - while (check) - { + while (check) { //Establish ids for this batch for (int i = start; i < finish; i++) { - fetchIds.add(ids[i]); - if(ids.length-1 == i) - { + if (ids.length - 1 == i) { check = false; break; } + + fetchIds.add(ids[i]); } //Mark where to start and end next time round @@ -762,18 +749,15 @@ protected FetchUsersTaskOutput doInBackground( //Convert arraylist into long[] long[] longArray = new long[fetchIds.size()]; - for (int i = 0; i < fetchIds.size(); i++){ + for (int i = 0; i < fetchIds.size(); i++) { longArray[i] = fetchIds.get(i); } fetchIds.clear(); //Get this batch of users - if (users==null) - { - users = twitter.lookupUsers(longArray); - } - else - { + if (users == null) { + users = twitter.lookupUsers(longArray); + } else { users.addAll(twitter.lookupUsers(longArray)); } } @@ -797,12 +781,12 @@ protected FetchUsersTaskOutput doInBackground( } } return new FetchUsersTaskOutput(new TwitterFetchResult( - errorDescription == null ? true : false, + errorDescription == null, errorDescription), input.mCallbackHandle, twitterUsers); } return new FetchUsersTaskOutput(new TwitterFetchResult( - errorDescription == null ? true : false, errorDescription), + errorDescription == null, errorDescription), input.mCallbackHandle, twitterUsers); } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterManager.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterManager.java index a2f12feb..34a4645c 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterManager.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterManager.java @@ -45,9 +45,9 @@ public class TwitterManager { // / TODO: This is probably too C++ ish. Will come back to this later... public static void initModule(SocialNetConstant.Type socNetType, - String consumerKey, String consumerSecret, String oAuthToken, - String oAuthSecret, String currentAccountKey, - ConnectionStatus.Callbacks connectionStatusCallbacks) { + String consumerKey, String consumerSecret, String oAuthToken, + String oAuthSecret, String currentAccountKey, + ConnectionStatus.Callbacks connectionStatusCallbacks) { mInstance = new TwitterManager(socNetType, consumerKey, consumerSecret, currentAccountKey); mInstance.setOAuthTokenWithSecret(oAuthToken, oAuthSecret, true); mInstance.setConnectionStatus(connectionStatusCallbacks); @@ -70,10 +70,10 @@ public static TwitterManager get() { private SocialNetApi mApi; /* - * + * */ - TwitterManager(SocialNetConstant.Type socialNetType, String consumerKey, - String consumerSecret, String currentAccountKey) { + private TwitterManager(SocialNetConstant.Type socialNetType, String consumerKey, + String consumerSecret, String currentAccountKey) { setSocialNetType(socialNetType, consumerKey, consumerSecret, currentAccountKey); } @@ -82,32 +82,31 @@ public SocialNetConstant.Type getSocialNetType() { } public void setSocialNetType(SocialNetConstant.Type socialNetType, - String consumerKey, String consumerSecret, String currentAccountKey) { + String consumerKey, String consumerSecret, String currentAccountKey) { switch (socialNetType) { - case Appdotnet: - mApi = new AppdotnetApi(socialNetType, consumerKey, consumerSecret, currentAccountKey); - break; + case Appdotnet: + mApi = new AppdotnetApi(socialNetType, consumerKey, consumerSecret, currentAccountKey); + break; - default: - mApi = new TwitterApi(socialNetType, consumerKey, consumerSecret, currentAccountKey); - break; + default: + mApi = new TwitterApi(socialNetType, consumerKey, consumerSecret, currentAccountKey); + break; } } - /* * */ public void setOAuthTokenWithSecret(String oAuthToken, String oAuthSecret, - boolean cancelPending) { + boolean cancelPending) { mApi.setOAuthTokenWithSecret(oAuthToken, oAuthSecret, cancelPending); } /* * */ - public void setConnectionStatus( + void setConnectionStatus( ConnectionStatus.Callbacks connectionStatusCallbacks) { mApi.setConnectionStatus(connectionStatusCallbacks); } @@ -126,10 +125,8 @@ public TwitterContentHandle getContentHandle( TwitterContentHandleBase contentHandleBase, String screenName, String identifier, String currentAccountKey) { - TwitterContentHandle handle = new TwitterContentHandle( + return new TwitterContentHandle( contentHandleBase, screenName, identifier, currentAccountKey); - - return handle; } /* @@ -140,11 +137,11 @@ public enum ProfileImageSize { NORMAL, // 48x48 BIGGER, // 73x73 ORIGINAL, // undefined. This will be the size the image was originally - // uploaded in. - // The filesize of original images can be very big so use this - // parameter with - // caution. - }; + // uploaded in. + // The filesize of original images can be very big so use this + // parameter with + // caution. + } /* * @@ -201,8 +198,8 @@ public void getAuthUrl(TwitterSignIn.GetAuthUrlCallback callback) { } public void getOAuthAccessToken(RequestToken requestToken, - String oauthVerifier, - TwitterSignIn.GetOAuthAccessTokenCallback callback) { + String oauthVerifier, + TwitterSignIn.GetOAuthAccessTokenCallback callback) { mApi.getOAuthAccessToken(requestToken, oauthVerifier, callback); } @@ -218,31 +215,25 @@ public TwitterUser getUser(String screenName) { } public TwitterUser getUser(Long userId, - TwitterFetchUser.FinishedCallback callback) { - TwitterUser cachedUser = mApi.getUser(userId, callback); - return cachedUser; + TwitterFetchUser.FinishedCallback callback) { + return mApi.getUser(userId, callback); } public TwitterUser getUser(String screenName, - TwitterFetchUser.FinishedCallback callback) { - TwitterUser cachedUser = mApi.getUser(screenName, callback); - return cachedUser; - } - - public void verifyUser(TwitterFetchUser.FinishedCallback callback) { - mApi.verifyUser(callback); + TwitterFetchUser.FinishedCallback callback) { + return mApi.getUser(screenName, callback); } /* * */ public TwitterUsers getUsers(TwitterContentHandle contentHandle, - TwitterPaging paging) { + TwitterPaging paging) { return mApi.getUsers(contentHandle, paging); } public TwitterUsers getUsers(TwitterContentHandle contentHandle, - TwitterPaging paging, TwitterFetchUsers.FinishedCallback callback) { + TwitterPaging paging, TwitterFetchUsers.FinishedCallback callback) { return mApi.getUsers(contentHandle, paging, callback); } @@ -251,22 +242,20 @@ public TwitterUsers getUsers(TwitterContentHandle contentHandle, */ public TwitterDirectMessages getDirectMessages( TwitterContentHandle contentHandle) { - TwitterDirectMessages cachedMessages = mApi + return mApi .getDirectMessages(contentHandle); - return cachedMessages; } public TwitterDirectMessages getDirectMessages( TwitterContentHandle contentHandle, TwitterPaging paging, TwitterFetchDirectMessagesFinishedCallback callback) { - TwitterDirectMessages cachedMessages = mApi.getDirectMessages( + return mApi.getDirectMessages( contentHandle, paging, callback); - return cachedMessages; } public void sendDirectMessage(long userId, String recipientScreenName, - String statusText, TwitterContentHandle contentHandle, - TwitterFetchDirectMessagesFinishedCallback callback) { + String statusText, TwitterContentHandle contentHandle, + TwitterFetchDirectMessagesFinishedCallback callback) { mApi.sendDirectMessage(userId, recipientScreenName, statusText, contentHandle, callback); } @@ -275,102 +264,41 @@ public void sendDirectMessage(long userId, String recipientScreenName, * */ public void updateFriendship(String currentUserScreenName, - TwitterUser userToUpdate, boolean create, - TwitterFetchUsers.FinishedCallback callback) { + TwitterUser userToUpdate, boolean create, + TwitterFetchUsers.FinishedCallback callback) { mApi.updateFriendship(currentUserScreenName, userToUpdate, create, callback); } - public void updateFriendship(String currentUserScreenName, - TwitterUsers usersToUpdate, boolean create, - TwitterFetchUsers.FinishedCallback callback) { - mApi.updateFriendship(currentUserScreenName, usersToUpdate, create, - callback); - } - - public void updateFriendshipScreenName(String currentUserScreenName, - String screenNameToUpdate, boolean create, - TwitterFetchUsers.FinishedCallback callback) { - mApi.updateFriendshipScreenName(currentUserScreenName, - screenNameToUpdate, create, callback); - } - - public void updateFriendshipScreenNames(String currentUserScreenName, - ArrayList screenNamesToUpdate, boolean create, - TwitterFetchUsers.FinishedCallback callback) { - mApi.updateFriendshipScreenNames(currentUserScreenName, - screenNamesToUpdate, create, callback); - } - - public void updateFriendshipUserId(long currentUserId, long userIdToUpdate, - boolean create, TwitterFetchUsers.FinishedCallback callback) { - mApi.updateFriendshipUserId(currentUserId, userIdToUpdate, create, - callback); - } - public void updateFriendshipUserIds(long currentUserId, - ArrayList userIdsToUpdate, boolean create, - TwitterFetchUsers.FinishedCallback callback) { + ArrayList userIdsToUpdate, boolean create, + TwitterFetchUsers.FinishedCallback callback) { mApi.updateFriendshipUserIds(currentUserId, userIdsToUpdate, create, callback); } - /* - * - */ - public void createBlock(long currentUserId, Long userId, - TwitterFetchUsers.FinishedCallback callback) { - mApi.createBlock(currentUserId, userId, callback); - } - public void createBlock(long currentUserId, ArrayList userIds, - TwitterFetchUsers.FinishedCallback callback) { + TwitterFetchUsers.FinishedCallback callback) { mApi.createBlock(currentUserId, userIds, callback); } - /* - * - */ - public void reportSpam(long currentUserId, Long userId, - TwitterFetchUsers.FinishedCallback callback) { - mApi.reportSpam(currentUserId, userId, callback); - } public void reportSpam(long currentUserId, ArrayList userIds, - TwitterFetchUsers.FinishedCallback callback) { + TwitterFetchUsers.FinishedCallback callback) { mApi.reportSpam(currentUserId, userIds, callback); } - /* - * - */ - public TwitterLists getLists(int userId) { - TwitterLists cachedLists = mApi.getLists(userId, null); - return cachedLists; - } - - public TwitterLists getLists(int userId, - TwitterFetchLists.FinishedCallback callback) { - TwitterLists cachedLists = mApi.getLists(userId, callback); - return cachedLists; - } - - public TwitterLists getLists(String screenName) { - TwitterLists cachedLists = mApi.getLists(screenName, null); - return cachedLists; - } public TwitterLists getLists(String screenName, - TwitterFetchLists.FinishedCallback callback) { - TwitterLists cachedLists = mApi.getLists(screenName, callback); - return cachedLists; + TwitterFetchLists.FinishedCallback callback) { + return mApi.getLists(screenName, callback); } /* * */ public TwitterStatus getStatus(long statusId, - TwitterFetchStatus.FinishedCallback callback) { + TwitterFetchStatus.FinishedCallback callback) { return mApi.getStatus(statusId, callback); } @@ -378,7 +306,7 @@ public TwitterStatus getStatus(long statusId, * */ public void setStatus(TwitterStatusUpdate statusUpdate, - TwitterFetchStatus.FinishedCallback callback) { + TwitterFetchStatus.FinishedCallback callback) { mApi.setStatus(statusUpdate, callback); } @@ -386,7 +314,7 @@ public void setStatus(TwitterStatusUpdate statusUpdate, * */ public void setRetweet(long statusId, - TwitterFetchStatus.FinishedCallback callback) { + TwitterFetchStatus.FinishedCallback callback) { mApi.setRetweet(statusId, callback); } @@ -394,12 +322,12 @@ public void setRetweet(long statusId, * */ public void setFavorite(TwitterStatus status, boolean isFavorite, - TwitterModifyStatuses.FinishedCallback callback) { + TwitterModifyStatuses.FinishedCallback callback) { mApi.setFavorite(status, isFavorite, callback); } public void setFavorite(TwitterStatuses statuses, boolean isFavorite, - TwitterModifyStatuses.FinishedCallback callback) { + TwitterModifyStatuses.FinishedCallback callback) { mApi.setFavorite(statuses, isFavorite, callback); } @@ -412,39 +340,25 @@ public void deleteTweet(TwitterStatuses statuses, TwitterModifyStatuses.Finished * */ public void triggerFetchStatuses(TwitterContentHandle contentHandle, - TwitterPaging paging, - TwitterFetchStatusesFinishedCallback callback, int priorityOffset) { + TwitterPaging paging, + TwitterFetchStatusesFinishedCallback callback, int priorityOffset) { mApi.triggerFetchStatuses(contentHandle, paging, callback, priorityOffset); } - /* - * - */ - public void cancelFetchStatuses( - TwitterFetchStatusesFinishedCallback callback) { - mApi.cancelFetchStatuses(callback); - } - /* * */ public void getFriendshipExists(String userScreenName, - String userScreenNameToCheck, - TwitterFetchBooleans.FinishedCallback callback) { + String userScreenNameToCheck, + TwitterFetchBooleans.FinishedCallback callback) { mApi.getFriendshipExists(userScreenName, userScreenNameToCheck, callback); } - /* - * - */ - public boolean isAuthenticated() { - return mApi.isAuthenticated(); - } public boolean hasValidTwitterInstance() { - return mApi == null ? false : true; + return mApi != null; } /* @@ -463,10 +377,10 @@ public String generateTwitterVerifyCredentialsAuthorizationHeader() { * Quick and dirty system to handle mapping an appdotnet username in an * entity to an id */ - private static HashMap mUserIdentifierHashMap = new HashMap(); + private static final HashMap mUserIdentifierHashMap = new HashMap(); public static void addUserIdentifier(String username, long id) { - if (mUserIdentifierHashMap.containsKey(username) == false) { + if (!mUserIdentifierHashMap.containsKey(username)) { mUserIdentifierHashMap.put(username, id); } } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterModifyStatuses.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterModifyStatuses.java index 9d13ce5f..fd46d7d9 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterModifyStatuses.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterModifyStatuses.java @@ -17,22 +17,24 @@ package org.tweetalib.android; import android.util.Log; + import org.appdotnet4j.model.AdnPost; import org.asynctasktex.AsyncTaskEx; import org.socialnetlib.android.AppdotnetApi; import org.tweetalib.android.TwitterConstant.StatusesType; import org.tweetalib.android.model.TwitterStatus; import org.tweetalib.android.model.TwitterStatuses; -import twitter4j.Twitter; -import twitter4j.TwitterException; import java.util.HashMap; +import twitter4j.Twitter; +import twitter4j.TwitterException; + public class TwitterModifyStatuses { private ModifyStatusesWorkerCallbacks mCallbacks; private Integer mModifyStatusesCallbackHandle; - private HashMap mFinishedCallbackMap; + private final HashMap mFinishedCallbackMap; /* * @@ -49,6 +51,7 @@ public void clearCallbacks() { public interface ModifyStatusesWorkerCallbacks { public Twitter getTwitterInstance(); + public AppdotnetApi getAppdotnetApi(); } @@ -72,10 +75,6 @@ public FinishedCallback() { mHandle = kInvalidHandle; } - void setHandle(int handle) { - mHandle = handle; - } - private int mHandle; } @@ -85,7 +84,7 @@ void setHandle(int handle) { public abstract class FinishedDeleteCallback extends FinishedCallback { static final int kInvalidHandle = -1; - private TwitterStatuses mStatuses; + private final TwitterStatuses mStatuses; public FinishedDeleteCallback(TwitterStatuses statuses) { @@ -113,7 +112,7 @@ public TwitterModifyStatuses() { } /* - * + * */ public void setWorkerCallbacks(ModifyStatusesWorkerCallbacks callbacks) { mCallbacks = callbacks; @@ -127,8 +126,7 @@ public void setWorkerCallbacks(ModifyStatusesWorkerCallbacks callbacks) { * */ FinishedCallback getModifyStatusesCallback(Integer callbackHandle) { - FinishedCallback callback = mFinishedCallbackMap.get(callbackHandle); - return callback; + return mFinishedCallbackMap.get(callbackHandle); } /* @@ -193,17 +191,17 @@ AppdotnetApi getAppdotnetApi() { class ModifyStatusesTaskInput { public ModifyStatusesTaskInput(Integer callbackHandle, StatusesType statusesType, TwitterStatuses statuses, - Integer value) { + Integer value) { mCallbackHandle = callbackHandle; mStatusesType = statusesType; mStatuses = new TwitterStatuses(statuses); mValue = value; } - Integer mCallbackHandle; - StatusesType mStatusesType; - TwitterStatuses mStatuses; - Integer mValue; + final Integer mCallbackHandle; + final StatusesType mStatusesType; + final TwitterStatuses mStatuses; + final Integer mValue; } /* @@ -212,17 +210,17 @@ public ModifyStatusesTaskInput(Integer callbackHandle, StatusesType statusesType class ModifyStatusesTaskOutput { ModifyStatusesTaskOutput(TwitterFetchResult result, Integer callbackHandle, TwitterStatuses feed, - Integer outputValue) { + Integer outputValue) { mCallbackHandle = callbackHandle; mFeed = feed; mValue = outputValue; mResult = result; } - Integer mCallbackHandle; - TwitterStatuses mFeed; - Integer mValue; - TwitterFetchResult mResult; + final Integer mCallbackHandle; + final TwitterStatuses mFeed; + final Integer mValue; + final TwitterFetchResult mResult; } /* @@ -241,89 +239,88 @@ protected ModifyStatusesTaskOutput doInBackground(ModifyStatusesTaskInput... inp AppdotnetApi appdotnetApi = getAppdotnetApi(); if (appdotnetApi != null) { switch (input.mStatusesType) { - case DELETE: { - if (input.mStatuses != null) { - for (int i = 0; i < input.mStatuses.getStatusCount(); i++) { - TwitterStatus twitterStatus = input.mStatuses.getStatus(i); - AdnPost post = appdotnetApi.deleteTweet(twitterStatus.mId); - if (post == null) { - errorDescription = "Unable to delete status"; - } - } - } - break; - } - - case SET_FAVORITE: { - boolean favorite = input.mValue == 1 ? true : false; - - if (input.mStatuses != null) { - for (int i = 0; i < input.mStatuses.getStatusCount(); i++) { - TwitterStatus twitterStatus = input.mStatuses.getStatus(i); - if (twitterStatus.mIsFavorited != favorite) { - AdnPost post = appdotnetApi.setAdnFavorite(twitterStatus.mId, favorite); - - if (post != null) { - twitterStatus = new TwitterStatus(post); - twitterStatus.setFavorite(favorite); - contentFeed.add(twitterStatus); - } - } - } - } - break; - } - } - } - else if (twitter != null) { - - try { - switch (input.mStatusesType) { case DELETE: { if (input.mStatuses != null) { for (int i = 0; i < input.mStatuses.getStatusCount(); i++) { TwitterStatus twitterStatus = input.mStatuses.getStatus(i); - twitter.destroyStatus(twitterStatus.mId); + AdnPost post = appdotnetApi.deleteTweet(twitterStatus.mId); + if (post == null) { + errorDescription = "Unable to delete status"; + } } } break; } case SET_FAVORITE: { - boolean favorite = input.mValue == 1 ? true : false; + boolean favorite = input.mValue == 1; if (input.mStatuses != null) { for (int i = 0; i < input.mStatuses.getStatusCount(); i++) { TwitterStatus twitterStatus = input.mStatuses.getStatus(i); if (twitterStatus.mIsFavorited != favorite) { - try { - twitter4j.Status status; - if (favorite) { - status = twitter.createFavorite(twitterStatus.mId); - } else { - status = twitter.destroyFavorite(twitterStatus.mId); - } + AdnPost post = appdotnetApi.setAdnFavorite(twitterStatus.mId, favorite); - // Yuck: See the comment for - // TwitterStatus.setFavorite() for - // reasons for this - twitterStatus = new TwitterStatus(status); + if (post != null) { + twitterStatus = new TwitterStatus(post); twitterStatus.setFavorite(favorite); - contentFeed.add(twitterStatus); - } catch (TwitterException e) { - // we might get errors setting the favorite - // state to the same - // value again. - // Just ignore those ones... } } } - } - break; } + } + } else if (twitter != null) { + + try { + switch (input.mStatusesType) { + case DELETE: { + if (input.mStatuses != null) { + for (int i = 0; i < input.mStatuses.getStatusCount(); i++) { + TwitterStatus twitterStatus = input.mStatuses.getStatus(i); + twitter.destroyStatus(twitterStatus.mId); + } + } + break; + } + + case SET_FAVORITE: { + boolean favorite = input.mValue == 1; + + if (input.mStatuses != null) { + for (int i = 0; i < input.mStatuses.getStatusCount(); i++) { + TwitterStatus twitterStatus = input.mStatuses.getStatus(i); + if (twitterStatus.mIsFavorited != favorite) { + try { + twitter4j.Status status; + if (favorite) { + status = twitter.createFavorite(twitterStatus.mId); + } else { + status = twitter.destroyFavorite(twitterStatus.mId); + } + + // Yuck: See the comment for + // TwitterStatus.setFavorite() for + // reasons for this + twitterStatus = new TwitterStatus(status); + twitterStatus.setFavorite(favorite); + + contentFeed.add(twitterStatus); + } catch (TwitterException e) { + // we might get errors setting the favorite + // state to the same + // value again. + // Just ignore those ones... + } + } + } + + } + + break; + } } } catch (TwitterException e) { e.printStackTrace(); @@ -337,7 +334,7 @@ else if (twitter != null) { } return new ModifyStatusesTaskOutput( - new TwitterFetchResult(errorDescription == null ? true : false, errorDescription), + new TwitterFetchResult(errorDescription == null, errorDescription), input.mCallbackHandle, contentFeed, null); } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterPaging.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterPaging.java index 4b1dd044..6ae8887c 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterPaging.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterPaging.java @@ -17,12 +17,16 @@ package org.tweetalib.android; import android.util.Log; + import org.appdotnet4j.model.AdnPaging; + import twitter4j.Paging; public class TwitterPaging { public static final int DEFAULT_STATUS_COUNT = 100; + public static final int INCREMENTING_STATUS_COUNT_START = 25; + public static final int INCREMENTING_STATUS_COUNT_MAX = 200; /* * @@ -50,7 +54,7 @@ public TwitterPaging(Integer page, Integer count, Long sinceId, Long maxId) { if (page != null) { mPage = page; } - if (count != null) { + if (count != null && count > 0) { mCount = count; } else { mCount = DEFAULT_STATUS_COUNT; @@ -138,33 +142,15 @@ public AdnPaging getAdnPaging() { } } - if (mCount != null) { - result.setCount(mCount); - } else { - result.setCount(DEFAULT_STATUS_COUNT); - } - return result; } - public Integer getPage() { - return mPage; - } - public Integer getCount() { return mCount; } - public Long getMaxId() { - return mMaxId; - } - - public Long getSinceId() { - return mSinceId; - } - private Integer mPage; - private Integer mCount; + private final Integer mCount; private Long mMaxId; private Long mSinceId; diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterSignIn.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterSignIn.java index dad7112d..b437d794 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterSignIn.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterSignIn.java @@ -16,38 +16,29 @@ package org.tweetalib.android; -import java.util.HashMap; - import org.asynctasktex.AsyncTaskEx; - import org.socialnetlib.android.SocialNetConstant; -import org.socialnetlib.android.SocialNetConstant.Type; +import org.tweetalib.android.model.TwitterUser; + +import java.util.HashMap; + import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken; -import org.tweetalib.android.model.TwitterUser; - public class TwitterSignIn { private SignInWorkerCallbacks mCallbacks; private Integer mGetAuthUrlCallbackHandle; - private HashMap mGetAuthUrlCallbackMap; + private final HashMap mGetAuthUrlCallbackMap; private Integer mGetOAuthAccessTokenCallbackHandle; - private HashMap mGetOAuthAccessTokenCallbackMap; + private final HashMap mGetOAuthAccessTokenCallbackMap; - /* - * - */ - public void clearCallbacks() { - mGetAuthUrlCallbackMap.clear(); - mGetOAuthAccessTokenCallbackMap.clear(); - } /* - * + * */ public interface SignInWorkerCallbacks { @@ -58,7 +49,7 @@ public interface SignInWorkerCallbacks { public String getConsumerSecret(); public TwitterUser verifyCredentials(String accessToken, - String accessTokenSecret); + String accessTokenSecret); } /* @@ -75,7 +66,7 @@ public void setWorkerCallbacks(SignInWorkerCallbacks callbacks) { public interface GetAuthUrlCallbackInterface { public void finished(boolean successful, String url, - RequestToken requestToken); + RequestToken requestToken); } @@ -91,10 +82,6 @@ public GetAuthUrlCallback() { mHandle = kInvalidHandle; } - void setHandle(int handle) { - mHandle = handle; - } - private int mHandle; } @@ -104,7 +91,7 @@ void setHandle(int handle) { public interface GetOAuthAccessTokenCallbackInterface { public void finished(boolean successful, TwitterUser user, - String accessToken, String accessTokenSecret); + String accessToken, String accessTokenSecret); } @@ -142,9 +129,8 @@ public TwitterSignIn() { * */ GetAuthUrlCallback getAuthUrlCallback(Integer callbackHandle) { - GetAuthUrlCallback callback = mGetAuthUrlCallbackMap + return mGetAuthUrlCallbackMap .get(callbackHandle); - return callback; } /* @@ -161,9 +147,8 @@ void removeAuthUrlCallback(GetAuthUrlCallback callback) { */ GetOAuthAccessTokenCallback getOAuthAccessTokenCallback( Integer callbackHandle) { - GetOAuthAccessTokenCallback callback = mGetOAuthAccessTokenCallbackMap + return mGetOAuthAccessTokenCallbackMap .get(callbackHandle); - return callback; } /* @@ -180,12 +165,12 @@ void removeGetOAuthAccessTokenCallback(GetOAuthAccessTokenCallback callback) { */ public void getAuthUrl(GetAuthUrlCallback callback) { - assert (mGetAuthUrlCallbackMap.containsValue(callback) == false); + assert (!mGetAuthUrlCallbackMap.containsValue(callback)); mGetAuthUrlCallbackMap.put(mGetAuthUrlCallbackHandle, callback); new FetchAuthUrlTask().execute(AsyncTaskEx.PRIORITY_HIGHEST, "Get Auth URL", new FetchAuthUrlTaskInput( - mGetAuthUrlCallbackHandle)); + mGetAuthUrlCallbackHandle)); mGetAuthUrlCallbackHandle += 1; } @@ -194,16 +179,16 @@ public void getAuthUrl(GetAuthUrlCallback callback) { * */ public void getOAuthAccessToken(RequestToken requestToken, - String oauthVerifier, GetOAuthAccessTokenCallback callback) { + String oauthVerifier, GetOAuthAccessTokenCallback callback) { - assert (mGetOAuthAccessTokenCallbackMap.containsValue(callback) == false); + assert (!mGetOAuthAccessTokenCallbackMap.containsValue(callback)); mGetOAuthAccessTokenCallbackMap.put(mGetOAuthAccessTokenCallbackHandle, callback); new FetchOAuthAccessTokenTask().execute(AsyncTaskEx.PRIORITY_HIGHEST, "Get OAuth AccessToken", new FetchOAuthAccessTokenTaskInput( - requestToken, oauthVerifier, - mGetOAuthAccessTokenCallbackHandle)); + requestToken, oauthVerifier, + mGetOAuthAccessTokenCallbackHandle)); mGetOAuthAccessTokenCallbackHandle += 1; } @@ -217,7 +202,7 @@ class FetchAuthUrlTaskInput { mCallbackHandle = callbackHandle; } - Integer mCallbackHandle; + final Integer mCallbackHandle; } /* @@ -226,15 +211,15 @@ class FetchAuthUrlTaskInput { class FetchAuthUrlTaskOutput { FetchAuthUrlTaskOutput(Integer callbackHandle, - RequestToken requestToken, String url) { + RequestToken requestToken, String url) { mCallbackHandle = callbackHandle; mRequestToken = requestToken; mUrl = url; } - Integer mCallbackHandle; - RequestToken mRequestToken; - String mUrl; + final Integer mCallbackHandle; + final RequestToken mRequestToken; + final String mUrl; } /* @@ -287,16 +272,16 @@ protected void onPostExecute(FetchAuthUrlTaskOutput output) { class FetchOAuthAccessTokenTaskInput { FetchOAuthAccessTokenTaskInput(RequestToken requestToken, - String oauthVerifier, Integer callbackHandle) { + String oauthVerifier, Integer callbackHandle) { mRequestToken = requestToken; mOAuthVerifier = oauthVerifier; mCallbackHandle = callbackHandle; } - RequestToken mRequestToken; - String mOAuthVerifier; - Integer mCallbackHandle; + final RequestToken mRequestToken; + final String mOAuthVerifier; + final Integer mCallbackHandle; } /* @@ -305,7 +290,7 @@ class FetchOAuthAccessTokenTaskInput { class FetchOAuthAccessTokenTaskOutput { FetchOAuthAccessTokenTaskOutput(TwitterUser user, String accessToken, - String accessTokenSecret, Integer callbackHandle) { + String accessTokenSecret, Integer callbackHandle) { mUser = user; mAccessToken = accessToken; @@ -313,10 +298,10 @@ class FetchOAuthAccessTokenTaskOutput { mCallbackHandle = callbackHandle; } - TwitterUser mUser; - String mAccessToken; - String mAccessTokenSecret; - Integer mCallbackHandle; + final TwitterUser mUser; + final String mAccessToken; + final String mAccessTokenSecret; + final Integer mCallbackHandle; } /* @@ -337,19 +322,19 @@ protected FetchOAuthAccessTokenTaskOutput doInBackground( String accessTokenSecret = null; switch (mCallbacks.getType()) { - case Twitter: - Twitter twitter = new TwitterFactory().getInstance(); - twitter.setOAuthConsumer(mCallbacks.getConsumerKey(), - mCallbacks.getConsumerSecret()); - AccessToken at = twitter.getOAuthAccessToken( - input.mRequestToken, input.mOAuthVerifier); - accessToken = at.getToken(); - accessTokenSecret = at.getTokenSecret(); - break; - - case Appdotnet: - accessToken = input.mOAuthVerifier; - break; + case Twitter: + Twitter twitter = new TwitterFactory().getInstance(); + twitter.setOAuthConsumer(mCallbacks.getConsumerKey(), + mCallbacks.getConsumerSecret()); + AccessToken at = twitter.getOAuthAccessToken( + input.mRequestToken, input.mOAuthVerifier); + accessToken = at.getToken(); + accessTokenSecret = at.getTokenSecret(); + break; + + case Appdotnet: + accessToken = input.mOAuthVerifier; + break; } TwitterUser user = mCallbacks.verifyCredentials(accessToken, @@ -357,11 +342,9 @@ protected FetchOAuthAccessTokenTaskOutput doInBackground( return new FetchOAuthAccessTokenTaskOutput(user, accessToken, accessTokenSecret, input.mCallbackHandle); - } - catch (NullPointerException e) { + } catch (NullPointerException e) { e.printStackTrace(); - } - catch (TwitterException e) { + } catch (TwitterException e) { e.printStackTrace(); } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterUtil.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterUtil.java index f687f131..f222e3d4 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterUtil.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/TwitterUtil.java @@ -16,13 +16,15 @@ package org.tweetalib.android; +import com.twitter.Autolink; + +import org.appdotnet4j.model.AdnPost; + import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; -import org.appdotnet4j.model.AdnPost; -import org.tweetalib.android.model.TwitterMediaEntity; import twitter4j.MediaEntity; import twitter4j.Paging; import twitter4j.Query; @@ -30,84 +32,67 @@ import twitter4j.URLEntity; import twitter4j.UserMentionEntity; -import com.twitter.Autolink; -import com.twitter.AutolinkEx; - public class TwitterUtil { - private static AutolinkEx mAutolinkEx; - private static Autolink mAutolink; + private static Autolink mAutoLink; + private static boolean mAllowReInit = true; private static void initCommon() { - if (mAutolinkEx == null) { - mAutolinkEx = new AutolinkEx(); - mAutolinkEx.setNoFollow(false); - mAutolinkEx.setUsernameIncludeSymbol(true); - mAutolinkEx.setUrlTarget("_blank"); - } + if(mAllowReInit) + { + if (mAutoLink == null) { + mAutoLink = new Autolink(); + } - if (mAutolink == null) { - mAutolink = new Autolink(); - mAutolink.setNoFollow(false); - mAutolink.setUsernameIncludeSymbol(true); - mAutolink.setUrlTarget("_blank"); + mAutoLink.setExtractURLWithoutProtocol(false); } } /* - * + * */ public static String stripMarkup(String text) { return text != null ? android.text.Html.fromHtml(text).toString() : null; } - /* - * - */ - public static String getTextMarkup(String text) { - return getStatusMarkup(text, null, null, null); + public static String getTextMarkup(String text, URLEntity[] urlEntities) { + return getStatusMarkup(text, null, urlEntities); } /* * return the markup for a status, which replaces t.co/ links with the * visible links */ - public static String getStatusMarkup(Status status, - TwitterMediaEntity twitterMediaEntity) { - return getStatusMarkup(status.getText(), twitterMediaEntity, - status.getMediaEntities(), status.getURLEntities()); + public static String getStatusMarkup(Status status) { + return getStatusMarkup(status.getText(), status.getMediaEntities(), status.getURLEntities()); } /* * */ - public static String getStatusMarkup(Status tweet) { - return getStatusMarkup(tweet.getText(), null, tweet.getMediaEntities(), - tweet.getURLEntities()); - } + public static String getStatusMarkup(AdnPost post) { - /* - * - */ - public static String getStatusMarkup(AdnPost post, - TwitterMediaEntity mediaEntity) { - return getStatusMarkup(post.mText, mediaEntity, null, null); + initCommon(); + mAutoLink.setExtractURLWithoutProtocol(true); + mAllowReInit = false; + + String statusMarkup = getStatusMarkup(post.mText, null, post.mUrls); + mAllowReInit = true; + + return statusMarkup; } /* * */ - public static String getStatusMarkup(String statusText, - TwitterMediaEntity twitterMediaEntity, MediaEntity[] mediaEntities, - URLEntity[] urlEntities) { + public static String getStatusMarkup(String statusText, MediaEntity[] mediaEntities, + URLEntity[] urlEntities) { initCommon(); - String autoLinkAll = mAutolinkEx.autoLinkAll(statusText, - twitterMediaEntity, mediaEntities, urlEntities); - return autoLinkAll; + return mAutoLink.autoLinkAll(statusText, mediaEntities, urlEntities); } /* @@ -188,8 +173,7 @@ public static Date iso6801StringToDate(String iso8601string) } catch (IndexOutOfBoundsException e) { throw new ParseException("Invalid length", 0); } - Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s); - return date; + return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s); } } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/callback/TwitterFetchDirectMessagesFinishedCallback.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/callback/TwitterFetchDirectMessagesFinishedCallback.java index a45211f6..64c87969 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/callback/TwitterFetchDirectMessagesFinishedCallback.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/callback/TwitterFetchDirectMessagesFinishedCallback.java @@ -22,16 +22,12 @@ public abstract class TwitterFetchDirectMessagesFinishedCallback implements TwitterFetchDirectMessagesFinishedCallbackInterface { - static final int kInvalidHandle = -1; + private static final int kInvalidHandle = -1; public TwitterFetchDirectMessagesFinishedCallback() { mHandle = kInvalidHandle; } - public void setHandle(int handle) { - mHandle = handle; - } - public int getHandle() { return mHandle; } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/callback/TwitterFetchDirectMessagesFinishedCallbackInterface.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/callback/TwitterFetchDirectMessagesFinishedCallbackInterface.java index 3d2d0527..0a0a57ac 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/callback/TwitterFetchDirectMessagesFinishedCallbackInterface.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/callback/TwitterFetchDirectMessagesFinishedCallbackInterface.java @@ -23,6 +23,6 @@ public interface TwitterFetchDirectMessagesFinishedCallbackInterface { public void finished(TwitterContentHandle contentHandle, TwitterFetchResult result, - TwitterDirectMessages messages); + TwitterDirectMessages messages); } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/callback/TwitterFetchStatusesFinishedCallback.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/callback/TwitterFetchStatusesFinishedCallback.java index 0a6ffcd7..f3b507b2 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/callback/TwitterFetchStatusesFinishedCallback.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/callback/TwitterFetchStatusesFinishedCallback.java @@ -22,16 +22,12 @@ public abstract class TwitterFetchStatusesFinishedCallback implements TwitterFetchStatusesFinishedCallbackInterface { - static final int kInvalidHandle = -1; + private static final int kInvalidHandle = -1; public TwitterFetchStatusesFinishedCallback() { mHandle = kInvalidHandle; } - public void setHandle(int handle) { - mHandle = handle; - } - public int getHandle() { return mHandle; } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/fetch/TwitterFetchDirectMessages.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/fetch/TwitterFetchDirectMessages.java index 2942675f..2d18fc38 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/fetch/TwitterFetchDirectMessages.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/fetch/TwitterFetchDirectMessages.java @@ -39,15 +39,15 @@ public class TwitterFetchDirectMessages { private FetchMessagesWorkerCallbacks mCallbacks; - private HashMap mMessagesHashMap; + private final HashMap mMessagesHashMap; private Integer mFetchMessagesCallbackHandle; - private HashMap mFinishedCallbackMap; + private final HashMap mFinishedCallbackMap; /* - * + * */ public void clearCallbacks() { - if (mFinishedCallbackMap != null ) { + if (mFinishedCallbackMap != null) { mFinishedCallbackMap.clear(); } } @@ -83,9 +83,8 @@ public void setWorkerCallbacks(FetchMessagesWorkerCallbacks callbacks) { */ TwitterFetchDirectMessagesFinishedCallback getFetchStatusesCallback( Integer callbackHandle) { - TwitterFetchDirectMessagesFinishedCallback callback = mFinishedCallbackMap + return mFinishedCallbackMap .get(callbackHandle); - return callback; } /* @@ -135,7 +134,7 @@ public TwitterDirectMessages getDirectMessages( TwitterFetchDirectMessagesFinishedCallback callback, ConnectionStatus connectionStatus) { - if (connectionStatus != null && connectionStatus.isOnline() == false) { + if (connectionStatus != null && !connectionStatus.isOnline()) { if (callback != null) { callback.finished(contentHandle, new TwitterFetchResult(false, connectionStatus.getErrorMessageNoConnection()), null); @@ -148,10 +147,10 @@ public TwitterDirectMessages getDirectMessages( } mFinishedCallbackMap.put(mFetchMessagesCallbackHandle, callback); - new FetchStatusesTask().execute(AsyncTaskEx.PRIORITY_MEDIUM, + new FetchStatusesTask().execute(AsyncTaskEx.PRIORITY_HIGH, "Fetch DMs", new FetchDirectMessagesTaskInput( - mFetchMessagesCallbackHandle, contentHandle, paging, - connectionStatus)); + mFetchMessagesCallbackHandle, contentHandle, paging, + connectionStatus)); mFetchMessagesCallbackHandle += 1; return null; @@ -161,11 +160,11 @@ public TwitterDirectMessages getDirectMessages( * */ public void sendDirectMessage(long userId, String recipientScreenName, - String statusText, - TwitterContentHandle contentHandle, - TwitterFetchDirectMessagesFinishedCallback callback, - ConnectionStatus connectionStatus) { - if (connectionStatus != null && connectionStatus.isOnline() == false) { + String statusText, + TwitterContentHandle contentHandle, + TwitterFetchDirectMessagesFinishedCallback callback, + ConnectionStatus connectionStatus) { + if (connectionStatus != null && !connectionStatus.isOnline()) { if (callback != null) { callback.finished(contentHandle, new TwitterFetchResult(false, connectionStatus.getErrorMessageNoConnection()), null); @@ -173,10 +172,10 @@ public void sendDirectMessage(long userId, String recipientScreenName, } mFinishedCallbackMap.put(mFetchMessagesCallbackHandle, callback); - new FetchStatusesTask().execute(AsyncTaskEx.PRIORITY_MEDIUM, + new FetchStatusesTask().execute(AsyncTaskEx.PRIORITY_HIGH, "Fetch DMs", new FetchDirectMessagesTaskInput( - mFetchMessagesCallbackHandle, userId, - recipientScreenName, statusText, connectionStatus)); + mFetchMessagesCallbackHandle, userId, + recipientScreenName, statusText, connectionStatus)); mFetchMessagesCallbackHandle += 1; } @@ -194,8 +193,8 @@ public void cancel(TwitterFetchDirectMessagesFinishedCallback callback) { class FetchDirectMessagesTaskInput { FetchDirectMessagesTaskInput(Integer callbackHandle, - TwitterContentHandle contentHandle, TwitterPaging paging, - ConnectionStatus connectionStatus) { + TwitterContentHandle contentHandle, TwitterPaging paging, + ConnectionStatus connectionStatus) { mCallbackHandle = callbackHandle; mContentHandle = contentHandle; mPaging = paging; @@ -203,8 +202,8 @@ class FetchDirectMessagesTaskInput { } FetchDirectMessagesTaskInput(Integer callbackHandle, Long userId, - String recipientScreenName, String statusText, - ConnectionStatus connectionStatus) { + String recipientScreenName, String statusText, + ConnectionStatus connectionStatus) { mCallbackHandle = callbackHandle; mUserId = userId; mRecipientScreenName = recipientScreenName; @@ -212,13 +211,13 @@ class FetchDirectMessagesTaskInput { mConnectionStatus = connectionStatus; } - Integer mCallbackHandle; + final Integer mCallbackHandle; Long mUserId; String mRecipientScreenName; String mStatusText; TwitterContentHandle mContentHandle; TwitterPaging mPaging; - ConnectionStatus mConnectionStatus; + final ConnectionStatus mConnectionStatus; } /* @@ -227,17 +226,17 @@ class FetchDirectMessagesTaskInput { class FetchDirectMessagesTaskOutput { FetchDirectMessagesTaskOutput(TwitterContentHandle contentHandle, TwitterFetchResult result, - Integer callbackHandle, TwitterDirectMessages messages) { + Integer callbackHandle, TwitterDirectMessages messages) { mContentHandle = contentHandle; mResult = result; mCallbackHandle = callbackHandle; mMessages = messages; } - TwitterContentHandle mContentHandle; - TwitterFetchResult mResult; - Integer mCallbackHandle; - TwitterDirectMessages mMessages; + final TwitterContentHandle mContentHandle; + final TwitterFetchResult mResult; + final Integer mCallbackHandle; + final TwitterDirectMessages mMessages; } /* @@ -258,7 +257,7 @@ protected FetchDirectMessagesTaskOutput doInBackground( Twitter twitter = getTwitterInstance(); String errorDescription = null; - if (input.mConnectionStatus != null && input.mConnectionStatus.isOnline() == false) { + if (input.mConnectionStatus != null && !input.mConnectionStatus.isOnline()) { return new FetchDirectMessagesTaskOutput(input.mContentHandle, new TwitterFetchResult(false, input.mConnectionStatus @@ -280,7 +279,7 @@ protected FetchDirectMessagesTaskOutput doInBackground( } else { Paging defaultPaging = new Paging(1); defaultPaging.setCount(30); - Paging paging = null; + Paging paging; if (input.mPaging != null) { paging = input.mPaging.getT4JPaging(); } else { @@ -288,33 +287,33 @@ protected FetchDirectMessagesTaskOutput doInBackground( } switch (input.mContentHandle.getDirectMessagesType()) { - case ALL_MESSAGES: { - messages = getDirectMessages(input.mContentHandle); - // Annoyingly, DMs can't be retrieved in a threaded - // format. Handle this - // by getting sent and received and managing - // ourselves... - Log.d("api-call", "getDirectMessages"); - ResponseList receivedDirectMessages = twitter - .getDirectMessages(paging); - Log.d("api-call", "getSendDirectMessages"); - ResponseList sentDirectMessages = twitter - .getSentDirectMessages(paging); - - AddUserCallback addUserCallback = new AddUserCallback() { - - @Override - public void addUser(User user) { - mCallbacks.addUser(user); - } - }; - - messages.add(sentDirectMessages, - receivedDirectMessages, addUserCallback); - break; - } - default: - break; + case ALL_MESSAGES: { + messages = getDirectMessages(input.mContentHandle); + // Annoyingly, DMs can't be retrieved in a threaded + // format. Handle this + // by getting sent and received and managing + // ourselves... + Log.d("api-call", "getDirectMessages"); + ResponseList receivedDirectMessages = twitter + .getDirectMessages(paging); + Log.d("api-call", "getSendDirectMessages"); + ResponseList sentDirectMessages = twitter + .getSentDirectMessages(paging); + + AddUserCallback addUserCallback = new AddUserCallback() { + + @Override + public void addUser(User user) { + mCallbacks.addUser(user); + } + }; + + messages.add(sentDirectMessages, + receivedDirectMessages, addUserCallback); + break; + } + default: + break; } } @@ -330,7 +329,7 @@ public void addUser(User user) { } return new FetchDirectMessagesTaskOutput(input.mContentHandle, new TwitterFetchResult( - errorDescription == null ? true : false, errorDescription), + errorDescription == null, errorDescription), input.mCallbackHandle, messages); } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/fetch/TwitterFetchStatuses.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/fetch/TwitterFetchStatuses.java index be0df660..5e929599 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/fetch/TwitterFetchStatuses.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/fetch/TwitterFetchStatuses.java @@ -45,16 +45,16 @@ public class TwitterFetchStatuses { private FetchStatusesWorkerCallbacks mCallbacks; - private HashMap mStatusesHashMap; + private final HashMap mStatusesHashMap; private Integer mFetchStatusesCallbackHandle; - private HashMap mFinishedCallbackMap; - private HashMap mHashtagMap; + private final HashMap mFinishedCallbackMap; + private final HashMap mHashtagMap; /* * */ public void clearCallbacks() { - if (mFinishedCallbackMap != null ) { + if (mFinishedCallbackMap != null) { for (Integer key : mFinishedCallbackMap.keySet()) { TwitterFetchStatusesFinishedCallback callback = mFinishedCallbackMap.get(key); cancel(callback); @@ -102,8 +102,7 @@ public void setWorkerCallbacks(FetchStatusesWorkerCallbacks callbacks) { * */ TwitterFetchStatusesFinishedCallback getFetchStatusesCallback(Integer callbackHandle) { - TwitterFetchStatusesFinishedCallback callback = mFinishedCallbackMap.get(callbackHandle); - return callback; + return mFinishedCallbackMap.get(callbackHandle); } /* @@ -127,7 +126,7 @@ AppdotnetApi getAppdotnetApi() { } /* - * + * */ TwitterStatuses setStatuses(TwitterContentHandle contentHandle, QueryResult result) { TwitterStatuses feed = getStatuses(contentHandle); @@ -185,14 +184,17 @@ public void addUser(AdnUser user) { if (posts != null && posts.mPosts != null && posts.mPosts.size() > 0) { feed.add(posts, addUserCallback); } + else { + feed.setFeedFullyRefreshed(); + } return feed; } /* * */ - public TwitterStatuses setStatuses(TwitterContentHandle contentHandle, TwitterStatuses statuses, - boolean resetExisting) { + TwitterStatuses setStatuses(TwitterContentHandle contentHandle, TwitterStatuses statuses, + boolean resetExisting) { TwitterStatuses feed = getStatuses(contentHandle); if (resetExisting) { feed.reset(); @@ -223,9 +225,9 @@ public TwitterStatuses getStatuses(TwitterContentHandle handle) { * */ public void trigger(TwitterContentHandle contentHandle, TwitterPaging paging, - TwitterFetchStatusesFinishedCallback callback, ConnectionStatus connectionStatus, int priorityOffset) { + TwitterFetchStatusesFinishedCallback callback, ConnectionStatus connectionStatus, int priorityOffset) { - if (connectionStatus != null && connectionStatus.isOnline() == false) { + if (connectionStatus != null && !connectionStatus.isOnline()) { if (callback != null) { callback.finished(new TwitterFetchResult(false, connectionStatus.getErrorMessageNoConnection()), null, contentHandle); @@ -238,7 +240,7 @@ public void trigger(TwitterContentHandle contentHandle, TwitterPaging paging, } mFinishedCallbackMap.put(mFetchStatusesCallbackHandle, callback); - new FetchStatusesTask().execute(AsyncTaskEx.PRIORITY_HIGH + priorityOffset, "Fetch Statuses", + new FetchStatusesTask().execute(AsyncTaskEx.PRIORITY_NOT_QUITE_HIGHEST + priorityOffset, "Fetch Statuses", new FetchStatusesTaskInput(mFetchStatusesCallbackHandle, contentHandle, paging, connectionStatus)); mFetchStatusesCallbackHandle += 1; @@ -258,17 +260,17 @@ public void cancel(TwitterFetchStatusesFinishedCallback callback) { class FetchStatusesTaskInput { FetchStatusesTaskInput(Integer callbackHandle, TwitterContentHandle contentHandle, TwitterPaging paging, - ConnectionStatus connectionStatus) { + ConnectionStatus connectionStatus) { mCallbackHandle = callbackHandle; mContentHandle = contentHandle; mPaging = paging; mConnectionStatus = connectionStatus; } - Integer mCallbackHandle; - TwitterContentHandle mContentHandle; - TwitterPaging mPaging; - ConnectionStatus mConnectionStatus; + final Integer mCallbackHandle; + final TwitterContentHandle mContentHandle; + final TwitterPaging mPaging; + final ConnectionStatus mConnectionStatus; } /* @@ -277,17 +279,17 @@ class FetchStatusesTaskInput { class FetchStatusesTaskOutput { FetchStatusesTaskOutput(TwitterFetchResult result, Integer callbackHandle, TwitterStatuses feed, - TwitterContentHandle contentHandle) { + TwitterContentHandle contentHandle) { mResult = result; mCallbackHandle = callbackHandle; mContentHandle = contentHandle; mFeed = feed; } - TwitterFetchResult mResult; - Integer mCallbackHandle; - TwitterContentHandle mContentHandle; - TwitterStatuses mFeed; + final TwitterFetchResult mResult; + final Integer mCallbackHandle; + final TwitterContentHandle mContentHandle; + final TwitterStatuses mFeed; } /* @@ -304,7 +306,7 @@ protected FetchStatusesTaskOutput doInBackground(FetchStatusesTaskInput... input FetchStatusesTaskInput input = inputArray[0]; String errorDescription = null; - if (input.mConnectionStatus != null && input.mConnectionStatus.isOnline() == false) { + if (input.mConnectionStatus != null && !input.mConnectionStatus.isOnline()) { return new FetchStatusesTaskOutput( new TwitterFetchResult(false, input.mConnectionStatus.getErrorMessageNoConnection()), input.mCallbackHandle, null, input.mContentHandle); @@ -314,8 +316,7 @@ protected FetchStatusesTaskOutput doInBackground(FetchStatusesTaskInput... input if (appdotnetApi != null) { AdnPaging defaultPaging = new AdnPaging(1); - defaultPaging.setCount(TwitterPaging.DEFAULT_STATUS_COUNT); - AdnPaging paging = null; + AdnPaging paging; if (input.mPaging != null) { paging = input.mPaging.getAdnPaging(); @@ -324,123 +325,122 @@ protected FetchStatusesTaskOutput doInBackground(FetchStatusesTaskInput... input } switch (input.mContentHandle.getStatusesType()) { - case USER_HOME_TIMELINE: { - AdnPosts posts = appdotnetApi.getAdnStream(paging); - contentFeed = setStatuses(input.mContentHandle, posts); - break; - } - - case USER_TIMELINE: { - String userIdAsString = input.mContentHandle.getIdentifier(); - try { - int userId = Integer.valueOf(userIdAsString); - AdnPosts posts = appdotnetApi.getAdnUserStream(userId, paging); + case USER_HOME_TIMELINE: { + AdnPosts posts = appdotnetApi.getAdnStream(paging); contentFeed = setStatuses(input.mContentHandle, posts); - } catch (NumberFormatException e) { + break; } - break; - } - case RETWEETS_OF_ME: { - AdnInteractions interactions = appdotnetApi.getAdnInteractions(); - AdnPosts posts = null; - if (interactions != null) { - posts = interactions.getAsPosts(); + case USER_TIMELINE: { + String userIdAsString = input.mContentHandle.getIdentifier(); + try { + int userId = Integer.valueOf(userIdAsString); + AdnPosts posts = appdotnetApi.getAdnUserStream(userId, paging); + contentFeed = setStatuses(input.mContentHandle, posts); + } catch (NumberFormatException e) { + } + break; } - contentFeed = setStatuses(input.mContentHandle, posts); - break; - } - case SCREEN_NAME_SEARCH: - case USER_MENTIONS: { - String userIdAsString = input.mContentHandle.getIdentifier(); - try { - int userId = Integer.valueOf(userIdAsString); - AdnPosts posts = appdotnetApi.getAdnMentions(userId, paging); + case RETWEETS_OF_ME: { + AdnInteractions interactions = appdotnetApi.getAdnInteractions(); + AdnPosts posts = null; + if (interactions != null) { + posts = interactions.getAsPosts(); + } contentFeed = setStatuses(input.mContentHandle, posts); - } catch (NumberFormatException e) { + break; } - break; - } - case USER_FAVORITES: { - String userIdAsString = input.mContentHandle.getIdentifier(); - AdnPosts posts = appdotnetApi.getAdnFavorites(userIdAsString, paging); - contentFeed = setStatuses(input.mContentHandle, posts); - break; - } + case SCREEN_NAME_SEARCH: + case USER_MENTIONS: { + String userIdAsString = input.mContentHandle.getIdentifier(); + try { + int userId = Integer.valueOf(userIdAsString); + AdnPosts posts = appdotnetApi.getAdnMentions(userId, paging); + contentFeed = setStatuses(input.mContentHandle, posts); + } catch (NumberFormatException e) { + } + break; + } - case STATUS_SEARCH: { - String searchTerm = input.mContentHandle.getScreenName(); - if (searchTerm.length() > 1 && searchTerm.charAt(0) == '#') { - searchTerm = searchTerm.substring(1); + case USER_FAVORITES: { + String userIdAsString = input.mContentHandle.getIdentifier(); + AdnPosts posts = appdotnetApi.getAdnFavorites(userIdAsString, paging); + contentFeed = setStatuses(input.mContentHandle, posts); + break; } - AdnPosts posts = appdotnetApi.getAdnTagPosts(searchTerm, paging); - contentFeed = setStatuses(input.mContentHandle, posts); - break; - } - case GLOBAL_FEED: { - AdnPosts posts = appdotnetApi.getAdnGlobalStream(paging); - contentFeed = setStatuses(input.mContentHandle, posts); - break; - } + case STATUS_SEARCH: { + String searchTerm = input.mContentHandle.getScreenName(); + if (searchTerm.length() > 1 && searchTerm.charAt(0) == '#') { + searchTerm = searchTerm.substring(1); + } + AdnPosts posts = appdotnetApi.getAdnTagPosts(searchTerm, paging); + contentFeed = setStatuses(input.mContentHandle, posts); + break; + } - case PREVIOUS_CONVERSATION: { - TwitterStatuses statuses = new TwitterStatuses(); - long statusId = Long.parseLong(input.mContentHandle.getIdentifier()); - AdnPost post = appdotnetApi.getAdnPost(statusId); - if (post != null) { - TwitterStatus status = new TwitterStatus(post); - if (status.mInReplyToStatusId != null) { - long inReplyToStatusId = status.mInReplyToStatusId; - for (int i = 0; i < 4; i++) { - TwitterStatus reply = new TwitterStatus(appdotnetApi.getAdnPost(inReplyToStatusId)); - statuses.add(reply, false); - if (reply.mInReplyToStatusId != null) { - inReplyToStatusId = reply.mInReplyToStatusId; - } else { - break; + case GLOBAL_FEED: { + AdnPosts posts = appdotnetApi.getAdnGlobalStream(paging); + contentFeed = setStatuses(input.mContentHandle, posts); + break; + } + + case PREVIOUS_CONVERSATION: { + TwitterStatuses statuses = new TwitterStatuses(); + long statusId = Long.parseLong(input.mContentHandle.getIdentifier()); + AdnPost post = appdotnetApi.getAdnPost(statusId); + if (post != null) { + TwitterStatus status = new TwitterStatus(post); + if (status.mInReplyToStatusId != null) { + long inReplyToStatusId = status.mInReplyToStatusId; + for (int i = 0; i < 4; i++) { + TwitterStatus reply = new TwitterStatus(appdotnetApi.getAdnPost(inReplyToStatusId)); + statuses.add(reply, false); + if (reply.mInReplyToStatusId != null) { + inReplyToStatusId = reply.mInReplyToStatusId; + } else { + break; + } } } - } - statuses.add(status, false); - if (statuses.getStatusCount() > 0) { - statuses.sort(); - contentFeed = setStatuses(input.mContentHandle, statuses, false); + statuses.add(status, false); + if (statuses.getStatusCount() > 0) { + statuses.sort(); + contentFeed = setStatuses(input.mContentHandle, statuses, false); + } } } - statuses = null; - } - case FULL_CONVERSATION: { - long statusId = Long.parseLong(input.mContentHandle.getIdentifier()); + case FULL_CONVERSATION: { + long statusId = Long.parseLong(input.mContentHandle.getIdentifier()); - AddUserCallback addUserCallback = new AddUserCallback() { + AddUserCallback addUserCallback = new AddUserCallback() { - @Override - public void addUser(User user) { - mCallbacks.addUser(user); - } + @Override + public void addUser(User user) { + mCallbacks.addUser(user); + } - @Override - public void addUser(AdnUser user) { - mCallbacks.addUser(user); - } - }; + @Override + public void addUser(AdnUser user) { + mCallbacks.addUser(user); + } + }; - AdnPosts conversation = appdotnetApi.getAdnConversation(statusId, paging); - if (conversation != null && conversation.mPosts != null && conversation.mPosts.size() > 0) { - TwitterStatuses statuses = new TwitterStatuses(); - statuses.add(conversation, addUserCallback); - contentFeed = setStatuses(input.mContentHandle, statuses, true); + AdnPosts conversation = appdotnetApi.getAdnConversation(statusId, paging); + if (conversation != null && conversation.mPosts != null && conversation.mPosts.size() > 0) { + TwitterStatuses statuses = new TwitterStatuses(); + statuses.add(conversation, addUserCallback); + contentFeed = setStatuses(input.mContentHandle, statuses, true); + } } - } - break; - - default: break; + + default: + break; } } else { @@ -449,7 +449,7 @@ public void addUser(AdnUser user) { Paging defaultPaging = new Paging(1); defaultPaging.setCount(TwitterPaging.DEFAULT_STATUS_COUNT); - Paging paging = null; + Paging paging; if (input.mPaging != null) { paging = input.mPaging.getT4JPaging(); } else { @@ -458,107 +458,109 @@ public void addUser(AdnUser user) { try { switch (input.mContentHandle.getStatusesType()) { - case USER_HOME_TIMELINE: { - Log.d("api-call", "getHomeTimeline"); - ResponseList statuses; - statuses = twitter.getHomeTimeline(paging); - contentFeed = setStatuses(input.mContentHandle, statuses); - break; - } - - case USER_TIMELINE: { - Log.d("api-call", "getUserTimeline"); - ResponseList statuses = - twitter.getUserTimeline(input.mContentHandle.getScreenName(), paging); - contentFeed = setStatuses(input.mContentHandle, statuses); - break; - } + case USER_HOME_TIMELINE: { + Log.d("api-call", "getHomeTimeline"); + ResponseList statuses; + statuses = twitter.getHomeTimeline(paging); + contentFeed = setStatuses(input.mContentHandle, statuses); + break; + } - case USER_MENTIONS: { - Log.d("api-call", "getMentionsTimeline"); - ResponseList statuses = twitter.getMentionsTimeline(paging); - contentFeed = setStatuses(input.mContentHandle, statuses); - break; - } + case USER_TIMELINE: { + Log.d("api-call", "getUserTimeline"); + ResponseList statuses = + twitter.getUserTimeline(input.mContentHandle.getScreenName(), paging); + contentFeed = setStatuses(input.mContentHandle, statuses); + break; + } - case USER_LIST_TIMELINE: { - String listIdAsString = input.mContentHandle.getIdentifier(); - try { - Log.d("api-call", "getUserListStatuses"); - int listId = Integer.valueOf(listIdAsString); - ResponseList statuses = twitter.getUserListStatuses(listId, paging); + case USER_MENTIONS: { + Log.d("api-call", "getMentionsTimeline"); + ResponseList statuses = twitter.getMentionsTimeline(paging); contentFeed = setStatuses(input.mContentHandle, statuses); - } catch (NumberFormatException e) { + break; } - break; - } - case USER_FAVORITES: { - Log.d("api-call", "getFavorites"); - ResponseList statuses = - twitter.getFavorites(input.mContentHandle.getScreenName(), paging); - contentFeed = setStatuses(input.mContentHandle, statuses); - break; - } + case USER_LIST_TIMELINE: { + String listIdAsString = input.mContentHandle.getIdentifier(); + try { + Log.d("api-call", "getUserListStatuses"); + int listId = Integer.valueOf(listIdAsString); + ResponseList statuses = twitter.getUserListStatuses(listId, paging); + contentFeed = setStatuses(input.mContentHandle, statuses); + } catch (NumberFormatException e) { + }catch (OutOfMemoryError e) { + errorDescription="There was an out of memory doing that!"; + } + break; + } - case RETWEETS_OF_ME: { - Log.d("api-call", "getRetweetsOfMe"); - ResponseList statuses = twitter.getRetweetsOfMe(paging); - contentFeed = setStatuses(input.mContentHandle, statuses); - break; - } + case USER_FAVORITES: { + Log.d("api-call", "getFavorites"); + ResponseList statuses = + twitter.getFavorites(input.mContentHandle.getScreenName(), paging); + contentFeed = setStatuses(input.mContentHandle, statuses); + break; + } - case SCREEN_NAME_SEARCH: { - Log.d("api-call", "search"); - Query query = new Query("@" + input.mContentHandle.getScreenName()); - query = TwitterUtil.updateQueryWithPaging(query, paging); - QueryResult result = twitter.search(query); - contentFeed = setStatuses(input.mContentHandle, result); - break; - } + case RETWEETS_OF_ME: { + Log.d("api-call", "getRetweetsOfMe"); + ResponseList statuses = twitter.getRetweetsOfMe(paging); + contentFeed = setStatuses(input.mContentHandle, statuses); + break; + } - case STATUS_SEARCH: { - Log.d("api-call", "search"); - Query query = new Query(input.mContentHandle.getScreenName()); - query = TwitterUtil.updateQueryWithPaging(query, paging); - QueryResult result = twitter.search(query); - contentFeed = setStatuses(input.mContentHandle, result); - break; - } + case SCREEN_NAME_SEARCH: { + Log.d("api-call", "search"); + Query query = new Query("@" + input.mContentHandle.getScreenName()); + query = TwitterUtil.updateQueryWithPaging(query, paging); + QueryResult result = twitter.search(query); + contentFeed = setStatuses(input.mContentHandle, result); + break; + } + case STATUS_SEARCH: { + Log.d("api-call", "search"); + Query query = new Query(input.mContentHandle.getScreenName()); + query = TwitterUtil.updateQueryWithPaging(query, paging); + QueryResult result = twitter.search(query); + contentFeed = setStatuses(input.mContentHandle, result); + break; + } - case PREVIOUS_CONVERSATION: - case FULL_CONVERSATION: { - Log.d("api-call", "showStatus"); - TwitterStatuses statuses = new TwitterStatuses(); - long statusId = Long.parseLong(input.mContentHandle.getIdentifier()); - TwitterStatus status = new TwitterStatus(twitter.showStatus(statusId)); - if (status.mInReplyToStatusId != null) { - long inReplyToStatusId = status.mInReplyToStatusId; - for (int i = 0; i < 4; i++) { - Log.d("api-call", "showStatus"); - TwitterStatus reply = new TwitterStatus(twitter.showStatus(inReplyToStatusId)); - statuses.add(reply, false); - if (reply.mInReplyToStatusId != null) { - inReplyToStatusId = reply.mInReplyToStatusId; - } else { - break; + + case PREVIOUS_CONVERSATION: + case FULL_CONVERSATION: { + Log.d("api-call", "showStatus"); + TwitterStatuses statuses = new TwitterStatuses(); + long statusId = Long.parseLong(input.mContentHandle.getIdentifier()); + TwitterStatus status = new TwitterStatus(twitter.showStatus(statusId)); + if (status.mInReplyToStatusId != null) { + long inReplyToStatusId = status.mInReplyToStatusId; + for (int i = 0; i < 4; i++) { + Log.d("api-call", "showStatus"); + TwitterStatus reply = new TwitterStatus(twitter.showStatus(inReplyToStatusId)); + statuses.add(reply, false); + if (reply.mInReplyToStatusId != null) { + inReplyToStatusId = reply.mInReplyToStatusId; + } else { + break; + } } } - } - statuses.add(status, false); + statuses.add(status, false); - if (statuses.getStatusCount() > 0) { - statuses.sort(); - contentFeed = setStatuses(input.mContentHandle, statuses, true); + if (statuses.getStatusCount() > 0) { + statuses.sort(); + contentFeed = setStatuses(input.mContentHandle, statuses, true); + } + + break; } - statuses = null; - break; - } - default: - break; + default: + break; } } catch (TwitterException e) { @@ -569,6 +571,14 @@ public void addUser(AdnUser user) { errorDescription += "\nTry again in " + e.getRateLimitStatus().getSecondsUntilReset() + " " + "seconds"; } + } catch (OutOfMemoryError e){ + e.printStackTrace(); + errorDescription = e.getMessage(); + Log.e("api-call", errorDescription, e); + } catch (Exception e){ + e.printStackTrace(); + errorDescription = e.getMessage(); + Log.e("api-call", errorDescription, e); } } } @@ -576,7 +586,7 @@ public void addUser(AdnUser user) { cacheHashtags(contentFeed); return new FetchStatusesTaskOutput( - new TwitterFetchResult(errorDescription == null ? true : false, errorDescription), + new TwitterFetchResult(errorDescription == null, errorDescription), input.mCallbackHandle, contentFeed, input.mContentHandle); } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterDirectMessage.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterDirectMessage.java index 24a3d1da..9ea94810 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterDirectMessage.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterDirectMessage.java @@ -16,23 +16,24 @@ package org.tweetalib.android.model; -import java.util.Date; +import android.text.Html; +import android.text.Spanned; import org.tweetalib.android.TwitterUtil; + +import java.util.Date; + import twitter4j.DirectMessage; import twitter4j.User; -import android.text.Html; -import android.text.Spanned; - public class TwitterDirectMessage implements Comparable { /* - * + * */ public enum MessageType { SENT, RECEIVED - }; + } /* * @@ -43,11 +44,10 @@ public TwitterDirectMessage(DirectMessage message, User otherUser) { : MessageType.RECEIVED; mText = message.getText(); TwitterMediaEntity mediaEntity = TwitterMediaEntity.createMediaEntity(message); - String descriptionMarkup = TwitterUtil.getStatusMarkup(mText,mediaEntity, message.getMediaEntities() ,message.getURLEntities()); + String descriptionMarkup = TwitterUtil.getStatusMarkup(mText, message.getMediaEntities(), message.getURLEntities()); mTextSpanned = Html.fromHtml(descriptionMarkup + " "); mCreatedAt = message.getCreatedAt(); mOtherUserId = otherUser.getId(); - mOtherUserName = otherUser.getName(); mOtherUserScreenName = otherUser.getScreenName(); mOtherUser = new TwitterUser(otherUser); mSender = new TwitterUser(message.getSender()); @@ -76,37 +76,30 @@ public long getOtherUserId() { return mOtherUserId; } - public String getOtherUserName() { - return mOtherUserName; - } - public String getOtherUserScreenName() { return mOtherUserScreenName; } - public TwitterUser getOtherUser() - { + public TwitterUser getOtherUser() { return mOtherUser; } - public TwitterUser getSender() - { + public TwitterUser getSender() { return mSender; } /* * */ - private long mId; - private MessageType mMessageType; - public String mText; - public Spanned mTextSpanned; - private Date mCreatedAt; - private long mOtherUserId; - private String mOtherUserName; - private String mOtherUserScreenName; - private TwitterUser mOtherUser; - private TwitterUser mSender; + private final long mId; + private final MessageType mMessageType; + private final String mText; + public final Spanned mTextSpanned; + private final Date mCreatedAt; + private final long mOtherUserId; + private final String mOtherUserScreenName; + private final TwitterUser mOtherUser; + private final TwitterUser mSender; /* * (non-Javadoc) diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterDirectMessages.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterDirectMessages.java index 04ccb933..e6c6ca32 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterDirectMessages.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterDirectMessages.java @@ -42,7 +42,7 @@ public ArrayList getRawReceivedMessages() { class Conversation implements Comparable { /* - * + * */ public Conversation(Long otherUserId) { mMessages = new ArrayList(); @@ -92,7 +92,7 @@ public int compareTo(Conversation other) { if (thisMostRecent != null && otherMostRecent != null && thisMostRecent.getCreatedAt().before( - otherMostRecent.getCreatedAt())) { + otherMostRecent.getCreatedAt())) { return 1; } return -1; @@ -113,7 +113,7 @@ void removeDuplicates() { if (size != 0) { TwitterDirectMessage previous = null; for (Iterator it = mMessages.iterator(); it - .hasNext();) { + .hasNext(); ) { TwitterDirectMessage current = it.next(); if (previous != null && current.getId() == previous.getId()) { it.remove(); @@ -134,8 +134,8 @@ public ArrayList getMessages() { /* * */ - private ArrayList mMessages; - Long mOtherUserId; + private final ArrayList mMessages; + final Long mOtherUserId; } /* @@ -156,19 +156,12 @@ public TwitterDirectMessages(long messageOwnerId) { mMessageOwnerId = messageOwnerId; } - public TwitterDirectMessages(TwitterDirectMessages another, Long otherUserId) { - mConversations = new ArrayList(another.mConversations); - mConversationHandle = new TwitterDirectMessagesHandle( - another.mMessageOwnerId, otherUserId); - mMessageOwnerId = another.mMessageOwnerId; - } - /* * */ public void add(ResponseList sentDirectMessages, - ResponseList receivedDirectMessages, - AddUserCallback addUserCallback) { + ResponseList receivedDirectMessages, + AddUserCallback addUserCallback) { for (int i = 0; i < 2; i++) { @@ -213,7 +206,7 @@ public void add(DirectMessage directMessage) { /* * */ - public void add(TwitterDirectMessage message) { + void add(TwitterDirectMessage message) { Conversation conversation = getConversationForMessage(message); if (conversation == null) { @@ -289,32 +282,6 @@ public ArrayList getList( return null; } - /* - * - */ - public TwitterDirectMessage getFirstMessage( - TwitterDirectMessagesHandle handle) { - ArrayList messages = getList(handle); - if (messages != null) { - return messages.get(0); - } - - return null; - } - - /* - * - */ - public TwitterDirectMessage getMessage(TwitterDirectMessagesHandle handle, - int position) { - ArrayList messages = getList(handle); - if (messages != null && position < messages.size()) { - return messages.get(position); - } - - return null; - } - /* * */ @@ -326,16 +293,6 @@ public int getConversationCount() { return 0; } - /* - * - */ - Conversation getConversation(int index) { - if (mConversations != null) { - return mConversations.get(index); - } - return null; - } - /* * */ @@ -361,14 +318,14 @@ public Long getOldestDirectMessageId() { /* * */ - public void sort() { + void sort() { Collections.sort(mConversations); } /* * */ - private long mMessageOwnerId; - private ArrayList mConversations; - private TwitterDirectMessagesHandle mConversationHandle; + private final long mMessageOwnerId; + private final ArrayList mConversations; + private final TwitterDirectMessagesHandle mConversationHandle; } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterDirectMessagesHandle.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterDirectMessagesHandle.java index 97bb34c7..6bc38e99 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterDirectMessagesHandle.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterDirectMessagesHandle.java @@ -19,7 +19,7 @@ public class TwitterDirectMessagesHandle { /* - * + * */ public TwitterDirectMessagesHandle(long userId, Long otherUserId) { mUserId = userId; @@ -37,6 +37,6 @@ String getKey() { return key; } - Long mUserId; - Long mOtherUserId; + private final Long mUserId; + final Long mOtherUserId; } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterIds.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterIds.java index 4f340bc9..7109580d 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterIds.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterIds.java @@ -30,7 +30,7 @@ public Long getId(int index) { return mIds.get(index); } - private ArrayList mIds; + private final ArrayList mIds; public void add(IDs ids) { long[] idsArray = ids.getIDs(); diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterList.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterList.java index 7f408dd2..121a8bec 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterList.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterList.java @@ -63,14 +63,14 @@ public int getSubscriberCount() { return mSubscriberCount; } - private int mId; - private String mName; - private String mFullName; - private String mDescription; - private boolean mIsPublic; - private boolean mIsFollowing; - private int mMemberCount; - private int mSubscriberCount; + private final int mId; + private final String mName; + private final String mFullName; + private final String mDescription; + private final boolean mIsPublic; + private final boolean mIsFollowing; + private final int mMemberCount; + private final int mSubscriberCount; @Override public int compareTo(TwitterList another) { diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterLists.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterLists.java index b6d171fa..06f8c41b 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterLists.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterLists.java @@ -53,6 +53,6 @@ private void sort() { Collections.sort(mLists); } - ArrayList mLists; + private final ArrayList mLists; } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterMediaEntity.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterMediaEntity.java index b2429072..bde47d06 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterMediaEntity.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterMediaEntity.java @@ -16,9 +16,8 @@ package org.tweetalib.android.model; -import java.net.URL; +import android.net.Uri; -import org.appdotnet4j.model.AdnPost; import org.json.JSONException; import org.json.JSONObject; @@ -27,18 +26,16 @@ import twitter4j.Status; import twitter4j.URLEntity; -import android.net.Uri; - public class TwitterMediaEntity { // https://dev.twitter.com/docs/tweet-entities /* - * + * */ public enum Source { TWITTER, INSTAGRAM, TWITPIC, LOCKERZ, // Note that Plixi and Lockerz use - // the same API, so - // Plixi is treated as Lockerz + // the same API, so + // Plixi is treated as Lockerz YFROG, IMGUR, YOUTUBE, } @@ -47,7 +44,7 @@ public enum Source { */ public enum Size { THUMB, SMALL, MEDIUM, LARGE, - }; + } /* * @@ -71,12 +68,10 @@ public static TwitterMediaEntity createMediaEntity(Status status) { MediaEntity[] mediaEntities; URLEntity[] urlEntities; - if(status.isRetweet()){ + if (status.isRetweet()) { mediaEntities = status.getRetweetedStatus().getMediaEntities(); urlEntities = status.getRetweetedStatus().getURLEntities(); - } - else - { + } else { mediaEntities = status.getMediaEntities(); urlEntities = status.getURLEntities(); } @@ -131,30 +126,6 @@ public static TwitterMediaEntity createMediaEntity(DirectMessage status) { return null; } - /* - * - */ - public static TwitterMediaEntity createMediaEntity(AdnPost post) { - - // TODO: This is a hack, but for now just replace newlines with a space - // so the split works. - String status = post.mText.replace("\n", " ").replace("<", "<") - .replace(">", ">"); - String[] tokens = status.split(" "); - for (String token : tokens) { - if (token.length() > 1) { - if (token.contains("http://") || token.contains("https://")) { - TwitterMediaEntity entity = getTwitterMediaEntityFromUrl( - token, token); - if (entity != null) { - return entity; - } - } - } - } - - return null; - } private static TwitterMediaEntity getTwitterMediaEntityFromUrl( String tinyUrl, String expandedUrl) { @@ -204,30 +175,30 @@ private static TwitterMediaEntity getTwitterMediaEntityFromUrl( private static String getInstagramMediaUrl(String url) { String lowerCaseUrl = url.toLowerCase(); - if (lowerCaseUrl.indexOf("://instagr.am/p/") > -1 ) { - String instagramMatch = "://instagr.am/p/"; - int startIndex = lowerCaseUrl.indexOf(instagramMatch); - if (startIndex > -1) { - startIndex += instagramMatch.length(); - int endIndex = lowerCaseUrl.indexOf("/", startIndex); - if (endIndex > -1) { - String code = url.substring(startIndex, endIndex); - return "http://instagr.am/p/" + code + "/media/"; - } - } - } - if (lowerCaseUrl.indexOf("://instagram.com/p/") > -1 ) { - String instagramMatch = "://instagram.com/p/"; - int startIndex = lowerCaseUrl.indexOf(instagramMatch); - if (startIndex > -1) { - startIndex += instagramMatch.length(); - int endIndex = lowerCaseUrl.indexOf("/", startIndex); - if (endIndex > -1) { - String code = url.substring(startIndex, endIndex); - return "http://instagram.com/p/" + code + "/media/"; - } - } - } + if (lowerCaseUrl.indexOf("://instagr.am/p/") > -1) { + String instagramMatch = "://instagr.am/p/"; + int startIndex = lowerCaseUrl.indexOf(instagramMatch); + if (startIndex > -1) { + startIndex += instagramMatch.length(); + int endIndex = lowerCaseUrl.indexOf("/", startIndex); + if (endIndex > -1) { + String code = url.substring(startIndex, endIndex); + return "http://instagr.am/p/" + code + "/media/"; + } + } + } + if (lowerCaseUrl.indexOf("://instagram.com/p/") > -1) { + String instagramMatch = "://instagram.com/p/"; + int startIndex = lowerCaseUrl.indexOf(instagramMatch); + if (startIndex > -1) { + startIndex += instagramMatch.length(); + int endIndex = lowerCaseUrl.indexOf("/", startIndex); + if (endIndex > -1) { + String code = url.substring(startIndex, endIndex); + return "http://instagram.com/p/" + code + "/media/"; + } + } + } return null; } @@ -241,8 +212,7 @@ private static String getTwitpicMediaUrl(String url) { int startIndex = lowerCaseUrl.indexOf(match); if (startIndex > -1) { startIndex += match.length(); - String code = url.substring(startIndex); - return code; + return url.substring(startIndex); } return null; @@ -328,7 +298,7 @@ private static String getYouTubeUrl(String url) { * */ private TwitterMediaEntity(Source source, String mediaCode, String url, - String expandedUrl) { + String expandedUrl) { mSource = source; mMediaCode = mediaCode; mUrl = url; @@ -340,9 +310,9 @@ private TwitterMediaEntity(Source source, String mediaCode, String url, */ private TwitterMediaEntity(MediaEntity mediaEntity) { mSource = Source.TWITTER; - mMediaCode = mediaEntity.getMediaURL().toString(); - mUrl = mediaEntity.getURL().toString(); - mExpandedUrl = mediaEntity.getExpandedURL().toString(); + mMediaCode = mediaEntity.getMediaURL(); + mUrl = mediaEntity.getURL(); + mExpandedUrl = mediaEntity.getExpandedURL(); /* * mSizeThumb = new @@ -359,7 +329,7 @@ private TwitterMediaEntity(MediaEntity mediaEntity) { /* * */ - public TwitterMediaEntity(String jsonAsString) throws JSONException { + private TwitterMediaEntity(String jsonAsString) throws JSONException { JSONObject object = new JSONObject(jsonAsString); mSource = Source.valueOf(object.getString(KEY_SOURCE)); mMediaCode = object.getString(KEY_MEDIA_CODE); @@ -393,13 +363,6 @@ public String toString() { return object.toString(); } - /* - * - */ - public String getUrl() { - return mUrl; - } - public String getExpandedUrl() { return mExpandedUrl; } @@ -414,98 +377,98 @@ public Source getSource() { public String getMediaUrl(Size size) { switch (mSource) { - case TWITTER: - switch (size) { - case THUMB: - return mMediaCode + ":thumb"; - case SMALL: - return mMediaCode + ":small"; - case MEDIUM: - return mMediaCode + ":medium"; - case LARGE: - return mMediaCode + ":large"; - } - break; - - case INSTAGRAM: - switch (size) { - case THUMB: - return mMediaCode + "?size=t"; - case SMALL: - return mMediaCode + "?size=t"; - case MEDIUM: - return mMediaCode + "?size=m"; - case LARGE: - return mMediaCode + "?size=l"; - } - break; - - case TWITPIC: - switch (size) { - case THUMB: - return "http://twitpic.com/show/mini/" + mMediaCode; - case SMALL: - return "http://twitpic.com/show/thumb/" + mMediaCode; - case MEDIUM: - return "http://twitpic.com/show/thumb/" + mMediaCode; - case LARGE: - return "http://twitpic.com/show/full/" + mMediaCode; - } - break; - - case LOCKERZ: - switch (size) { - case THUMB: - return mMediaCode + "&size=thumbnail"; - case SMALL: - return mMediaCode + "&size=small"; - case MEDIUM: - return mMediaCode + "&size=medium"; - case LARGE: - return mMediaCode + "&size=big"; - } + case TWITTER: + switch (size) { + case THUMB: + return mMediaCode + ":thumb"; + case SMALL: + return mMediaCode + ":small"; + case MEDIUM: + return mMediaCode + ":medium"; + case LARGE: + return mMediaCode + ":large"; + } + break; + + case INSTAGRAM: + switch (size) { + case THUMB: + return mMediaCode + "?size=t"; + case SMALL: + return mMediaCode + "?size=t"; + case MEDIUM: + return mMediaCode + "?size=m"; + case LARGE: + return mMediaCode + "?size=l"; + } + break; + + case TWITPIC: + switch (size) { + case THUMB: + return "http://twitpic.com/show/mini/" + mMediaCode; + case SMALL: + return "http://twitpic.com/show/thumb/" + mMediaCode; + case MEDIUM: + return "http://twitpic.com/show/thumb/" + mMediaCode; + case LARGE: + return "http://twitpic.com/show/full/" + mMediaCode; + } + break; + + case LOCKERZ: + switch (size) { + case THUMB: + return mMediaCode + "&size=thumbnail"; + case SMALL: + return mMediaCode + "&size=small"; + case MEDIUM: + return mMediaCode + "&size=medium"; + case LARGE: + return mMediaCode + "&size=big"; + } - case YFROG: - switch (size) { - // http://yfrog.com/page/api#a5 - case THUMB: - return mMediaCode + ":small"; - case SMALL: - return mMediaCode + ":small"; - case MEDIUM: - return mMediaCode + ":iphone"; - case LARGE: - return mMediaCode + ":medium"; - } + case YFROG: + switch (size) { + // http://yfrog.com/page/api#a5 + case THUMB: + return mMediaCode + ":small"; + case SMALL: + return mMediaCode + ":small"; + case MEDIUM: + return mMediaCode + ":iphone"; + case LARGE: + return mMediaCode + ":medium"; + } - case IMGUR: - switch (size) { - // http://webapps.stackexchange.com/a/16104 - case THUMB: - return "http://i.imgur.com/" + mMediaCode + "s.png"; - case SMALL: - return "http://i.imgur.com/" + mMediaCode + "b.png"; - case MEDIUM: - return "http://i.imgur.com/" + mMediaCode + "m.png"; - case LARGE: - return "http://i.imgur.com/" + mMediaCode + ".png"; - } + case IMGUR: + switch (size) { + // http://webapps.stackexchange.com/a/16104 + case THUMB: + return "http://i.imgur.com/" + mMediaCode + "s.png"; + case SMALL: + return "http://i.imgur.com/" + mMediaCode + "b.png"; + case MEDIUM: + return "http://i.imgur.com/" + mMediaCode + "m.png"; + case LARGE: + return "http://i.imgur.com/" + mMediaCode + ".png"; + } - case YOUTUBE: { - switch (size) { - case THUMB: - case SMALL: - return "http://img.youtube.com/vi/" + mMediaCode - + "/default.jpg"; - case MEDIUM: - return "http://img.youtube.com/vi/" + mMediaCode - + "/mqdefault.jpg"; - case LARGE: - return "http://img.youtube.com/vi/" + mMediaCode - + "/hqdefault.jpg"; + case YOUTUBE: { + switch (size) { + case THUMB: + case SMALL: + return "http://img.youtube.com/vi/" + mMediaCode + + "/default.jpg"; + case MEDIUM: + return "http://img.youtube.com/vi/" + mMediaCode + + "/mqdefault.jpg"; + case LARGE: + return "http://img.youtube.com/vi/" + mMediaCode + + "/hqdefault.jpg"; + } } } - } return null; } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterStatus.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterStatus.java index 4d8c4bbe..eaf9d7f5 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterStatus.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterStatus.java @@ -36,7 +36,7 @@ public class TwitterStatus implements Comparable { /* - * + * */ public TwitterStatus(TwitterStatus other) { mAuthorId = other.mAuthorId; @@ -114,7 +114,7 @@ public TwitterStatus(Status status) { mMediaEntity = TwitterMediaEntity.createMediaEntity(status); boolean useDefaultAuthor = true; - if (mIsRetweet == true) { + if (mIsRetweet) { if (status.getRetweetedStatus() != null && status.getRetweetedStatus().getUser() != null) { SetProfileImagesFromUser(new TwitterUser(status.getRetweetedStatus().getUser())); } @@ -138,15 +138,13 @@ public TwitterStatus(Status status) { mUserMentions = TwitterUtil.getUserMentions(retweetedStatus.getUserMentionEntities()); mIsRetweetedByMe = retweetedStatus.isRetweetedByMe(); } - } - else - { + } else { if (statusUser != null) { SetProfileImagesFromUser(new TwitterUser(statusUser)); } } - if (useDefaultAuthor == true) { + if (useDefaultAuthor) { if (statusUser != null) { mAuthorId = statusUser.getId(); } @@ -177,9 +175,12 @@ public TwitterStatus(AdnPost post) { mInReplyToStatusId = post.mInReplyTo; mSource = post.mSource; - mUserId = post.mUser.mId; - mUserName = post.mUser.mName; - mUserScreenName = post.mUser.mUserName; + if(post.mUser != null) + { + mUserId = post.mUser.mId; + mUserName = post.mUser.mName; + mUserScreenName = post.mUser.mUserName; + } mIsFavorited = post.mIsFavorited; mIsRetweetedByMe = post.mIsRetweetedByMe; @@ -188,10 +189,8 @@ public TwitterStatus(AdnPost post) { mAuthorName = post.mOriginalAuthor.mName; mAuthorScreenName = post.mOriginalAuthor.mUserName; SetProfileImagesFromUser(new TwitterUser(post.mOriginalAuthor)); - mOriginalRetweetId = post.mOriginalAuthor.mId; - } - else - { + mOriginalRetweetId = post.mOriginalId; + } else { SetProfileImagesFromUser(new TwitterUser(post.mUser)); } @@ -204,8 +203,7 @@ public TwitterStatus(AdnPost post) { } - private void SetProfileImagesFromUser(TwitterUser user) - { + private void SetProfileImagesFromUser(TwitterUser user) { if (user.getProfileImageUrlOriginal() != null) { mProfileImageOriginalUrl = user.getProfileImageUrlOriginal(); } @@ -336,6 +334,7 @@ public TwitterStatus(String jsonAsString) { if (object.has(KEY_STATUS_SLIM_MARKUP)) { String statusFullMarkup = null; + String KEY_STATUS_FULL_MARKUP = "mStatusFullMarkup"; if (object.has(KEY_STATUS_FULL_MARKUP)) { statusFullMarkup = object.getString(KEY_STATUS_FULL_MARKUP); } @@ -368,19 +367,19 @@ public String toString() { } object.put(KEY_CREATED_AT, mCreatedAt.getTime()); if (mProfileImageOriginalUrl != null) { - String url = mProfileImageOriginalUrl.toString(); + String url = mProfileImageOriginalUrl; object.put(KEY_PROFILE_IMAGE_ORIGINAL_URL, url); } if (mProfileImageMiniUrl != null) { - String url = mProfileImageMiniUrl.toString(); + String url = mProfileImageMiniUrl; object.put(KEY_PROFILE_IMAGE_MINI_URL, url); } if (mProfileImageNormalUrl != null) { - String url = mProfileImageNormalUrl.toString(); + String url = mProfileImageNormalUrl; object.put(KEY_PROFILE_IMAGE_NORMAL_URL, url); } if (mProfileImageBiggerUrl != null) { - String url = mProfileImageBiggerUrl.toString(); + String url = mProfileImageBiggerUrl; object.put(KEY_PROFILE_IMAGE_BIGGER_URL, url); } object.put(KEY_ID, mId); @@ -454,7 +453,6 @@ public String toString() { private final String KEY_RETWEET_COUNT = "mRetweetCount"; private final String KEY_STATUS = "mStatus"; private final String KEY_STATUS_SLIM_MARKUP = "mStatusMarkup"; - private final String KEY_STATUS_FULL_MARKUP = "mStatusFullMarkup"; private final String KEY_SOURCE = "mSource"; private final String KEY_USER_ID = "mUserId"; private final String KEY_USER_SCREEN_NAME = "mUserScreenName"; @@ -471,15 +469,15 @@ public String toString() { private String mAuthorScreenName; public long mFavoriteCount; public Date mCreatedAt; - public String mProfileImageOriginalUrl; - public String mProfileImageMiniUrl; - public String mProfileImageNormalUrl; - public String mProfileImageBiggerUrl; + private String mProfileImageOriginalUrl; + private String mProfileImageMiniUrl; + private String mProfileImageNormalUrl; + private String mProfileImageBiggerUrl; public long mId; public long mOriginalRetweetId; public Long mInReplyToStatusId; - public Long mInReplyToUserId; - public String mInReplyToUserScreenName; + private Long mInReplyToUserId; + private String mInReplyToUserScreenName; public boolean mIsFavorited; public boolean mIsRetweet; public boolean mIsRetweetedByMe; @@ -488,7 +486,7 @@ public String toString() { // public String mStatusSlimMarkup; // 'Slim' has the first media link // removed from the text // public Spanned mStatusSlimSpanned; - public String mStatusFullMarkup; // 'Full' contains all media links. Used in + private String mStatusFullMarkup; // 'Full' contains all media links. Used in // conversation view. public Spanned mStatusFullSpanned; public String mSource; @@ -556,7 +554,7 @@ public int compareTo(TwitterStatus other) { /* * */ - private boolean compareString(String string1, String string2) { + private static boolean compareString(String string1, String string2) { if (string1 == null) { if (string2 == null) { return true; @@ -570,7 +568,7 @@ private boolean compareString(String string1, String string2) { return false; } - private boolean compareLong(Long long1, Long long2) { + private static boolean compareLong(Long long1, Long long2) { if (long1 == null) { if (long2 == null) { return true; @@ -590,43 +588,43 @@ private boolean compareLong(Long long1, Long long2) { public boolean isEqualTo(TwitterStatus other) { if (mAuthorId != other.mAuthorId) return false; - if (compareString(mAuthorName, other.mAuthorName) == false) + if (!compareString(mAuthorName, other.mAuthorName)) return false; - if (compareString(mAuthorScreenName, other.mAuthorScreenName) == false) + if (!compareString(mAuthorScreenName, other.mAuthorScreenName)) return false; if (mFavoriteCount != other.mFavoriteCount) return false; if (mCreatedAt.getTime() != other.mCreatedAt.getTime()) return false; - if (mProfileImageOriginalUrl.toString().equals( - other.mProfileImageOriginalUrl.toString()) == false) return false; - if (mProfileImageNormalUrl.toString().equals( - other.mProfileImageNormalUrl.toString()) == false) return false; - if (mProfileImageMiniUrl.toString().equals( - other.mProfileImageMiniUrl.toString()) == false) return false; - if (mProfileImageBiggerUrl.toString().equals( - other.mProfileImageBiggerUrl.toString()) == false) return false; + if (!mProfileImageOriginalUrl.equals( + other.mProfileImageOriginalUrl)) return false; + if (!mProfileImageNormalUrl.equals( + other.mProfileImageNormalUrl)) return false; + if (!mProfileImageMiniUrl.equals( + other.mProfileImageMiniUrl)) return false; + if (!mProfileImageBiggerUrl.equals( + other.mProfileImageBiggerUrl)) return false; if (mId != other.mId) return false; - if (compareLong(mInReplyToStatusId, other.mInReplyToStatusId) == false) + if (!compareLong(mInReplyToStatusId, other.mInReplyToStatusId)) return false; - if (compareLong(mInReplyToUserId, other.mInReplyToUserId) == false) + if (!compareLong(mInReplyToUserId, other.mInReplyToUserId)) return false; - if (compareString(mInReplyToUserScreenName, - other.mInReplyToUserScreenName) == false) return false; + if (!compareString(mInReplyToUserScreenName, + other.mInReplyToUserScreenName)) return false; if (mIsFavorited != other.mIsFavorited) return false; if (mIsRetweet != other.mIsRetweet) return false; if (mIsRetweetedByMe != other.mIsRetweetedByMe) return false; if (mOriginalRetweetId != other.mOriginalRetweetId) return false; if (mRetweetCount != other.mRetweetCount) return false; - if (compareString(mStatus, other.mStatus) == false) return false; + if (!compareString(mStatus, other.mStatus)) return false; // if (compareString(mStatusSlimMarkup, other.mStatusSlimMarkup) == // false) // return false; - if (compareString(mStatusFullMarkup, other.mStatusFullMarkup) == false) + if (!compareString(mStatusFullMarkup, other.mStatusFullMarkup)) return false; - if (compareString(mSource, other.mSource) == false) return false; + if (!compareString(mSource, other.mSource)) return false; if (mUserId != other.mUserId) return false; - if (compareString(mUserScreenName, other.mUserScreenName) == false) + if (!compareString(mUserScreenName, other.mUserScreenName)) return false; - if (compareString(mUserName, other.mUserName) == false) return false; + if (!compareString(mUserName, other.mUserName)) return false; if (mUserMentions != null) { if (other.mUserMentions == null) { @@ -646,22 +644,21 @@ public boolean isEqualTo(TwitterStatus other) { * */ void setStatusMarkup(Status status) { - mStatusFullMarkup = TwitterUtil.getStatusMarkup(status, mMediaEntity); + mStatusFullMarkup = TwitterUtil.getStatusMarkup(status); mStatusFullSpanned = URLSpanNoUnderline.stripUnderlines(Html .fromHtml(mStatusFullMarkup.replace("\n", "
    ") + " ")); } void setStatusMarkup(String full) { mStatusFullMarkup = full; - if (mStatusFullMarkup != null) - { + if (mStatusFullMarkup != null) { mStatusFullSpanned = URLSpanNoUnderline.stripUnderlines(Html - .fromHtml(mStatusFullMarkup.replace("\n", "
    ") + " ")); + .fromHtml(mStatusFullMarkup.replace("\n", "
    ") + " ")); } } void setStatusMarkup(AdnPost post) { - mStatusFullMarkup = TwitterUtil.getStatusMarkup(post, mMediaEntity); + mStatusFullMarkup = TwitterUtil.getStatusMarkup(post); mStatusFullSpanned = URLSpanNoUnderline.stripUnderlines(Html .fromHtml(mStatusFullMarkup.replace("\n", "
    ") + " ")); } @@ -683,8 +680,7 @@ public void setRetweet(Boolean isRetweetedByMe) { public String getProfileImageUrl(TwitterManager.ProfileImageSize size) { - switch (size) - { + switch (size) { case MINI: return mProfileImageMiniUrl; case NORMAL: diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterStatusUpdate.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterStatusUpdate.java index a9226983..943a4c8a 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterStatusUpdate.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterStatusUpdate.java @@ -20,6 +20,8 @@ import android.graphics.BitmapFactory; import android.os.Environment; +import org.appdotnet4j.model.AdnPostCompose; + import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; @@ -27,9 +29,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; -import java.net.SecureCacheResponse; -import org.appdotnet4j.model.AdnPostCompose; import twitter4j.StatusUpdate; public class TwitterStatusUpdate { @@ -52,13 +52,11 @@ public StatusUpdate getT4JStatusUpdate() { } if (mMediaFilePath != null) { - try{ + try { statusUpdate.setMedia(getMediaFile(mMediaFilePath)); - } - catch (IOException error){ + } catch (IOException error) { error.printStackTrace(); - } - catch (OutOfMemoryError error){ + } catch (OutOfMemoryError error) { error.printStackTrace(); } } @@ -68,54 +66,48 @@ public StatusUpdate getT4JStatusUpdate() { public AdnPostCompose getAdnComposePost() { File mediaFile = null; - try{ + try { mediaFile = getMediaFile(mMediaFilePath); - } - catch (IOException error){ + } catch (IOException error) { error.printStackTrace(); - } - catch (OutOfMemoryError error){ + } catch (OutOfMemoryError error) { error.printStackTrace(); } - AdnPostCompose statusUpdate = new AdnPostCompose(mStatus, mInReplyToStatusId, mediaFile); - return statusUpdate; + return new AdnPostCompose(mStatus, mInReplyToStatusId, mediaFile); } public void setMediaFilePath(String mediaFilePath) { mMediaFilePath = mediaFilePath; } - String mStatus; - Long mInReplyToStatusId; - String mMediaFilePath; - + private final String mStatus; + private final Long mInReplyToStatusId; + private String mMediaFilePath; - private File getMediaFile(String mediaFilePath) throws IOException { + private static File getMediaFile(String mediaFilePath) throws IOException { - if(mediaFilePath==null){ + if (mediaFilePath == null) { return null; } File originalFile = new File(mediaFilePath); Bitmap resizeImage = TryResizeImage(originalFile); - if (resizeImage == null){ + if (resizeImage == null) { return originalFile; } File resizedFile = SaveImage(resizeImage); - if (resizedFile==null) - { + if (resizedFile == null) { return originalFile; } return resizedFile; } - private Bitmap TryResizeImage(File originalFile) throws FileNotFoundException - { + private static Bitmap TryResizeImage(File originalFile) throws FileNotFoundException { Bitmap resizeImage = null; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; @@ -129,46 +121,40 @@ private Bitmap TryResizeImage(File originalFile) throws FileNotFoundException int requiredWidth = 1500; int requiredHeight = 1500; - while (width_tmp / 2 >= requiredWidth || height_tmp / 2 >= requiredHeight) - { + while (width_tmp / 2 >= requiredWidth || height_tmp / 2 >= requiredHeight) { width_tmp /= 2; height_tmp /= 2; scale *= 2; } - if (scale > 1) - { + if (scale > 1) { // decode with inSampleSize options = new BitmapFactory.Options(); options.inSampleSize = scale; - resizeImage = BitmapFactory.decodeStream(new FileInputStream(originalFile), null, options); + resizeImage = BitmapFactory.decodeStream(new FileInputStream(originalFile), null, + options); } return resizeImage; } - private File SaveImage(Bitmap resizeImage) throws IOException - { - File path = new File(Environment.getExternalStorageDirectory(),"temp/images/Tweet Lanes"); + private static File SaveImage(Bitmap resizeImage) { + final File path = new File(Environment.getExternalStorageDirectory(), + "temp/images/Tweet Lanes"); File tempFile = null; OutputStream outStream = null; - try - { + try { path.mkdirs(); tempFile = File.createTempFile("img", ".jpeg", path); outStream = new BufferedOutputStream(new FileOutputStream(tempFile)); resizeImage.compress(Bitmap.CompressFormat.JPEG, 100, outStream); - } - catch (Exception ex) - { + } catch (Exception ex) { tempFile = null; - } - finally - { + } finally { if (outStream != null) { try { outStream.close(); diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterStatuses.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterStatuses.java index 79a7cc2b..917f1949 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterStatuses.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterStatuses.java @@ -16,10 +16,6 @@ package org.tweetalib.android.model; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - import org.appdotnet4j.model.AdnPost; import org.appdotnet4j.model.AdnPosts; import org.appdotnet4j.model.AdnUser; @@ -27,6 +23,11 @@ import org.json.JSONException; import org.json.JSONObject; import org.tweetalib.android.model.TwitterStatusesFilter.FilterType; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + import twitter4j.QueryResult; import twitter4j.ResponseList; import twitter4j.Status; @@ -35,19 +36,12 @@ public class TwitterStatuses { /* - * + * */ public TwitterStatuses(TwitterStatuses another) { _mStatuses = new ArrayList(another._mStatuses); - mCounts = (int[]) another.mCounts.clone(); + mCounts = another.mCounts.clone(); mGetNewStatusesMaxId = another.mGetNewStatusesMaxId; - // TwitterStatusesFilter filter = new TwitterStatusesFilter(); - // filter.setShowReplies(false); - // filterTest(filter); - // filter.setShowRetweets(false); - // filterTest(filter); - // filter.setShowReplies(true); - // filterTest(filter); } /* @@ -68,7 +62,7 @@ public TwitterStatuses(TwitterStatus status) { /* * */ - static final String KEY_STATUSES = "statuses"; + private static final String KEY_STATUSES = "statuses"; public TwitterStatuses(String jsonAsString) { _mStatuses = new ArrayList(); @@ -155,30 +149,30 @@ public TwitterStatus getStatus(int index, TwitterStatusesFilter filter) { if (status != null) { boolean isReply = status.mInReplyToStatusId != null; - boolean isRetweet = status.mIsRetweet == true; + boolean isRetweet = status.mIsRetweet; switch (filterType) { - case HIDE_RETWEETS: - if (isRetweet) { - // filterCount += 1; - continue; - } - break; - case HIDE_REPLIES: - if (isReply) { - // filterCount += 1; - continue; - } - break; - case HIDE_RETWEETS_REPLIES: - if (isReply || isRetweet) { - // filterCount += 1; - continue; - } - break; - - default: - break; + case HIDE_RETWEETS: + if (isRetweet) { + // filterCount += 1; + continue; + } + break; + case HIDE_REPLIES: + if (isReply) { + // filterCount += 1; + continue; + } + break; + case HIDE_RETWEETS_REPLIES: + if (isReply || isRetweet) { + // filterCount += 1; + continue; + } + break; + + default: + break; } if (filteredIndex == index) { @@ -242,6 +236,10 @@ public void add(QueryResult result) { sort(); } + public void setFeedFullyRefreshed() { + mGetNewStatusesMaxId = null; + } + /* * */ @@ -256,7 +254,7 @@ public interface AddUserCallback { * */ public void add(ResponseList statuses, - AddUserCallback addUserCallback) { + AddUserCallback addUserCallback) { TwitterStatus firstItem = size() > 0 ? get(0) : null; int addCount = 0; @@ -288,7 +286,7 @@ public void add(ResponseList statuses, addCount += 1; } - if (stillMore == true && lastAddedStatus != null) { + if (stillMore && lastAddedStatus != null) { mGetNewStatusesMaxId = lastAddedStatus.mId; } @@ -321,17 +319,12 @@ public void add(AdnPosts posts, AddUserCallback addUserCallback) { if (addUserCallback != null) { addUserCallback.addUser(post.mUser); - /* - * if (post.isRetweet()) { Status retweetedStatus = - * post.getRetweetedStatus(); if (retweetedStatus != null) { - * addUserCallback.addUser(retweetedStatus.getUser()); } } - */ } addCount += 1; } - if (stillMore == true && lastAddedStatus != null) { + if (stillMore && lastAddedStatus != null) { mGetNewStatusesMaxId = lastAddedStatus.mId; } @@ -453,8 +446,12 @@ public Integer getStatusIndex(long statusId) { high = middle - 1; } else if (statusId < status.mId) { low = middle + 1; - } else { // The element has been found + } else if (statusId == status.mId){ + // The element has been found return middle; + } else{ + // Couldn't find the element + break; } } @@ -463,15 +460,14 @@ public Integer getStatusIndex(long statusId) { return getStatusIndexFromOriginalStatusId(statusId); } - public Integer getStatusIndexFromOriginalStatusId(long originalStatusId) { + Integer getStatusIndexFromOriginalStatusId(long originalStatusId) { if (size() == 0) { return null; } //Since original status ids have no order, a long search through each is required. - for (int i=0; i = _mStatuses.size()){ + return null; + } + return _mStatuses.get(index); } @@ -499,8 +500,8 @@ private void remove(int index) { /* * */ - ArrayList _mStatuses; - int[] mCounts = new int[FilterType.FILTER_MAX.ordinal()]; + private final ArrayList _mStatuses; + private int[] mCounts = new int[FilterType.FILTER_MAX.ordinal()]; private Long mGetNewStatusesMaxId = null; @@ -516,46 +517,4 @@ public void reset() { mCounts = new int[FilterType.FILTER_MAX.ordinal()]; mGetNewStatusesMaxId = null; } - - /* - * - */ - /* - * public class Iterator { - * - * public Iterator(TwitterStatusesFilter filter) { mFilter = filter; - * mLastIndex = 0; } - * - * public void next() { int size = size(); for (; mLastIndex < size; - * mLastIndex++) { TwitterStatus status = get(mLastIndex); if (status != - * null) { if (status.getInReplyToStatusId() != null && - * mFilter.getShowReplies() == false) { mSkipReplyCount += 1; continue; } if - * (status.getIsRetweet() == true && mFilter.getShowRetweets() == false) { - * mSkipRetweetCount += 1; continue; } break; } } } - * - * public boolean finished() { - * - * if (mLastIndex == size()) { Log.d("TwitterStatus iterator", - * "finished - skipped " + mSkipRetweetCount + " retweets, skipped " + - * mSkipReplyCount + " replies."); } - * - * return mLastIndex == size() ? true : false; } - * - * private TwitterStatusesFilter mFilter; int mLastIndex; - * - * int mSkipRetweetCount = 0; int mSkipReplyCount = 0; } - */ - - /* - * - */ - /* - * private void filterTest(TwitterStatusesFilter filter) { - * - * int[] counts = mCounts.clone(); - * - * int count = getStatusCount(filter); for (int i = 0; i < count; i++) { - * TwitterStatus status = getStatus(i, filter); if (status == null) { - * getStatus(i, filter); } } } - */ } \ No newline at end of file diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterStatusesFilter.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterStatusesFilter.java index d241794a..a4d8afd8 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterStatusesFilter.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterStatusesFilter.java @@ -23,7 +23,7 @@ public final class TwitterStatusesFilter { enum FilterType { ALL, HIDE_RETWEETS, HIDE_REPLIES, HIDE_RETWEETS_REPLIES, FILTER_MAX, - }; + } public void setShowRetweets(boolean show) { mShowRetweets = show; @@ -42,19 +42,19 @@ public boolean getShowReplies() { } /* - * + * */ - boolean mShowRetweets = true; - boolean mShowReplies = true; + private boolean mShowRetweets = true; + private boolean mShowReplies = true; FilterType getFilterType() { - if (mShowRetweets == false && mShowReplies == false) { + if (!mShowRetweets && !mShowReplies) { return FilterType.HIDE_RETWEETS_REPLIES; - } else if (mShowReplies == false) { + } else if (!mShowReplies) { return FilterType.HIDE_REPLIES; - } else if (mShowRetweets == false) { + } else if (!mShowRetweets) { return FilterType.HIDE_RETWEETS; } return FilterType.ALL; } -}; \ No newline at end of file +} \ No newline at end of file diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterUser.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterUser.java index d37b5eb0..ebb2f2ab 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterUser.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterUser.java @@ -15,6 +15,10 @@ import org.socialnetlib.android.SocialNetConstant; import org.tweetalib.android.TwitterManager.ProfileImageSize; +import java.util.ArrayList; +import java.util.Arrays; + +import twitter4j.URLEntity; import twitter4j.User; public class TwitterUser { @@ -24,28 +28,37 @@ public TwitterUser(User user) { mScreenName = user.getScreenName(); mName = user.getName(); mDescription = user.getDescription(); - if (user.getLocation() != null - && user.getLocation().equals("") == false) { - mLocation = user.getLocation(); + ArrayList urlEntityArrayList = new ArrayList(); + if (user.getDescriptionURLEntities() != null) { + urlEntityArrayList = new ArrayList(Arrays.asList(user.getDescriptionURLEntities())); } + if (user.getURL() != null) { - mUrl = user.getURL().toString(); + mUrl = user.getURL(); + urlEntityArrayList.add(user.getURLEntity()); + } + + mUrlEntities = urlEntityArrayList.toArray(new URLEntity[urlEntityArrayList.size()]); + + if (user.getLocation() != null + && !user.getLocation().equals("")) { + mLocation = user.getLocation(); } if (user.getOriginalProfileImageURLHttps() != null) { - mProfileImageUrlOriginal = user.getOriginalProfileImageURLHttps().toString(); + mProfileImageUrlOriginal = user.getOriginalProfileImageURLHttps(); } if (user.getBiggerProfileImageURLHttps() != null) { - mProfileImageUrlBigger = user.getBiggerProfileImageURLHttps().toString(); + mProfileImageUrlBigger = user.getBiggerProfileImageURLHttps(); } if (user.getProfileImageURLHttps() != null) { - mProfileImageUrlNormal = user.getProfileImageURLHttps().toString(); + mProfileImageUrlNormal = user.getProfileImageURLHttps(); } if (user.getMiniProfileImageURLHttps() != null) { - mProfileImageUrlMini = user.getMiniProfileImageURLHttps().toString(); + mProfileImageUrlMini = user.getMiniProfileImageURLHttps(); } mStatusesCount = user.getStatusesCount(); @@ -82,8 +95,10 @@ public TwitterUser(TwitterUser user) { mScreenName = user.getScreenName(); mName = user.getName(); mDescription = user.getDescription(); + mUrlEntities = user.getUrlEntities(); mLocation = user.getLocation(); mUrl = user.getUrl(); + mProfileImageUrlMini = user.getProfileImageUrlMini(); mProfileImageUrlNormal = user.getProfileImageUrlNormal(); mProfileImageUrlBigger = user.getProfileImageUrlBigger(); @@ -159,7 +174,7 @@ public int getFavoritesCount() { return mFavoritesCount; } - public int getListedCount() { + int getListedCount() { return mListedCount; } @@ -185,8 +200,7 @@ public SocialNetConstant.Type getSocialNetType() { public String getProfileImageUrl(ProfileImageSize size) { - switch (size) - { + switch (size) { case MINI: return mProfileImageUrlMini; case NORMAL: @@ -199,10 +213,15 @@ public String getProfileImageUrl(ProfileImageSize size) { return ""; } - private long mId; - private String mScreenName; - private String mName; - private String mDescription; + public URLEntity[] getUrlEntities() { + return mUrlEntities; + } + + private final long mId; + private final String mScreenName; + private final String mName; + private final String mDescription; + private URLEntity[] mUrlEntities; private String mCoverImageUrl; private String mLocation; private String mProfileImageUrlMini; @@ -210,14 +229,14 @@ public String getProfileImageUrl(ProfileImageSize size) { private String mProfileImageUrlBigger; private String mProfileImageUrlOriginal; private String mUrl; - private int mStatusesCount; - private int mFriendsCount; - private int mFollowersCount; - private int mFavoritesCount; + private final int mStatusesCount; + private final int mFriendsCount; + private final int mFollowersCount; + private final int mFavoritesCount; private int mListedCount; private boolean mVerified; private boolean mProtected; - private SocialNetConstant.Type mSocialNetType; + private final SocialNetConstant.Type mSocialNetType; private boolean mFollowsCurrentUser; private boolean mCurrentUserFollows; } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterUsers.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterUsers.java index 0b8538b5..8c2a6cba 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterUsers.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/model/TwitterUsers.java @@ -21,7 +21,7 @@ public class TwitterUsers { /* - * + * */ public TwitterUsers() { mUsers = new ArrayList(); @@ -90,5 +90,5 @@ public void remove(TwitterUsers users) { /* * */ - private ArrayList mUsers; + private final ArrayList mUsers; } diff --git a/android/libraries/SocialNetLib/src/org/tweetalib/android/widget/URLSpanNoUnderline.java b/android/libraries/SocialNetLib/src/org/tweetalib/android/widget/URLSpanNoUnderline.java index 5156c5e1..0587245e 100644 --- a/android/libraries/SocialNetLib/src/org/tweetalib/android/widget/URLSpanNoUnderline.java +++ b/android/libraries/SocialNetLib/src/org/tweetalib/android/widget/URLSpanNoUnderline.java @@ -29,9 +29,9 @@ public class URLSpanNoUnderline extends URLSpan { /* - * + * */ - public URLSpanNoUnderline(String url) { + private URLSpanNoUnderline(String url) { super(url); } @@ -65,7 +65,7 @@ public static Spannable stripUnderlines(Spanned s) { /* * */ - public static Spannable stripUnderlines(Spannable s) { + private static Spannable stripUnderlines(Spannable s) { URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class); for (URLSpan span : spans) { int start = s.getSpanStart(span); diff --git a/android/libraries/TweetLanesCore/TweetLanesCore.iml b/android/libraries/TweetLanesCore/TweetLanesCore.iml index f94144c4..8cebb27f 100644 --- a/android/libraries/TweetLanesCore/TweetLanesCore.iml +++ b/android/libraries/TweetLanesCore/TweetLanesCore.iml @@ -5,6 +5,12 @@ @@ -14,7 +20,7 @@ - + diff --git a/android/libraries/TweetLanesCore/res/drawable-hdpi/ic_action_star_pressed_dark.png b/android/libraries/TweetLanesCore/res/drawable-hdpi/ic_action_star_pressed_dark.png new file mode 100644 index 00000000..2d5f0410 Binary files /dev/null and b/android/libraries/TweetLanesCore/res/drawable-hdpi/ic_action_star_pressed_dark.png differ diff --git a/android/libraries/TweetLanesCore/res/drawable-hdpi/ic_action_star_pressed_light.png b/android/libraries/TweetLanesCore/res/drawable-hdpi/ic_action_star_pressed_light.png new file mode 100644 index 00000000..d68eaf56 Binary files /dev/null and b/android/libraries/TweetLanesCore/res/drawable-hdpi/ic_action_star_pressed_light.png differ diff --git a/android/libraries/TweetLanesCore/res/drawable-mdpi/ic_action_star_pressed_dark.png b/android/libraries/TweetLanesCore/res/drawable-mdpi/ic_action_star_pressed_dark.png new file mode 100644 index 00000000..f5d73c80 Binary files /dev/null and b/android/libraries/TweetLanesCore/res/drawable-mdpi/ic_action_star_pressed_dark.png differ diff --git a/android/libraries/TweetLanesCore/res/drawable-mdpi/ic_action_star_pressed_light.png b/android/libraries/TweetLanesCore/res/drawable-mdpi/ic_action_star_pressed_light.png new file mode 100644 index 00000000..63ce196a Binary files /dev/null and b/android/libraries/TweetLanesCore/res/drawable-mdpi/ic_action_star_pressed_light.png differ diff --git a/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_rt_pressed_dark.png b/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_rt_pressed_dark.png new file mode 100644 index 00000000..97afbda9 Binary files /dev/null and b/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_rt_pressed_dark.png differ diff --git a/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_rt_pressed_light.png b/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_rt_pressed_light.png new file mode 100644 index 00000000..ae60d520 Binary files /dev/null and b/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_rt_pressed_light.png differ diff --git a/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_star_off_light.png b/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_star_off_light.png index 600ae03a..7ff6c8d0 100644 Binary files a/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_star_off_light.png and b/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_star_off_light.png differ diff --git a/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_star_on_light.png b/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_star_on_light.png index 06e66ab2..da44dd82 100644 Binary files a/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_star_on_light.png and b/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_star_on_light.png differ diff --git a/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_star_pressed_dark.png b/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_star_pressed_dark.png new file mode 100644 index 00000000..880e80f4 Binary files /dev/null and b/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_star_pressed_dark.png differ diff --git a/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_star_pressed_light.png b/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_star_pressed_light.png new file mode 100644 index 00000000..9bdce39b Binary files /dev/null and b/android/libraries/TweetLanesCore/res/drawable-xhdpi/ic_action_star_pressed_light.png differ diff --git a/android/libraries/TweetLanesCore/res/layout/account_row.xml b/android/libraries/TweetLanesCore/res/layout/account_row.xml index 35d9b3f7..ada61bbe 100644 --- a/android/libraries/TweetLanesCore/res/layout/account_row.xml +++ b/android/libraries/TweetLanesCore/res/layout/account_row.xml @@ -38,4 +38,11 @@ android:text="ScreenName" android:textSize="@dimen/account_row_size" android:layout_marginLeft="10dp"/> + + \ No newline at end of file diff --git a/android/libraries/TweetLanesCore/res/layout/profile.xml b/android/libraries/TweetLanesCore/res/layout/profile.xml index 69e96132..4a088ef0 100644 --- a/android/libraries/TweetLanesCore/res/layout/profile.xml +++ b/android/libraries/TweetLanesCore/res/layout/profile.xml @@ -108,7 +108,7 @@ android:paddingRight="20dip" android:layout_width="match_parent" android:layout_height="wrap_content" - android:text="The person's bio goes here. It could be anywhere up to 160 characters in length, which is anywhere up to and including the length of this wordly, informative string" + android:text="Loading bio..." android:linksClickable="true" /> diff --git a/android/libraries/TweetLanesCore/res/layout/profile_adn.xml b/android/libraries/TweetLanesCore/res/layout/profile_adn.xml index 865c7cc9..50236c5a 100644 --- a/android/libraries/TweetLanesCore/res/layout/profile_adn.xml +++ b/android/libraries/TweetLanesCore/res/layout/profile_adn.xml @@ -117,7 +117,7 @@ android:paddingRight="20dip" android:layout_width="match_parent" android:layout_height="wrap_content" - android:text="The person's bio goes here. It could be anywhere up to 160 characters in length, which is anywhere up to and including the length of this wordly, informative string" + android:text="Loading bio..." android:linksClickable="true" /> diff --git a/android/libraries/TweetLanesCore/res/layout/profile_title_thin.xml b/android/libraries/TweetLanesCore/res/layout/profile_title_thin.xml index 9eafb40b..7fceb01c 100644 --- a/android/libraries/TweetLanesCore/res/layout/profile_title_thin.xml +++ b/android/libraries/TweetLanesCore/res/layout/profile_title_thin.xml @@ -1,25 +1,8 @@ - - - - - - - - \ No newline at end of file + diff --git a/android/libraries/TweetLanesCore/res/layout/tweet_feed_conversation_item.xml b/android/libraries/TweetLanesCore/res/layout/tweet_feed_conversation_item.xml index df915329..e0bb6d6f 100644 --- a/android/libraries/TweetLanesCore/res/layout/tweet_feed_conversation_item.xml +++ b/android/libraries/TweetLanesCore/res/layout/tweet_feed_conversation_item.xml @@ -59,44 +59,59 @@ android:orientation="horizontal" > - - - - - + + + + + + + + + + + diff --git a/android/libraries/TweetLanesCore/res/values/arrays.xml b/android/libraries/TweetLanesCore/res/values/arrays.xml index 6aca3350..4f39f0c1 100644 --- a/android/libraries/TweetLanesCore/res/values/arrays.xml +++ b/android/libraries/TweetLanesCore/res/values/arrays.xml @@ -2,18 +2,20 @@ + + Relative + Absolute + Mixed + + Extra Small Small Medium Large Extra Large - - - - small - medium - large + Extra Extra Large + Supersize @@ -22,22 +24,12 @@ Large - - small - medium - large - - Holo Light + Holo Light w/ Dark Bar Holo Dark - - light - dark - - Standard Quote RT with Comment @@ -57,13 +49,6 @@ Name, \@username - - username - name - username_name - name_username - - Never 2 Minutes\n(Rate limit errors may occur) diff --git a/android/libraries/TweetLanesCore/res/values/dimens.xml b/android/libraries/TweetLanesCore/res/values/dimens.xml index 8571d911..d213202b 100644 --- a/android/libraries/TweetLanesCore/res/values/dimens.xml +++ b/android/libraries/TweetLanesCore/res/values/dimens.xml @@ -35,11 +35,14 @@ All Rights Reserved. --> 16sp 18sp 20sp + 22sp + 24sp 80dp 80dp 0dp - 0dp16sp + 0dp + 16sp diff --git a/android/libraries/TweetLanesCore/res/values/strings.xml b/android/libraries/TweetLanesCore/res/values/strings.xml index 7646acc2..bb05ebae 100644 --- a/android/libraries/TweetLanesCore/res/values/strings.xml +++ b/android/libraries/TweetLanesCore/res/values/strings.xml @@ -27,7 +27,7 @@
    AOSP, Copyright 2008-2013, Android Open Source Project.\n GestureImageView, Copyright 2012 Jason Polites.\n - Prime, Copyright (C) 2012 Daniel Huckaby.\n + Prime, Copyright 2012 Daniel Huckaby.\n UrlImageViewHelper, Copyright 2013 Koushik Dutta.\n ViewPagerIndicator, Copyright 2012 Jake Wharton.\n @@ -174,6 +174,8 @@ Failed to post status Posting Posting … + The position on the feed has been lost + The refresh was cancelled to stop position being lost Tweet Text Link to Tweet @@ -200,12 +202,15 @@ Your status update cannot be posted as it contains invalid characters. + Twitter doesn\'t know how to read silence. + App.net doesn\'t know how to read silence. Please enter the Twitter username of the person to message. The text of your Direct Message is too long and cannot be posted.\n\nYou message can be a maximum 140 characters in length. + Got nothin\' to say do ya? Your Direct Message cannot be posted as it contains invalid characters. @@ -233,6 +238,7 @@ Favorited successfully Unfavorited successfully Favorited failed + Favorite being marked Unfavorited failed Unable to change Favorite marker Retweeted successfully @@ -270,6 +276,7 @@ An unknown error has occurred + An error occured processing URL Unable to save image until it has finished downloading Successfully saved image @@ -431,6 +438,9 @@ Customize Lanes Show/hide specific lanes + Time Format/Display + Time Format/Display + Font Size Font Size diff --git a/android/libraries/TweetLanesCore/res/values/styles.xml b/android/libraries/TweetLanesCore/res/values/styles.xml index 55e2baac..fbdb5805 100644 --- a/android/libraries/TweetLanesCore/res/values/styles.xml +++ b/android/libraries/TweetLanesCore/res/values/styles.xml @@ -33,6 +33,40 @@ + + + +