List of usage examples for org.apache.commons.lang3 StringEscapeUtils unescapeHtml4
public static final String unescapeHtml4(final String input)
Unescapes a string containing entity escapes to a string containing the actual Unicode characters corresponding to the escapes.
From source file:eu.nerdz.api.impl.reverse.messages.ReverseConversationHandler.java
/** * Parses a raw conversation string, returning a Conversation. * * @param row a raw conversation string//from ww w .j a va2 s . c om * @return A Conversation containing data parsed from row. * @throws ContentException */ private MessageFetcher parseConversationRow(String row) throws ContentException { int otherNamePosition = row.indexOf("<a href="); if (otherNamePosition < 0) { throw new ContentException("Malformed content \"" + row + "\""); } String otherName = StringEscapeUtils .unescapeHtml4(row.substring(row.indexOf('>', otherNamePosition) + 1, row.indexOf("</a>"))); int dataFromPosition = row.indexOf("data-from=\""); if (dataFromPosition < 0) { throw new ContentException("Malformed content \"" + row + "\""); } dataFromPosition += 11; int dataFrom = Integer.parseInt(row.substring(dataFromPosition, row.indexOf('"', dataFromPosition))); int dataTimePosition = row.indexOf("data-timestamp=\""); if (dataTimePosition < 0) { throw new ContentException("Malformed content \"" + row + "\""); } dataTimePosition += 16; Date lastDate = new Date( Long.parseLong(row.substring(dataTimePosition, row.indexOf('"', dataTimePosition))) * 1000L); return new ReverseMessageFetcher(otherName, dataFrom, lastDate); }
From source file:net.pms.util.OpenSubtitle.java
/** * Attempt to return information from IMDb about the file based on information * from the filename; either the hash, the IMDb ID or the filename itself. * * @param hash the video hash/* w w w . j a v a 2s . c o m*/ * @param size the bytesize to be used with the hash * @param imdb the IMDb ID * @param query the string to search IMDb for * * @return a string array including the IMDb ID, episode title, season number, * episode number relative to the season, and the show name, or null * if we couldn't find it on IMDb. * * @throws IOException */ private static String[] getInfo(String hash, long size, String imdb, String query, RendererConfiguration r) throws IOException { if (!login()) { return null; } String lang = UMSUtils.getLangList(r, true); URL url = new URL(OPENSUBS_URL); String hashStr = ""; String imdbStr = ""; String qStr = ""; if (!StringUtils.isEmpty(hash)) { hashStr = "<member><name>moviehash</name><value><string>" + hash + "</string></value></member>\n" + "<member><name>moviebytesize</name><value><double>" + size + "</double></value></member>\n"; } else if (!StringUtils.isEmpty(imdb)) { imdbStr = "<member><name>imdbid</name><value><string>" + imdb + "</string></value></member>\n"; } else if (!StringUtils.isEmpty(query)) { qStr = "<member><name>query</name><value><string>" + query + "</string></value></member>\n"; } else { return null; } String req = null; tokenLock.readLock().lock(); try { req = "<methodCall>\n<methodName>SearchSubtitles</methodName>\n" + "<params>\n<param>\n<value><string>" + token + "</string></value>\n</param>\n" + "<param>\n<value>\n<array>\n<data>\n<value><struct><member><name>sublanguageid" + "</name><value><string>" + lang + "</string></value></member>" + hashStr + imdbStr + qStr + "\n" + "</struct></value></data>\n</array>\n</value>\n</param>" + "</params>\n</methodCall>\n"; } finally { tokenLock.readLock().unlock(); } Pattern re = Pattern.compile(".*IDMovieImdb</name>.*?<string>([^<]+)</string>.*?" + "" + "MovieName</name>.*?<string>([^<]+)</string>.*?" + "SeriesSeason</name>.*?<string>([^<]+)</string>.*?" + "SeriesEpisode</name>.*?<string>([^<]+)</string>.*?" + "MovieYear</name>.*?<string>([^<]+)</string>.*?", Pattern.DOTALL); String page = postPage(url.openConnection(), req); Matcher m = re.matcher(page); if (m.find()) { LOGGER.debug("match " + m.group(1) + "," + m.group(2) + "," + m.group(3) + "," + m.group(4) + "," + m.group(5)); Pattern re1 = Pattern.compile(""([^&]+)"(.*)"); String name = m.group(2); Matcher m1 = re1.matcher(name); String eptit = ""; if (m1.find()) { eptit = m1.group(2).trim(); name = m1.group(1).trim(); } return new String[] { ImdbUtil.ensureTT(m.group(1).trim()), StringEscapeUtils.unescapeHtml4(eptit), StringEscapeUtils.unescapeHtml4(name), m.group(3).trim(), // Season number m.group(4).trim(), // Episode number m.group(5).trim() // Year }; } return null; }
From source file:com.nttec.everychan.chans.krautchan.KrautModule.java
@Override public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception { String url = (useHttps() ? "https://" : "http://") + CHAN_DOMAIN + "/post"; ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create().setDelegates(listener, task) .addString("internal_n", model.name).addString("internal_s", model.subject); if (model.sage) postEntityBuilder.addString("sage", "1"); postEntityBuilder.addString("internal_t", model.comment); if (lastCaptchaId != null) { postEntityBuilder.addString("captcha_name", lastCaptchaId).addString("captcha_secret", model.captchaAnswer);/*w w w. j av a2 s . c o m*/ lastCaptchaId = null; } if (model.attachments != null) { String[] images = new String[] { "file_0", "file_1", "file_2", "file_3" }; for (int i = 0; i < model.attachments.length; ++i) { postEntityBuilder.addFile(images[i], model.attachments[i], model.randomHash); } } postEntityBuilder.addString("forward", "thread").addString("password", model.password).addString("board", model.boardName); if (model.threadNumber != null) postEntityBuilder.addString("parent", model.threadNumber); HttpRequestModel request = HttpRequestModel.builder().setPOST(postEntityBuilder.build()).setNoRedirect(true) .build(); HttpResponseModel response = null; try { response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, null, task); if (response.statusCode == 302) { for (Header header : response.headers) { if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) { String location = header.getValue(); if (location.contains("banned")) throw new Exception("You are banned"); return fixRelativeUrl(header.getValue()); } } } else if (response.statusCode == 200) { ByteArrayOutputStream output = new ByteArrayOutputStream(1024); IOUtils.copyStream(response.stream, output); String htmlResponse = output.toString("UTF-8"); int messageErrorPos = htmlResponse.indexOf("class=\"message_error"); if (messageErrorPos == -1) return null; //assume success int p2 = htmlResponse.indexOf('>', messageErrorPos); if (p2 != -1) { String errorMessage = htmlResponse.substring(p2 + 1); int p3 = errorMessage.indexOf("</tr>"); if (p3 != -1) errorMessage = errorMessage.substring(0, p3); errorMessage = RegexUtils.trimToSpace( StringEscapeUtils.unescapeHtml4(RegexUtils.removeHtmlTags(errorMessage)).trim()); throw new Exception(errorMessage); } } throw new HttpWrongStatusCodeException(response.statusCode, response.statusCode + " - " + response.statusReason); } finally { if (response != null) response.release(); } }
From source file:com.ryan.ryanreader.fragments.CommentListingFragment.java
private void makeFirstRequest(final Context context) { final RedditAccount user = RedditAccountManager.getInstance(context).getDefaultAccount(); final CacheManager cm = CacheManager.getInstance(context); // TODO parameterise limit request = new CacheRequest(url, user, session, Constants.Priority.API_COMMENT_LIST, 0, downloadType, Constants.FileType.COMMENT_LIST, true, true, false, context) { @Override/*from w ww . ja va 2 s . c o m*/ protected void onDownloadNecessary() { new Handler(Looper.getMainLooper()).post(new Runnable() { public void run() { listFooter.addView(loadingView); adapter.notifyDataSetChanged(); } }); } @Override protected void onDownloadStarted() { loadingView.setIndeterminate(context.getString(R.string.download_connecting)); } @Override protected void onCallbackException(final Throwable t) { request = null; BugReportActivity.handleGlobalError(context, t); } @Override protected void onFailure(final RequestFailureType type, final Throwable t, final StatusLine status, final String readableMessage) { request = null; if (!isAdded()) return; if (loadingView != null) loadingView.setDoneNoAnim(R.string.download_failed); final RRError error = General.getGeneralErrorForFailure(context, type, t, status); new Handler(Looper.getMainLooper()).post(new Runnable() { public void run() { notifications.addView(new ErrorView(getSupportActivity(), error)); } }); } @Override protected void onProgress(final long bytesRead, final long totalBytes) { } @Override protected void onSuccess(final CacheManager.ReadableCacheFile cacheFile, final long timestamp, final UUID session, final boolean fromCache, final String mimetype) { request = null; } @Override public void onJsonParseStarted(final JsonValue value, final long timestamp, final UUID session, final boolean fromCache) { if (isAdded() && loadingView != null) loadingView.setIndeterminate("Downloading..."); // TODO pref (currently 10 mins) // TODO xml if (fromCache && RRTime.since(timestamp) > 10 * 60 * 1000) { new Handler(Looper.getMainLooper()).post(new Runnable() { public void run() { if (isDetached()) return; final TextView cacheNotif = new TextView(context); cacheNotif.setText(context.getString(R.string.listing_cached) + " " + RRTime.formatDateTime(timestamp, context)); final int paddingPx = General.dpToPixels(context, 6); final int sidePaddingPx = General.dpToPixels(context, 10); cacheNotif.setPadding(sidePaddingPx, paddingPx, sidePaddingPx, paddingPx); cacheNotif.setTextSize(13f); listHeaderNotifications.addView(cacheNotif); adapter.notifyDataSetChanged(); } }); } ((SessionChangeListener) getSupportActivity()).onSessionChanged(session, SessionChangeListener.SessionChangeType.COMMENTS, timestamp); // TODO {"error": 403} is received for unauthorized subreddits try { // Download main post if (value.getType() == JsonValue.Type.ARRAY) { // lol, reddit api final JsonBufferedArray root = value.asArray(); final JsonBufferedObject thing = root.get(0).asObject(); final JsonBufferedObject listing = thing.getObject("data"); final JsonBufferedArray postContainer = listing.getArray("children"); final RedditThing postThing = postContainer.getObject(0, RedditThing.class); final RedditPost post = postThing.asPost(); // TODO show upvote/downvote/etc buttons final RedditSubreddit parentSubreddit = new RedditSubreddit("/r/" + post.subreddit, post.subreddit, false); CommentListingFragment.this.post = new RedditPreparedPost(context, cm, 0, post, timestamp, true, parentSubreddit, false, false, false, user); final ViewGroup selfText; if (post.is_self && post.selftext != null && post.selftext.trim().length() > 0) { selfText = RedditCommentTextParser.parse(StringEscapeUtils.unescapeHtml4(post.selftext)) .generate(context, 14f * commentFontScale, null, new ActiveTextView.OnLinkClickedListener() { public void onClickUrl(String url) { if (url != null) LinkHandler.onLinkClicked(getSupportActivity(), url, false); } public void onClickText(Object attachment) { } }, CommentListingFragment.this.post); } else { selfText = null; } new Handler(Looper.getMainLooper()).post(new Runnable() { public void run() { final RedditPostHeaderView postHeader = new RedditPostHeaderView( getSupportActivity(), CommentListingFragment.this.post, CommentListingFragment.this); listHeaderPost.addView(postHeader); if (selfText != null) { selfText.setFocusable(false); selfText.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); final int paddingPx = General.dpToPixels(context, 10); listHeaderSelftext.addView(selfText); listHeaderSelftext.setPadding(paddingPx, paddingPx, paddingPx, paddingPx); listHeaderNotifications.setBackgroundColor(Color.argb(35, 128, 128, 128)); } if (!General.isTablet(context, PreferenceManager.getDefaultSharedPreferences(context))) { getSupportActivity().getSupportActionBar().setTitle(post.title); } } }); } // Download comments final JsonBufferedObject thing; if (value.getType() == JsonValue.Type.ARRAY) { thing = value.asArray().get(1).asObject(); } else { thing = value.asObject(); } final JsonBufferedObject listing = thing.getObject("data"); final JsonBufferedArray topLevelComments = listing.getArray("children"); final HashSet<String> needsChanging = RedditChangeDataManager.getInstance(context) .getChangedForParent(parentPostIdAndType, user); for (final JsonValue commentThingValue : topLevelComments) { buildComments(commentThingValue, null, timestamp, needsChanging); } commentHandler.sendMessage(General.handlerMessage(0, buffer)); } catch (Throwable t) { notifyFailure(RequestFailureType.PARSE, t, null, "Parse failure"); return; } if (isAdded() && loadingView != null) loadingView.setDoneNoAnim(R.string.download_done); } private ArrayList<RedditPreparedComment> buffer = new ArrayList<RedditPreparedComment>(); private void buildComments(final JsonValue value, final RedditPreparedComment parent, final long timestamp, final HashSet<String> needsChanging) throws IOException, InterruptedException, IllegalAccessException, java.lang.InstantiationException, NoSuchMethodException, InvocationTargetException { final RedditThing commentThing = value.asObject(RedditThing.class); if (commentThing.getKind() != RedditThing.Kind.COMMENT) return; final RedditComment comment = commentThing.asComment(); final RedditPreparedComment preparedComment = new RedditPreparedComment(context, comment, parent, timestamp, needsChanging.contains(comment.name), post, user, headerItems); after = preparedComment.idAndType; buffer.add(preparedComment); if (buffer.size() >= 40) { commentHandler.sendMessage(General.handlerMessage(0, buffer)); buffer = new ArrayList<RedditPreparedComment>(); } if (comment.replies.getType() == JsonValue.Type.OBJECT) { final JsonBufferedObject replies = comment.replies.asObject(); final JsonBufferedArray children = replies.getObject("data").getArray("children"); for (final JsonValue v : children) { buildComments(v, preparedComment, timestamp, needsChanging); } } } }; cm.makeRequest(request); }
From source file:com.wellsandwhistles.android.redditsp.reddit.prepared.RedditPreparedPost.java
public static void onActionMenuItemSelected(final RedditPreparedPost post, final AppCompatActivity activity, final Action action) { switch (action) { case UPVOTE:/*from w w w . ja v a 2 s .co m*/ post.action(activity, RedditAPI.ACTION_UPVOTE); break; case DOWNVOTE: post.action(activity, RedditAPI.ACTION_DOWNVOTE); break; case UNVOTE: post.action(activity, RedditAPI.ACTION_UNVOTE); break; case SAVE: post.action(activity, RedditAPI.ACTION_SAVE); break; case UNSAVE: post.action(activity, RedditAPI.ACTION_UNSAVE); break; case HIDE: post.action(activity, RedditAPI.ACTION_HIDE); break; case UNHIDE: post.action(activity, RedditAPI.ACTION_UNHIDE); break; case EDIT: final Intent editIntent = new Intent(activity, CommentEditActivity.class); editIntent.putExtra("commentIdAndType", post.src.getIdAndType()); editIntent.putExtra("commentText", StringEscapeUtils.unescapeHtml4(post.src.getRawSelfText())); editIntent.putExtra("isSelfPost", true); activity.startActivity(editIntent); break; case DELETE: new AlertDialog.Builder(activity).setTitle(R.string.accounts_delete).setMessage(R.string.delete_confirm) .setPositiveButton(R.string.action_delete, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { post.action(activity, RedditAPI.ACTION_DELETE); } }).setNegativeButton(R.string.dialog_cancel, null).show(); break; case REPORT: new AlertDialog.Builder(activity).setTitle(R.string.action_report) .setMessage(R.string.action_report_sure) .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { post.action(activity, RedditAPI.ACTION_REPORT); // TODO update the view to show the result // TODO don't forget, this also hides } }).setNegativeButton(R.string.dialog_cancel, null).show(); break; case EXTERNAL: { final Intent intent = new Intent(Intent.ACTION_VIEW); String url = (activity instanceof WebViewActivity) ? ((WebViewActivity) activity).getCurrentUrl() : post.src.getUrl(); intent.setData(Uri.parse(url)); activity.startActivity(intent); break; } case SELFTEXT_LINKS: { final HashSet<String> linksInComment = LinkHandler .computeAllLinks(StringEscapeUtils.unescapeHtml4(post.src.getRawSelfText())); if (linksInComment.isEmpty()) { General.quickToast(activity, R.string.error_toast_no_urls_in_self); } else { final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]); final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setItems(linksArr, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { LinkHandler.onLinkClicked(activity, linksArr[which], false, post.src.getSrc()); dialog.dismiss(); } }); final AlertDialog alert = builder.create(); alert.setTitle(R.string.action_selftext_links); alert.setCanceledOnTouchOutside(true); alert.show(); } break; } case SAVE_IMAGE: { ((BaseActivity) activity).requestPermissionWithCallback(Manifest.permission.WRITE_EXTERNAL_STORAGE, new SaveImageCallback(activity, post.src.getUrl())); break; } case SHARE: { final Intent mailer = new Intent(Intent.ACTION_SEND); mailer.setType("text/plain"); mailer.putExtra(Intent.EXTRA_SUBJECT, post.src.getTitle()); mailer.putExtra(Intent.EXTRA_TEXT, post.src.getUrl()); activity.startActivity(Intent.createChooser(mailer, activity.getString(R.string.action_share))); break; } case SHARE_COMMENTS: { final boolean shareAsPermalink = PrefsUtility.pref_behaviour_share_permalink(activity, PreferenceManager.getDefaultSharedPreferences(activity)); final Intent mailer = new Intent(Intent.ACTION_SEND); mailer.setType("text/plain"); mailer.putExtra(Intent.EXTRA_SUBJECT, "Comments for " + post.src.getTitle()); if (shareAsPermalink) { mailer.putExtra(Intent.EXTRA_TEXT, Constants.Reddit.getNonAPIUri(post.src.getPermalink()).toString()); } else { mailer.putExtra(Intent.EXTRA_TEXT, Constants.Reddit .getNonAPIUri(Constants.Reddit.PATH_COMMENTS + post.src.getIdAlone()).toString()); } activity.startActivity( Intent.createChooser(mailer, activity.getString(R.string.action_share_comments))); break; } case SHARE_IMAGE: { ((BaseActivity) activity).requestPermissionWithCallback(Manifest.permission.WRITE_EXTERNAL_STORAGE, new ShareImageCallback(activity, post.src.getUrl())); break; } case COPY: { ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE); manager.setText(post.src.getUrl()); break; } case GOTO_SUBREDDIT: { try { final Intent intent = new Intent(activity, PostListingActivity.class); intent.setData(SubredditPostListURL.getSubreddit(post.src.getSubreddit()).generateJsonUri()); activity.startActivityForResult(intent, 1); } catch (RedditSubreddit.InvalidSubredditNameException e) { Toast.makeText(activity, R.string.invalid_subreddit_name, Toast.LENGTH_LONG).show(); } break; } case USER_PROFILE: LinkHandler.onLinkClicked(activity, new UserProfileURL(post.src.getAuthor()).toString()); break; case PROPERTIES: PostPropertiesDialog.newInstance(post.src.getSrc()).show(activity.getSupportFragmentManager(), null); break; case COMMENTS: ((PostSelectionListener) activity).onPostCommentsSelected(post); new Thread() { @Override public void run() { post.markAsRead(activity); } }.start(); break; case LINK: ((PostSelectionListener) activity).onPostSelected(post); break; case COMMENTS_SWITCH: if (!(activity instanceof MainActivity)) activity.finish(); ((PostSelectionListener) activity).onPostCommentsSelected(post); break; case LINK_SWITCH: if (!(activity instanceof MainActivity)) activity.finish(); ((PostSelectionListener) activity).onPostSelected(post); break; case ACTION_MENU: showActionMenu(activity, post); break; case REPLY: final Intent intent = new Intent(activity, CommentReplyActivity.class); intent.putExtra(CommentReplyActivity.PARENT_ID_AND_TYPE_KEY, post.src.getIdAndType()); intent.putExtra(CommentReplyActivity.PARENT_MARKDOWN_KEY, post.src.getUnescapedSelfText()); activity.startActivity(intent); break; case BACK: activity.onBackPressed(); break; case PIN: try { String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit()); List<String> pinnedSubreddits = PrefsUtility.pref_pinned_subreddits(activity, PreferenceManager.getDefaultSharedPreferences(activity)); if (!pinnedSubreddits.contains(subredditCanonicalName)) { PrefsUtility.pref_pinned_subreddits_add(activity, PreferenceManager.getDefaultSharedPreferences(activity), subredditCanonicalName); } else { Toast.makeText(activity, R.string.mainmenu_toast_pinned, Toast.LENGTH_SHORT).show(); } } catch (RedditSubreddit.InvalidSubredditNameException e) { throw new RuntimeException(e); } break; case UNPIN: try { String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit()); List<String> pinnedSubreddits = PrefsUtility.pref_pinned_subreddits(activity, PreferenceManager.getDefaultSharedPreferences(activity)); if (pinnedSubreddits.contains(subredditCanonicalName)) { PrefsUtility.pref_pinned_subreddits_remove(activity, PreferenceManager.getDefaultSharedPreferences(activity), subredditCanonicalName); } else { Toast.makeText(activity, R.string.mainmenu_toast_not_pinned, Toast.LENGTH_SHORT).show(); } } catch (RedditSubreddit.InvalidSubredditNameException e) { throw new RuntimeException(e); } break; case BLOCK: try { String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit()); List<String> blockedSubreddits = PrefsUtility.pref_blocked_subreddits(activity, PreferenceManager.getDefaultSharedPreferences(activity)); if (!blockedSubreddits.contains(subredditCanonicalName)) { PrefsUtility.pref_blocked_subreddits_add(activity, PreferenceManager.getDefaultSharedPreferences(activity), subredditCanonicalName); } else { Toast.makeText(activity, R.string.mainmenu_toast_blocked, Toast.LENGTH_SHORT).show(); } } catch (RedditSubreddit.InvalidSubredditNameException e) { throw new RuntimeException(e); } break; case UNBLOCK: try { String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit()); List<String> blockedSubreddits = PrefsUtility.pref_blocked_subreddits(activity, PreferenceManager.getDefaultSharedPreferences(activity)); if (blockedSubreddits.contains(subredditCanonicalName)) { PrefsUtility.pref_blocked_subreddits_remove(activity, PreferenceManager.getDefaultSharedPreferences(activity), subredditCanonicalName); } else { Toast.makeText(activity, R.string.mainmenu_toast_not_blocked, Toast.LENGTH_SHORT).show(); } } catch (RedditSubreddit.InvalidSubredditNameException e) { throw new RuntimeException(e); } break; case SUBSCRIBE: try { String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit()); RedditSubredditSubscriptionManager subMan = RedditSubredditSubscriptionManager .getSingleton(activity, RedditAccountManager.getInstance(activity).getDefaultAccount()); if (subMan.getSubscriptionState( subredditCanonicalName) == RedditSubredditSubscriptionManager.SubredditSubscriptionState.NOT_SUBSCRIBED) { subMan.subscribe(subredditCanonicalName, activity); Toast.makeText(activity, R.string.options_subscribing, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(activity, R.string.mainmenu_toast_subscribed, Toast.LENGTH_SHORT).show(); } } catch (RedditSubreddit.InvalidSubredditNameException e) { throw new RuntimeException(e); } break; case UNSUBSCRIBE: try { String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit()); RedditSubredditSubscriptionManager subMan = RedditSubredditSubscriptionManager .getSingleton(activity, RedditAccountManager.getInstance(activity).getDefaultAccount()); if (subMan.getSubscriptionState( subredditCanonicalName) == RedditSubredditSubscriptionManager.SubredditSubscriptionState.SUBSCRIBED) { subMan.unsubscribe(subredditCanonicalName, activity); Toast.makeText(activity, R.string.options_unsubscribing, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(activity, R.string.mainmenu_toast_not_subscribed, Toast.LENGTH_SHORT).show(); } } catch (RedditSubreddit.InvalidSubredditNameException e) { throw new RuntimeException(e); } break; } }
From source file:cx.fbn.nevernote.sql.NoteTable.java
public Note mapNoteFromQuery(NSqlQuery query, boolean loadContent, boolean loadResources, boolean loadRecognition, boolean loadBinary, boolean loadTags) { DateFormat indfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); // indfm = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy"); Note n = new Note(); NoteAttributes na = new NoteAttributes(); n.setAttributes(na);/*ww w. j a v a 2s . co m*/ n.setGuid(query.valueString(0)); n.setUpdateSequenceNum(new Integer(query.valueString(1))); n.setTitle(query.valueString(2)); try { n.setCreated(indfm.parse(query.valueString(3)).getTime()); n.setUpdated(indfm.parse(query.valueString(4)).getTime()); n.setDeleted(indfm.parse(query.valueString(5)).getTime()); } catch (ParseException e) { e.printStackTrace(); } n.setActive(query.valueBoolean(6, true)); n.setNotebookGuid(query.valueString(7)); try { String attributeSubjectDate = query.valueString(8); if (!attributeSubjectDate.equals("")) na.setSubjectDate(indfm.parse(attributeSubjectDate).getTime()); } catch (ParseException e) { e.printStackTrace(); } na.setLatitude(new Float(query.valueString(9))); na.setLongitude(new Float(query.valueString(10))); na.setAltitude(new Float(query.valueString(11))); na.setAuthor(query.valueString(12)); na.setSource(query.valueString(13)); na.setSourceURL(query.valueString(14)); na.setSourceApplication(query.valueString(15)); na.setContentClass(query.valueString(16)); if (loadTags) { List<String> tagGuids = noteTagsTable.getNoteTags(n.getGuid()); List<String> tagNames = new ArrayList<String>(); TagTable tagTable = db.getTagTable(); for (int i = 0; i < tagGuids.size(); i++) { String currentGuid = tagGuids.get(i); Tag tag = tagTable.getTag(currentGuid); if (tag.getName() != null) tagNames.add(tag.getName()); else tagNames.add(""); } n.setTagNames(tagNames); n.setTagGuids(tagGuids); } if (loadContent) { QTextCodec codec = QTextCodec.codecForLocale(); codec = QTextCodec.codecForName("UTF-8"); String unicode = codec.fromUnicode(query.valueString(17)).toString(); // This is a hack. Basically I need to convert HTML Entities to "normal" text, but if I // convert the < character to < it will mess up the XML parsing. So, to get around this // I am "bit stuffing" the < to &< so StringEscapeUtils doesn't unescape it. After // I'm done I convert it back. StringBuffer buffer = new StringBuffer(unicode); if (Global.enableHTMLEntitiesFix && unicode.indexOf("&#") > 0) { unicode = query.valueString(17); //System.out.println(unicode); //unicode = unicode.replace("<", "&_lt;"); //unicode = codec.fromUnicode(StringEscapeUtils.unescapeHtml(unicode)).toString(); //unicode = unicode.replace("&_lt;", "<"); //System.out.println("************************"); int j = 1; for (int i = buffer.indexOf("&#"); i != -1 && buffer.indexOf("&#", i) > 0; i = buffer.indexOf("&#", i + 1)) { j = buffer.indexOf(";", i) + 1; if (i < j) { String entity = buffer.substring(i, j).toString(); int len = entity.length() - 1; String tempEntity = entity.substring(2, len); try { Integer.parseInt(tempEntity); entity = codec.fromUnicode(StringEscapeUtils.unescapeHtml4(entity)).toString(); buffer.delete(i, j); buffer.insert(i, entity); } catch (Exception e) { } } } } n.setContent(unicode); // n.setContent(query.valueString(16).toString()); String contentHash = query.valueString(18); if (contentHash != null) n.setContentHash(contentHash.getBytes()); n.setContentLength(new Integer(query.valueString(19))); } if (loadResources) n.setResources(noteResourceTable.getNoteResources(n.getGuid(), loadBinary)); if (loadRecognition) { if (n.getResources() == null) { List<Resource> resources = noteResourceTable.getNoteResourcesRecognition(n.getGuid()); n.setResources(resources); } else { // We need to merge the recognition resources with the note resources retrieved earlier for (int i = 0; i < n.getResources().size(); i++) { Resource r = noteResourceTable.getNoteResourceRecognition(n.getResources().get(i).getGuid()); n.getResources().get(i).setRecognition(r.getRecognition()); } } } n.setContent(fixCarriageReturn(n.getContent())); return n; }
From source file:com.norconex.collector.http.url.impl.GenericLinkExtractor.java
private String toCleanAbsoluteURL(final Referer urlParts, final String newURL) { String url = StringUtils.trimToNull(newURL); if (!isValidNewURL(url)) { return null; }/*from ww w . j a v a2 s . c o m*/ // Decode HTML entities. url = StringEscapeUtils.unescapeHtml4(url); if (url.startsWith("//")) { // this is URL relative to protocol url = urlParts.protocol + StringUtils.substringAfter(url, "//"); } else if (url.startsWith("/")) { // this is a URL relative to domain name url = urlParts.absoluteBase + url; } else if (url.startsWith("?") || url.startsWith("#")) { // this is a relative url and should have the full page base url = urlParts.documentBase + url; } else if (!url.contains("://")) { if (urlParts.relativeBase.endsWith("/")) { // This is a URL relative to the last URL segment url = urlParts.relativeBase + url; } else { url = urlParts.relativeBase + "/" + url; } } if (url.length() > maxURLLength) { LOG.debug("URL length (" + url.length() + ") exeeding " + "maximum length allowed (" + maxURLLength + ") to be extracted. URL (showing first " + LOGGING_MAX_URL_LENGTH + " chars): " + StringUtils.substring(url, 0, LOGGING_MAX_URL_LENGTH) + "..."); return null; } return url; }
From source file:edu.illinois.cs.cogcomp.ner.Main.java
/** * process the single input string, produce output on standard out if no output directory is * defined, or produce the output in the output directory by the same file name as the input * file, or if a specific output filename is specified, use that name. * //from w w w . j av a2 s . com * @param data the string to process * @throws Exception if anything goes wrong. */ private void processInputString(String data) throws Exception { data = StringEscapeUtils.unescapeHtml4(data); TextAnnotation ta = tab.createTextAnnotation(data); data = this.produceOutput(this.nerAnnotator.getView(ta), ta); this.getResultProcessor().publish(data, Long.toString(System.currentTimeMillis()) + ".txt"); }
From source file:com.basetechnology.s0.agentserver.util.XmlUtils.java
static public String unescapeEntities(String xmlString) { return StringEscapeUtils.unescapeHtml4(xmlString); }
From source file:cfappserver.Bot.java
public static String remSpace(String s) { for (int i = 0; i < s.length(); i++) { if ((int) s.charAt(i) > 32) { s = s.substring(i);// w ww . j a v a 2 s .com break; } } for (int i = s.length() - 1; i >= 0; i--) { if ((int) s.charAt(i) > 32) { s = s.substring(0, i + 1); break; } } for (int i = 1; i < s.length(); i++) { if ((int) s.charAt(i) <= 32 && (int) s.charAt(i - 1) <= 32) { s = s.substring(0, i - 1) + s.substring(i); i--; } } s = StringEscapeUtils.unescapeHtml4(s); s = s.replace("{", "("); s = s.replace("}", ")"); return s; }